diff --git a/.changeset/batch-node-cache.md b/.changeset/batch-node-cache.md new file mode 100644 index 00000000..96d275eb --- /dev/null +++ b/.changeset/batch-node-cache.md @@ -0,0 +1,7 @@ +--- +"@convex-dev/aggregate": patch +--- + +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) diff --git a/src/component/nodeCache.test.ts b/src/component/nodeCache.test.ts new file mode 100644 index 00000000..3d7f7bf8 --- /dev/null +++ b/src/component/nodeCache.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, test } from "vitest"; +import type { DatabaseWriter } from "./_generated/server.js"; +import { NodeCachingDatabaseWriter } from "./nodeCache.js"; +import { initConvexTest } from "./setup.test.js"; + +function countingGets(db: DatabaseWriter) { + const counter = { gets: 0 }; + const counted = new Proxy(db, { + get(target, key, receiver) { + const value = Reflect.get(target, key, receiver); + if (key === "get") { + return (...args: unknown[]) => { + counter.gets++; + return (value as (...a: unknown[]) => unknown).apply(target, args); + }; + } + return typeof value === "function" ? value.bind(target) : value; + }, + }); + return { counted, counter }; +} + +const emptyNode = { + items: [], + subtrees: [], + aggregate: { count: 0, sum: 0 }, +}; + +describe("NodeCachingDatabaseWriter", () => { + test("reads a node from the database once", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const id = await ctx.db.insert("btreeNode", emptyNode); + const { counted, counter } = countingGets(ctx.db); + const db = new NodeCachingDatabaseWriter(counted); + const first = await db.get("btreeNode", id); + const second = await db.get("btreeNode", id); + expect(second).toEqual(first); + expect(counter.gets).toBe(1); + }); + }); + + test("a patch leaves earlier reads of the node unchanged", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const id = await ctx.db.insert("btreeNode", emptyNode); + const db = new NodeCachingDatabaseWriter(ctx.db); + const before = (await db.get("btreeNode", id))!; + const item = { k: 1, v: "a", s: 2 }; + await db.patch("btreeNode", id, { + items: [item], + 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([]); + }); + }); + + test("a delete makes later reads return null", 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.get("btreeNode", id); + await db.delete("btreeNode", id); + expect(await db.get("btreeNode", id)).toBeNull(); + expect(await ctx.db.get("btreeNode", id)).toBeNull(); + }); + }); + + test("refuses to query or replace nodes", async () => { + const t = initConvexTest(); + await t.run(async (ctx) => { + const id = await ctx.db.insert("btreeNode", emptyNode); + const db = new NodeCachingDatabaseWriter(ctx.db); + expect(() => db.query("btreeNode")).toThrow(); + await expect(db.replace("btreeNode", id, emptyNode)).rejects.toThrow(); + }); + }); +}); diff --git a/src/component/nodeCache.ts b/src/component/nodeCache.ts new file mode 100644 index 00000000..6cf1459f --- /dev/null +++ b/src/component/nodeCache.ts @@ -0,0 +1,179 @@ +import type { + NamedTableInfo, + QueryInitializer, + TableNamesInDataModel, + WithOptionalSystemFields, + WithoutSystemFields, +} from "convex/server"; +import type { DatabaseWriter } from "./_generated/server.js"; +import type { DataModel, Doc, Id } from "./_generated/dataModel.js"; + +type TableName = TableNamesInDataModel; + +/** + * 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. + * + * Cached documents are replaced rather than mutated, so callers holding an + * earlier copy of a node keep seeing that snapshot, as with `db.get`. + * + * Every call must name its table, and `btreeNode` can't be queried or + * replaced, since the cache wouldn't see it. + */ +export class NodeCachingDatabaseWriter implements DatabaseWriter { + readonly system: DatabaseWriter["system"]; + readonly vars: DatabaseWriter["vars"]; + private readonly nodes = new Map, Doc<"btreeNode"> | null>(); + + constructor(private readonly db: DatabaseWriter) { + this.system = db.system; + this.vars = db.vars; + } + + normalizeId(table: T, id: string): Id | null { + return this.db.normalizeId(table, id); + } + + query( + table: T, + ): QueryInitializer> { + if (table === "btreeNode") { + throw new Error( + "[aggregate] btreeNode can't be queried through the node cache", + ); + } + return this.db.query(table); + } + + get(table: T, id: Id): Promise | null>; + get(id: Id): Promise; + async get( + table: TableName | Id, + id?: Id, + ): Promise | null> { + if (id === undefined) { + throw missingTable(); + } + if (table === "btreeNode") { + return await this.getNode(id as Id<"btreeNode">); + } + return await this.db.get(table as TableName, id); + } + + async insert( + table: T, + value: WithoutSystemFields>, + ): Promise> { + return await this.db.insert(table, value); + } + + patch( + table: T, + id: Id, + value: Partial>, + ): Promise; + patch(id: Id, value: unknown): Promise; + async patch( + table: TableName | Id, + id: Id | unknown, + value?: unknown, + ): Promise { + if (value === undefined) { + throw missingTable(); + } + 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( + table: T, + id: Id, + value: WithOptionalSystemFields>, + ): Promise; + replace(id: Id, value: unknown): Promise; + async replace( + table: TableName | Id, + id: Id | unknown, + value?: unknown, + ): Promise { + if (value === undefined) { + throw missingTable(); + } + if (table === "btreeNode") { + throw new Error( + "[aggregate] btreeNode can't be replaced through the node cache", + ); + } + await this.db.replace( + table as TableName, + id as Id, + value as WithOptionalSystemFields>, + ); + } + + delete(table: T, id: Id): Promise; + delete(id: Id): Promise; + async delete( + table: TableName | Id, + id?: Id, + ): Promise { + if (id === undefined) { + throw missingTable(); + } + await this.db.delete(table as TableName, id); + if (table === "btreeNode") { + this.nodes.set(id as Id<"btreeNode">, null); + } + } + + private async getNode(id: Id<"btreeNode">): Promise | null> { + const cached = this.nodes.get(id); + if (cached !== undefined) { + return cached; + } + const doc = await this.db.get("btreeNode", id); + this.nodes.set(id, doc); + return doc; + } +} + +function missingTable(): Error { + return new Error("[aggregate] pass the table name to the node cache"); +} + +/** + * Returns a copy of `doc` with `fields` applied the way `db.patch` applies them: + * each field is set, and a field set to `undefined` is removed. `doc` itself + * is left unchanged. + */ +function patched( + doc: Doc<"btreeNode">, + fields: Partial>>, +): Doc<"btreeNode"> { + const updated: Record = { ...doc }; + for (const [key, value] of Object.entries(fields)) { + if (value === undefined) { + delete updated[key]; + } else { + updated[key] = value; + } + } + return updated as Doc<"btreeNode">; +} diff --git a/src/component/worker.ts b/src/component/worker.ts index 4562ff5f..9a6f5fa9 100644 --- a/src/component/worker.ts +++ b/src/component/worker.ts @@ -24,6 +24,7 @@ import { replaceOrInsertHandler, } from "./btree.js"; import type { Doc } from "./_generated/dataModel.js"; +import { NodeCachingDatabaseWriter } from "./nodeCache.js"; export function batchMaxBytes(metrics: TransactionMetrics): number { const { used, remaining } = metrics.bytesRead; @@ -228,12 +229,13 @@ export const processBatchInner = internalMutation({ args: { entries: v.array(vBatchEntry) }, returns: v.int64(), handler: async (ctx, { entries }) => { + const db = new NodeCachingDatabaseWriter(ctx.db); let cursor: bigint | null = null; for (const [entryIndex, entry] of entries.entries()) { let applied = 0; for (const operation of entry.operations) { try { - await applyOperation(ctx, operation); + await applyOperation({ db }, operation); } catch (e) { throw new ConvexError({ code: OPERATION_FAILED,