From 31c3412bbb325938e451a6ac365194846a48ce63 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:31:21 -0600 Subject: [PATCH] perf(db): build tx.query on first read instead of for every transaction (#21148) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Every server module reaches PostgreSQL through one client, `createDb` in `packages/db`. The server has about 1,260 `transaction(` call sites. Run events, runner checkpoints and the run queue use a transaction for each write. > - Drizzle builds one relational query builder for every schema table when it creates a database object. It creates a database object for each transaction and for each savepoint. > - The Paperclip schema has 321 tables. One `BEGIN` therefore allocates about 100 KB and uses about 80 microseconds of CPU before the first statement. One `SAVEPOINT` costs the same again. Five places read the relational API inside a transaction. > - On a hosted instance the server main thread was near one full core, and garbage collection used a quarter of it. A fixed 100 KB for each transaction is garbage that no caller asked for, and it grows with every new table. > - This pull request makes `createDb` build `tx.query` the first time a transaction reads it. > - The benefit is 82% less allocation and 7 times fewer garbage collections for an empty transaction, and 45% less allocation for one native run event. Transaction behavior does not change. ## Linked Issues or Issue Description Related: #21131 (one transaction of two statements for a native run event). That pull request reported this cost as a follow-up. No issue exists for it. **What existing behavior does this improve?** The cost of `db.transaction()` and of a nested `tx.transaction()` (savepoint) on the client that `createDb` returns. **Subsystem affected** Database client (`packages/db`). **Current behavior** `createDb` calls `drizzle(sql, { schema })`. Drizzle's `PgDatabase` constructor then runs this loop for the root client, for every transaction and for every savepoint: ```js for (const [tableName, columns] of Object.entries(this._.schema)) { this.query[tableName] = new RelationalQueryBuilder(...); } ``` A transaction is a `PgTransaction`, which extends `PgDatabase` (`drizzle-orm/pg-core/session.js`). `PostgresJsSession.transaction` and `PostgresJsTransaction.transaction` construct one for each `BEGIN` and each `SAVEPOINT` (`drizzle-orm/postgres-js/session.js`). Measured on `master` at 4e932fd178, Node 26, local PostgreSQL, 3,000 iterations, median of 5 passes: | Scenario | Allocated | CPU | Collections per 1,000 | | --- | --- | --- | --- | | Statement outside a transaction | 11.5 KB | 27 µs | 0.3 | | Empty transaction | 125.8 KB | 131 µs | 5.0 | | Transaction with one statement | 136.6 KB | 153 µs | 5.3 | | Transaction with an empty savepoint | 231.6 KB | 235 µs | 9.7 | | Empty transaction, Drizzle without a schema | 18.5 KB | 53 µs | 0.7 | The allocation profile of an empty transaction attributes 96.8 KB of 115.6 KB sampled to the `PgDatabase` constructor (`pg-core/db.js:17`), reached from `PgTransaction` and `postgres-js/session.js:109`. About 50 KB is the builders and the `query` object. About 46 KB is `Object.entries` of the schema. The relational API is in use, always as a single-table `findFirst({ where[, columns] })`. It has 22 call sites. Five of them run on a transaction: `services/announcements.ts:19` and `:25`, `services/decision-training.ts:331`, and `services/resource-memberships.ts:361` and `:369` (the service is built on a transaction in `updateAgent` and in `services/primary-agent.ts:60`). The other 17 run on the root client. **Proposed behavior** A transaction or savepoint that does not read `tx.query` builds no relational query builder. A transaction that reads `tx.query` gets the same builders as before, bound to that transaction. **Reason and benefit** Less garbage and less CPU on the server main thread for every write path. Hosted statement statistics showed 13.4 native run events per second and 5.3 checkpoint inserts per second. Each is one transaction, so those two paths alone discarded about 2 MB per second. The total transaction rate of the hosted instance was not measured. **Breaking changes** None. No schema change, no API change, and the `Db` type is identical. ## What Changed - `packages/db/src/lazy-transaction-queries.ts` (new): `drizzleWithLazyTransactionQueries(client, schema)`. - It creates the root client with the schema, as before. `db.query` and `db._` do not change. - It creates a second Drizzle client on the same postgres.js client, without the schema, and `db.transaction` opens transactions through it. `BEGIN`, `SAVEPOINT`, commit, rollback and connection reservation are still Drizzle's and the driver's own code. No Drizzle internals are patched. - Each transaction and savepoint gets a `query` accessor. The first read builds one `RelationalQueryBuilder` for each table from the root client's schema description and the transaction's session, then stores the result as a plain property. `tx._.schema`, `tx._.fullSchema` and `tx._.tableNamesMap` keep their values. - `packages/db/src/client.ts`: `createDbClient` calls the new function. The work-signal and response-capture wrappers install on top of it in the same order as before. - `packages/db/scripts/benchmark-transaction-allocation.ts` (new): the benchmark in this description. - `doc/DATABASE.md`: new section "Relational queries inside transactions". ## Verification Benchmark, same script before and after (`createDb` client): ```sh cd packages/db TSX_DISABLE_CACHE=1 node --expose-gc --import tsx scripts/benchmark-transaction-allocation.ts 3000 5 ``` | Scenario | Allocated before | Allocated after | CPU before | CPU after | Collections per 1,000 before | after | | --- | --- | --- | --- | --- | --- | --- | | Statement outside a transaction | 11.5 KB | 11.3 KB | 27 µs | 31 µs | 0.3 | 0.3 | | Empty transaction | 125.8 KB | 22.4 KB | 131 µs | 54 µs | 5.0 | 0.7 | | Transaction with one statement | 136.6 KB | 35.6 KB | 153 µs | 82 µs | 5.3 | 1.0 | | Transaction with an empty savepoint | 231.6 KB | 35.6 KB | 235 µs | 111 µs | 9.7 | 1.3 | | Transaction with a savepoint of one statement | 242.7 KB | 44.8 KB | 331 µs | 217 µs | 10.7 | 2.0 | After the change, no Drizzle frame is in the allocation profile of an empty transaction (19.8 KB sampled). The script also runs Drizzle with the schema and Drizzle without a schema in the same process, so the comparison can be repeated on any later revision. The machine was shared and under load (load average 6 to 35 on 18 CPUs). Allocation and collection counts were stable across four runs. CPU values moved by a factor of two between runs. The CPU columns come from the two runs with the lowest load. One native run event, through the real append path: ```sh TSX_DISABLE_CACHE=1 EVENTS=1500 PASSES=3 pnpm --filter @paperclipai/server exec tsx scripts/benchmark-run-event-append.ts ``` `native-stream`: 220.4 -> 120.9 KB allocated for each event, 12.0 -> 5.3 collection pauses per 1,000 events. `native-burst`: 221.1 -> 121.0 KB, 10.6 -> 5.3 pauses. Statements for each event do not change (4.6). Tests, all on real PostgreSQL (`packages/db/src/lazy-transaction-queries.test.ts`, 15 tests): - Red and green for the mechanism. On `master` these fail, and with the change they pass: - `builds none for a transaction or savepoint that never reads tx.query`: 321 builders for the transaction and 321 for the savepoint on `master`, 0 with the change. - `allocates the same for an empty transaction as a client without the schema`: 101 KB more than a schema-less client on `master`, below the 16 KB limit with the change. It reads V8's allocation counter, not a timer, and it skips on a Node.js without that counter. - Semantics. These pass on `master` and with the change, which shows the behavior is the same: - `commits and returns the callback's value` - `rolls back and rejects with the thrown error` (thrown error, `tx.rollback()`, SQL error) - `keeps the outer transaction usable after a savepoint rolls back` (three levels) - `discards a released savepoint when the outer transaction rolls back` - `applies the isolation level and access mode` - `runs concurrent transactions on separate reserved connections and releases them` (12 transactions on a pool of 3) - `returns the only connection to the pool after a commit, a rollback and a failed savepoint` (pool of 1) - `behaves the same with prepared statements enabled` - Instrumentation. These pass on `master` and with the change: - `registers each transaction and savepoint with the client's work signals`: the transaction and the savepoint have the client's work-signal scope, the registration statement runs on the transaction's own connection, listeners get `intent` at once and `settled` only after the outer commit, and a rollback reconciles. When transactions bypass the work-signal wrapper, this test and five tests in `work-signals.test.ts` fail. - `response capture counts every statement of a transaction, a savepoint and tx.query`: six statements, counted for each operation and table, including two relational reads. - Every `tx.query` pattern in the codebase: - `reads tx.query through the transaction, as the announcement and decision-training services do` - `reads tx.query inside a savepoint and follows its rollback` - `gives tx.query one builder per schema table, the same object on every read` Commands run locally on the final revision: - `pnpm exec vitest run src/lazy-transaction-queries.test.ts src/work-signals.test.ts src/response-capture-postgres.test.ts` in `packages/db` on the final revision: 43 passed. `prepared-queries-postgres.test.ts` passed on the first commit. - Before the rebase onto current `master`, also `response-capture.test.ts`, `response-capture-bundle.test.ts`, `client-options.test.ts`, `client-teardown-registry.test.ts`, `checkpoint-pool.test.ts`, `client-disconnect-replay.test.ts`: 111 passed in 10 files. - On the first commit, server callers of `tx.query` and `db.query`, and hot transaction paths: `announcements-routes`, `decision-training`, `heartbeat-run-event-atomic-append`, `heartbeat-run-event-sequencing`, `primary-agent`, `resource-memberships-routes`, `workspace-preferences`, `sidebar-preferences-routes`, `paperclip-control-plane-port`, `native-runner-checkpoint-authority.integration`, `dispatch-work`, `decision-target-work`, `issue-thread-interactions-service`: all passed. `workspace-preferences` timed out once in its database start hook while eight suites ran in parallel, and passed alone. - `pnpm exec tsc --noEmit` in `packages/db`: passed. A type probe showed that `Db` is the same type as before. - `pnpm check:module-boundaries`: passed. - `pnpm verify` exits 2: `packages/db` is a broad input. CI supplies the full suites. I did not run the full local suite, repo-wide typecheck or build. Not verified: the hosted transaction rate, and the effect on a hosted instance. CI uses Node 24, which has no V8 allocation counter. On CI the allocation test skips itself, and the builder-count test covers the mechanism. The benchmark needs Node.js 25 or later and stops with that message on Node 24. I did not run that error path, because this machine has Node 26 only. ## Risks - Every module uses this client. The mitigation is that the transaction path is still Drizzle's own `transaction()` on the same postgres.js client. Only the schema argument is absent. The semantics tests pass unchanged on `master` and on this branch. - The change relies on Drizzle surface that is not documented API. The lazy `tx.query` calls the `RelationalQueryBuilder` constructor from `drizzle-orm/pg-core/query-builders/query`. That subpath is in Drizzle's export map and the constructor is typed, but `drizzle-orm/pg-core` does not re-export it. The change also writes the three schema fields of `tx._`, which the types mark `readonly`. In `drizzle-orm@1.0.0-beta.22` the same path exports a different class. An upgrade that changes the constructor fails the typecheck and the `tx.query` tests. An upgrade that renames `db._.schema` makes the function return the plain eager client: behavior stays correct, the saving is lost, and the builder-count test fails. The repository owner decides whether this dependency on Drizzle is acceptable. A version that uses only documented API removes the 22 relational reads from the server and creates the client without the schema. - `tx.query` is now an accessor until its first read. Code that reads the property descriptor of `query` sees the difference. No code in the repository does that. - The second client and the builders use Drizzle's default dialect options, as the root client does. If `createDb` ever passes `casing`, `logger` or `cache` to Drizzle, the same option must go to all three. The source comment says so. - A transaction that reads `tx.query` pays the old cost once, on first read. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), in Claude Code, with tool use and local code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 --- doc/DATABASE.md | 20 + .../benchmark-transaction-allocation.ts | 161 ++++++++ packages/db/src/client.ts | 4 +- .../db/src/lazy-transaction-queries.test.ts | 369 ++++++++++++++++++ packages/db/src/lazy-transaction-queries.ts | 74 ++++ 5 files changed, 626 insertions(+), 2 deletions(-) create mode 100644 packages/db/scripts/benchmark-transaction-allocation.ts create mode 100644 packages/db/src/lazy-transaction-queries.test.ts create mode 100644 packages/db/src/lazy-transaction-queries.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 29600277132..0b5a64bffd6 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -2119,6 +2119,26 @@ register before writing, or they can remain unseen until the next startup or another notification. Tests should verify both the producer and its outer transaction boundary. +## Relational queries inside transactions + +Drizzle builds one relational query builder for every schema table when it +creates a database object, and it creates one for each transaction and each +savepoint. With the Paperclip schema that is about 100 KB per transaction. +`createDb` therefore opens transactions through a second Drizzle client on the +same postgres.js client, created without the schema, and builds `tx.query` the +first time a transaction reads it (`packages/db/src/lazy-transaction-queries.ts`). +`db.query`, `tx.query`, and `tx._` keep their contents. `BEGIN`, `SAVEPOINT`, +commit, rollback, and connection reservation remain Drizzle's and the driver's. + +Measure the cost of a transaction and a savepoint with the command below. It +needs Node.js 25 or later, because Node.js 24 has no V8 allocation counter, and +it stops with that message on an older runtime: + +```sh +cd packages/db +TSX_DISABLE_CACHE=1 node --expose-gc --import tsx scripts/benchmark-transaction-allocation.ts +``` + ### Installed skill packages `company_skill_repository_snapshots` retains its identity and company/content-hash diff --git a/packages/db/scripts/benchmark-transaction-allocation.ts b/packages/db/scripts/benchmark-transaction-allocation.ts new file mode 100644 index 00000000000..4b40f38b44e --- /dev/null +++ b/packages/db/scripts/benchmark-transaction-allocation.ts @@ -0,0 +1,161 @@ +// What one transaction or savepoint costs on the Paperclip database client, +// measured against a local PostgreSQL. +// +// cd packages/db +// TSX_DISABLE_CACHE=1 node --expose-gc --import tsx scripts/benchmark-transaction-allocation.ts [iterations] [passes] +// +// Three clients run the same scenarios: `createDb`, Drizzle given the schema +// directly (one relational query builder per table for every transaction, which +// is what `createDb` did before transactions built `tx.query` on first read), +// and Drizzle without a schema (the floor). +// +// Each scenario runs `passes` times for `iterations` iterations, with a forced +// collection before every pass, and reports the median pass. Allocation is +// V8's total_allocated_bytes counter, CPU is process.cpuUsage(), and a +// collection counts only when it starts inside the measured window. The +// allocation profile attributes an empty transaction's bytes to named frames. +// TSX_DISABLE_CACHE keeps tsx from scanning its shared cache while passes run. +// +// Needs Node.js 25 or later: Node.js 24 has no total_allocated_bytes counter, +// and the script stops with that message instead of printing empty numbers. +import inspector from "node:inspector/promises"; +import { cpus, loadavg } from "node:os"; +import { PerformanceObserver, performance } from "node:perf_hooks"; +import v8 from "node:v8"; +import { sql } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; +import { createDb } from "../src/client.js"; +import * as schema from "../src/schema/index.js"; +import { startEmbeddedPostgresTestDatabase } from "../src/test-embedded-postgres.js"; + +const iterations = Number(process.argv[2] ?? 3000); +const passes = Number(process.argv[3] ?? 5); +if (!Number.isInteger(iterations) || iterations < 1 || !Number.isInteger(passes) || passes < 1) { + throw new Error("Usage: benchmark-transaction-allocation.ts [iterations] [passes]"); +} +const collect = (globalThis as { gc?: () => void }).gc; +if (!collect) throw new Error("Run node with --expose-gc"); + +type Sample = { allocatedBytes: number; cpuMicros: number; wallMicros: number; collections: number; collectionMs: number }; +const allocated = () => (v8.getHeapStatistics() as unknown as { total_allocated_bytes: number }).total_allocated_bytes; +if (typeof allocated() !== "number") { + throw new Error(`This benchmark needs Node.js 25 or later; ${process.version} has no v8 total_allocated_bytes counter`); +} +const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!; +const settle = () => new Promise(resolve => setImmediate(resolve)); + +const collectionEntries: { start: number; duration: number }[] = []; +const observer = new PerformanceObserver(list => { + for (const entry of list.getEntries()) collectionEntries.push({ start: entry.startTime, duration: entry.duration }); +}); +observer.observe({ entryTypes: ["gc"] }); + +async function pass(action: () => Promise | unknown): Promise { + collect!(); collect!(); + await settle(); + const startedAt = performance.now(), cpu = process.cpuUsage(), before = allocated(); + for (let index = 0; index < iterations; index += 1) await action(); + const allocatedBytes = allocated() - before, used = process.cpuUsage(cpu), endedAt = performance.now(); + await settle(); await settle(); + const inWindow = collectionEntries.filter(entry => entry.start >= startedAt && entry.start < endedAt); + return { + allocatedBytes: allocatedBytes / iterations, + cpuMicros: (used.user + used.system) / iterations, + wallMicros: (endedAt - startedAt) * 1000 / iterations, + collections: inWindow.length * 1000 / iterations, + collectionMs: inWindow.reduce((sum, entry) => sum + entry.duration, 0) * 1000 / iterations, + }; +} + +async function measure(client: string, scenario: string, action: () => Promise | unknown) { + for (let index = 0; index < 300; index += 1) await action(); + const samples: Sample[] = []; + for (let index = 0; index < passes; index += 1) samples.push(await pass(action)); + const result = { + kind: "scenario", client, scenario, + allocatedBytesPerIteration: Math.round(median(samples.map(sample => sample.allocatedBytes))), + cpuMicrosPerIteration: Number(median(samples.map(sample => sample.cpuMicros)).toFixed(1)), + cpuMicrosMin: Number(Math.min(...samples.map(sample => sample.cpuMicros)).toFixed(1)), + wallMicrosPerIteration: Number(median(samples.map(sample => sample.wallMicros)).toFixed(1)), + collectionsPer1000: Number(median(samples.map(sample => sample.collections)).toFixed(1)), + collectionMsPer1000: Number(median(samples.map(sample => sample.collectionMs)).toFixed(2)), + }; + console.log(JSON.stringify(result)); + return result; +} + +type AnyDb = { + execute(query: unknown): Promise; + transaction(callback: (tx: AnyDb) => Promise, config?: unknown): Promise; +}; + +async function scenarios(client: string, db: AnyDb) { + const statement = sql`select 1`; + await measure(client, "statement outside a transaction", () => db.execute(statement)); + await measure(client, "empty transaction", () => db.transaction(async () => {})); + await measure(client, "transaction with one statement", () => db.transaction(async tx => { await tx.execute(statement); })); + await measure(client, "transaction with an empty savepoint", () => db.transaction(async tx => { await tx.transaction(async () => {}); })); + await measure(client, "transaction with a savepoint of one statement", + () => db.transaction(async tx => { await tx.transaction(async inner => { await inner.execute(statement); }); })); +} + +type Node = { callFrame: { functionName: string; url: string; lineNumber: number }; selfSize: number; children?: Node[] }; + +async function allocationProfile(client: string, db: AnyDb, count: number) { + for (let index = 0; index < 300; index += 1) await db.transaction(async () => {}); + collect!(); collect!(); + const session = new inspector.Session(); + session.connect(); + await session.post("HeapProfiler.enable"); + await session.post("HeapProfiler.startSampling", { + samplingInterval: 256, includeObjectsCollectedByMajorGC: true, includeObjectsCollectedByMinorGC: true, + } as never); + for (let index = 0; index < count; index += 1) await db.transaction(async () => {}); + const { profile } = await session.post("HeapProfiler.stopSampling") as unknown as { profile: { head: Node } }; + session.disconnect(); + const self = new Map(), inclusive = new Map(); + let total = 0; + const label = (node: Node) => { + const file = node.callFrame.url.replace(/^.*node_modules\//, "").replace(/^file:\/\/.*\/packages\//, "packages/"); + return `${node.callFrame.functionName || "(anonymous)"} ${file}:${node.callFrame.lineNumber + 1}`; + }; + const walk = (node: Node, ancestors: string[]): number => { + const name = label(node); + let size = node.selfSize; + for (const child of node.children ?? []) size += walk(child, [...ancestors, name]); + self.set(name, (self.get(name) ?? 0) + node.selfSize); + // Count a frame once per stack so recursion does not double its share. + if (!ancestors.includes(name)) inclusive.set(name, (inclusive.get(name) ?? 0) + size); + total += node.selfSize; + return size; + }; + walk(profile.head, []); + const top = (map: Map, limit: number) => [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit) + .map(([frame, bytes]) => ({ frame, bytesPerTransaction: Math.round(bytes / count), share: Number((bytes / total).toFixed(3)) })); + console.log(JSON.stringify({ kind: "allocation-profile", client, scenario: "empty transaction", transactions: count, + sampledBytesPerTransaction: Math.round(total / count), self: top(self, 6), inclusive: top(inclusive, 10) })); +} + +const database = await startEmbeddedPostgresTestDatabase("paperclip-db-transaction-allocation-"); +// These two pools are not registered with createDb, so database.cleanup() does +// not end them. End them before PostgreSQL stops, also when a scenario throws. +const eagerSql = postgres(database.connectionString, { max: 10, onnotice: () => {} }); +const bareSql = postgres(database.connectionString, { max: 10, onnotice: () => {} }); +try { + const db = createDb(database.connectionString) as unknown as AnyDb & { _: { schema: Record } }; + const eager = drizzle(eagerSql, { schema }) as unknown as AnyDb; + const bare = drizzle(bareSql) as unknown as AnyDb; + console.log(JSON.stringify({ kind: "host", node: process.version, logicalCpus: cpus().length, loadavg: loadavg().map(value => Number(value.toFixed(1))), + iterations, passes, schemaTables: Object.keys(db._.schema).length, + boundary: "three clients on one local PostgreSQL; allocation = V8 total_allocated_bytes; CPU = process user+system; median pass" })); + await scenarios("paperclip createDb", db); + await scenarios("drizzle with the schema", eager); + await scenarios("drizzle without a schema", bare); + await allocationProfile("paperclip createDb", db, Math.min(iterations, 2000)); + await allocationProfile("drizzle with the schema", eager, Math.min(iterations, 2000)); +} finally { + observer.disconnect(); + await Promise.allSettled([eagerSql.end({ timeout: 1 }), bareSql.end({ timeout: 1 })]); + await database.cleanup(); +} diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 6e6df8060c9..aa4f0c9fd06 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -1,11 +1,11 @@ import { createHash } from "node:crypto"; -import { drizzle as drizzlePg } from "drizzle-orm/postgres-js"; import { readFile, readdir } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import postgres from "postgres"; import { installDatabaseWorkSignals } from "./work-signals.js"; import { installDatabaseResponseCapture } from "./response-capture.js"; import { installPreparedQueries } from "./prepared-queries.js"; +import { drizzleWithLazyTransactionQueries } from "./lazy-transaction-queries.js"; import * as schema from "./schema/index.js"; const MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); @@ -392,7 +392,7 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob // postgres.js calls that error "write CONNECTION_CLOSED" too, so the // message cannot establish that replay is safe. Leave retries to callers // that know the complete operation is idempotent. - const db = installDatabaseWorkSignals(drizzlePg(sql, { schema }), owner); + const db = installDatabaseWorkSignals(drizzleWithLazyTransactionQueries(sql, schema), owner); installDatabaseResponseCapture(db, schema); dedicatedDbFactories.set(db, () => createDbClient(url, { ...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock", diff --git a/packages/db/src/lazy-transaction-queries.test.ts b/packages/db/src/lazy-transaction-queries.test.ts new file mode 100644 index 00000000000..2cefdf6c8a6 --- /dev/null +++ b/packages/db/src/lazy-transaction-queries.test.ts @@ -0,0 +1,369 @@ +import v8 from "node:v8"; +import { and, eq, sql, TransactionRollbackError } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/postgres-js"; +import postgres from "postgres"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { createDb, type Db } from "./client.js"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "./response-capture.js"; +import { announcementDismissals, announcementPublications } from "./schema/index.js"; +import { + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./test-embedded-postgres.js"; +import { + databaseWorkPending, databaseWorkScopeKey, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork, +} from "./work-signals.js"; + +type Tx = Parameters[0]>[0]; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; +const allocatedBytes = () => (v8.getHeapStatistics() as { total_allocated_bytes?: number }).total_allocated_bytes; + +/** Relational query builders a database object holds without `query` having been read. */ +function builtQueryBuilders(connection: object): number { + const query = Object.getOwnPropertyDescriptor(connection, "query")?.value as object | undefined; + return query ? Object.keys(query).length : 0; +} + +const publication = (tx: Pick, announcementId: string) => + tx.insert(announcementPublications).values({ announcementId }); +const publicationIds = async (connection: Pick) => + (await connection.select().from(announcementPublications)).map(row => row.announcementId).sort(); +const backendPid = async (connection: Pick) => + (await connection.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`))[0]!.pid; + +describeEmbeddedPostgres("transactions on the Paperclip database client", () => { + let database: Awaited>; + let db: Db; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-db-lazy-transaction-queries-"); + db = createDb(database.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterEach(async () => { + await db.delete(announcementDismissals); + await db.delete(announcementPublications); + }); + afterAll(async () => { await database?.cleanup(); }); + + describe("relational query builders", () => { + it("builds none for a transaction or savepoint that never reads tx.query", async () => { + const schemaTables = Object.keys(db.query).length; + expect(schemaTables).toBeGreaterThan(100); + expect(builtQueryBuilders(db)).toBe(schemaTables); + const built = await db.transaction(async (tx) => { + await publication(tx, "unread"); + const outer = builtQueryBuilders(tx); + const savepoint = await tx.transaction(async (nested) => { + await nested.select().from(announcementPublications); + return builtQueryBuilders(nested); + }); + return { outer, savepoint, outerAfterSavepoint: builtQueryBuilders(tx) }; + }); + expect(built).toEqual({ outer: 0, savepoint: 0, outerAfterSavepoint: 0 }); + }); + + it.skipIf(allocatedBytes() === undefined)("allocates the same for an empty transaction as a client without the schema", async () => { + const bareClient = postgres(database.connectionString, { max: 1, onnotice: () => {} }); + try { + const bare = drizzle(bareClient); + const perTransaction = async (connection: { transaction(callback: () => Promise): Promise }) => { + for (let index = 0; index < 100; index += 1) await connection.transaction(async () => {}); + const before = allocatedBytes()!; + for (let index = 0; index < 300; index += 1) await connection.transaction(async () => {}); + return (allocatedBytes()! - before) / 300; + }; + const withoutSchema = await perTransaction(bare); + const withSchema = await perTransaction(db); + // Eager builders cost about 100 KB per transaction for 321 tables. + expect(withSchema - withoutSchema).toBeLessThan(16 * 1024); + } finally { + await bareClient.end({ timeout: 1 }); + } + }); + + it("gives tx.query one builder per schema table, the same object on every read", async () => { + await db.transaction(async (tx) => { + const query = tx.query; + expect(tx.query).toBe(query); + expect(Object.keys(query)).toEqual(Object.keys(db.query)); + expect(builtQueryBuilders(tx)).toBe(Object.keys(db.query).length); + expect(query.announcementPublications.constructor).toBe(db.query.announcementPublications.constructor); + expect(query.announcementPublications).not.toBe(db.query.announcementPublications); + expect(Object.keys(tx)).toContain("query"); + expect(tx._.fullSchema).toBe(db._.fullSchema); + expect(tx._.schema).toBe(db._.schema); + expect(tx._.tableNamesMap).toBe(db._.tableNamesMap); + await tx.transaction(async (nested) => { + expect(nested.query).not.toBe(query); + expect(Object.keys(nested.query)).toEqual(Object.keys(db.query)); + expect(nested._.fullSchema).toBe(db._.fullSchema); + }); + }); + }); + + it("reads tx.query through the transaction, as the announcement and decision-training services do", async () => { + await db.transaction(async (tx) => { + await publication(tx, "in-transaction"); + await tx.insert(announcementDismissals).values({ userId: "user-1", announcementId: "in-transaction" }); + const known = await tx.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), + }); + expect(known).toEqual({ announcementId: "in-transaction" }); + const dismissal = await tx.query.announcementDismissals.findFirst({ + where: and(eq(announcementDismissals.userId, "user-1"), eq(announcementDismissals.announcementId, "in-transaction")), + }); + expect(dismissal).toMatchObject({ userId: "user-1", announcementId: "in-transaction" }); + expect(dismissal!.dismissedAt).toBeInstanceOf(Date); + expect(await tx.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "missing"), + })).toBeUndefined(); + expect(await tx.query.announcementDismissals.findMany({ columns: { userId: true } })).toEqual([{ userId: "user-1" }]); + // Another connection must not see the uncommitted rows the transaction's own query read. + expect(await db.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), + })).toBeUndefined(); + }); + expect(await db.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "in-transaction"), columns: { announcementId: true }, + })).toEqual({ announcementId: "in-transaction" }); + }); + + it("reads tx.query inside a savepoint and follows its rollback", async () => { + await db.transaction(async (tx) => { + await publication(tx, "outer"); + await expect(tx.transaction(async (nested) => { + await publication(nested, "savepoint"); + expect((await nested.query.announcementPublications.findMany()).map(row => row.announcementId).sort()) + .toEqual(["outer", "savepoint"]); + throw new Error("undo the savepoint"); + })).rejects.toThrow("undo the savepoint"); + expect(await tx.query.announcementPublications.findMany()).toEqual([{ announcementId: "outer" }]); + }); + expect(await db.query.announcementPublications.findMany()).toEqual([{ announcementId: "outer" }]); + }); + }); + + describe("instrumentation of transactions", () => { + const assignedXid = async (connection: Pick) => + (await connection.execute<{ xid: string | null }>(sql`select pg_current_xact_id_if_assigned()::text as xid`))[0]!.xid; + + it("registers each transaction and savepoint with the client's work signals", async () => { + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, "lazy-transaction-queries", event => events.push(event)); + try { + await db.transaction(async (tx) => { + expect(databaseWorkScopeKey(tx)).toBe(databaseWorkScopeKey(db)); + expect(await assignedXid(tx)).toBeNull(); + await tx.transaction(async (nested) => { + expect(databaseWorkScopeKey(nested)).toBe(databaseWorkScopeKey(db)); + await signalDatabaseWork(nested, "lazy-transaction-queries"); + // The registration asked for the transaction ID on this transaction's connection. + expect(await assignedXid(nested)).not.toBeNull(); + await publication(nested, "signalled"); + }); + expect(events).toEqual(["intent"]); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(true); + expect(await tx.query.announcementPublications.findMany()).toEqual([{ announcementId: "signalled" }]); + // A released savepoint and a relational read settle nothing before the outer commit. + expect(events).toEqual(["intent"]); + }); + expect(events).toEqual(["intent", "settled"]); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(false); + + await expect(db.transaction(async (tx) => { + await signalDatabaseWork(tx, "lazy-transaction-queries"); + await publication(tx, "rolled-back"); + throw new Error("rollback"); + })).rejects.toThrow("rollback"); + expect(events).toEqual(["intent", "settled", "intent", "settled"]); + await reconcileDatabaseWork(db, "lazy-transaction-queries"); + expect(databaseWorkPending(db, "lazy-transaction-queries")).toBe(false); + expect(await publicationIds(db)).toEqual(["signalled"]); + await expect(signalDatabaseWork(db, "lazy-transaction-queries")).rejects.toThrow("inside a transaction"); + } finally { unsubscribe(); } + }); + + it("response capture counts every statement of a transaction, a savepoint and tx.query", async () => { + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + const captured = createDb(database.connectionString, { maxConnections: 2 }); + try { + installDatabaseResponseCapture(captured, { announcementPublications, announcementDismissals }, capture); + await captured.transaction(async (tx: Tx) => { + await publication(tx, "captured"); + await tx.select().from(announcementPublications); + await tx.transaction(async (nested: Tx) => { + await nested.update(announcementPublications).set({ announcementId: "captured-renamed" }) + .where(eq(announcementPublications.announcementId, "captured")); + await nested.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "captured-renamed"), + }); + await nested.delete(announcementDismissals); + }); + await tx.query.announcementDismissals.findMany(); + }); + capture.flush(); + expect(events.find(event => event.event === "paperclip.db_response_capture.summary.v2")) + .toMatchObject({ startedQueries: 6, completedQueries: 6, inFlightAtEnd: 0 }); + const calls: Record = {}; + for (const event of events.filter(entry => entry.event === "paperclip.db_response_capture.entry.v2")) { + const key = `${String(event.operation)} ${String(event.table)}`; + calls[key] = (calls[key] ?? 0) + Number(event.calls); + } + expect(calls).toEqual({ + "insert announcement_publications": 1, + "select announcement_publications": 2, + "update announcement_publications": 1, + "delete announcement_dismissals": 1, + "select announcement_dismissals": 1, + }); + } finally { + capture.flush(); + await captured.$client.end({ timeout: 1 }); + } + }); + }); + + describe("transaction semantics", () => { + it("commits and returns the callback's value", async () => { + const result = await db.transaction(async (tx) => { + await publication(tx, "committed"); + const [updated] = await tx.update(announcementPublications).set({ announcementId: "renamed" }) + .where(eq(announcementPublications.announcementId, "committed")).returning(); + await publication(tx, "deleted"); + await tx.delete(announcementPublications).where(eq(announcementPublications.announcementId, "deleted")); + return updated; + }); + expect(result).toEqual({ announcementId: "renamed" }); + expect(await publicationIds(db)).toEqual(["renamed"]); + }); + + it("rolls back and rejects with the thrown error", async () => { + const failure = new Error("abort"); + await expect(db.transaction(async (tx) => { + await publication(tx, "discarded"); + throw failure; + })).rejects.toBe(failure); + await expect(db.transaction(async (tx) => { + await publication(tx, "discarded"); + tx.rollback(); + })).rejects.toBeInstanceOf(TransactionRollbackError); + await expect(db.transaction(async (tx) => { + await publication(tx, "duplicate"); + await publication(tx, "duplicate"); + })).rejects.toMatchObject({ cause: { code: "23505" } }); + expect(await publicationIds(db)).toEqual([]); + }); + + it("keeps the outer transaction usable after a savepoint rolls back", async () => { + await db.transaction(async (tx) => { + await publication(tx, "before"); + await expect(tx.transaction(async (nested) => { + await publication(nested, "undone"); + await publication(nested, "undone"); + })).rejects.toMatchObject({ cause: { code: "23505" } }); + await expect(tx.transaction(async (nested) => { + await publication(nested, "undone"); + nested.rollback(); + })).rejects.toBeInstanceOf(TransactionRollbackError); + expect(await publicationIds(tx)).toEqual(["before"]); + await tx.transaction(async (nested) => { + await publication(nested, "released"); + await nested.transaction(async (inner) => { await publication(inner, "released-inner"); }); + await expect(nested.transaction(async (inner) => { + await publication(inner, "undone-inner"); + throw new Error("inner"); + })).rejects.toThrow("inner"); + }); + await publication(tx, "after"); + }); + expect(await publicationIds(db)).toEqual(["after", "before", "released", "released-inner"]); + }); + + it("discards a released savepoint when the outer transaction rolls back", async () => { + await expect(db.transaction(async (tx) => { + await tx.transaction(async (nested) => { await publication(nested, "released"); }); + expect(await publicationIds(tx)).toEqual(["released"]); + throw new Error("outer"); + })).rejects.toThrow("outer"); + expect(await publicationIds(db)).toEqual([]); + }); + + it("applies the isolation level and access mode", async () => { + const settings = await db.transaction(async (tx) => { + const [isolation] = await tx.execute<{ transaction_isolation: string }>(sql`show transaction_isolation`); + const [readOnly] = await tx.execute<{ transaction_read_only: string }>(sql`show transaction_read_only`); + return { ...isolation, ...readOnly }; + }, { isolationLevel: "serializable", accessMode: "read only" }); + expect(settings).toEqual({ transaction_isolation: "serializable", transaction_read_only: "on" }); + await expect(db.transaction(async (tx) => { await publication(tx, "read-only"); }, { accessMode: "read only" })) + .rejects.toMatchObject({ cause: { code: "25006" } }); + const [isolation] = await db.transaction( + async (tx) => tx.execute<{ transaction_isolation: string }>(sql`show transaction_isolation`)); + expect(isolation).toEqual({ transaction_isolation: "read committed" }); + }); + + it("runs concurrent transactions on separate reserved connections and releases them", async () => { + const pooled = createDb(database.connectionString, { maxConnections: 3 }); + let open = 0, mostOpen = 0; + const pids = new Set(); + const run = (index: number) => pooled.transaction(async (tx: Tx) => { + open += 1; mostOpen = Math.max(mostOpen, open); + try { + const pid = await backendPid(tx); + pids.add(pid); + await publication(tx, `concurrent-${index}`); + await tx.execute(sql`select pg_sleep(0.02)`); + // Uncommitted rows of the other open transactions are invisible here. + expect((await publicationIds(tx)).filter(id => id !== `concurrent-${index}` && Number(id.split("-")[1]) % 2 === 1)).toEqual([]); + expect(await tx.transaction(async (nested: Tx) => backendPid(nested))).toBe(pid); + expect(await backendPid(tx)).toBe(pid); + if (index % 2 === 1) throw new Error(`abort ${index}`); + return index; + } finally { open -= 1; } + }); + const settled = await Promise.allSettled(Array.from({ length: 12 }, (_, index) => run(index))); + expect(settled.map(result => result.status === "fulfilled" ? result.value : (result.reason as Error).message)) + .toEqual(Array.from({ length: 12 }, (_, index) => index % 2 === 1 ? `abort ${index}` : index)); + expect(mostOpen).toBeGreaterThan(1); + expect(mostOpen).toBeLessThanOrEqual(3); + expect(pids.size).toBeLessThanOrEqual(3); + expect(await publicationIds(pooled)).toEqual([0, 10, 2, 4, 6, 8].map(index => `concurrent-${index}`)); + await pooled.$client.end({ timeout: 1 }); + }); + + it("returns the only connection to the pool after a commit, a rollback and a failed savepoint", async () => { + const single = createDb(database.connectionString, { maxConnections: 1 }); + const pid = await backendPid(single); + await single.transaction(async (tx: Tx) => { await publication(tx, "single"); }); + await expect(single.transaction(async (tx: Tx) => { + await expect(tx.transaction(async () => { throw new Error("savepoint"); })).rejects.toThrow("savepoint"); + throw new Error("outer"); + })).rejects.toThrow("outer"); + expect(await single.transaction(async (tx: Tx) => backendPid(tx))).toBe(pid); + expect(await publicationIds(single)).toEqual(["single"]); + await single.$client.end({ timeout: 1 }); + }); + + it("behaves the same with prepared statements enabled", async () => { + const prepared = createDb(database.connectionString, { prepare: true, maxConnections: 2 }); + await prepared.transaction(async (tx: Tx) => { + await publication(tx, "prepared"); + await expect(tx.transaction(async (nested: Tx) => { + await publication(nested, "prepared-undone"); + expect(await nested.query.announcementPublications.findFirst({ + where: eq(announcementPublications.announcementId, "prepared-undone"), + })).toEqual({ announcementId: "prepared-undone" }); + throw new Error("undo"); + })).rejects.toThrow("undo"); + expect(builtQueryBuilders(tx)).toBe(0); + }); + expect(await prepared.query.announcementPublications.findMany()).toEqual([{ announcementId: "prepared" }]); + await prepared.$client.end({ timeout: 1 }); + }); + }); +}); diff --git a/packages/db/src/lazy-transaction-queries.ts b/packages/db/src/lazy-transaction-queries.ts new file mode 100644 index 00000000000..e153ca6452b --- /dev/null +++ b/packages/db/src/lazy-transaction-queries.ts @@ -0,0 +1,74 @@ +import { PgDialect, type PgSession, type PgTable } from "drizzle-orm/pg-core"; +import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query"; +import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; +import type { TableRelationalConfig } from "drizzle-orm"; +import type postgres from "postgres"; + +type Callback = (tx: Transaction) => unknown; +type Transaction = { + _: { schema: unknown; fullSchema: unknown; tableNamesMap: unknown; session: PgSession }; + query: unknown; + transaction(callback: Callback, ...rest: unknown[]): unknown; +}; + +/** + * `drizzle(client, { schema })` whose transactions build `tx.query` on first + * read instead of at `BEGIN`. + * + * Drizzle constructs one relational query builder per schema table for every + * database object it creates, and it creates one for each transaction and each + * savepoint. With the Paperclip schema that is about 100 KB per transaction, + * for an API that almost no transaction reads. + * + * Transactions are therefore opened through a second Drizzle client on the same + * postgres.js client, created without the schema. `BEGIN`, `SAVEPOINT`, commit, + * rollback and connection handling stay Drizzle's and the driver's own. A + * transaction that does read `tx.query` gets the builders Drizzle would have + * built, bound to that transaction's session, and `tx._` still describes the + * schema. + * + * Both clients and the builders' dialect take Drizzle's defaults. A Drizzle + * option added here (`casing`, `logger`, `cache`) must go to all three. + */ +export function drizzleWithLazyTransactionQueries, TClient extends postgres.Sql>( + client: TClient, + schema: TSchema, +): PostgresJsDatabase & { $client: TClient } { + const db = drizzle(client, { schema }); + const tables = db._.schema; + if (!tables) return db; + const { fullSchema, tableNamesMap } = db._; + const transactions = drizzle(client) as unknown as Transaction; + const dialect = new PgDialect(); + const resolved = (value: unknown): PropertyDescriptor => ({ value, writable: true, enumerable: true, configurable: true }); + const lazyQuery: PropertyDescriptor = { + enumerable: true, + configurable: true, + get(this: Transaction) { + const query: Record = {}; + for (const [name, table] of Object.entries(tables as Record)) { + query[name] = new RelationalQueryBuilder( + fullSchema, tables, tableNamesMap, fullSchema[name] as PgTable, table, dialect, this._.session, + ); + } + Object.defineProperty(this, "query", resolved(query)); + return query; + }, + set(this: Transaction, value: unknown) { + Object.defineProperty(this, "query", resolved(value)); + }, + }; + const within = (callback: Callback): Callback => (tx) => { + tx._.schema = tables; + tx._.fullSchema = fullSchema; + tx._.tableNamesMap = tableNamesMap; + Object.defineProperty(tx, "query", lazyQuery); + const savepoint = tx.transaction; + tx.transaction = function (this: Transaction, nested, ...rest) { + return Reflect.apply(savepoint, this, [within(nested), ...rest]); + }; + return callback(tx); + }; + (db as unknown as Transaction).transaction = (callback, ...rest) => transactions.transaction(within(callback), ...rest); + return db; +}