From 4e0a605c2d84cfbdc061cc5411ca4658931f78be Mon Sep 17 00:00:00 2001 From: Renee Yang <7040416+reeceyang@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:35:07 -0800 Subject: [PATCH] Write each changed B-tree node once per async batch Every write patches each node on its path to keep counts and sums current, so a batch rewrote a tree's root once per operation. Hold node writes in the batch's node cache and flush them when the batch ends, counting the held writes against the transaction's headroom so the flush always fits. Co-Authored-By: Claude Opus 5.5 --- .changeset/batch-node-cache.md | 5 +- src/component/nodeCache.test.ts | 83 +++++++++++++++++++++- src/component/nodeCache.ts | 121 ++++++++++++++++++++++++++------ src/component/worker.test.ts | 55 ++++++++++++++- src/component/worker.ts | 32 +++++++-- 5 files changed, 266 insertions(+), 30 deletions(-) diff --git a/.changeset/batch-node-cache.md b/.changeset/batch-node-cache.md index 96d275eb..4243c261 100644 --- a/.changeset/batch-node-cache.md +++ b/.changeset/batch-node-cache.md @@ -3,5 +3,6 @@ --- Keep B-tree nodes in memory while the batch worker applies a batch of async -writes, so consecutive writes to the same tree stop re-reading its root and -internal nodes from the database. (#306) +writes, and write each changed node once at the end of the batch, so consecutive +writes to the same tree stop re-reading and rewriting its root and internal +nodes. (#306, #307) diff --git a/src/component/nodeCache.test.ts b/src/component/nodeCache.test.ts index 3d7f7bf8..56fed140 100644 --- a/src/component/nodeCache.test.ts +++ b/src/component/nodeCache.test.ts @@ -1,3 +1,4 @@ +import { getDocumentSize } from "convex/values"; import { describe, expect, test } from "vitest"; import type { DatabaseWriter } from "./_generated/server.js"; import { NodeCachingDatabaseWriter } from "./nodeCache.js"; @@ -52,7 +53,6 @@ describe("NodeCachingDatabaseWriter", () => { aggregate: undefined, }); const after = (await db.get("btreeNode", id))!; - expect(after).toEqual(await ctx.db.get("btreeNode", id)); expect(after.items).toEqual([item]); expect("aggregate" in after).toBe(false); expect(before.items).toEqual([]); @@ -81,3 +81,84 @@ describe("NodeCachingDatabaseWriter", () => { }); }); }); + +describe("NodeCachingDatabaseWriter pending writes", () => { + test("keeps patches pending until flush", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const id = await ctx.db.insert("btreeNode", emptyNode); + const stored = await ctx.db.get("btreeNode", id); + const db = new NodeCachingDatabaseWriter(ctx.db); + const item = { k: 1, v: "a", s: 2 }; + await db.patch("btreeNode", id, { items: [item] }); + await db.patch("btreeNode", id, { aggregate: undefined }); + const pending = (await db.get("btreeNode", id))!; + expect(pending.items).toEqual([item]); + expect("aggregate" in pending).toBe(false); + expect(await ctx.db.get("btreeNode", id)).toEqual(stored); + expect(db.pendingWriteUsage()).toEqual({ + documents: 1, + bytesWritten: getDocumentSize(pending), + bytesRead: getDocumentSize(stored!), + }); + + await db.flushPendingWrites(); + expect(await ctx.db.get("btreeNode", id)).toEqual(pending); + expect(db.pendingWriteUsage()).toEqual({ + documents: 0, + bytesWritten: 0, + bytesRead: 0, + }); + }); + }); + + test("deleting a node drops its pending write", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const id = await ctx.db.insert("btreeNode", emptyNode); + const db = new NodeCachingDatabaseWriter(ctx.db); + await db.patch("btreeNode", id, { items: [{ k: 1, v: "a", s: 1 }] }); + await db.delete("btreeNode", id); + expect(db.pendingWriteUsage()).toEqual({ + documents: 0, + bytesWritten: 0, + bytesRead: 0, + }); + await db.flushPendingWrites(); + expect(await ctx.db.get("btreeNode", id)).toBeNull(); + }); + }); + + test("pendingWriteUsage matches what flush reads and writes", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const ids = await Promise.all( + [1, 2, 3].map(() => ctx.db.insert("btreeNode", emptyNode)), + ); + const db = new NodeCachingDatabaseWriter(ctx.db); + for (const [i, id] of ids.entries()) { + const items = Array.from({ length: i + 1 }, (_, k) => ({ + k: "x".repeat(100 * (k + 1)), + v: k, + s: k, + })); + await db.patch("btreeNode", id, { items }); + } + await db.delete("btreeNode", ids[2]); + const pending = db.pendingWriteUsage(); + const before = await ctx.meta.getTransactionMetrics(); + await db.flushPendingWrites(); + const after = await ctx.meta.getTransactionMetrics(); + expect(pending.documents).toBe(2); + expect(after.bytesRead.used - before.bytesRead.used).toBe( + pending.bytesRead, + ); + expect(after.bytesWritten.used - before.bytesWritten.used).toBe( + pending.bytesWritten, + ); + expect(after.documentsRead.used - before.documentsRead.used).toBe( + pending.documents, + ); + }); + }); +}); diff --git a/src/component/nodeCache.ts b/src/component/nodeCache.ts index 6cf1459f..2aa465f3 100644 --- a/src/component/nodeCache.ts +++ b/src/component/nodeCache.ts @@ -5,16 +5,33 @@ import type { WithOptionalSystemFields, WithoutSystemFields, } from "convex/server"; +import { getDocumentSize } from "convex/values"; import type { DatabaseWriter } from "./_generated/server.js"; import type { DataModel, Doc, Id } from "./_generated/dataModel.js"; type TableName = TableNamesInDataModel; +// https://docs.convex.dev/production/state/limits#documents +const MAX_DOCUMENT_SIZE = 1 << 20; + +type CachedNode = + | { node: null } + | { + node: Doc<"btreeNode">; + // Encoded size of the node currently stored in the database. We keep + // track of this because `flushPendingWrites` will read back the stored + // node when replacing it. + storedSize: number; + // Encoded size of `node` when it has a pending write. + pendingSize?: number; + }; + /** * Wraps `db` to keep B-tree nodes in memory once read, for a batch of writes * where consecutive operations on a tree keep re-reading its root and internal - * nodes. Node writes go to the database and update the cached copy. Other - * tables pass straight through. + * nodes. Node patches are kept in memory as pending writes until + * `flushPendingWrites`, which writes each changed node once; node inserts and + * deletes go to the database right away. Other tables pass straight through. * * Cached documents are replaced rather than mutated, so callers holding an * earlier copy of a node keep seeing that snapshot, as with `db.get`. @@ -25,7 +42,10 @@ type TableName = TableNamesInDataModel; export class NodeCachingDatabaseWriter implements DatabaseWriter { readonly system: DatabaseWriter["system"]; readonly vars: DatabaseWriter["vars"]; - private readonly nodes = new Map, Doc<"btreeNode"> | null>(); + private readonly nodes = new Map, CachedNode>(); + private pendingDocuments = 0; + private pendingWriteBytes = 0; + private pendingReadBytes = 0; constructor(private readonly db: DatabaseWriter) { this.system = db.system; @@ -57,7 +77,7 @@ export class NodeCachingDatabaseWriter implements DatabaseWriter { throw missingTable(); } if (table === "btreeNode") { - return await this.getNode(id as Id<"btreeNode">); + return (await this.getEntry(id as Id<"btreeNode">)).node; } return await this.db.get(table as TableName, id); } @@ -83,23 +103,18 @@ export class NodeCachingDatabaseWriter implements DatabaseWriter { if (value === undefined) { throw missingTable(); } + if (table === "btreeNode") { + await this.patchNode( + id as Id<"btreeNode">, + value as Partial>>, + ); + return; + } await this.db.patch( table as TableName, id as Id, value as Partial>, ); - if (table === "btreeNode") { - const cached = this.nodes.get(id as Id<"btreeNode">); - if (cached) { - this.nodes.set( - id as Id<"btreeNode">, - patched( - cached, - value as Partial>>, - ), - ); - } - } } replace( @@ -139,18 +154,82 @@ export class NodeCachingDatabaseWriter implements DatabaseWriter { } await this.db.delete(table as TableName, id); if (table === "btreeNode") { - this.nodes.set(id as Id<"btreeNode">, null); + const entry = this.nodes.get(id as Id<"btreeNode">); + if (entry?.node && entry.pendingSize !== undefined) { + // Since we directly delete the node from the database, the usage has + // already been charged, and we no longer need to flush the node. + this.pendingDocuments--; + this.pendingWriteBytes -= entry.pendingSize; + this.pendingReadBytes -= entry.storedSize; + } + this.nodes.set(id as Id<"btreeNode">, { node: null }); } } - private async getNode(id: Id<"btreeNode">): Promise | null> { + async flushPendingWrites(): Promise { + for (const [id, entry] of this.nodes) { + if (!entry.node || entry.pendingSize === undefined) { + continue; + } + const { _id, _creationTime, ...fields } = entry.node; + await this.db.replace("btreeNode", _id, fields); + this.nodes.set(id, { node: entry.node, storedSize: entry.pendingSize }); + } + this.pendingDocuments = 0; + this.pendingWriteBytes = 0; + this.pendingReadBytes = 0; + } + + pendingWriteUsage(): { + documents: number; + bytesWritten: number; + bytesRead: number; + } { + return { + documents: this.pendingDocuments, + bytesWritten: this.pendingWriteBytes, + bytesRead: this.pendingReadBytes, + }; + } + + private async getEntry(id: Id<"btreeNode">): Promise { const cached = this.nodes.get(id); - if (cached !== undefined) { + if (cached) { return cached; } const doc = await this.db.get("btreeNode", id); - this.nodes.set(id, doc); - return doc; + const entry: CachedNode = doc + ? { node: doc, storedSize: getDocumentSize(doc) } + : { node: null }; + this.nodes.set(id, entry); + return entry; + } + + private async patchNode( + id: Id<"btreeNode">, + fields: Partial>>, + ): Promise { + const entry = await this.getEntry(id); + if (!entry.node) { + // Let the database report the missing node. + await this.db.patch("btreeNode", id, fields); + return; + } + const node = patched(entry.node, fields); + const pendingSize = getDocumentSize(node); + // The database would only reject an oversized node at flush, after the + // operation that grew it, so reject it here instead. + if (pendingSize > MAX_DOCUMENT_SIZE) { + throw new Error( + `[aggregate] B-tree node ${id} would be ${pendingSize} bytes, over the ${MAX_DOCUMENT_SIZE}-byte document limit`, + ); + } + if (entry.pendingSize === undefined) { + this.pendingDocuments++; + this.pendingReadBytes += entry.storedSize; + } + this.pendingWriteBytes += pendingSize - (entry.pendingSize ?? 0); + this.nodes.set(id, { node, storedSize: entry.storedSize, pendingSize }); } } diff --git a/src/component/worker.test.ts b/src/component/worker.test.ts index 73f49f6d..986cb533 100644 --- a/src/component/worker.test.ts +++ b/src/component/worker.test.ts @@ -667,6 +667,28 @@ describe("failures and dead letters", () => { }); }); + test("an operation that grows a node past the document size limit is dead-lettered", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + await getOrCreateTree(ctx.db, {}, 4, false); + }); + const value = "x".repeat(300_000); + for (const key of [1, 2, 3]) { + await enqueue(t, { type: "insert", key, value }); + } + const bad = await enqueue(t, { type: "insert", key: 4, value }); + await drainViaWorker(t); + await t.run(async (ctx) => { + expect(await ctx.db.query("pendingOperations").first()).toBeNull(); + const { count } = await aggregateBetweenHandler(ctx, {}); + expect(count).toEqual(3); + const dead = await ctx.db.query("deadLetterOperations").collect(); + expect(dead).toHaveLength(1); + expect(dead[0].commitTs).toEqual(bad); + expect(dead[0].operation).toEqual({ type: "insert", key: 4, value }); + }); + }); + test("only the failing operation is dropped; its neighbours in the entry still apply", async () => { const t = initConvexTest(); await t.run(async (ctx) => { @@ -906,8 +928,13 @@ describe("transaction limits", () => { } test("hasHeadroomToFinish is false once the reserve is all that's left", () => { + const noPendingWrites = { + documents: 0, + bytesWritten: 0, + bytesRead: 0, + }; // A fresh transaction has room for another operation. - expect(hasHeadroomToFinish(metricsWith({}))).toBe(true); + expect(hasHeadroomToFinish(metricsWith({}), noPendingWrites)).toBe(true); // Down to the reserve, so there's only room to wrap up. expect( hasHeadroomToFinish( @@ -917,15 +944,41 @@ describe("transaction limits", () => { remaining: RESERVE_BYTES, }, }), + noPendingWrites, ), ).toBe(false); // One exhausted limit is enough to stop, with the rest wide open. expect( hasHeadroomToFinish( metricsWith({ documentsWritten: { used: 15_994, remaining: 6 } }), + noPendingWrites, ), ).toBe(false); }); + + test("hasHeadroomToFinish counts pending writes flushed at the end of the cycle", () => { + const metrics = metricsWith({}); + const none = { documents: 0, bytesWritten: 0, bytesRead: 0 }; + expect(hasHeadroomToFinish(metrics, none)).toBe(true); + expect( + hasHeadroomToFinish(metrics, { + ...none, + bytesWritten: TRANSACTION_LIMITS.bytesWritten - RESERVE_BYTES, + }), + ).toBe(false); + expect( + hasHeadroomToFinish(metrics, { + ...none, + bytesRead: TRANSACTION_LIMITS.bytesRead - RESERVE_BYTES, + }), + ).toBe(false); + expect( + hasHeadroomToFinish(metrics, { + ...none, + documents: TRANSACTION_LIMITS.documentsWritten - 100, + }), + ).toBe(false); + }); }); }); diff --git a/src/component/worker.ts b/src/component/worker.ts index 9a6f5fa9..bec7f2f9 100644 --- a/src/component/worker.ts +++ b/src/component/worker.ts @@ -203,10 +203,26 @@ export const FINISH_RESERVE: Record = { documentsWritten: RESERVE_HEADROOM, }; -// Whether this transaction still has room to finish the cycle. -export function hasHeadroomToFinish(metrics: TransactionMetrics): boolean { +// Whether this transaction still has room to finish the cycle, including +// pending writes that need to be flushed at the end. +export function hasHeadroomToFinish( + metrics: TransactionMetrics, + pendingWriteUsage: { + documents: number; + bytesWritten: number; + bytesRead: number; + }, +): boolean { + const pending: Record = { + bytesRead: pendingWriteUsage.bytesRead, + bytesWritten: pendingWriteUsage.bytesWritten, + databaseQueries: 0, + documentsRead: pendingWriteUsage.documents, + documentsWritten: pendingWriteUsage.documents, + }; return BATCH_LIMITS.every( - (limit) => metrics[limit].remaining > FINISH_RESERVE[limit], + (limit) => + metrics[limit].remaining - pending[limit] > FINISH_RESERVE[limit], ); } @@ -230,6 +246,11 @@ export const processBatchInner = internalMutation({ returns: v.int64(), handler: async (ctx, { entries }) => { const db = new NodeCachingDatabaseWriter(ctx.db); + const hasHeadroom = async () => + hasHeadroomToFinish( + await ctx.meta.getTransactionMetrics(), + db.pendingWriteUsage(), + ); let cursor: bigint | null = null; for (const [entryIndex, entry] of entries.entries()) { let applied = 0; @@ -245,7 +266,7 @@ export const processBatchInner = internalMutation({ }); } applied++; - if (!hasHeadroomToFinish(await ctx.meta.getTransactionMetrics())) { + if (!(await hasHeadroom())) { break; } } @@ -257,13 +278,14 @@ export const processBatchInner = internalMutation({ break; } await ctx.db.delete("pendingOperations", entry.id); - if (!hasHeadroomToFinish(await ctx.meta.getTransactionMetrics())) { + if (!(await hasHeadroom())) { break; } } if (cursor === null) { throw new Error("[aggregate] a cycle made no progress on its batch"); } + await db.flushPendingWrites(); return cursor; }, });