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
5 changes: 3 additions & 2 deletions .changeset/batch-node-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
83 changes: 82 additions & 1 deletion src/component/nodeCache.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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([]);
Expand Down Expand Up @@ -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,
);
});
});
});
121 changes: 100 additions & 21 deletions src/component/nodeCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<DataModel>;

// 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`.
Expand All @@ -25,7 +42,10 @@ type TableName = TableNamesInDataModel<DataModel>;
export class NodeCachingDatabaseWriter implements DatabaseWriter {
readonly system: DatabaseWriter["system"];
readonly vars: DatabaseWriter["vars"];
private readonly nodes = new Map<Id<"btreeNode">, Doc<"btreeNode"> | null>();
private readonly nodes = new Map<Id<"btreeNode">, CachedNode>();
private pendingDocuments = 0;
private pendingWriteBytes = 0;
private pendingReadBytes = 0;

constructor(private readonly db: DatabaseWriter) {
this.system = db.system;
Expand Down Expand Up @@ -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);
}
Expand All @@ -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<WithoutSystemFields<Doc<"btreeNode">>>,
);
return;
}
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>(
Expand Down Expand Up @@ -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;

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.

I think we still charge for reads when the user deletes

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah, though we directly delete the node from the database, so the usage will have been charged already (and won't be charged again when flushing). Added a comment to clarify

}
this.nodes.set(id as Id<"btreeNode">, { node: null });
}
}

private async getNode(id: Id<"btreeNode">): Promise<Doc<"btreeNode"> | null> {
async flushPendingWrites(): Promise<void> {
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<CachedNode> {
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<WithoutSystemFields<Doc<"btreeNode">>>,
): Promise<void> {
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 });
}
}

Expand Down
55 changes: 54 additions & 1 deletion src/component/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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(
Expand All @@ -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);
});
});
});

Expand Down
Loading
Loading