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/.changeset/batch-oversized-op.md b/.changeset/batch-oversized-op.md new file mode 100644 index 00000000..b19ab2d3 --- /dev/null +++ b/.changeset/batch-oversized-op.md @@ -0,0 +1,8 @@ +--- +"@convex-dev/aggregate": patch +--- + +Keep async updates draining when a single operation reads more than the batch +worker's reserve, such as a split of a large B-tree node, instead of rolling the +batch back and retrying forever. An operation too big for a batch of its own is +dead-lettered. (#311) diff --git a/src/component/btree.ts b/src/component/btree.ts index d7fd9d32..a62d4199 100644 --- a/src/component/btree.ts +++ b/src/component/btree.ts @@ -888,12 +888,14 @@ function nodeCounts(node: Doc<"btreeNode">): Aggregate[] { } async function subtreeCounts(db: DatabaseReader, node: Doc<"btreeNode">) { - return await Promise.all( - node.subtrees.map(async (subtree) => { - const s = (await db.get("btreeNode", subtree))!; - return nodeAggregate(db, s); - }), - ); + // One at a time: reads in flight when a limit trips all count, so parallel + // reads could overshoot the worker's reserve by many nodes. + const counts: Aggregate[] = []; + for (const subtree of node.subtrees) { + const s = (await db.get("btreeNode", subtree))!; + counts.push(await nodeAggregate(db, s)); + } + return counts; } async function nodeAggregate( 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..fef40665 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,80 @@ 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) { + 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/schema.ts b/src/component/schema.ts index a9f980a2..f30b2aaf 100644 --- a/src/component/schema.ts +++ b/src/component/schema.ts @@ -91,6 +91,9 @@ export default defineSchema({ pendingOperations: defineTable({ commitTs: v.commitTs(), operations: v.array(vOperation), + // A cycle ran out of room on the operation at this index, so the next one + // stops before it unless it's the cycle's first operation. + stopBefore: v.optional(v.number()), }).index("by_commitTs", ["commitTs"]), deadLetterOperations: defineTable({ commitTs: v.int64(), diff --git a/src/component/worker.test.ts b/src/component/worker.test.ts index 73f49f6d..842e734f 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) => { @@ -880,6 +902,47 @@ describe("transaction limits", () => { }); }); + test("operations that each read more than the reserve still drain", async () => { + // With 100 KB values in a tree of 4-item nodes, an insert reads several + // MiB, more when it splits an internal node, so the last operation a + // cycle starts can overflow the limit or eat the room to finish. + const t = initConvexTest({ transactionLimits: true }); + await t.run(async (ctx) => { + await getOrCreateTree(ctx.db, {}, 4, true); + }); + const value = "x".repeat(100_000); + for (let key = 0; key < 40; key++) { + await enqueueRows(t, [{ type: "insert", key, value }]); + } + await drainManually(t); + await t.run(async (ctx) => { + expect(await ctx.db.query("pendingOperations").first()).toBeNull(); + expect(await ctx.db.query("deadLetterOperations").first()).toBeNull(); + expect((await aggregateBetweenHandler(ctx, {})).count).toEqual(40); + }); + }); + + test("an operation too big for a cycle of its own is dead-lettered", async () => { + // A 2.2 MiB budget leaves a cycle half of it. The first 400 KB insert + // fits; the second reads the first's node and rereads it to write it back. + const t = initConvexTest({ + transactionLimits: { bytesRead: 2.2 * 1024 * 1024 }, + }); + await t.run(async (ctx) => { + await getOrCreateTree(ctx.db, {}, 4, false); + }); + const value = "x".repeat(400_000); + await enqueueRows(t, [{ type: "insert", key: 1, value }]); + const tooBig = await enqueueRows(t, [{ type: "insert", key: 2, value }]); + await drainManually(t); + await t.run(async (ctx) => { + expect(await ctx.db.query("pendingOperations").first()).toBeNull(); + const dead = await ctx.db.query("deadLetterOperations").collect(); + expect(dead.map((d) => d.commitTs)).toEqual([tooBig]); + expect((await aggregateBetweenHandler(ctx, {})).count).toEqual(1); + }); + }); + describe("operation headroom", () => { const TRANSACTION_LIMITS = { bytesRead: 16 * 1024 * 1024, @@ -906,8 +969,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 +985,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..a7c454a2 100644 --- a/src/component/worker.ts +++ b/src/component/worker.ts @@ -124,6 +124,7 @@ const vBatchEntry = v.object({ id: v.id("pendingOperations"), commitTs: v.int64(), operations: v.array(vOperation), + stopBefore: v.optional(v.number()), }); type BatchEntry = Infer; @@ -164,6 +165,7 @@ export const getBatch = internalQuery({ id: row._id, commitTs: row.commitTs, operations: row.operations, + stopBefore: row.stopBefore, }); bytes += rowBytes; operations += row.operations.length; @@ -203,16 +205,34 @@ 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], ); } const OPERATION_FAILED = "OPERATION_FAILED"; +const OUT_OF_ROOM = "OUT_OF_ROOM"; type OperationFailure = { + code: typeof OPERATION_FAILED | typeof OUT_OF_ROOM; entryIndex: number; operationIndex: number; error: string; @@ -222,7 +242,9 @@ function operationFailure(e: unknown): OperationFailure | null { if (!(e instanceof ConvexError)) { return null; } - return e.data?.code === OPERATION_FAILED ? e.data : null; + return e.data?.code === OPERATION_FAILED || e.data?.code === OUT_OF_ROOM + ? e.data + : null; } export const processBatchInner = internalMutation({ @@ -230,36 +252,54 @@ 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; - for (const operation of entry.operations) { - try { + // A failure anywhere in the cycle is pinned on the latest operation: it + // either threw or used up the room to finish. + let latest = { entryIndex: 0, operationIndex: 0 }; + try { + for (const [entryIndex, entry] of entries.entries()) { + let applied = 0; + for (const operation of entry.operations) { + if (applied === entry.stopBefore && (entryIndex > 0 || applied > 0)) { + break; + } + latest = { entryIndex, operationIndex: applied }; await applyOperation({ db }, operation); - } catch (e) { - throw new ConvexError({ - code: OPERATION_FAILED, - entryIndex, - operationIndex: applied, - error: String(e), + applied++; + if (!(await hasHeadroom())) { + break; + } + } + cursor = entry.commitTs; + if (applied < entry.operations.length) { + await ctx.db.patch("pendingOperations", entry.id, { + operations: entry.operations.slice(applied), + stopBefore: undefined, }); + break; } - applied++; - if (!hasHeadroomToFinish(await ctx.meta.getTransactionMetrics())) { + await ctx.db.delete("pendingOperations", entry.id); + if (!(await hasHeadroom())) { break; } } - cursor = entry.commitTs; - if (applied < entry.operations.length) { - await ctx.db.patch("pendingOperations", entry.id, { - operations: entry.operations.slice(applied), - }); - break; - } - await ctx.db.delete("pendingOperations", entry.id); - if (!hasHeadroomToFinish(await ctx.meta.getTransactionMetrics())) { - break; - } + await db.flushPendingWrites(); + } catch (e) { + // Out of room after other operations ran, the latest one might fit in a + // cycle of its own; as the first, it never will. + const metrics = await ctx.meta.getTransactionMetrics(); + const overLimit = Object.values(metrics).some((m) => m.remaining < 0); + const first = latest.entryIndex === 0 && latest.operationIndex === 0; + throw new ConvexError({ + code: overLimit && !first ? OUT_OF_ROOM : OPERATION_FAILED, + ...latest, + error: String(e), + }); } if (cursor === null) { throw new Error("[aggregate] a cycle made no progress on its batch"); @@ -278,11 +318,26 @@ export const processBatch = internalMutation({ if (entries.length === 0) { throw new Error("[aggregate] a cycle got an empty batch"); } + const metrics = await ctx.meta.getTransactionMetrics(); try { - // Apply operations in a subtransaction so that we can rollback the changes if an operation fails. - const cursor = await ctx.runMutation(internal.worker.processBatchInner, { - entries, - }); + // Apply operations in a subtransaction so that we can rollback the + // changes if an operation fails. Its tighter limits keep the reserve (or + // half of a smaller budget) free for recording a failure here. + const cursor = await ctx.runMutation( + internal.worker.processBatchInner, + { entries }, + { + transactionLimits: Object.fromEntries( + BATCH_LIMITS.map((limit) => [ + limit, + Math.max( + metrics[limit].remaining - FINISH_RESERVE[limit], + metrics[limit].remaining / 2, + ), + ]), + ), + }, + ); return { cursor }; } catch (e) { const failure = operationFailure(e); @@ -290,6 +345,12 @@ export const processBatch = internalMutation({ throw e; } const entry = entries[failure.entryIndex]; + if (failure.code === OUT_OF_ROOM) { + await ctx.db.patch("pendingOperations", entry.id, { + stopBefore: failure.operationIndex, + }); + return; + } const operation = entry.operations[failure.operationIndex]; console.error( `[aggregate] dead-lettering a ${operation.type} operation from commitTs ${entry.commitTs}: ${failure.error}`,