Repository navigation
Cache B-tree nodes while applying an async batch #306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>>, | ||
| ); | ||
| } | ||
|
|
||
| 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">; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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