Skip to content
Draft
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)
8 changes: 8 additions & 0 deletions .changeset/batch-oversized-op.md
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 8 additions & 6 deletions src/component/btree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
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,
);
});
});
});
119 changes: 98 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,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<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
3 changes: 3 additions & 0 deletions src/component/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading
Loading