Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/batch-node-cache.md
Original file line number Diff line number Diff line change
@@ -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)
83 changes: 83 additions & 0 deletions src/component/nodeCache.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
});
179 changes: 179 additions & 0 deletions src/component/nodeCache.ts
Original file line number Diff line number Diff line change
@@ -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<DataModel>;

/**
* 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<Id<"btreeNode">, Doc<"btreeNode"> | null>();

constructor(private readonly db: DatabaseWriter) {
this.system = db.system;
this.vars = db.vars;
}

normalizeId<T extends TableName>(table: T, id: string): Id<T> | null {
return this.db.normalizeId(table, id);
}

query<T extends TableName>(
table: T,
): QueryInitializer<NamedTableInfo<DataModel, T>> {
if (table === "btreeNode") {
throw new Error(
"[aggregate] btreeNode can't be queried through the node cache",
);
}
return this.db.query(table);
}

get<T extends TableName>(table: T, id: Id<T>): Promise<Doc<T> | null>;
get(id: Id<TableName>): Promise<never>;
async get(
table: TableName | Id<TableName>,
id?: Id<TableName>,
): Promise<Doc<TableName> | 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<T extends TableName>(
table: T,
value: WithoutSystemFields<Doc<T>>,
): Promise<Id<T>> {
return await this.db.insert(table, value);
}

patch<T extends TableName>(
table: T,
id: Id<T>,
value: Partial<Doc<T>>,
): Promise<void>;
patch(id: Id<TableName>, value: unknown): Promise<never>;
async patch(
table: TableName | Id<TableName>,
id: Id<TableName> | unknown,
value?: unknown,
): Promise<void> {
if (value === undefined) {
throw missingTable();
}
await this.db.patch(
table as TableName,
id as Id<TableName>,
value as Partial<Doc<TableName>>,
);
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<WithoutSystemFields<Doc<"btreeNode">>>,
),
);
}
}
}

replace<T extends TableName>(
table: T,
id: Id<T>,
value: WithOptionalSystemFields<Doc<T>>,
): Promise<void>;
replace(id: Id<TableName>, value: unknown): Promise<never>;
async replace(
table: TableName | Id<TableName>,
id: Id<TableName> | unknown,
value?: unknown,
): Promise<void> {
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<TableName>,
value as WithOptionalSystemFields<Doc<TableName>>,
);
Comment on lines +124 to +128

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why aren't we updating the cache in this scenario?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah we're skipping all replaces on this table, nm

}

delete<T extends TableName>(table: T, id: Id<T>): Promise<void>;
delete(id: Id<TableName>): Promise<never>;
async delete(
table: TableName | Id<TableName>,
id?: Id<TableName>,
): Promise<void> {
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<Doc<"btreeNode"> | 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<WithoutSystemFields<Doc<"btreeNode">>>,
): Doc<"btreeNode"> {
const updated: Record<string, unknown> = { ...doc };
for (const [key, value] of Object.entries(fields)) {
if (value === undefined) {
delete updated[key];
} else {
updated[key] = value;
}
}
return updated as Doc<"btreeNode">;
}
4 changes: 3 additions & 1 deletion src/component/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
Loading