Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres): aborted transactions cancel their running statement (#6598)
garrytan255e23572978
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 1cf3c7017a..566eacc380 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -55,4 +55,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/schema-migrations/v232-fts-cjk-boundary.ts` — #6370, handler-only and idempotent: creates `gbrain_fts_input`, recreates both search_vector trigger functions under `getFtsLanguage()` with the shared builders, then rebuilds only pages (`title`/`timeline`) and chunks (`chunk_text`/`doc_comment`/`symbol_name_qualified`) matching `FTS_CJK_BOUNDARY_REGEX` through `search-vector-backfill.ts` (checkpoints `fts_cjk_pages`/`fts_cjk_content_chunks`, cleared at the end); every other row's vector is byte-identical under the helper and is not touched. Pinned by `test/fts-cjk-boundary.test.ts` and `test/e2e/fts-cjk-boundary-postgres.test.ts`.- `src/core/schema-migrations/v245-page-search-vector-bounded-timeline.ts` — Large pages, handler-only and idempotent: recreates the pages search_vector trigger function under `getFtsLanguage()` with the bounded timeline (`PAGE_TIMELINE_FTS_MAX_CHARS`) and entries (`PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS`) cuts, then rebuilds only pages whose timeline is longer than half the timeline cap through `search-vector-backfill.ts` (checkpoint `page_vector_bounded_timeline`, cleared at the end); shorter timelines index byte-identically and are not touched. Pinned by `test/large-pages/page-timeline-tsvector-bound.test.ts` and `test/e2e/page-timeline-tsvector-bound-postgres.test.ts`.-- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort discards the transaction's connection through the begin handle's `discard()`, so the server rolls the transaction back and the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause`; an already-aborted signal rejects before BEGIN); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.+- `src/core/postgres-engine/` + `src/core/pglite-engine/` — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the `migrated` rows of `scripts/engine-sql-baseline.tsv`) do not live here: their SQL exists once in `src/core/engine-sql/` (see that entry in engines-2.md). What remains: `pglite-engine/checkpoint-guard.ts`, `pglite-engine/code-edges.ts` (PGLite's `getEdgesByChunk`, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in `docs/designs/refactor-wave-1/w1-inventory.md`), `postgres-engine/cancellation.ts`, `postgres-engine/init-schema-lock.ts`, `postgres-engine/keyword-statement-timeout.ts` (#6495: `KEYWORD_STATEMENT_TIMEOUT_KEY` = `search.keyword_statement_timeout_ms`, default 8000, range 1000-60000; `keywordStatementTimeoutMs` accepts an integer in range, `resolveKeywordStatementTimeoutMs(file, db)` applies file > DB > default, `keywordStatementTimeoutValueProblem` is the `config set` refusal text, and `loadKeywordStatementTimeout(reader, fileValue)` yields the `<ms>ms` setting one connection binds; pinned by `test/keyword-statement-timeout-knob-6495.test.ts` on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), `postgres-engine/schema-lock-timeout.ts` (#5227: `resolveSchemaLockTimeoutMs` reads `GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS`, default 60 s; `withSchemaLockTimeout` sets a session-level `lock_timeout` on the reserved DDL backend and restores the prior value on release, used by the `schema.sql` replay in `postgres-engine.ts` and the `transaction: false` path of `migrate.ts`, while a transaction-wrapped migration binds the same wait with `SET LOCAL`; `schemaDiagnosticConnection` opens a one-backend connection that samples `pg_blocking_pids()` of the waiting backend while the wait is active so `schemaLockBlockedError` names blockers by pid, application, state and transaction age, never query text; `init-schema-retry.ts` retries `schema_lock_blocked` / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration `verifySchema` run outside the bound) and `postgres-engine/search-settings.ts` (search transactions run with `jit = off`), `postgres-engine/reserved-transactions.ts` (`withReservedConnection` lends its connection a `transaction()`; BEGIN and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), `postgres-engine/transaction-abort.ts` (`transaction(fn, { signal })`: an abort calls the begin handle's `cancelAndDiscard()`, which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded by `GBRAIN_CANCEL_SETTLE_MS`), then discards the connection, so a statement blocked on a lock stops instead of waiting out its statement timeout (#6598) and the server rolls the transaction back; the caller gets an `AbortError` with the driver's `CONNECTION_CLOSED` as `cause` and, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), the `CANCEL_UNCONFIRMED` rejection as `cancelFailure`; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline by `test/postgres-transaction-cancel-order.test.ts` and on direct Postgres and PgBouncer by `test/e2e/transaction-cancel-held-lock.test.ts`); the forward-reference bootstrap lives once in `engine-sql/bootstrap.ts` for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.diff --git a/patches/[email protected] b/patches/[email protected]index e4a8a7e12a..7367ed773a 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -606,7 +606,7 @@ index 07f6716..a15e780 100644seconds = typeof seconds === 'function' ? seconds() : secondsif (!seconds)diff --git a/cjs/src/index.js b/vendor/postgres/cjs/src/index.js-index f09c61c..93eb66d 100644+index f09c61c..b25e0b6 100644--- a/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js@@ -62,10 +62,36 @@ function Postgres(a, b) {@@ -647,7 +647,7 @@ index f09c61c..93eb66d 100644Object.assign(sql, {get parameters() { return options.parameters },largeObject: largeObject.bind(null, sql),-@@ -200,40 +226,134 @@ function Postgres(a, b) {+@@ -200,40 +226,181 @@ function Postgres(a, b) {return await sql`select pg_notify(${ channel }, ${ '' + payload })`}@@ -656,7 +656,7 @@ index f09c61c..93eb66d 100644const queue = Queue()- const c = open.length- ? open.shift()-+ let busy = false, fence = null, holding = null, releasing = false++ let busy = false, fence = null, holding = null, releasing = false, discarding = false, discardPromise = null+ const reservation = c.reserved = (ended = false) => {+ if (c.reserved !== reservation)+ return@@ -680,7 +680,7 @@ index f09c61c..93eb66d 100644+ }+ }+ reservation.enqueue = q => {-+ if (c.reserved !== reservation || releasing)++ if (c.reserved !== reservation || releasing || discarding)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))+ queue.push(q)+ pump()@@ -696,6 +696,52 @@ index f09c61c..93eb66d 100644+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))+ c.terminate()+ }++ // A Terminate message on the busy socket cannot interrupt its current++ // statement. Preserve the fenced Query/canceller until CancelRequest and++ // the query's backend response settle; never let a later query use it.++ // The bounded fallback still discards, but rejects as unconfirmed.++ reservation.cancelAndDiscard = ({ timeout = 2000 } = {}) => {++ if (discardPromise)++ return discardPromise++ if (c.reserved !== reservation)++ return Promise.resolve()++ discarding = true++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is being discarded'))++ const q = fence || holding++ if (!q) {++ // A busy, unfenced query has no retained canceller/settlement proof.++ // Retire the socket but never report that as confirmed server stop.++ const unconfirmed = busy++ reservation.discard()++ return discardPromise = unconfirmed++ ? Promise.reject(Errors.generic('CANCEL_UNCONFIRMED', 'Busy unfenced query cancellation cannot be confirmed'))++ : Promise.resolve()++ }++ let timer++ let cancelling++ try {++ cancelling = q.cancel()++ } catch (error) {++ reservation.discard()++ return discardPromise = Promise.reject(error)++ }++ discardPromise = Promise.race([++ Promise.all([++ cancelling,++ Promise.prototype.then.call(q, () => {}, error => {++ if (!error || error.code !== '57014')++ throw error++ })++ ]),++ new Promise((_, reject) => {++ timer = setTimeout(() => reject(Errors.generic('CANCEL_UNCONFIRMED', 'Query cancellation did not settle before discard')), timeout)++ })++ ]).then(() => {}).finally(() => {++ clearTimeout(timer)++ reservation.discard()++ })++ return discardPromise++ }+ reservation.releaseConnection = () => {+ if (c.reserved !== reservation)+ return@@ -705,7 +751,7 @@ index f09c61c..93eb66d 100644+ return reservation++ function pump() {-+ if (c.reserved !== reservation || holding || fence)++ if (c.reserved !== reservation || discarding || holding || fence)+ return+ while (queue.length) {+ const q = queue.peek()@@ -791,6 +837,7 @@ index f09c61c..93eb66d 100644+ const sql = Sql(reservation.enqueue)+ sql.release = reservation.releaseConnection+ sql.discard = reservation.discard++ sql.cancelAndDiscard = reservation.cancelAndDiscard+ return sql}}@@ -801,7 +848,7 @@ index f09c61c..93eb66d 100644let savepoints = 0, connection, prepare = null-@@ -249,9 +369,13 @@ function Postgres(a, b) {+@@ -249,9 +416,14 @@ function Postgres(a, b) {}async function scope(c, fn, name) {@@ -812,10 +859,11 @@ index f09c61c..93eb66d 100644sql.savepoint = savepointsql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)+ sql.discard = reservation.discard++ sql.cancelAndDiscard = reservation.cancelAndDiscardlet uncaughtError, result-@@ -281,6 +405,8 @@ function Postgres(a, b) {+@@ -281,6 +453,8 @@ function Postgres(a, b) {return resultfunction savepoint(name, fn) {@@ -824,7 +872,7 @@ index f09c61c..93eb66d 100644if (name && Array.isArray(name.raw))return savepoint(sql => sql.apply(sql, arguments))-@@ -290,18 +416,16 @@ function Postgres(a, b) {+@@ -290,18 +464,16 @@ function Postgres(a, b) {function handler(q) {q.catch(e => uncaughtError || (uncaughtError = e))@@ -847,7 +895,7 @@ index f09c61c..93eb66d 100644}}-@@ -351,7 +475,7 @@ function Postgres(a, b) {+@@ -351,7 +523,7 @@ function Postgres(a, b) {return new Promise((resolve, reject) => {query.state? query.active@@ -856,7 +904,7 @@ index f09c61c..93eb66d 100644: query.cancelled = { resolve, reject }: (queries.remove(query),-@@ -362,6 +486,25 @@ function Postgres(a, b) {+@@ -362,6 +534,25 @@ function Postgres(a, b) {})}@@ -882,7 +930,7 @@ index f09c61c..93eb66d 100644async function end({ timeout = null } = {}) {if (ending)return ending-@@ -398,7 +541,14 @@ function Postgres(a, b) {+@@ -398,7 +589,14 @@ function Postgres(a, b) {move(c, ended)}@@ -898,7 +946,7 @@ index f09c61c..93eb66d 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +568,50 @@ function Postgres(a, b) {+@@ -418,12 +616,50 @@ function Postgres(a, b) {: move(c, full)}@@ -950,7 +998,7 @@ index f09c61c..93eb66d 100644}}-@@ -444,7 +632,7 @@ function parseOptions(a, b) {+@@ -444,7 +680,7 @@ function parseOptions(a, b) {'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-linequery.sslrootcert === 'system' && (query.ssl = 'verify-full')@@ -959,7 +1007,7 @@ index f09c61c..93eb66d 100644const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +641,9 @@ function parseOptions(a, b) {+@@ -453,6 +689,9 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,@@ -969,7 +1017,7 @@ index f09c61c..93eb66d 100644backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +682,18 @@ function parseOptions(a, b) {+@@ -491,11 +730,18 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,@@ -1666,7 +1714,7 @@ index 1b1cccd..7b6372c 100644seconds = typeof seconds === 'function' ? seconds() : secondsif (!seconds)diff --git a/src/index.js b/vendor/postgres/src/index.js-index c7fba3d..5bfd92f 100644+index c7fba3d..5458638 100644--- a/src/index.js+++ b/vendor/postgres/src/index.js@@ -62,10 +62,36 @@ function Postgres(a, b) {@@ -1707,7 +1755,7 @@ index c7fba3d..5bfd92f 100644Object.assign(sql, {get parameters() { return options.parameters },largeObject: largeObject.bind(null, sql),-@@ -200,40 +226,134 @@ function Postgres(a, b) {+@@ -200,40 +226,181 @@ function Postgres(a, b) {return await sql`select pg_notify(${ channel }, ${ '' + payload })`}@@ -1716,7 +1764,7 @@ index c7fba3d..5bfd92f 100644const queue = Queue()- const c = open.length- ? open.shift()-+ let busy = false, fence = null, holding = null, releasing = false++ let busy = false, fence = null, holding = null, releasing = false, discarding = false, discardPromise = null+ const reservation = c.reserved = (ended = false) => {+ if (c.reserved !== reservation)+ return@@ -1740,7 +1788,7 @@ index c7fba3d..5bfd92f 100644+ }+ }+ reservation.enqueue = q => {-+ if (c.reserved !== reservation || releasing)++ if (c.reserved !== reservation || releasing || discarding)+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))+ queue.push(q)+ pump()@@ -1756,6 +1804,52 @@ index c7fba3d..5bfd92f 100644+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))+ c.terminate()+ }++ // A Terminate message on the busy socket cannot interrupt its current++ // statement. Preserve the fenced Query/canceller until CancelRequest and++ // the query's backend response settle; never let a later query use it.++ // The bounded fallback still discards, but rejects as unconfirmed.++ reservation.cancelAndDiscard = ({ timeout = 2000 } = {}) => {++ if (discardPromise)++ return discardPromise++ if (c.reserved !== reservation)++ return Promise.resolve()++ discarding = true++ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is being discarded'))++ const q = fence || holding++ if (!q) {++ // A busy, unfenced query has no retained canceller/settlement proof.++ // Retire the socket but never report that as confirmed server stop.++ const unconfirmed = busy++ reservation.discard()++ return discardPromise = unconfirmed++ ? Promise.reject(Errors.generic('CANCEL_UNCONFIRMED', 'Busy unfenced query cancellation cannot be confirmed'))++ : Promise.resolve()++ }++ let timer++ let cancelling++ try {++ cancelling = q.cancel()++ } catch (error) {++ reservation.discard()++ return discardPromise = Promise.reject(error)++ }++ discardPromise = Promise.race([++ Promise.all([++ cancelling,++ Promise.prototype.then.call(q, () => {}, error => {++ if (!error || error.code !== '57014')++ throw error++ })++ ]),++ new Promise((_, reject) => {++ timer = setTimeout(() => reject(Errors.generic('CANCEL_UNCONFIRMED', 'Query cancellation did not settle before discard')), timeout)++ })++ ]).then(() => {}).finally(() => {++ clearTimeout(timer)++ reservation.discard()++ })++ return discardPromise++ }+ reservation.releaseConnection = () => {+ if (c.reserved !== reservation)+ return@@ -1765,7 +1859,7 @@ index c7fba3d..5bfd92f 100644+ return reservation++ function pump() {-+ if (c.reserved !== reservation || holding || fence)++ if (c.reserved !== reservation || discarding || holding || fence)+ return+ while (queue.length) {+ const q = queue.peek()@@ -1851,6 +1945,7 @@ index c7fba3d..5bfd92f 100644+ const sql = Sql(reservation.enqueue)+ sql.release = reservation.releaseConnection+ sql.discard = reservation.discard++ sql.cancelAndDiscard = reservation.cancelAndDiscard+ return sql}}@@ -1861,7 +1956,7 @@ index c7fba3d..5bfd92f 100644let savepoints = 0, connection, prepare = null-@@ -249,9 +369,13 @@ function Postgres(a, b) {+@@ -249,9 +416,14 @@ function Postgres(a, b) {}async function scope(c, fn, name) {@@ -1872,10 +1967,11 @@ index c7fba3d..5bfd92f 100644sql.savepoint = savepointsql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)+ sql.discard = reservation.discard++ sql.cancelAndDiscard = reservation.cancelAndDiscardlet uncaughtError, result-@@ -281,6 +405,8 @@ function Postgres(a, b) {+@@ -281,6 +453,8 @@ function Postgres(a, b) {return resultfunction savepoint(name, fn) {@@ -1884,7 +1980,7 @@ index c7fba3d..5bfd92f 100644if (name && Array.isArray(name.raw))return savepoint(sql => sql.apply(sql, arguments))-@@ -290,18 +416,16 @@ function Postgres(a, b) {+@@ -290,18 +464,16 @@ function Postgres(a, b) {function handler(q) {q.catch(e => uncaughtError || (uncaughtError = e))@@ -1907,7 +2003,7 @@ index c7fba3d..5bfd92f 100644}}-@@ -351,7 +475,7 @@ function Postgres(a, b) {+@@ -351,7 +523,7 @@ function Postgres(a, b) {return new Promise((resolve, reject) => {query.state? query.active@@ -1916,7 +2012,7 @@ index c7fba3d..5bfd92f 100644: query.cancelled = { resolve, reject }: (queries.remove(query),-@@ -362,6 +486,25 @@ function Postgres(a, b) {+@@ -362,6 +534,25 @@ function Postgres(a, b) {})}@@ -1942,7 +2038,7 @@ index c7fba3d..5bfd92f 100644async function end({ timeout = null } = {}) {if (ending)return ending-@@ -398,7 +541,14 @@ function Postgres(a, b) {+@@ -398,7 +589,14 @@ function Postgres(a, b) {move(c, ended)}@@ -1958,7 +2054,7 @@ index c7fba3d..5bfd92f 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +568,50 @@ function Postgres(a, b) {+@@ -418,12 +616,50 @@ function Postgres(a, b) {: move(c, full)}@@ -2010,7 +2106,7 @@ index c7fba3d..5bfd92f 100644}}-@@ -444,7 +632,7 @@ function parseOptions(a, b) {+@@ -444,7 +680,7 @@ function parseOptions(a, b) {'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) // eslint-disable-linequery.sslrootcert === 'system' && (query.ssl = 'verify-full')@@ -2019,7 +2115,7 @@ index c7fba3d..5bfd92f 100644const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +641,9 @@ function parseOptions(a, b) {+@@ -453,6 +689,9 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,@@ -2029,7 +2125,7 @@ index c7fba3d..5bfd92f 100644backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +682,18 @@ function parseOptions(a, b) {+@@ -491,11 +730,18 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,@@ -2119,7 +2215,7 @@ index 7c7c2b9..d462498 100644return '$' + (types.push(diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts-index 13c3432..0d48716 100644+index 13c3432..49c8e53 100644--- a/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts@@ -119,6 +119,51 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {@@ -2200,7 +2296,7 @@ index 13c3432..0d48716 100644end(options?: { timeout?: number | undefined } | undefined): Promise<void>;-@@ -717,10 +765,11 @@ declare namespace postgres {+@@ -717,10 +765,12 @@ declare namespace postgres {begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;@@ -2210,14 +2306,16 @@ index 13c3432..0d48716 100644interface TransactionSql<TTypes extends Record<string, unknown> = {}> extends ISql<TTypes> {+ discard(): void;++ cancelAndDiscard(options?: { timeout?: number }): Promise<void>;savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;-@@ -728,6 +777,7 @@ declare namespace postgres {+@@ -728,6 +778,8 @@ declare namespace postgres {}interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {+ discard(): void;++ cancelAndDiscard(options?: { timeout?: number }): Promise<void>;release(): void;}}diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 129239a575..5cc78de211 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -662,7 +662,7 @@ export class PostgresEngine implements BrainEngine {Object.defineProperty(txEngine, 'sql', { get: () => tx });Object.defineProperty(txEngine, '_sql', { value: tx as unknown as ReturnType<typeof postgres>, writable: false });return fn(txEngine);- }) as Promise<T>));+ }) as Promise<T>), { cancelSettleMs: cancelSettleMs() });} finally {if (!this._pageTransaction) this.checkoutGauge.release('tx');}diff --git a/src/core/postgres-engine/transaction-abort.ts b/src/core/postgres-engine/transaction-abort.tsindex 9f4cd402f7..24e4c3b327 100644--- a/src/core/postgres-engine/transaction-abort.ts+++ b/src/core/postgres-engine/transaction-abort.ts@@ -1,46 +1,85 @@/**- * `transaction(fn, { signal })` on Postgres: aborting the signal discards the- * transaction's connection.+ * `transaction(fn, { signal })` on Postgres: aborting the signal cancels the+ * transaction's running statement, then discards its connection.** postgres.js gives every `begin()` callback a handle whose `discard()` (the* vendored #5466/#5560 hunk, `sql.discard = reservation.discard` in* vendor/postgres/src/index.js) rejects the reservation's queue with- * `CONNECTION_CLOSED`, drops the reservation and terminates the socket. The- * server sees the socket close and rolls the open transaction back on its- * own, directly or behind a transaction-mode pooler, so no `pg_cancel_backend`- * round trip is needed and nothing half-committed survives; the pool- * reconnects on its next checkout. An abort that lands while `BEGIN` is still- * on the wire is applied as soon as the handle exists. One that lands after- * `COMMIT` returned finds no owned reservation and is a no-op in the driver.+ * `CONNECTION_CLOSED`, drops the reservation and terminates the socket. A+ * Terminate on a busy socket does not stop the statement already running on+ * the backend, so a discard alone can leave it holding locks until its+ * statement timeout (#6598). The handle's `cancelAndDiscard()` (#6598 hunk)+ * sends the fenced statement's CancelRequest first, keeps the reservation+ * closed to successors until the statement settles, then discards; it rejects+ * `CANCEL_UNCONFIRMED` when the statement does not settle inside the settle+ * window (or ran without a cancel fence), and that rejection rides on the+ * abort as `cancelFailure`. `cause` stays the driver error the transaction+ * itself ended with, which callers classify for retry. The server rolls the+ * open transaction back when the socket closes, directly or behind a+ * transaction-mode pooler; the pool reconnects on its next checkout. An abort+ * that lands while `BEGIN` is still on the wire is applied as soon as the+ * handle exists. One that lands after `COMMIT` returned finds no owned+ * reservation, is a no-op in the driver, and keeps the committed result.*/-export interface Discardable { discard?: () => void }+export interface Discardable {+ discard?: () => void;+ cancelAndDiscard?: (opts?: { timeout?: number }) => Promise<void>;+}-/** The rejection for an aborted transaction: an `AbortError` carrying the signal's reason and the driver error that ended it. */-export function transactionAborted(signal: AbortSignal, cause?: unknown): Error {+/**+ * The rejection for an aborted transaction: an `AbortError` carrying the+ * signal's reason, the driver error that ended it (`cause`) and, when the+ * running statement's cancellation could not be confirmed, that failure+ * (`cancelFailure`).+ */+export function transactionAborted(signal: AbortSignal, cause?: unknown, cancelFailure?: unknown): Error {const reason = signal.reason;const error = new DOMException(reason instanceof Error ? reason.message : 'transaction aborted', 'AbortError');if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause, configurable: true, writable: true });+ if (cancelFailure !== undefined) Object.defineProperty(error, 'cancelFailure', { value: cancelFailure, configurable: true, writable: true, enumerable: true });return error;}/*** Runs `run`, whose `attach` callback hands over the transaction handle once- * `begin()` has produced it. While `signal` is live, an abort discards the- * attached handle; a rejection that follows an abort is rethrown as- * `transactionAborted(signal, error)`.+ * `begin()` has produced it. While `signal` is live, an abort cancels and+ * discards the attached handle (`discard()` alone on a driver without+ * `cancelAndDiscard()`); the helper waits for that to settle before it+ * returns. A rejection that follows an abort is rethrown as+ * `transactionAborted(signal, error, cancelFailure)`.*/-export async function withTransactionAbort<T>(signal: AbortSignal | undefined, run: (attach: (handle: Discardable) => void) => Promise<T>): Promise<T> {+export async function withTransactionAbort<T>(+ signal: AbortSignal | undefined,+ run: (attach: (handle: Discardable) => void) => Promise<T>,+ opts?: { cancelSettleMs?: number },+): Promise<T> {if (!signal) return run(() => {});let handle: Discardable | null = null;- const onAbort = () => { handle?.discard?.(); };+ let aborting: Promise<void> | undefined;+ let abortFailure: unknown;+ const onAbort = () => {+ if (!handle || aborting) return;+ try {+ aborting = Promise.resolve(handle.cancelAndDiscard+ ? handle.cancelAndDiscard(opts?.cancelSettleMs === undefined ? undefined : { timeout: opts.cancelSettleMs })+ : handle.discard?.())+ .catch(error => { abortFailure = error; });+ } catch (error) {+ abortFailure = error;+ aborting = Promise.resolve();+ }+ };signal.addEventListener('abort', onAbort, { once: true });try {- return await run(h => {+ const result = await run(h => {handle = h;if (signal.aborted) onAbort();});+ await aborting;+ return result;} catch (error) {- if (signal.aborted) throw transactionAborted(signal, error);+ await aborting;+ if (signal.aborted) throw transactionAborted(signal, error, abortFailure);throw error;} finally {signal.removeEventListener('abort', onAbort);diff --git a/test/e2e/transaction-cancel-held-lock.test.ts b/test/e2e/transaction-cancel-held-lock.test.tsnew file mode 100644index 0000000000..678effbf62--- /dev/null+++ b/test/e2e/transaction-cancel-held-lock.test.ts@@ -0,0 +1,156 @@+/**+ * #6598: an aborted `engine.transaction(fn, { signal })` cancels the statement it is running instead of only closing+ * the socket. A Terminate on a busy connection does not interrupt the backend: a statement waiting on a row lock keeps+ * waiting (holding its own locks and the pooler's server connection) until the lock frees or its statement timeout+ * fires. With the vendored `cancelAndDiscard()` the transaction's abort listener sends the fenced statement's+ * CancelRequest before discarding, so the backend stops while the blocking lock is still held.+ *+ * Protects, on direct Postgres (`DATABASE_URL`) and through transaction-mode PgBouncer (`GBRAIN_PGBOUNCER_URL` ++ * `GBRAIN_PGBOUNCER_DIRECT_URL`, the CI fixture): the aborted transaction rejects with `AbortError` well inside the+ * statement timeout; an observer connection sees no backend still running the blocked statement BEFORE the lock holder+ * lets go; after the holder commits, neither the blocked UPDATE nor the transaction's earlier INSERT is applied (the+ * late statement never commits); the engine serves the next caller. Fails on master: the abort only discards, the+ * backend stays in `Lock` wait until the holder releases, and the observer finds it active.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const directUrl = process.env.DATABASE_URL;+const pooled = process.env.GBRAIN_PGBOUNCER_URL;+const pooledDirect = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;+const pooledAvailable = Boolean(pooled && pooledDirect);+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && !pooledAvailable) throw new Error('The transaction-cancel pooled arm requires the configured CI PgBouncer fixture.');++const MARK = `w18b_6598_${randomUUID().replaceAll('-', '').slice(0, 12)}`;++interface Arm {+ engine: PostgresEngine;+ holder: ReturnType<typeof postgres>;+ observer: ReturnType<typeof postgres>;+ cleanup: () => Promise<void>;+}++async function openArm(engineUrl: string, adminUrl: string): Promise<Arm> {+ const engine = new PostgresEngine();+ await engine.connect({ engine: 'postgres', database_url: engineUrl, poolSize: 2 });+ const holder = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });+ const observer = postgres(adminUrl, { max: 1, prepare: false, onnotice: () => {} });+ await engine.executeRaw(`CREATE TABLE ${MARK}_rows (id int PRIMARY KEY, v int NOT NULL)`);+ await engine.executeRaw(`CREATE TABLE ${MARK}_log (x int)`);+ await engine.executeRaw(`INSERT INTO ${MARK}_rows VALUES (1, 0)`);+ return {+ engine, holder, observer,+ cleanup: async () => {+ await engine.executeRaw(`DROP TABLE IF EXISTS ${MARK}_rows`).catch(() => {});+ await engine.executeRaw(`DROP TABLE IF EXISTS ${MARK}_log`).catch(() => {});+ await engine.disconnect();+ await holder.end();+ await observer.end();+ },+ };+}++async function blockedBackends(observer: ReturnType<typeof postgres>): Promise<Array<{ pid: number; state: string; wait: string | null }>> {+ return observer.unsafe(+ `SELECT pid, state, wait_event_type AS wait FROM pg_stat_activity+ WHERE query LIKE $1 AND query NOT LIKE '%pg_stat_activity%' AND state <> 'idle'`,+ [`%${MARK}_blocked%`],+ ) as unknown as Promise<Array<{ pid: number; state: string; wait: string | null }>>;+}++async function waitFor(predicate: () => Promise<boolean>, ms: number): Promise<boolean> {+ const until = Date.now() + ms;+ while (Date.now() < until) {+ if (await predicate()) return true;+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ return predicate();+}++async function scenario(arm: Arm): Promise<void> {+ const { engine, holder, observer } = arm;+ const release = Promise.withResolvers<void>();+ const locked = Promise.withResolvers<void>();+ const holding = holder.begin(async sql => {+ await sql.unsafe(`SELECT v FROM ${MARK}_rows WHERE id = 1 FOR UPDATE`);+ locked.resolve();+ await release.promise;+ await sql.unsafe(`UPDATE ${MARK}_rows SET v = 100 WHERE id = 1`);+ });+ await locked.promise;++ const ac = new AbortController();+ const started = Date.now();+ const tx = engine.transaction(async t => {+ await t.executeRaw("SELECT set_config('statement_timeout', '30000', true)");+ await t.executeRaw(`INSERT INTO ${MARK}_log VALUES (1)`);+ await t.executeRaw(`UPDATE ${MARK}_rows SET v = v + 1 WHERE id = 1 /* ${MARK}_blocked */`, [], { signal: ac.signal });+ await t.executeRaw(`INSERT INTO ${MARK}_log VALUES (2)`);+ }, { signal: ac.signal }).then(() => null, (e: Error) => e);++ try {+ expect(await waitFor(async () => (await blockedBackends(observer)).some(r => r.wait === 'Lock'), 5000)).toBe(true);+ ac.abort(new Error('deadline'));+ const error = await Promise.race([tx, new Promise<'hung'>(resolve => setTimeout(() => resolve('hung'), 8000))]);+ expect(error).not.toBe('hung');+ expect((error as Error).name).toBe('AbortError');+ expect(Date.now() - started).toBeLessThan(15000);+ // The holder still has the row: the blocked statement must already be gone from the server.+ const stopped = await waitFor(async () => (await blockedBackends(observer)).length === 0, 1500);+ if (!stopped) console.log(JSON.stringify({ evidence: 'blocked_backend_still_active', rows: await blockedBackends(observer) }));+ expect(stopped).toBe(true);+ } finally {+ release.resolve();+ await holding;+ }++ const [row] = await engine.executeRaw<{ v: number }>(`SELECT v FROM ${MARK}_rows WHERE id = 1`);+ expect(row!.v).toBe(100);+ await new Promise(resolve => setTimeout(resolve, 300));+ expect((await engine.executeRaw<{ v: number }>(`SELECT v FROM ${MARK}_rows WHERE id = 1`))[0]!.v).toBe(100);+ expect((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${MARK}_log`))[0]!.n).toBe(0);+ expect(await engine.executeRaw<{ x: number }>('SELECT 1 AS x')).toEqual([{ x: 1 }]);+ expect(engine.getPoolDiagnostics()?.tracked.tx).toBe(0);+}++describe.skipIf(!directUrl)('aborted transaction cancels its lock-blocked statement (direct Postgres)', () => {+ let arm: Arm;+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(directUrl!);+ arm = await openArm(directUrl!, directUrl!);+ }, 60_000);+ afterAll(async () => { await arm?.cleanup(); });++ test('the blocked statement stops before the lock holder releases, and nothing the transaction wrote commits', async () => {+ await scenario(arm);+ }, 30_000);+});++describe.skipIf(!pooledAvailable)('aborted transaction cancels its lock-blocked statement (PgBouncer transaction mode)', () => {+ let arm: Arm;+ let admin: ReturnType<typeof postgres>;+ let database: string;+ beforeAll(async () => {+ assertSafeE2eDatabaseUrl(pooledDirect!);+ database = `gbrain_test_tx_cancel_${randomUUID().replaceAll('-', '')}`;+ admin = postgres(pooledDirect!, { max: 1, prepare: false, onnotice: () => {} });+ await admin.unsafe(`CREATE DATABASE ${database}`);+ const engineUrl = new URL(pooled!);+ engineUrl.pathname = `/${database}`;+ engineUrl.searchParams.set('prepare', 'false');+ const adminUrl = new URL(pooledDirect!);+ adminUrl.pathname = `/${database}`;+ arm = await openArm(engineUrl.toString(), adminUrl.toString());+ }, 60_000);+ afterAll(async () => {+ await arm?.cleanup();+ if (admin) { try { await admin.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`); } finally { await admin.end(); } }+ });++ test('the blocked statement stops before the lock holder releases, and nothing the transaction wrote commits', async () => {+ await scenario(arm);+ }, 30_000);+});diff --git a/test/postgres-transaction-cancel-order.test.ts b/test/postgres-transaction-cancel-order.test.tsnew file mode 100644index 0000000000..14d5c45540--- /dev/null+++ b/test/postgres-transaction-cancel-order.test.ts@@ -0,0 +1,182 @@+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+const { default: Queue } = await import(new URL('../vendor/postgres/src/queue.js', import.meta.url).href);+const { Query } = await import(new URL('../vendor/postgres/src/query.js', import.meta.url).href);+import { withTransactionAbort } from '../src/core/postgres-engine/transaction-abort.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';++// Offline forced interleaving: actual reservation/Query/helper code, simulated+// transport and backend response. This cannot certify PostgreSQL termination.+const source = readFileSync(new URL('../vendor/postgres/src/index.js', import.meta.url), 'utf8');+const ownSource = source.slice(source.indexOf(' function own(c) {'), source.indexOf(' async function reserve('));+const cancelSource = source.slice(source.indexOf(' function cancel(query) {'), source.indexOf(' async function end('));+function fixture(mode: 'reply' | 'fail' | 'hang' = 'reply') {+ const events: string[] = [];+ let active: any;+ let reply!: () => void;+ const ready = Promise.withResolvers<void>();+ const c: any = {+ execute(q: any) { active = q; q.active = true; q.state = { pid: 1, secret: 0 }; events.push('execute'); ready.resolve(); return true; },+ terminate() { events.push('terminate'); active?.reject(Object.assign(new Error('destroyed'), { code: 'CONNECTION_DESTROYED' })); },+ };+ const own = new Function('Queue', 'Errors', 'move', 'reserved', 'full', 'onopen', ownSource + '\nreturn own;')(+ Queue, { generic: (code: string, message: string) => Object.assign(new Error(message), { code }) },+ () => {}, {}, {}, () => events.push('release'),+ );+ const reservation = own(c);+ const handle: any = {+ discard: reservation.discard,+ cancelAndDiscard: reservation.cancelAndDiscard,+ };+ const cancel = new Function('Connection', 'options', 'queries', 'Errors', cancelSource + '\nreturn cancel;')(+ () => ({ cancel(_state: unknown, resolve: () => void, reject: (e: Error) => void) {+ events.push('cancel:start');+ if (mode === 'fail') { reject(new Error('cancel transport failed')); return; }+ reply = () => {+ events.push('backend:57014');+ active.reject(Object.assign(new Error('cancelled'), { code: '57014' }));+ reservation(); resolve(); events.push('cancel:confirmed');+ };+ } }), {}, Queue(), { generic: (code: string, message: string) => Object.assign(new Error(message), { code }) },+ );+ const query = () => new Query(['SELECT synthetic'], [], (q: any) => reservation.enqueue(q), cancel, { cancelFence: true });+ handle.unsafe = query;+ return { events, ready: ready.promise, reservation, handle, query, respond: () => reply(), c };+}++describe('transaction cancellation ordering (offline actual Query/reservation)', () => {+ test('parent abort preserves canceller until backend response, with child listener registered later', async () => {+ const traces: string[][] = [];+ await Promise.all(Array.from({ length: 8 }, async () => {+ const f = fixture(); const ac = new AbortController();+ const engine = new PostgresEngine();+ Object.defineProperty(engine, '_sql', { value: f.handle });+ const result = withTransactionAbort(ac.signal, async attach => {+ attach(f.handle);+ return await engine.executeRaw('SELECT synthetic', [], { signal: ac.signal });+ }).then(() => null, e => e);+ await f.ready; ac.abort(new Error('deadline'));+ if (!f.events.includes('cancel:start')) console.log(JSON.stringify({ evidence: 'offline-failed-order', events: f.events }));+ expect(f.events.filter(e => e === 'cancel:start')).toHaveLength(1);+ expect(f.events).not.toContain('terminate');+ f.respond();+ const error = await result;+ expect(error.name).toBe('AbortError');+ expect(f.events.indexOf('cancel:confirmed')).toBeLessThan(f.events.indexOf('terminate'));+ traces.push(f.events);+ }));+ console.log(JSON.stringify({ evidence: 'offline-forced-interleaving', traces }));+ });++ test('queued and new queries cannot execute while cancellation awaits a backend response', async () => {+ const f = fixture(); const q = f.query(); const first = q.catch((e: any) => e);+ await f.ready;+ const stop = f.reservation.cancelAndDiscard();+ const second = f.query().catch((e: any) => e);+ expect((await second).code).toBe('CONNECTION_CLOSED');+ expect(f.events.filter(e => e === 'execute')).toHaveLength(1);+ expect(f.events).not.toContain('release');+ f.respond(); await stop; await first;+ expect(f.events.filter(e => e === 'terminate')).toHaveLength(1);+ expect(f.events).not.toContain('release');+ });++ test('repeat cancelAndDiscard shares one promise and one CancelRequest', async () => {+ const f = fixture(); const first = f.query().catch((e: any) => e); await f.ready;+ const a = f.reservation.cancelAndDiscard(); const b = f.reservation.cancelAndDiscard();+ expect(a).toBe(b); expect(f.events.filter(e => e === 'cancel:start')).toHaveLength(1);+ f.respond(); await a; await first;+ expect(f.events.filter(e => e === 'terminate')).toHaveLength(1);+ });++ test('cancel transport failure discards but does not certify cancellation', async () => {+ const f = fixture('fail'); const first = f.query().catch((e: any) => e); await f.ready;+ await expect(f.reservation.cancelAndDiscard()).rejects.toThrow('cancel transport failed');+ expect((await first).code).toBe('CONNECTION_DESTROYED');+ expect(f.events).not.toContain('backend:57014');+ expect(f.events.filter(e => e === 'terminate')).toHaveLength(1);+ });++ test('missing backend response triggers a bounded unconfirmed fallback', async () => {+ const f = fixture('hang'); const first = f.query().catch((e: any) => e); await f.ready;+ await expect(f.reservation.cancelAndDiscard({ timeout: 5 })).rejects.toMatchObject({ code: 'CANCEL_UNCONFIRMED' });+ expect((await first).code).toBe('CONNECTION_DESTROYED');+ expect(f.events).not.toContain('backend:57014');+ // Simulate a delayed cancel response after force discard. No later query+ // can be admitted to the old reservation or receive that cancellation.+ f.respond(); await Promise.resolve();+ expect((await f.query().catch((e: any) => e)).code).toBe('CONNECTION_CLOSED');+ expect(f.events.filter(e => e === 'execute')).toHaveLength(1);+ });++ test('independent force discard rejects cancellation confirmation', async () => {+ const f = fixture(); const first = f.query().catch((e: any) => e); await f.ready;+ const stop = f.reservation.cancelAndDiscard(); f.reservation.discard(); f.respond();+ await expect(stop).rejects.toMatchObject({ code: 'CONNECTION_DESTROYED' });+ await first;+ });++ test('a synchronous canceller failure still retires the connection', async () => {+ const f = fixture(); const q = f.query(); const first = q.catch((e: any) => e); await f.ready;+ q.canceller = () => { throw new Error('synchronous cancel failure'); };+ await expect(f.reservation.cancelAndDiscard()).rejects.toThrow('synchronous cancel failure');+ expect((await first).code).toBe('CONNECTION_DESTROYED');+ expect(f.events.filter(e => e === 'terminate')).toHaveLength(1);+ });++ test('abort before handle attachment uses cancellation when attached and waits for it', async () => {+ const ac = new AbortController(); const attachReady = Promise.withResolvers<void>();+ const cancelled = Promise.withResolvers<void>(); let called = 0, done = false;+ const run = withTransactionAbort(ac.signal, async attach => {+ await attachReady.promise;+ attach({ cancelAndDiscard: () => { called++; return cancelled.promise; }, discard: () => { throw new Error('wrong path'); } });+ throw new Error('driver stopped');+ }).catch((e: any) => e).finally(() => { done = true; });+ ac.abort(); attachReady.resolve(); await Promise.resolve(); await Promise.resolve();+ expect(called).toBe(1); expect(done).toBe(false);+ cancelled.resolve(); expect((await run).name).toBe('AbortError');+ });++ test('helper retains cancellation failure without an unhandled rejection, keeping the driver error as cause', async () => {+ const ac = new AbortController(); const failed = new Error('unconfirmed'); const closed = new Error('closed');+ const result = withTransactionAbort(ac.signal, async attach => {+ attach({ cancelAndDiscard: () => Promise.reject(failed) }); ac.abort(); throw closed;+ }).catch((e: any) => e);+ const error = await result;+ expect(error.name).toBe('AbortError');+ expect(error.cancelFailure).toBe(failed);+ expect(error.cause).toBe(closed);+ });++ test('late abort after successful COMMIT preserves the committed result', async () => {+ const ac = new AbortController(); const f = fixture();+ const result = withTransactionAbort(ac.signal, async attach => {+ attach(f.handle);+ // COMMIT ReadyForQuery released the reservation before the caller's+ // continuation sees the abort. The driver's cancellation is now a no-op.+ f.reservation.releaseConnection(); ac.abort();+ return { committed: true, writeCount: 1 };+ });+ expect(await result).toEqual({ committed: true, writeCount: 1 });+ expect(f.events).not.toContain('terminate');+ expect(f.events).not.toContain('cancel:start');+ });++ test('busy unfenced query must not certify server cancellation', async () => {+ const f = fixture(); const q = f.query(); q.options.cancelFence = false;+ const result = q.catch((e: any) => e); await f.ready;+ await expect(f.reservation.cancelAndDiscard()).rejects.toMatchObject({ code: 'CANCEL_UNCONFIRMED' });+ expect((await result).code).toBe('CONNECTION_DESTROYED');+ expect(f.events).not.toContain('backend:57014');+ expect((await f.query().catch((e: any) => e)).code).toBe('CONNECTION_CLOSED');+ });++ test('idle discard does not send a cancel or affect a successor reservation', async () => {+ const f = fixture(); await f.reservation.cancelAndDiscard();+ expect(f.events).toEqual(['terminate']);+ const successor = { marker: 'successor' }; f.c.reserved = successor;+ await f.reservation.cancelAndDiscard(); f.reservation.discard();+ expect(f.c.reserved).toBe(successor);+ expect(f.events).toEqual(['terminate']);+ });+});diff --git a/vendor/README.md b/vendor/README.mdindex 4fb82db38a..70436cc3e0 100644--- a/vendor/README.md+++ b/vendor/README.md@@ -36,6 +36,15 @@ the `onpoisoned(status)` option (#5730). Cancellationmust settle or retire the connection before another query can own it. Thisis necessary for worker admission, query timeout and lease-release safety.See issues #5466 and #5560 and `test/e2e/persistence-chaos.test.ts`.+Reserved and transaction owners also expose `cancelAndDiscard({ timeout })`+(#6598): a Terminate cannot interrupt the statement already running on a busy+socket, so it sends the fenced statement's CancelRequest first, refuses new and+queued statements while it waits for that statement to settle, then discards.+It rejects `CANCEL_UNCONFIRMED` when the statement does not settle within+`timeout` (default 2000 ms) or was not fenced, so a socket close is never+reported as a confirmed server stop+(`test/postgres-transaction-cancel-order.test.ts`,+`test/e2e/transaction-cancel-held-lock.test.ts`).A statement that fails to build is answered in its place in the pipeline(#6383; the approach of upstream PR porsager/postgres#1236, which fixesdiff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.jsindex b04150f5ad..a78a452812 100644--- a/vendor/postgres/cf/src/index.js+++ b/vendor/postgres/cf/src/index.js@@ -229,7 +229,7 @@ function Postgres(a, b) {function own(c) {const queue = Queue()- let busy = false, fence = null, holding = null, releasing = false+ let busy = false, fence = null, holding = null, releasing = false, discarding = false, discardPromise = nullconst reservation = c.reserved = (ended = false) => {if (c.reserved !== reservation)return@@ -253,7 +253,7 @@ function Postgres(a, b) {}}reservation.enqueue = q => {- if (c.reserved !== reservation || releasing)+ if (c.reserved !== reservation || releasing || discarding)return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))queue.push(q)pump()@@ -269,6 +269,52 @@ function Postgres(a, b) {reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))c.terminate()}+ // A Terminate message on the busy socket cannot interrupt its current+ // statement. Preserve the fenced Query/canceller until CancelRequest and+ // the query's backend response settle; never let a later query use it.+ // The bounded fallback still discards, but rejects as unconfirmed.+ reservation.cancelAndDiscard = ({ timeout = 2000 } = {}) => {+ if (discardPromise)+ return discardPromise+ if (c.reserved !== reservation)+ return Promise.resolve()+ discarding = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is being discarded'))+ const q = fence || holding+ if (!q) {+ // A busy, unfenced query has no retained canceller/settlement proof.+ // Retire the socket but never report that as confirmed server stop.+ const unconfirmed = busy+ reservation.discard()+ return discardPromise = unconfirmed+ ? Promise.reject(Errors.generic('CANCEL_UNCONFIRMED', 'Busy unfenced query cancellation cannot be confirmed'))+ : Promise.resolve()+ }+ let timer+ let cancelling+ try {+ cancelling = q.cancel()+ } catch (error) {+ reservation.discard()+ return discardPromise = Promise.reject(error)+ }+ discardPromise = Promise.race([+ Promise.all([+ cancelling,+ Promise.prototype.then.call(q, () => {}, error => {+ if (!error || error.code !== '57014')+ throw error+ })+ ]),+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(Errors.generic('CANCEL_UNCONFIRMED', 'Query cancellation did not settle before discard')), timeout)+ })+ ]).then(() => {}).finally(() => {+ clearTimeout(timer)+ reservation.discard()+ })+ return discardPromise+ }reservation.releaseConnection = () => {if (c.reserved !== reservation)return@@ -278,7 +324,7 @@ function Postgres(a, b) {return reservationfunction pump() {- if (c.reserved !== reservation || holding || fence)+ if (c.reserved !== reservation || discarding || holding || fence)returnwhile (queue.length) {const q = queue.peek()@@ -349,6 +395,7 @@ function Postgres(a, b) {const sql = Sql(reservation.enqueue)sql.release = reservation.releaseConnectionsql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardreturn sql}}@@ -377,6 +424,7 @@ function Postgres(a, b) {sql.savepoint = savepointsql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)sql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardlet uncaughtError, resultdiff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.jsindex 93eb66dae2..b25e0b60ab 100644--- a/vendor/postgres/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js@@ -228,7 +228,7 @@ function Postgres(a, b) {function own(c) {const queue = Queue()- let busy = false, fence = null, holding = null, releasing = false+ let busy = false, fence = null, holding = null, releasing = false, discarding = false, discardPromise = nullconst reservation = c.reserved = (ended = false) => {if (c.reserved !== reservation)return@@ -252,7 +252,7 @@ function Postgres(a, b) {}}reservation.enqueue = q => {- if (c.reserved !== reservation || releasing)+ if (c.reserved !== reservation || releasing || discarding)return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))queue.push(q)pump()@@ -268,6 +268,52 @@ function Postgres(a, b) {reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))c.terminate()}+ // A Terminate message on the busy socket cannot interrupt its current+ // statement. Preserve the fenced Query/canceller until CancelRequest and+ // the query's backend response settle; never let a later query use it.+ // The bounded fallback still discards, but rejects as unconfirmed.+ reservation.cancelAndDiscard = ({ timeout = 2000 } = {}) => {+ if (discardPromise)+ return discardPromise+ if (c.reserved !== reservation)+ return Promise.resolve()+ discarding = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is being discarded'))+ const q = fence || holding+ if (!q) {+ // A busy, unfenced query has no retained canceller/settlement proof.+ // Retire the socket but never report that as confirmed server stop.+ const unconfirmed = busy+ reservation.discard()+ return discardPromise = unconfirmed+ ? Promise.reject(Errors.generic('CANCEL_UNCONFIRMED', 'Busy unfenced query cancellation cannot be confirmed'))+ : Promise.resolve()+ }+ let timer+ let cancelling+ try {+ cancelling = q.cancel()+ } catch (error) {+ reservation.discard()+ return discardPromise = Promise.reject(error)+ }+ discardPromise = Promise.race([+ Promise.all([+ cancelling,+ Promise.prototype.then.call(q, () => {}, error => {+ if (!error || error.code !== '57014')+ throw error+ })+ ]),+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(Errors.generic('CANCEL_UNCONFIRMED', 'Query cancellation did not settle before discard')), timeout)+ })+ ]).then(() => {}).finally(() => {+ clearTimeout(timer)+ reservation.discard()+ })+ return discardPromise+ }reservation.releaseConnection = () => {if (c.reserved !== reservation)return@@ -277,7 +323,7 @@ function Postgres(a, b) {return reservationfunction pump() {- if (c.reserved !== reservation || holding || fence)+ if (c.reserved !== reservation || discarding || holding || fence)returnwhile (queue.length) {const q = queue.peek()@@ -348,6 +394,7 @@ function Postgres(a, b) {const sql = Sql(reservation.enqueue)sql.release = reservation.releaseConnectionsql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardreturn sql}}@@ -376,6 +423,7 @@ function Postgres(a, b) {sql.savepoint = savepointsql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)sql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardlet uncaughtError, resultdiff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.jsindex 5bfd92f51f..5458638195 100644--- a/vendor/postgres/src/index.js+++ b/vendor/postgres/src/index.js@@ -228,7 +228,7 @@ function Postgres(a, b) {function own(c) {const queue = Queue()- let busy = false, fence = null, holding = null, releasing = false+ let busy = false, fence = null, holding = null, releasing = false, discarding = false, discardPromise = nullconst reservation = c.reserved = (ended = false) => {if (c.reserved !== reservation)return@@ -252,7 +252,7 @@ function Postgres(a, b) {}}reservation.enqueue = q => {- if (c.reserved !== reservation || releasing)+ if (c.reserved !== reservation || releasing || discarding)return q.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is no longer owned'))queue.push(q)pump()@@ -268,6 +268,52 @@ function Postgres(a, b) {reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection was discarded'))c.terminate()}+ // A Terminate message on the busy socket cannot interrupt its current+ // statement. Preserve the fenced Query/canceller until CancelRequest and+ // the query's backend response settle; never let a later query use it.+ // The bounded fallback still discards, but rejects as unconfirmed.+ reservation.cancelAndDiscard = ({ timeout = 2000 } = {}) => {+ if (discardPromise)+ return discardPromise+ if (c.reserved !== reservation)+ return Promise.resolve()+ discarding = true+ reservation.reject(Errors.generic('CONNECTION_CLOSED', 'Connection is being discarded'))+ const q = fence || holding+ if (!q) {+ // A busy, unfenced query has no retained canceller/settlement proof.+ // Retire the socket but never report that as confirmed server stop.+ const unconfirmed = busy+ reservation.discard()+ return discardPromise = unconfirmed+ ? Promise.reject(Errors.generic('CANCEL_UNCONFIRMED', 'Busy unfenced query cancellation cannot be confirmed'))+ : Promise.resolve()+ }+ let timer+ let cancelling+ try {+ cancelling = q.cancel()+ } catch (error) {+ reservation.discard()+ return discardPromise = Promise.reject(error)+ }+ discardPromise = Promise.race([+ Promise.all([+ cancelling,+ Promise.prototype.then.call(q, () => {}, error => {+ if (!error || error.code !== '57014')+ throw error+ })+ ]),+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(Errors.generic('CANCEL_UNCONFIRMED', 'Query cancellation did not settle before discard')), timeout)+ })+ ]).then(() => {}).finally(() => {+ clearTimeout(timer)+ reservation.discard()+ })+ return discardPromise+ }reservation.releaseConnection = () => {if (c.reserved !== reservation)return@@ -277,7 +323,7 @@ function Postgres(a, b) {return reservationfunction pump() {- if (c.reserved !== reservation || holding || fence)+ if (c.reserved !== reservation || discarding || holding || fence)returnwhile (queue.length) {const q = queue.peek()@@ -348,6 +394,7 @@ function Postgres(a, b) {const sql = Sql(reservation.enqueue)sql.release = reservation.releaseConnectionsql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardreturn sql}}@@ -376,6 +423,7 @@ function Postgres(a, b) {sql.savepoint = savepointsql.prepare = x => prepare = x.replace(/[^a-z0-9$-_. ]/gi)sql.discard = reservation.discard+ sql.cancelAndDiscard = reservation.cancelAndDiscardlet uncaughtError, resultdiff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.tsindex 0d487167c6..49c8e53d49 100644--- a/vendor/postgres/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts@@ -770,6 +770,7 @@ declare namespace postgres {interface TransactionSql<TTypes extends Record<string, unknown> = {}> extends ISql<TTypes> {discard(): void;+ cancelAndDiscard(options?: { timeout?: number }): Promise<void>;savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;@@ -778,6 +779,7 @@ declare namespace postgres {interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {discard(): void;+ cancelAndDiscard(options?: { timeout?: number }): Promise<void>;release(): void;}}