From 7bf7e8bf8938811d5044b91450b0f1594326092f Mon Sep 17 00:00:00 2001 From: zetazzz Date: Mon, 17 Aug 2026 15:16:29 +0800 Subject: [PATCH 1/2] feat(pg): sanitize reused PostgreSQL checkouts --- pnpm-lock.yaml | 3 + postgres/pg-cache/README.md | 6 + .../pg-cache/src/__tests__/driver.test.ts | 2 + .../pg-cache/src/__tests__/sanitizer.test.ts | 129 ++++++++++++++++++ postgres/pg-cache/src/pg.ts | 3 +- postgres/pg-cache/src/sanitizer.ts | 79 +++++++++++ postgres/pg-query-context/package.json | 1 + .../__tests__/postgres.integration.test.ts | 124 +++++++++++++++++ 8 files changed, 346 insertions(+), 1 deletion(-) create mode 100644 postgres/pg-cache/src/__tests__/sanitizer.test.ts create mode 100644 postgres/pg-cache/src/sanitizer.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c624189e66..40e3cef7e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3564,6 +3564,9 @@ importers: makage: specifier: ^0.8.0 version: 0.8.0 + pg-cache: + specifier: workspace:^ + version: link:../pg-cache/dist pgsql-test: specifier: workspace:^ version: link:../pgsql-test/dist diff --git a/postgres/pg-cache/README.md b/postgres/pg-cache/README.md index 8888375971..8fac82be64 100644 --- a/postgres/pg-cache/README.md +++ b/postgres/pg-cache/README.md @@ -23,6 +23,7 @@ npm install pg-cache ## Features - LRU cache for PostgreSQL connection pools +- Checkout sanitation for reused node-postgres clients - Automatic pool cleanup and disposal - Extensible cleanup callback system - Service cache for general use @@ -126,6 +127,11 @@ The main PostgreSQL pool cache instance. ### getPgPool(config: Partial): Pool Get or create a cached PostgreSQL pool using the provided configuration. +Clients from the default node-postgres factory run `DISCARD ALL` before every +checkout, and stale client-side prepared-statement bookkeeping is cleared to +match the server. If sanitation fails, the client is destroyed and the checkout +fails. Alternate registered pool factories retain ownership of backend-specific +checkout sanitation. ### svcCache diff --git a/postgres/pg-cache/src/__tests__/driver.test.ts b/postgres/pg-cache/src/__tests__/driver.test.ts index dd155d538f..105e3a669a 100644 --- a/postgres/pg-cache/src/__tests__/driver.test.ts +++ b/postgres/pg-cache/src/__tests__/driver.test.ts @@ -47,6 +47,7 @@ describe('pg-cache pool-factory seam', () => { it('getPgPool builds via the registered factory (no real pg connection)', () => { const cfg = freshConfig(); const mock = createMockPool(); + const alternateConnect = mock.connect; const factory = jest.fn(() => mock); registerPgPoolFactory(factory); @@ -54,6 +55,7 @@ describe('pg-cache pool-factory seam', () => { expect(factory).toHaveBeenCalledTimes(1); expect(pool).toBe(mock); + expect(pool.connect).toBe(alternateConnect); pgCache.delete(cfg.database); }); diff --git a/postgres/pg-cache/src/__tests__/sanitizer.test.ts b/postgres/pg-cache/src/__tests__/sanitizer.test.ts new file mode 100644 index 0000000000..0c38c47206 --- /dev/null +++ b/postgres/pg-cache/src/__tests__/sanitizer.test.ts @@ -0,0 +1,129 @@ +import type { Pool, PoolClient } from 'pg'; + +import { + installCheckoutSanitizer, + sanitizePgClient, +} from '../sanitizer'; + +type PreparedConnection = { + parsedStatements: Record; + _graphilePreparedStatementCache?: { dispose: jest.Mock }; +}; + +const createClient = ( + connection: PreparedConnection, + query = jest.fn().mockResolvedValue({ rows: [] }) +): PoolClient => + ({ + connection, + query, + release: jest.fn(), + }) as unknown as PoolClient; + +const createPool = (connect: jest.Mock): Pool => + ({ + connect, + }) as unknown as Pool; + +describe('PostgreSQL checkout sanitation', () => { + it('discards session state and clears client-side prepared-statement bookkeeping', async () => { + const graphileCache = { dispose: jest.fn() }; + const connection: PreparedConnection = { + parsedStatements: { + tenantLookup: 'select 1', + tenantMutation: 'select 2', + }, + _graphilePreparedStatementCache: graphileCache, + }; + const client = createClient(connection); + + await expect(sanitizePgClient(client)).resolves.toBe(client); + + expect(client.query).toHaveBeenCalledWith('DISCARD ALL'); + expect(connection.parsedStatements).toEqual({}); + expect(connection).not.toHaveProperty('_graphilePreparedStatementCache'); + expect(graphileCache.dispose).not.toHaveBeenCalled(); + expect(client.release).not.toHaveBeenCalled(); + }); + + it('destroys a client and preserves the original sanitation error', async () => { + const error = new Error('DISCARD ALL failed'); + const connection: PreparedConnection = { + parsedStatements: { tenantLookup: 'select 1' }, + }; + const client = createClient( + connection, + jest.fn().mockRejectedValue(error) + ); + + await expect(sanitizePgClient(client)).rejects.toBe(error); + + expect(client.release).toHaveBeenCalledWith(true); + expect(connection.parsedStatements).toEqual({ + tenantLookup: 'select 1', + }); + }); + + it('sanitizes every promise-based checkout and installs only once', async () => { + const connection: PreparedConnection = { parsedStatements: {} }; + const client = createClient(connection); + const connect = jest.fn().mockResolvedValue(client); + const pool = createPool(connect); + + expect(installCheckoutSanitizer(pool)).toBe(pool); + expect(installCheckoutSanitizer(pool)).toBe(pool); + + await expect(pool.connect()).resolves.toBe(client); + await expect(pool.connect()).resolves.toBe(client); + + expect(connect).toHaveBeenCalledTimes(2); + expect(client.query).toHaveBeenNthCalledWith(1, 'DISCARD ALL'); + expect(client.query).toHaveBeenNthCalledWith(2, 'DISCARD ALL'); + }); + + it('preserves node-postgres callback checkout semantics', async () => { + const connection: PreparedConnection = { parsedStatements: {} }; + const client = createClient(connection); + const pool = createPool(jest.fn().mockResolvedValue(client)); + installCheckoutSanitizer(pool); + + await new Promise((resolve, reject) => { + pool.connect((error, checkedOutClient, done) => { + try { + expect(error).toBeUndefined(); + expect(checkedOutClient).toBe(client); + expect(done).toEqual(expect.any(Function)); + done(); + expect(client.release).toHaveBeenCalledWith(); + resolve(); + } catch (assertionError) { + reject(assertionError); + } + }); + }); + }); + + it('reports callback checkout failures only after destroying the client', async () => { + const error = new Error('cannot sanitize client'); + const connection: PreparedConnection = { parsedStatements: {} }; + const client = createClient( + connection, + jest.fn().mockRejectedValue(error) + ); + const pool = createPool(jest.fn().mockResolvedValue(client)); + installCheckoutSanitizer(pool); + + await new Promise((resolve, reject) => { + pool.connect((checkoutError, checkedOutClient) => { + try { + expect(checkoutError).toBe(error); + expect(checkedOutClient).toBeUndefined(); + expect(client.release).toHaveBeenCalledWith(true); + resolve(); + } catch (assertionError) { + reject(assertionError); + } + }); + }); + }); +}); diff --git a/postgres/pg-cache/src/pg.ts b/postgres/pg-cache/src/pg.ts index 08920e924d..920a900ddd 100644 --- a/postgres/pg-cache/src/pg.ts +++ b/postgres/pg-cache/src/pg.ts @@ -5,6 +5,7 @@ import { getPgEnvOptions, PgConfig, PgPoolConfig } from 'pg-env'; import { getActivePgPoolFactory, PgPoolFactory } from './driver'; import { pgCache } from './lru'; +import { installCheckoutSanitizer } from './sanitizer'; const log = new Logger('pg-cache'); @@ -97,7 +98,7 @@ export const defaultPgPoolFactory: PgPoolFactory = (pgConfig): pg.Pool => { } }); - return pgPool; + return installCheckoutSanitizer(pgPool); }; export const getPgPool = (pgConfig: Partial & { pool?: PgPoolConfig }): pg.Pool => { diff --git a/postgres/pg-cache/src/sanitizer.ts b/postgres/pg-cache/src/sanitizer.ts new file mode 100644 index 0000000000..379763e3e9 --- /dev/null +++ b/postgres/pg-cache/src/sanitizer.ts @@ -0,0 +1,79 @@ +import type pg from 'pg'; + +type PgConnectionWithPreparedState = { + parsedStatements?: Record; + _graphilePreparedStatementCache?: unknown; +}; + +type PgClientWithPreparedState = pg.PoolClient & { + connection?: PgConnectionWithPreparedState; +}; + +const checkoutSanitizedPools = new WeakSet(); + +/** + * Forget prepared statements that PostgreSQL removed during `DISCARD ALL`. + * + * Graphile's cache is deliberately deleted rather than disposed: its disposer + * issues asynchronous `DEALLOCATE` queries, which would duplicate `DISCARD ALL` + * and could race with the next owner of the checked-out client. + */ +export function clearPreparedStatementBookkeeping(client: pg.PoolClient): void { + const connection = (client as PgClientWithPreparedState).connection; + if (!connection) return; + + if (connection.parsedStatements) { + for (const statementName of Object.keys(connection.parsedStatements)) { + delete connection.parsedStatements[statementName]; + } + } + + delete connection._graphilePreparedStatementCache; +} + +/** + * Restore a checked-out PostgreSQL client to server defaults before reuse. + * A client that cannot be sanitized is destroyed instead of being returned to + * application code with unknown session state. + */ +export async function sanitizePgClient(client: pg.PoolClient): Promise { + try { + await client.query('DISCARD ALL'); + clearPreparedStatementBookkeeping(client); + return client; + } catch (error) { + client.release(true); + throw error; + } +} + +/** + * Sanitize every client obtained from a node-postgres pool. `pool.query()` also + * goes through `connect()`, so both checkout APIs share the same boundary. + */ +export function installCheckoutSanitizer(pool: pg.Pool): pg.Pool { + if (checkoutSanitizedPools.has(pool)) return pool; + + const connect = pool.connect.bind(pool); + const sanitizedConnect = async (): Promise => { + const client = await connect(); + return sanitizePgClient(client); + }; + + pool.connect = ((callback?: ( + err: Error | undefined, + client: pg.PoolClient | undefined, + done: (release?: boolean | Error) => void + ) => void): Promise | void => { + const pendingClient = sanitizedConnect(); + if (!callback) return pendingClient; + + pendingClient.then( + (client) => callback(undefined, client, client.release.bind(client)), + (error: Error) => callback(error, undefined, () => undefined) + ); + }) as typeof pool.connect; + + checkoutSanitizedPools.add(pool); + return pool; +} diff --git a/postgres/pg-query-context/package.json b/postgres/pg-query-context/package.json index aede3b8bee..b226773d08 100644 --- a/postgres/pg-query-context/package.json +++ b/postgres/pg-query-context/package.json @@ -34,6 +34,7 @@ "devDependencies": { "@types/pg": "^8.20.4", "makage": "^0.8.0", + "pg-cache": "workspace:^", "pgsql-test": "workspace:^" }, "keywords": [ diff --git a/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts b/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts index 1b2e935aef..3de42a8413 100644 --- a/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts +++ b/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts @@ -1,4 +1,5 @@ import { Pool, type PoolClient } from 'pg'; +import { defaultPgPoolFactory } from 'pg-cache'; import { getConnections } from 'pgsql-test'; import pgQueryContext, { withPgClient } from '../index'; @@ -11,6 +12,23 @@ interface SessionState { user_id: string; } +interface CheckoutState { + application_name: string; + backend_pid: number; + default_transaction_read_only: string; + search_path: string; + row_security: string; +} + +const CHECKOUT_STATE_QUERY = ` + SELECT + current_setting('application_name') AS application_name, + pg_backend_pid() AS backend_pid, + current_setting('default_transaction_read_only') AS default_transaction_read_only, + current_setting('search_path') AS search_path, + current_setting('row_security') AS row_security +`; + async function readSessionState(client: PoolClient): Promise { const result = await client.query(` SELECT @@ -23,17 +41,28 @@ async function readSessionState(client: PoolClient): Promise { return result.rows[0]; } +async function readCheckoutState(client: PoolClient): Promise { + const result = await client.query(CHECKOUT_STATE_QUERY); + return result.rows[0]; +} + describe('pg-query-context transaction-local integration', () => { let db: Awaited>['db']; let teardown: Awaited>['teardown']; let singleClientPool: Pool; + let sanitizedPool: Pool; beforeAll(async () => { ({ db, teardown } = await getConnections({}, [])); singleClientPool = new Pool({ ...db.config, max: 1 }); + sanitizedPool = defaultPgPoolFactory({ + ...db.config, + pool: { max: 1 }, + }) as Pool; }); afterAll(async () => { + if (sanitizedPool) await sanitizedPool.end(); if (singleClientPool) await singleClientPool.end(); if (teardown) await teardown(); }); @@ -198,4 +227,99 @@ describe('pg-query-context transaction-local integration', () => { afterRollbackClient.release(); } }); + + it('sanitizes a reused checkout before applying the complete request context', async () => { + const firstClient = await sanitizedPool.connect(); + let baseline: CheckoutState; + try { + baseline = await readCheckoutState(firstClient); + await firstClient.query("SET application_name TO 'f10-tenant-poison'"); + await firstClient.query('SET default_transaction_read_only TO on'); + await firstClient.query('SET search_path TO pg_catalog'); + await firstClient.query('SET row_security TO off'); + await firstClient.query({ + name: 'f10-checkout-canary', + text: 'SELECT 1 AS value', + }); + } finally { + firstClient.release(); + } + + const insideContext = await withPgClient( + sanitizedPool, + { + role: 'none', + transaction_read_only: 'on', + search_path: 'pg_catalog', + row_security: 'on', + 'jwt.claims.user_id': 'f10-request-user', + }, + async (client) => { + const state = await readSessionState(client); + const statement = await client.query<{ value: number }>({ + name: 'f10-checkout-canary', + text: 'SELECT 2 AS value', + }); + const checkout = await readCheckoutState(client); + return { checkout, state, value: statement.rows[0].value }; + } + ); + + expect(insideContext.checkout.backend_pid).toBe(baseline.backend_pid); + expect(insideContext.checkout.application_name).toBe( + baseline.application_name + ); + expect(insideContext.state).toEqual({ + role: 'none', + transaction_read_only: 'on', + search_path: 'pg_catalog', + row_security: 'on', + user_id: 'f10-request-user', + }); + expect(insideContext.value).toBe(2); + + const afterRequest = await sanitizedPool.connect(); + try { + await expect(readCheckoutState(afterRequest)).resolves.toEqual(baseline); + } finally { + afterRequest.release(); + } + }); + + it('sanitizes direct pool.query checkouts through the same boundary', async () => { + const baseline = await sanitizedPool.query( + CHECKOUT_STATE_QUERY + ); + + await sanitizedPool.query("SET application_name TO 'f10-pool-query-poison'"); + + const restored = await sanitizedPool.query( + CHECKOUT_STATE_QUERY + ); + + expect(restored.rows[0]).toEqual(baseline.rows[0]); + }); + + it('destroys a checkout whose open transaction prevents sanitation', async () => { + const dirtyClient = await sanitizedPool.connect(); + const dirtyState = await readCheckoutState(dirtyClient); + await dirtyClient.query('BEGIN'); + await dirtyClient.query("SET application_name TO 'f10-open-transaction'"); + dirtyClient.release(); + + await expect(sanitizedPool.connect()).rejects.toMatchObject({ + code: '25001', + }); + + const replacementClient = await sanitizedPool.connect(); + try { + const replacementState = await readCheckoutState(replacementClient); + expect(replacementState.backend_pid).not.toBe(dirtyState.backend_pid); + expect(replacementState.application_name).not.toBe( + 'f10-open-transaction' + ); + } finally { + replacementClient.release(); + } + }); }); From aa8ee794c01da4e3f4cf93d4967ea8ee0f0f4be2 Mon Sep 17 00:00:00 2001 From: zetazzz Date: Wed, 9 Sep 2026 04:27:32 +0000 Subject: [PATCH 2/2] test(pg): measure checkout sanitation cost with owned fixtures --- postgres/pg-cache/README.md | 4 + .../pg-query-context/benchmarks/README.md | 25 ++ .../benchmarks/checkout-sanitation.cjs | 78 +++++++ .../checkout-sanitation.pg18-local.json | 213 ++++++++++++++++++ .../__tests__/postgres.integration.test.ts | 13 +- 5 files changed, 327 insertions(+), 6 deletions(-) create mode 100644 postgres/pg-query-context/benchmarks/README.md create mode 100644 postgres/pg-query-context/benchmarks/checkout-sanitation.cjs create mode 100644 postgres/pg-query-context/benchmarks/checkout-sanitation.pg18-local.json diff --git a/postgres/pg-cache/README.md b/postgres/pg-cache/README.md index 8fac82be64..8df67bc703 100644 --- a/postgres/pg-cache/README.md +++ b/postgres/pg-cache/README.md @@ -144,3 +144,7 @@ Gracefully close all cached pools and wait for disposal. ## Integration with Other Packages This package is designed to be extended. For example, `graphile-cache` uses the cleanup callback system to automatically clean up PostGraphile instances when their associated pools are disposed. + +### Checkout sanitation performance + +The default sanitizer adds a database round trip and invalidates prepared statements on every checkout. See the [reproducible benchmark and measured tradeoff](../pg-query-context/benchmarks/README.md) before setting a production throughput budget. The benchmark does not weaken the default sanitation contract. diff --git a/postgres/pg-query-context/benchmarks/README.md b/postgres/pg-query-context/benchmarks/README.md new file mode 100644 index 0000000000..0f0cf0d50a --- /dev/null +++ b/postgres/pg-query-context/benchmarks/README.md @@ -0,0 +1,25 @@ +# Checkout sanitation cost + +Run after building `pg-cache`, `pg-query-context`, and the `pgsql-test` dependencies, against an isolated PostgreSQL instance with the pgpm test users bootstrapped: + +```sh +node postgres/pg-query-context/benchmarks/checkout-sanitation.cjs /tmp/checkout-sanitation.json 1000 +``` + +Connection options come through the existing `pgsql-test` environment provider. The harness creates and drops its own database. The baseline uses a harness-owned unsanitized pool; the comparison uses the actual default `pg-cache` factory. Both use the application login, one client, and concurrency one. Each arm warms up for 50 operations; three rounds alternate arm order, with 1,000 measured operations per arm/workload/round. Results contain latency percentiles and throughput. + +## Local result, 2026-09-09 + +PostgreSQL 18.6, Node 24.20.0, localhost TCP. Values below are the median of each metric across the three rounds; the raw result is `checkout-sanitation.pg18-local.json`. + +| Workload | p50 ms, baseline → sanitized | p95 ms, baseline → sanitized | Operations/s, baseline → sanitized | +| --- | --- | --- | --- | +| Checkout and release | 0.013 → 0.322 | 0.017 → 1.947 | 33,818 → 1,519 | +| Named prepared SELECT | 0.383 → 0.825 | 1.981 → 3.378 | 1,749 → 632 | +| Request-context transaction + named SELECT | 1.884 → 2.143 | 5.845 → 5.293 | 401 → 371 | + +This shared host had unrelated CPU load. These measurements establish local cost, not production percentiles or a performance gate. In particular, the lower transaction p95 in the sanitized arm is noise, not evidence that sanitation improves tail latency. Repeat on representative deployment hardware, network latency, pool sizes, and query mixes before adopting a throughput budget. + +`DISCARD ALL` adds a server round trip to every checkout and removes prepared statements: the final baseline checkout retained one named prepared statement, while the sanitized checkout retained none. The prepared-query arm lost about 64% throughput locally; the complete transaction arm lost about 7%. A cheap query-heavy workload therefore needs particular scrutiny. + +The PR retains the fail-closed default while making this cost reviewable. A future cheaper reset must prove equivalent removal of roles/GUCs, temporary state, LISTEN state, advisory locks, and prepared-statement bookkeeping before replacing it. Merely using `RESET ALL`, or skipping cleanup based on assumptions about callers, does not provide that equivalence. This benchmark does not justify such a replacement or an opt-out. diff --git a/postgres/pg-query-context/benchmarks/checkout-sanitation.cjs b/postgres/pg-query-context/benchmarks/checkout-sanitation.cjs new file mode 100644 index 0000000000..b3875215a9 --- /dev/null +++ b/postgres/pg-query-context/benchmarks/checkout-sanitation.cjs @@ -0,0 +1,78 @@ +/* Non-gating microbenchmark. Run after building this package and its test dependencies. */ +const { performance } = require('node:perf_hooks'); +const { writeFileSync } = require('node:fs'); +const { getConnections } = require('pgsql-test'); +const { defaultPgPoolFactory } = require('pg-cache'); +const { withPgClient } = require('../dist'); + +async function run() { + const samples = Number(process.argv[3] ?? 500); + if (!Number.isSafeInteger(samples) || samples < 100) { + throw new Error('samples must be an integer >= 100'); + } + const fixture = await getConnections({}, []); + let sanitized; + try { + const config = { ...fixture.db.config, max: 1 }; + const baseline = fixture.manager.getPool(config); + // This factory is the behavior under measurement; the fixture owns the DB. + sanitized = defaultPgPoolFactory({ ...fixture.db.config, pool: { max: 1 } }); + const server = await baseline.query('SHOW server_version'); + const prepared = { name: 'checkout_cost', text: 'SELECT 1 AS value' }; + const workloads = { + checkout: async pool => { + const client = await pool.connect(); + client.release(); + }, + prepared_select: async pool => { + const client = await pool.connect(); + try { await client.query(prepared); } + finally { client.release(); } + }, + transaction: async pool => withPgClient(pool, { + role: fixture.db.config.user, + row_security: 'on', + search_path: 'pg_catalog', + 'jwt.claims.user_id': '', + }, client => client.query(prepared)), + }; + const results = []; + for (let round = 0; round < 3; round++) { + for (const [workload, operation] of Object.entries(workloads)) { + const arms = round % 2 ? [['sanitized', sanitized], ['baseline', baseline]] + : [['baseline', baseline], ['sanitized', sanitized]]; + for (const [arm, pool] of arms) { + for (let i = 0; i < 50; i++) await operation(pool); + const latencies = []; + const started = performance.now(); + for (let i = 0; i < samples; i++) { + const before = performance.now(); + await operation(pool); + latencies.push(performance.now() - before); + } + const elapsedMs = performance.now() - started; + latencies.sort((a, b) => a - b); + const percentile = p => latencies[Math.ceil(samples * p) - 1]; + results.push({ round: round + 1, workload, arm, samples, elapsedMs, + operationsPerSecond: samples * 1000 / elapsedMs, + p50Ms: percentile(0.5), p95Ms: percentile(0.95), p99Ms: percentile(0.99) }); + } + } + } + const preparedState = {}; + for (const [arm, pool] of [['baseline', baseline], ['sanitized', sanitized]]) { + const result = await pool.query("SELECT count(*)::int AS count FROM pg_prepared_statements WHERE name = 'checkout_cost'"); + preparedState[arm] = result.rows[0].count; + } + const report = { timestamp: new Date().toISOString(), node: process.version, + postgres: server.rows[0].server_version, clients: 1, concurrency: 1, + warmupPerArm: 50, order: 'alternating by round', preparedState, results }; + const output = JSON.stringify(report, null, 2) + '\n'; + if (process.argv[2]) writeFileSync(process.argv[2], output); + else process.stdout.write(output); + } finally { + try { if (sanitized) await sanitized.end(); } + finally { await fixture.teardown(); } + } +} +run().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/postgres/pg-query-context/benchmarks/checkout-sanitation.pg18-local.json b/postgres/pg-query-context/benchmarks/checkout-sanitation.pg18-local.json new file mode 100644 index 0000000000..fc274cd929 --- /dev/null +++ b/postgres/pg-query-context/benchmarks/checkout-sanitation.pg18-local.json @@ -0,0 +1,213 @@ +{ + "timestamp": "2026-09-09T04:25:47.607Z", + "node": "v24.20.0", + "postgres": "18.6", + "clients": 1, + "concurrency": 1, + "warmupPerArm": 50, + "order": "alternating by round", + "preparedState": { + "baseline": 1, + "sanitized": 0 + }, + "results": [ + { + "round": 1, + "workload": "checkout", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 36.203164000000015, + "operationsPerSecond": 27621.895147065035, + "p50Ms": 0.018110999999862543, + "p95Ms": 0.049364999999852444, + "p99Ms": 0.19730600000002596 + }, + { + "round": 1, + "workload": "checkout", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 658.2653730000002, + "operationsPerSecond": 1519.1441643703165, + "p50Ms": 0.4535110000001623, + "p95Ms": 1.9466569999999592, + "p99Ms": 2.827784999999949 + }, + { + "round": 1, + "workload": "prepared_select", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 774.8421929999995, + "operationsPerSecond": 1290.5853721365438, + "p50Ms": 0.5050600000004124, + "p95Ms": 2.1595499999998538, + "p99Ms": 3.433371000000079 + }, + { + "round": 1, + "workload": "prepared_select", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 1582.3473240000003, + "operationsPerSecond": 631.972503654956, + "p50Ms": 1.1145530000003419, + "p95Ms": 3.3778690000008282, + "p99Ms": 5.153209000000061 + }, + { + "round": 1, + "workload": "transaction", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 4116.908935, + "operationsPerSecond": 242.90068490426785, + "p50Ms": 2.8951149999993504, + "p95Ms": 11.492820999999822, + "p99Ms": 18.891061999999692 + }, + { + "round": 1, + "workload": "transaction", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 2654.5545359999996, + "operationsPerSecond": 376.7110400025325, + "p50Ms": 2.143340000000535, + "p95Ms": 4.725237000000561, + "p99Ms": 6.516456999999718 + }, + { + "round": 2, + "workload": "checkout", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 746.4313989999991, + "operationsPerSecond": 1339.7078436674944, + "p50Ms": 0.3215150000014546, + "p95Ms": 2.7295560000002297, + "p99Ms": 4.3268000000007305 + }, + { + "round": 2, + "workload": "checkout", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 29.56981700000142, + "operationsPerSecond": 33818.268134698024, + "p50Ms": 0.012894999999844003, + "p95Ms": 0.01690500000040629, + "p99Ms": 0.04099800000039977 + }, + { + "round": 2, + "workload": "prepared_select", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 1708.5425560000003, + "operationsPerSecond": 585.2941716249529, + "p50Ms": 0.8252430000011373, + "p95Ms": 4.723308000000543, + "p99Ms": 11.009928999999829 + }, + { + "round": 2, + "workload": "prepared_select", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 540.5481880000025, + "operationsPerSecond": 1849.9738269402826, + "p50Ms": 0.3831950000003417, + "p95Ms": 1.835321999998996, + "p99Ms": 2.5052509999986796 + }, + { + "round": 2, + "workload": "transaction", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 2696.2393999999986, + "operationsPerSecond": 370.8869472050592, + "p50Ms": 2.070953999998892, + "p95Ms": 5.2929259999982605, + "p99Ms": 9.943190999998478 + }, + { + "round": 2, + "workload": "transaction", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 2496.743677000002, + "operationsPerSecond": 400.52169119801846, + "p50Ms": 1.7455379999992147, + "p95Ms": 5.845160999997461, + "p99Ms": 10.184078000002046 + }, + { + "round": 3, + "workload": "checkout", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 9.899107000001095, + "operationsPerSecond": 101019.21314719493, + "p50Ms": 0.006733000001986511, + "p95Ms": 0.007228000002214685, + "p99Ms": 0.021767000002000714 + }, + { + "round": 3, + "workload": "checkout", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 500.14959199999794, + "operationsPerSecond": 1999.4018109685953, + "p50Ms": 0.3214140000018233, + "p95Ms": 1.845209999999497, + "p99Ms": 2.537365000000136 + }, + { + "round": 3, + "workload": "prepared_select", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 571.5955599999979, + "operationsPerSecond": 1749.4887469034986, + "p50Ms": 0.3712660000019241, + "p95Ms": 1.9807080000027781, + "p99Ms": 2.727685999998357 + }, + { + "round": 3, + "workload": "prepared_select", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 1014.8897780000007, + "operationsPerSecond": 985.3286747755571, + "p50Ms": 0.7470359999970242, + "p95Ms": 2.548804999998538, + "p99Ms": 3.442180999998527 + }, + { + "round": 3, + "workload": "transaction", + "arm": "baseline", + "samples": 1000, + "elapsedMs": 2317.362653, + "operationsPerSecond": 431.52503502437344, + "p50Ms": 1.8842420000000857, + "p95Ms": 4.489830000002257, + "p99Ms": 5.647777999998652 + }, + { + "round": 3, + "workload": "transaction", + "arm": "sanitized", + "samples": 1000, + "elapsedMs": 3205.106445999998, + "operationsPerSecond": 312.0021181349559, + "p50Ms": 2.643698999996559, + "p95Ms": 6.96096100000068, + "p99Ms": 10.79024600000048 + } + ] +} diff --git a/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts b/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts index 3de42a8413..8857f8eb71 100644 --- a/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts +++ b/postgres/pg-query-context/src/__tests__/postgres.integration.test.ts @@ -1,4 +1,4 @@ -import { Pool, type PoolClient } from 'pg'; +import { type Pool, type PoolClient } from 'pg'; import { defaultPgPoolFactory } from 'pg-cache'; import { getConnections } from 'pgsql-test'; @@ -53,8 +53,10 @@ describe('pg-query-context transaction-local integration', () => { let sanitizedPool: Pool; beforeAll(async () => { - ({ db, teardown } = await getConnections({}, [])); - singleClientPool = new Pool({ ...db.config, max: 1 }); + const fixture = await getConnections({}, []); + ({ db, teardown } = fixture); + const poolConfig = { ...db.config, max: 1 }; + singleClientPool = fixture.manager.getPool(poolConfig); sanitizedPool = defaultPgPoolFactory({ ...db.config, pool: { max: 1 }, @@ -62,9 +64,8 @@ describe('pg-query-context transaction-local integration', () => { }); afterAll(async () => { - if (sanitizedPool) await sanitizedPool.end(); - if (singleClientPool) await singleClientPool.end(); - if (teardown) await teardown(); + try { if (sanitizedPool) await sanitizedPool.end(); } + finally { if (teardown) await teardown(); } }); beforeEach(async () => {