Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres-driver): a cancelled query no longer leaves a pipelined query with the wrong result; desync tripwire
time-attack12c3584bf673
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3b8f56ed04..24860a4d72 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,20 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**The vendored Postgres driver fixes a latent bug where a cancelled query could leave a pipelined query with the wrong result, and it now retires any connection whose answers fall out of step.** No current gbrain code path reaches the bug; this is a driver fix plus a permanent tripwire, and it does not explain the open connector-holds flake (#6482).++### Things to watch++- **A new warn line.** `[gbrain] warn code=pg_connection_desync pool=<read|direct> message=<type> connection=<id> sql=<KEYWORD_table>` means a statement's answer arrived on a connection with no statement waiting for it. The connection is retired, statements queued on it fail with `CONNECTION_DESYNC`, and the pool reconnects. The line never carries SQL text or parameters. Notices, `LISTEN` notifications and parameter changes never trigger it.++### Itemized changes++- `vendor/postgres` (ESM, CommonJS, workerd) and `patches/[email protected]`: a query cancelled after it was written keeps its place in the answer order and rejects with `57014`; a cancelled prepared query is not retried. The 3.4.9 upstream release and upstream master carry the same code.+- The driver's `ondesync` option reports a desynced connection; `PoolIncidentCounter` logs it once per trip and counts it as `getPoolDiagnostics().desyncDiscards` (`desync_discards` in `/health?deep=1`).+- `test/e2e/postgres-driver-cancel-pipeline.test.ts` (direct and PgBouncer transaction mode, prepared and unprepared) and `test/e2e/postgres-driver-desync-tripwire.test.ts` fail on the old driver and pass on this one.+## [0.60.167.0] - 2026-10-11**Wave 14 PR4: the Google connector, open loops, contacts, calendar, Windows and polish.** Gmail loops now find the person page wherever it lives in the brain, extraction runs under a daily spend cap and your own label exclusions, contacts land next to your people pages, and three Windows reports (parked tests, console windows, backups) get native coverage on CI.diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 7ac3e532cf..52018f25c4 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -720,6 +720,20 @@ engine; `/health?deep=1` reports them as `stuck_discards`. Retry the failedcall; if the line repeats, run `gbrain doctor --json` and report the warn lineswith the operations that preceded them.+<a id="pg-connection-desync"></a>**`pg_connection_desync`** (warn). A statement's+answer (columns, rows, a completion, a parse or bind acknowledgement, or a+statement error) arrived on a pooled connection with no statement waiting for+it, so the client and the server no longer agreed on which answer belonged to+which statement. The vendored driver retired that connection, statements+queued on it failed with a connection error, and the pool reconnected on its+own. The line names the pool, the message type, the driver's connection id and+the last statement written on it by first keyword and table, never its text or+parameters. Notices, notifications and parameter changes never trigger it.+`getPoolDiagnostics().desyncDiscards` counts retirements per engine;+`/health?deep=1` reports them as `desync_discards`.+Retry the failed call; if the line repeats, run `gbrain doctor --json` and+report the warn lines.+<a id="pg-statement-build-failed"></a>**`pg_statement_build_failed`** (warn). Astatement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534@@ -758,7 +772,7 @@ probe does not return in time, when `inflight_oldest_ms` is past the readpool's in-flight budget, or when an earlier deep probe is still pending (onedeep probe per engine at a time). Its body carries the pool block:`{ checked_out, max, waiters, inflight_oldest_ms, completed, poisoned_discards,-stuck_discards, build_failures }`. It is cheap enough for a two-minute cron. The+stuck_discards, build_failures, desync_discards }`. It is cheap enough for a two-minute cron. Thesame pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex 98430f5b86..bee3091990 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server.+- `patches/[email protected]` — auditable delta for the driver ownership and cancellation repair already applied to the shipped `vendor/postgres` ESM/CommonJS/workerd source (not an install hook; `bash vendor/update-postgres.sh --check` verifies it), consumed by `PostgresEngine.runUnsafe` through `#postgres`. Abortable reservations settle atomically; shared transaction queues isolate cancellable SQL from tagged/savepoint siblings while preserving unfenced pipelining. A pooled connection (pool `max` above 1) or a released reservation whose last ReadyForQuery status is not idle is terminated instead of reused, and the `onpoisoned(status)` option reports it (pinned by `test/e2e/postgres-poisoned-connection.test.ts`). See [PostgreSQL cancellation ownership](../postgres-cancellation.md) for settlement, deadline, transport and clean-install invariants. Pinned by `test/e2e/persistence-chaos.test.ts`. The patch also shares each pool's described parameter types across its connections (`shared_types`; `db.resolveSharedTypes()` reads the `GBRAIN_PG_TYPE_CACHE=0` kill switch at the four pool construction sites, `db.clearSharedTypes()` runs after `initSchema` applies migrations), so a first run on another connection, and every run under `prepare: false`, skips the describe round trip; pinned by `test/e2e/postgres-shared-types.test.ts`. #6355: `closed()` settles a startup's internal query (the array-types fetch) and clears its saved error before reconnecting for `initial`, so a backend terminated during startup neither hands the caller's first statement a stale `57P01` on the fresh connection nor leaves an unhandled rejection (`fetchArrayTypes` also swallows its own failure); it clears the pending write buffer and its immediate handle, so a close that catches a buffered statement does not leave the next StartupMessage appended and unscheduled (a pool slot stuck at `CONNECT_TIMEOUT`); pinned by `test/postgres-driver-startup-death.test.ts` against a scripted wire-protocol server. A query cancelled after it was written stays current until its own ReadyForQuery, so its answer is never read for the next query, and rejects `57014` (pinned by `test/e2e/postgres-driver-cancel-pipeline.test.ts`, direct and PgBouncer). A statement answer that arrives with no current query retires the connection with `CONNECTION_DESYNC` and calls `ondesync({ message, connection, statement })`; `PoolIncidentCounter` logs `pg_connection_desync` (pinned by `test/e2e/postgres-driver-desync-tripwire.test.ts`).- `src/core/pg-type-cache.ts` — the store `shared_types` uses: one `SharedParameterTypes` Map per database target in this process (`sharedParameterTypes(url)`), keyed by SHA-256 digests of the driver's (types, SQL) key, and saved under `<gbrain home>/cache/pg-types/` (0600) for the next process. `db.checkPoolAndLoadSharedTypes` reads its scope (`server_version_num`, `config.version`, and the database as the server names it, so a proxy and a direct URL share a file) in each new pool's connection check and loads it; a different scope is ignored and replaced, a migration's `clearSharedTypes` deletes the file. `GBRAIN_PG_TYPE_CACHE_PERSIST=0` keeps it in-process. Pinned by `test/pg-type-cache.test.ts` and the new-process case in `test/e2e/postgres-shared-types.test.ts`.- `src/core/engine-sql/` — one SQL implementation per migrated storage domain (the domains are the `migrated` rows of `scripts/engine-sql-baseline.tsv`), run by both engines through one executor contract:diff --git a/llms-full.txt b/llms-full.txtindex b09c2baef0..eff0183851 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -5817,6 +5817,20 @@ engine; `/health?deep=1` reports them as `stuck_discards`. Retry the failedcall; if the line repeats, run `gbrain doctor --json` and report the warn lineswith the operations that preceded them.+<a id="pg-connection-desync"></a>**`pg_connection_desync`** (warn). A statement's+answer (columns, rows, a completion, a parse or bind acknowledgement, or a+statement error) arrived on a pooled connection with no statement waiting for+it, so the client and the server no longer agreed on which answer belonged to+which statement. The vendored driver retired that connection, statements+queued on it failed with a connection error, and the pool reconnected on its+own. The line names the pool, the message type, the driver's connection id and+the last statement written on it by first keyword and table, never its text or+parameters. Notices, notifications and parameter changes never trigger it.+`getPoolDiagnostics().desyncDiscards` counts retirements per engine;+`/health?deep=1` reports them as `desync_discards`.+Retry the failed call; if the line repeats, run `gbrain doctor --json` and+report the warn lines.+<a id="pg-statement-build-failed"></a>**`pg_statement_build_failed`** (warn). Astatement could not be built from its parameters (`error=UNDEFINED_VALUE`: aparameter was `undefined`; `error=MAX_PARAMETERS_EXCEEDED`: more than 65534@@ -5855,7 +5869,7 @@ probe does not return in time, when `inflight_oldest_ms` is past the readpool's in-flight budget, or when an earlier deep probe is still pending (onedeep probe per engine at a time). Its body carries the pool block:`{ checked_out, max, waiters, inflight_oldest_ms, completed, poisoned_discards,-stuck_discards, build_failures }`. It is cheap enough for a two-minute cron. The+stuck_discards, build_failures, desync_discards }`. It is cheap enough for a two-minute cron. Thesame pool numbers ride the persistence consumer's heartbeat row, so`gbrain sources writer status --json` shows `pool.inflight_oldest_ms` for theowner process.diff --git a/patches/[email protected] b/patches/[email protected]index 53b611a64e..60b33005bc 100644--- a/patches/[email protected]+++ b/patches/[email protected]@@ -1,5 +1,5 @@diff --git a/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js-index 07f67167..fd279e5d 100644+index 07f67167..f4afd61d 100644--- a/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -15,7 +15,7 @@ index 07f67167..fd279e5d 100644}-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {-+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop, ondesync = noop } = {}) {const {sslnegotiation,ssl,@@ -33,16 +33,17 @@ index 07f67167..fd279e5d 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -95,6 +100,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -95,6 +100,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, rows = 0, serverSignature = null, nextWriteTimer = null+ , lastWritten = null++ , lastExecuted = null+ , deferredRetries = [], terminated = false, incomings = null, results = null-@@ -105,11 +112,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +113,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null@@ -56,7 +57,7 @@ index 07f67167..fd279e5d 100644connect(query) {initial = queryreconnect()-@@ -143,11 +152,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +153,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -72,7 +73,7 @@ index 07f67167..fd279e5d 100644} catch (error) {reject(error)}-@@ -167,21 +178,71 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -167,21 +179,72 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.state = backendquery? sent.push(q)@@ -81,6 +82,7 @@ index 07f67167..fd279e5d 100644build(q)+ lastWritten = q++ lastExecuted = q+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst@@ -148,7 +150,7 @@ index 07f67167..fd279e5d 100644function toBuffer(q) {if (q.parameters.length >= 65534)throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +296,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +298,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -166,7 +168,7 @@ index 07f67167..fd279e5d 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +361,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +363,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -179,7 +181,7 @@ index 07f67167..fd279e5d 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +446,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,15 +448,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -201,7 +203,7 @@ index 07f67167..fd279e5d 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +511,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +513,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -241,7 +243,55 @@ index 07f67167..fd279e5d 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -533,8 +625,14 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose++ /* Handlers */+ function handle(xs, x = xs[0]) {++ if (!query && !initial && !stream && answersStatement(xs, x)) {++ desynced(x)++ return++ }+ (+ x === 68 ? DataRow : // D+ x === 100 ? CopyData : // d+@@ -489,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ )(xs)+ }+++ // GBrain: a message that answers a statement (its columns, rows, completion, parse/bind acknowledgements or a++ // statement error) arriving when no statement is waiting for one means the client and the server no longer++ // agree on which answer belongs to which statement: every later answer on this connection would be read for++ // the wrong query. The connection is retired and everything queued on it fails with CONNECTION_DESYNC.++ // Notices, parameter changes, notifications, ReadyForQuery and a FATAL/PANIC error legitimately arrive++ // without a statement and pass through.++ function answersStatement(xs, x) {++ if (x === 84 || x === 68 || x === 67 || x === 73 || x === 49 || x === 50 || x === 116 || x === 110)++ return true++ if (x !== 69)++ return false++ const fields = parseError(xs)++ const severity = fields.severity || fields.severity_local++ return severity !== 'FATAL' && severity !== 'PANIC'++ }++++ function desynced(x) {++ const s = socket++ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }++ error(Errors.connection('CONNECTION_DESYNC', options, socket))++ query = null++ connection.inflightSince = 0++ ondesync(connection, info)++ terminate()++ if (s && !s.destroyed) {++ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)++ t.unref && t.unref()++ }++ }+++ function DataRow(x) {+ let index = 7+ let length+@@ -533,13 +661,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -255,8 +305,18 @@ index 07f67167..fd279e5d 100644+ query.sharedTypes && options.shared_types.delete(query.typesKey)query.retried? errored(query.retried)- : query.prepared && retryRoutines.has(errorResponse.routine)-@@ -550,6 +648,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+- : query.prepared && retryRoutines.has(errorResponse.routine)++ : query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled+ ? retry(query, errorResponse)+ : errored(errorResponse)++ } else if (query.cancelled) {++ // GBrain: a query cancelled while it waited behind another one on this connection still gets the++ // server's answer to it; that answer is consumed here and the query rejects as cancelled.++ query.reject(Errors.generic('57014', 'canceling statement due to user request'))+ } else {+ query.resolve(results || result)+ }+@@ -550,6 +688,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -264,7 +324,7 @@ index 07f67167..fd279e5d 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +663,27 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +703,33 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -278,11 +338,19 @@ index 07f67167..fd279e5d 100644+ return}- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)--+ flushRetries()+- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the++ // server still sent for it was read for the next query (the next query resolved with another statement's++ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.++ if (sent.length) {++ query = sent.shift()++ query.active = true++ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ }+++ flushRetries()+if (query)- return // Consider opening if able and sent.length < 50+ return armInflight() // Consider opening if able and sent.length < 50@@ -296,7 +364,7 @@ index 07f67167..fd279e5d 100644: connection.reserved(): ending? terminate()-@@ -630,7 +733,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +779,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -308,7 +376,7 @@ index 07f67167..fd279e5d 100644}function RowDescription(x) {-@@ -767,14 +874,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +920,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -338,7 +406,7 @@ index 07f67167..fd279e5d 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +935,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +981,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -357,7 +425,7 @@ index 07f67167..fd279e5d 100644function NotificationResponse(x) {diff --git a/cjs/src/index.js b/vendor/postgres/cjs/src/index.js-index f09c61c7..abb4a158 100644+index f09c61c7..dc7e234d 100644--- a/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js@@ -62,10 +62,34 @@ function Postgres(a, b) {@@ -365,7 +433,7 @@ index f09c61c7..abb4a158 100644, queues = { connecting, reserved, closed, ended, open, busy, full }- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))-+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck, ondesync }))const sql = Sql(handler)@@ -647,7 +715,7 @@ index f09c61c7..abb4a158 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +566,41 @@ function Postgres(a, b) {+@@ -418,12 +566,50 @@ function Postgres(a, b) {: move(c, full)}@@ -660,6 +728,15 @@ index f09c61c7..abb4a158 100644+ } catch (_) {}+ }+++ // GBrain: a connection whose answers no longer match its statements leaves rotation before its socket closes.++ function ondesync(c, info) {++ c.queue !== ended && move(c, ended)++ c.reserved && c.reserved.reject && c.reserved.reject(Errors.generic('CONNECTION_DESYNC', 'The connection was retired: an answer arrived for no statement'))++ try {++ options.ondesync && options.ondesync(info)++ } catch (_) {}++ }+++ function poisoned(c) {+ if (c.queue === ended)+ return@@ -690,7 +767,7 @@ index f09c61c7..abb4a158 100644}}-@@ -444,7 +621,7 @@ function parseOptions(a, b) {+@@ -444,7 +630,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')@@ -699,7 +776,7 @@ index f09c61c7..abb4a158 100644const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +630,7 @@ function parseOptions(a, b) {+@@ -453,6 +639,7 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,@@ -707,13 +784,14 @@ index f09c61c7..abb4a158 100644backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +669,15 @@ function parseOptions(a, b) {+@@ -491,11 +678,16 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,+ onpoisoned : o.onpoisoned,+ onstuck : o.onstuck,+ onbuilderror : o.onbuilderror,++ ondesync : o.ondesync,+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,@@ -781,7 +859,7 @@ index 8438f5da..c444310f 100644const out = xs[index++]diff --git a/src/connection.js b/vendor/postgres/src/connection.js-index 1b1cccde..f570aaab 100644+index 1b1cccde..814037bc 100644--- a/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -20,6 +20,7 @@ const Sync = b().S().end()@@ -797,7 +875,7 @@ index 1b1cccde..f570aaab 100644}-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {-+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop, ondesync = noop } = {}) {const {sslnegotiation,ssl,@@ -815,16 +893,17 @@ index 1b1cccde..f570aaab 100644, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0)-@@ -95,6 +100,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -95,6 +100,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, rows = 0, serverSignature = null, nextWriteTimer = null+ , lastWritten = null++ , lastExecuted = null+ , deferredRetries = [], terminated = false, incomings = null, results = null-@@ -105,11 +112,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -105,11 +113,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, ended = null, nonce = null, query = null@@ -838,7 +917,7 @@ index 1b1cccde..f570aaab 100644connect(query) {initial = queryreconnect()-@@ -143,11 +152,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -143,11 +153,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}async function cancel({ pid, secret }, resolve, reject) {@@ -854,7 +933,7 @@ index 1b1cccde..f570aaab 100644} catch (error) {reject(error)}-@@ -167,21 +178,71 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -167,21 +179,72 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.state = backendquery? sent.push(q)@@ -863,6 +942,7 @@ index 1b1cccde..f570aaab 100644build(q)+ lastWritten = q++ lastExecuted = q+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst@@ -930,7 +1010,7 @@ index 1b1cccde..f570aaab 100644function toBuffer(q) {if (q.parameters.length >= 65534)throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')-@@ -235,10 +296,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -235,10 +298,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseq.onlyDescribe && (delete statements[q.signature])q.parameters = q.parameters || parametersq.prepared = q.prepare && q.signature in statements@@ -948,7 +1028,7 @@ index 1b1cccde..f570aaab 100644typeof options.debug === 'function' && options.debug(id, string, parameters, types)}-@@ -295,10 +361,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -295,10 +363,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* c8 ignore next 3 */function drain() {@@ -961,7 +1041,7 @@ index 1b1cccde..f570aaab 100644if (incomings) {incomings.push(x)remaining -= x.length-@@ -379,15 +446,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -379,15 +448,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function error(err) {@@ -983,7 +1063,7 @@ index 1b1cccde..f570aaab 100644stream && (stream.destroy(err), stream = null)query && queryError(query, err)initial && (queryError(initial, err), initial = null)-@@ -438,19 +511,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -438,19 +513,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseremaining = 0incomings = nullclearImmediate(nextWriteTimer)@@ -1023,7 +1103,55 @@ index 1b1cccde..f570aaab 100644closedTime = performance.now()hadError && options.shared.retries++delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000-@@ -533,8 +625,14 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -459,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose++ /* Handlers */+ function handle(xs, x = xs[0]) {++ if (!query && !initial && !stream && answersStatement(xs, x)) {++ desynced(x)++ return++ }+ (+ x === 68 ? DataRow : // D+ x === 100 ? CopyData : // d+@@ -489,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+ )(xs)+ }+++ // GBrain: a message that answers a statement (its columns, rows, completion, parse/bind acknowledgements or a++ // statement error) arriving when no statement is waiting for one means the client and the server no longer++ // agree on which answer belongs to which statement: every later answer on this connection would be read for++ // the wrong query. The connection is retired and everything queued on it fails with CONNECTION_DESYNC.++ // Notices, parameter changes, notifications, ReadyForQuery and a FATAL/PANIC error legitimately arrive++ // without a statement and pass through.++ function answersStatement(xs, x) {++ if (x === 84 || x === 68 || x === 67 || x === 73 || x === 49 || x === 50 || x === 116 || x === 110)++ return true++ if (x !== 69)++ return false++ const fields = parseError(xs)++ const severity = fields.severity || fields.severity_local++ return severity !== 'FATAL' && severity !== 'PANIC'++ }++++ function desynced(x) {++ const s = socket++ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }++ error(Errors.connection('CONNECTION_DESYNC', options, socket))++ query = null++ connection.inflightSince = 0++ ondesync(connection, info)++ terminate()++ if (s && !s.destroyed) {++ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)++ t.unref && t.unref()++ }++ }+++ function DataRow(x) {+ let index = 7+ let length+@@ -533,13 +661,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose}function ReadyForQuery(x) {@@ -1037,8 +1165,18 @@ index 1b1cccde..f570aaab 100644+ query.sharedTypes && options.shared_types.delete(query.typesKey)query.retried? errored(query.retried)- : query.prepared && retryRoutines.has(errorResponse.routine)-@@ -550,6 +648,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+- : query.prepared && retryRoutines.has(errorResponse.routine)++ : query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled+ ? retry(query, errorResponse)+ : errored(errorResponse)++ } else if (query.cancelled) {++ // GBrain: a query cancelled while it waited behind another one on this connection still gets the++ // server's answer to it; that answer is consumed here and the query rejects as cancelled.++ query.reject(Errors.generic('57014', 'canceling statement due to user request'))+ } else {+ query.resolve(results || result)+ }+@@ -550,6 +688,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery = results = errorResponse = nullresult = new Result()connectTimer.cancel()@@ -1046,7 +1184,7 @@ index 1b1cccde..f570aaab 100644if (initial) {if (target_session_attrs) {-@@ -564,23 +663,27 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -564,23 +703,33 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn fetchArrayTypes()}@@ -1060,11 +1198,19 @@ index 1b1cccde..f570aaab 100644+ return}- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)--+ flushRetries()+- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))+- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the++ // server still sent for it was read for the next query (the next query resolved with another statement's++ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.++ if (sent.length) {++ query = sent.shift()++ query.active = true++ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)++ }+++ flushRetries()+if (query)- return // Consider opening if able and sent.length < 50+ return armInflight() // Consider opening if able and sent.length < 50@@ -1078,7 +1224,7 @@ index 1b1cccde..f570aaab 100644: connection.reserved(): ending? terminate()-@@ -630,7 +733,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -630,7 +779,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))query.prepare && (statements[query.signature] = query.statement)@@ -1090,7 +1236,7 @@ index 1b1cccde..f570aaab 100644}function RowDescription(x) {-@@ -767,14 +874,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -767,14 +920,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, oncloseasync function fetchArrayTypes() {needsTypes = false@@ -1120,7 +1266,7 @@ index 1b1cccde..f570aaab 100644types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))}-@@ -821,7 +935,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose+@@ -821,7 +981,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosefunction retry(q, error) {delete statements[q.signature]q.retried = error@@ -1139,7 +1285,7 @@ index 1b1cccde..f570aaab 100644function NotificationResponse(x) {diff --git a/src/index.js b/vendor/postgres/src/index.js-index c7fba3da..32efd8bf 100644+index c7fba3da..6718a17d 100644--- a/src/index.js+++ b/vendor/postgres/src/index.js@@ -62,10 +62,34 @@ function Postgres(a, b) {@@ -1147,7 +1293,7 @@ index c7fba3da..32efd8bf 100644, queues = { connecting, reserved, closed, ended, open, busy, full }- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))-+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck, ondesync }))const sql = Sql(handler)@@ -1429,7 +1575,7 @@ index c7fba3da..32efd8bf 100644if (queries.length === 0)return move(c, open)-@@ -418,12 +566,41 @@ function Postgres(a, b) {+@@ -418,12 +566,50 @@ function Postgres(a, b) {: move(c, full)}@@ -1442,6 +1588,15 @@ index c7fba3da..32efd8bf 100644+ } catch (_) {}+ }+++ // GBrain: a connection whose answers no longer match its statements leaves rotation before its socket closes.++ function ondesync(c, info) {++ c.queue !== ended && move(c, ended)++ c.reserved && c.reserved.reject && c.reserved.reject(Errors.generic('CONNECTION_DESYNC', 'The connection was retired: an answer arrived for no statement'))++ try {++ options.ondesync && options.ondesync(info)++ } catch (_) {}++ }+++ function poisoned(c) {+ if (c.queue === ended)+ return@@ -1472,7 +1627,7 @@ index c7fba3da..32efd8bf 100644}}-@@ -444,7 +621,7 @@ function parseOptions(a, b) {+@@ -444,7 +630,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')@@ -1481,7 +1636,7 @@ index c7fba3da..32efd8bf 100644const defaults = {max : globalThis.Cloudflare ? 3 : 10,ssl : false,-@@ -453,6 +630,7 @@ function parseOptions(a, b) {+@@ -453,6 +639,7 @@ function parseOptions(a, b) {connect_timeout : 30,max_lifetime : max_lifetime,max_pipeline : 100,@@ -1489,13 +1644,14 @@ index c7fba3da..32efd8bf 100644backoff : backoff,keep_alive : 60,prepare : true,-@@ -491,11 +669,15 @@ function parseOptions(a, b) {+@@ -491,11 +678,16 @@ function parseOptions(a, b) {onnotice : o.onnotice,onnotify : o.onnotify,onclose : o.onclose,+ onpoisoned : o.onpoisoned,+ onstuck : o.onstuck,+ onbuilderror : o.onbuilderror,++ ondesync : o.ondesync,+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,@@ -1563,10 +1719,10 @@ index c4ef9716..8fba891b 100644const out = xs[index++]diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts-index 13c3432f..36233121 100644+index 13c3432f..53127d62 100644--- a/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts-@@ -119,6 +119,32 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {+@@ -119,6 +119,37 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {*/publications: stringonclose: (connId: number) => void;@@ -1590,6 +1746,11 @@ index 13c3432f..36233121 100644+ */+ onbuilderror: (code: string, statement: string) => void;+ /**++ * GBrain: called once per connection retired because a statement's answer arrived with no statement++ * waiting for it; `statement` is the last statement written on it, with `$n` placeholders.++ */++ ondesync: (desync: { message: string; connection: number; statement: string }) => void;++ /**+ * GBrain: share the parameter types of a described statement across this pool's+ * connections, so a connection running it for the first time skips the describe+ * round trip and keeps pipelining. Only built-in types are shared.@@ -1599,7 +1760,7 @@ index 13c3432f..36233121 100644backoff: boolean | ((attemptNum: number) => number);max_lifetime: number | null;keep_alive: number | null;-@@ -605,7 +631,7 @@ declare namespace postgres {+@@ -605,7 +636,7 @@ declare namespace postgres {writable(): Promise<Writable>;execute(): this;@@ -1608,7 +1769,7 @@ index 13c3432f..36233121 100644/*** @deprecated `.stream` has been renamed to `.forEach`-@@ -659,6 +685,7 @@ declare namespace postgres {+@@ -659,6 +690,7 @@ declare namespace postgres {| Fragment[]interface UnsafeQueryOptions {@@ -1616,7 +1777,7 @@ index 13c3432f..36233121 100644/*** When executes query as prepared statement.* @default false-@@ -705,6 +732,8 @@ declare namespace postgres {+@@ -705,6 +737,8 @@ declare namespace postgres {options: ParsedOptions<TTypes>;parameters: ConnectionParameters;@@ -1625,7 +1786,7 @@ index 13c3432f..36233121 100644end(options?: { timeout?: number | undefined } | undefined): Promise<void>;-@@ -717,10 +746,11 @@ declare namespace postgres {+@@ -717,10 +751,11 @@ 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>>;@@ -1638,7 +1799,7 @@ index 13c3432f..36233121 100644savepoint<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 +758,7 @@ declare namespace postgres {+@@ -728,6 +763,7 @@ declare namespace postgres {}interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 5a7b5117e9..a3ff305145 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,7 +21,7 @@ src/core/import-file.ts 2025 ratchet +2: pre-publication withdrawal validation;src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3012 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13-src/core/postgres-engine.ts 3014 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13+src/core/postgres-engine.ts 3015 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts)src/core/search/hybrid.ts 1632 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)src/core/types.ts 2271 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)diff --git a/src/core/db.ts b/src/core/db.tsindex f20b946889..50f9886126 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -313,7 +313,10 @@ export interface PoolHealthHooks {onstuck?: (info: StuckConnectionInfo) => void;/** #6383: a statement failed to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`) and was rejected alone. */onbuilderror?: (code: string, statement: string) => void;+ /** An answer arrived on a connection with no statement waiting for it; the driver retired the connection. */+ ondesync?: (info: DesyncConnectionInfo) => void;}+export interface DesyncConnectionInfo { message: string; connection: number; statement: string }const DEFAULT_STUCK_GRACE_MS = 30_000;@@ -351,6 +354,7 @@ export function poolHealthOptions(hooks: PoolHealthHooks | undefined, statementTonpoisoned: hooks?.onpoisoned,onstuck: hooks?.onstuck,onbuilderror: hooks?.onbuilderror,+ ondesync: hooks?.ondesync,inflight_timeout: resolveInflightTimeoutSeconds(statementTimeout),};}diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.tsindex b8d4950c5e..a27325fae5 100644--- a/src/core/pool-gauge.ts+++ b/src/core/pool-gauge.ts@@ -103,6 +103,7 @@ export function formatPoisonedDiscardWarning(pool: 'read' | 'direct', status: stexport class PoolIncidentCounter {private stuck = 0;private buildFailures = 0;+ private desyncs = 0;get stuckCount(): number {return this.stuck;@@ -112,9 +113,13 @@ export class PoolIncidentCounter {return this.buildFailures;}+ get desyncCount(): number {+ return this.desyncs;+ }+/** The driver hooks of one pool, bound to this counter (what an engine passes as `PoolHealthHooks`). */- hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string) => void } {- return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement) => this.recordBuildFailure(pool, code, statement) };+ hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string) => void; ondesync: (info: { message: string; connection: number; statement: string }) => void } {+ return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement) => this.recordBuildFailure(pool, code, statement), ondesync: (info) => this.recordDesync(pool, info) };}recordStuck(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): void {@@ -122,6 +127,11 @@ export class PoolIncidentCounter {try { console.warn(formatStuckConnectionWarning(pool, info)); } catch { /* best-effort */ }}+ recordDesync(pool: 'read' | 'direct', info: { message: string; connection: number; statement: string }): void {+ this.desyncs += 1;+ try { console.warn(formatDesyncWarning(pool, info)); } catch { /* best-effort */ }+ }+recordBuildFailure(pool: 'read' | 'direct', code: string, statement: string): void {this.buildFailures += 1;try { console.warn(formatBuildFailureWarning(pool, code, statement)); } catch { /* best-effort */ }@@ -134,6 +144,13 @@ export function formatStuckConnectionWarning(pool: 'read' | 'direct', info: { ag` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-stuck`;}+export function formatDesyncWarning(pool: 'read' | 'direct', info: { message: string; connection: number; statement: string }): string {+ const message = /^[A-Za-z0-9]$/.test(info.message) ? info.message : '?';+ return `[gbrain] warn code=pg_connection_desync pool=${pool} message=${message} connection=${Math.max(0, info.connection | 0)} sql=${sqlLabel(info.statement).replaceAll(' ', '_')}` ++ ` cause="a statement answer arrived on a connection with no statement waiting for it; the connection was retired and its queued statements failed with a connection error"` ++ ` fix="gbrain doctor --json" docs=docs/ENGINES.md#pg-connection-desync`;+}+export function formatBuildFailureWarning(pool: 'read' | 'direct', code: string, statement: string): string {const safeCode = /^[A-Z_]+$/.test(code) ? code : 'BUILD_FAILED';return `[gbrain] warn code=pg_statement_build_failed error=${safeCode} pool=${pool} sql=${sqlLabel(statement).replaceAll(' ', '_')}` +diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 50e405759c..239a8f9060 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -729,7 +729,7 @@ export class PostgresEngine implements BrainEngine {/** #5801: observe connection acquisition (see CheckoutGauge.onCheckout). Duck-typed like getPoolDiagnostics. */onCheckout(listener: () => void): () => void { return this.checkoutGauge.onCheckout(listener); }- getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; stuckDiscards: number; buildFailures: number; desyncDiscards: number; pool: DriverPoolStats | null; prepare: boolean | null } | null {try {const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;return {@@ -738,6 +738,7 @@ export class PostgresEngine implements BrainEngine {poisonedDiscards: this.poisonedDiscards?.count ?? 0,stuckDiscards: this.poolIncidents?.stuckCount ?? 0,buildFailures: this.poolIncidents?.buildFailureCount ?? 0,+ desyncDiscards: this.poolIncidents?.desyncCount ?? 0,pool: driverPoolStats(this.sql),prepare: (this.sql as unknown as { options?: { prepare?: boolean } }).options?.prepare ?? null,};diff --git a/src/core/postgres-engine/pool-stats.ts b/src/core/postgres-engine/pool-stats.tsindex 595e9d6354..8ec6316cd7 100644--- a/src/core/postgres-engine/pool-stats.ts+++ b/src/core/postgres-engine/pool-stats.ts@@ -51,17 +51,19 @@ export interface PoolHealthSnapshot extends DriverPoolStats {poisoned_discards: number;stuck_discards: number;build_failures: number;+ desync_discards: number;}export function poolHealthSnapshot(engine: unknown): PoolHealthSnapshot | null {try {- const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null; poisonedDiscards?: number; stuckDiscards?: number; buildFailures?: number } | null } | null)?.getPoolDiagnostics?.();+ const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null; poisonedDiscards?: number; stuckDiscards?: number; buildFailures?: number; desyncDiscards?: number } | null } | null)?.getPoolDiagnostics?.();if (!diagnostics?.pool) return null;return {...diagnostics.pool,poisoned_discards: diagnostics.poisonedDiscards ?? 0,stuck_discards: diagnostics.stuckDiscards ?? 0,build_failures: diagnostics.buildFailures ?? 0,+ desync_discards: diagnostics.desyncDiscards ?? 0,};} catch {return null;diff --git a/test/e2e/postgres-driver-cancel-pipeline.test.ts b/test/e2e/postgres-driver-cancel-pipeline.test.tsnew file mode 100644index 0000000000..a3ded43282--- /dev/null+++ b/test/e2e/postgres-driver-cancel-pipeline.test.ts@@ -0,0 +1,60 @@+/**+ * Vendored driver (vendor/postgres): a query cancelled while it waited behind another one on the same connection+ * had already been written to the server. The stock ReadyForQuery loop skipped it, so the answer the server still+ * sent for it was read for the next query: the next query resolved with the cancelled statement's rows (a bare+ * count resolved to []) and the cancelled query never settled. The cancelled query now stays current, absorbs its+ * own answer and rejects as cancelled (57014); every later query reads its own rows. Runs direct and, when+ * GBRAIN_PGBOUNCER_URL is set, through PgBouncer in transaction mode.+ */+import { describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const targets = [['direct', process.env.DATABASE_URL], ['pgbouncer', process.env.GBRAIN_PGBOUNCER_URL]].filter((t): t is [string, string] => !!t[1]);+type Outcome = { value: unknown[] } | { error: string } | { hung: true };+const settle = (p: Promise<Iterable<unknown>>): Promise<Outcome> => Promise.race([p.then(value => ({ value: [...value] }), (error: { code?: string }) => ({ error: error?.code ?? String(error) })),+ new Promise<{ hung: true }>(resolve => setTimeout(() => resolve({ hung: true }), 5_000))]);++describe.skipIf(targets.length === 0)('vendored driver: a query cancelled while queued behind another on one connection', () => {+ for (const [target, databaseUrl] of targets) for (const prepare of [true, false]) {+ for (const second of ["SELECT 'q2' AS who WHERE false", 'SELECT pg_sleep(0.3) AS slept']) {+ test(`the next query reads its own row and the cancelled one rejects 57014 (${target}, prepare ${prepare}, ${second})`, async () => {+ assertSafeE2eDatabaseUrl(databaseUrl);+ const sql = postgres(databaseUrl, { max: 1, prepare, onnotice: () => {} });+ const table = `driver_cancel_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;+ try {+ await sql.unsafe(`CREATE TABLE ${table} (id int PRIMARY KEY); INSERT INTO ${table} VALUES (1)`);+ for (const scope of ['reserved', 'transaction'] as const) {+ const run = async (q: Pick<postgres.Sql, 'unsafe'>): Promise<Record<string, Outcome>> => {+ const q1 = q.unsafe('SELECT pg_sleep(0.2) AS slept').execute();+ const q2 = q.unsafe(second).execute();+ const q3 = q.unsafe(`SELECT count(*)::int AS n FROM ${table}`).execute();+ await new Promise(resolve => setTimeout(resolve, 50));+ expect((q2 as unknown as { active: boolean }).active).toBe(false);+ const cancelled = q2.cancel();+ const [r1, r2, r3] = await Promise.all([settle(q1), settle(q2), settle(q3)]);+ await cancelled;+ const q4 = await settle(q.unsafe("SELECT 'q4' AS who").execute());+ return { r1, r2, r3, q4 };+ };+ const out = scope === 'reserved'+ ? await (async () => { const r = await sql.reserve(); try { return await run(r); } finally { r.release(); } })()+ : await sql.begin(async tx => run(tx)).catch((error: { code?: string }) => ({ txError: error?.code })) as Record<string, unknown>;+ if (scope === 'transaction' && 'txError' in out) {+ expect(out).toEqual({ txError: '57014' });+ continue;+ }+ expect(out.r1).toEqual({ value: [{ slept: '' }] });+ expect(out.r2).toEqual({ error: '57014' });+ expect(out.r3).toEqual({ value: [{ n: 1 }] });+ expect(out.q4).toEqual({ value: [{ who: 'q4' }] });+ }+ expect([...await sql.unsafe(`SELECT count(*)::int AS n FROM ${table}`)] as unknown[]).toEqual([{ n: 1 }]);+ } finally {+ await sql.unsafe(`DROP TABLE IF EXISTS ${table}`).catch(() => {});+ await sql.end();+ }+ }, 30_000);+ }+ }+});diff --git a/test/e2e/postgres-driver-desync-tripwire.test.ts b/test/e2e/postgres-driver-desync-tripwire.test.tsnew file mode 100644index 0000000000..8ea17727e9--- /dev/null+++ b/test/e2e/postgres-driver-desync-tripwire.test.ts@@ -0,0 +1,133 @@+/**+ * Vendored driver (vendor/postgres): a statement's answer (rows, completion, parse/bind acknowledgement, a+ * statement error) that arrives when no statement is waiting for one means every later answer on that connection+ * would be read for the wrong query. The connection is retired, everything queued on it fails with+ * CONNECTION_DESYNC, `ondesync` reports the message type, connection id and last statement, and the pool+ * reconnects. Notices, notifications and parameter changes legitimately arrive with no statement and never trip it.+ */+import { describe, expect, test } from 'bun:test';+import net from 'node:net';+import postgres from '#postgres';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { poolHealthOptions } from '../../src/core/db.ts';+import { PoolIncidentCounter } from '../../src/core/pool-gauge.ts';++const databaseUrl = process.env.DATABASE_URL;+type Desync = { message: string; connection: number; statement: string };++/** A CommandComplete ('C') for a statement nobody sent: the shape a desynced pipeline delivers. */+const strayCommandComplete = () => {+ const tag = Buffer.from('SELECT 1\0');+ const head = Buffer.alloc(5);+ head.write('C', 0);+ head.writeInt32BE(tag.length + 4, 1);+ return Buffer.concat([head, tag]);+};++describe.skipIf(!databaseUrl)('vendored driver: the desync tripwire', () => {+ test('an answer with no statement waiting retires the connection, reports once, and the pool reconnects', async () => {+ assertSafeE2eDatabaseUrl(databaseUrl!);+ const url = new URL(databaseUrl!);+ const sockets: net.Socket[] = [];+ const desyncs: Desync[] = [];+ const sql = postgres(databaseUrl!, {+ max: 1, onnotice: () => {}, ondesync: (info: Desync) => desyncs.push(info),+ socket: () => { const s = net.connect(Number(url.port || 5432), url.hostname); sockets.push(s); return s; },+ } as postgres.Options<Record<string, never>>);+ try {+ expect([...await sql.unsafe('SELECT $1::int AS n', [1])] as unknown[]).toEqual([{ n: 1 }]);+ const reserved = await sql.reserve();+ const slow = reserved.unsafe('SELECT pg_sleep(0.3) AS slept').execute();+ const queued = reserved.unsafe('SELECT 2 AS n').execute();+ await new Promise(resolve => setTimeout(resolve, 50));+ reserved.release();+ const outcomes = await Promise.allSettled([slow, queued]);+ expect(outcomes.map(o => o.status)).toEqual(['fulfilled', 'fulfilled']);+ sockets[0]!.emit('data', strayCommandComplete());+ expect(desyncs).toEqual([{ message: 'C', connection: expect.any(Number), statement: 'SELECT 2 AS n' }]);+ const pipelined = await Promise.allSettled([sql.unsafe('SELECT 3 AS n'), sql.unsafe('SELECT 4 AS n')]);+ expect(pipelined.every(o => o.status === 'fulfilled')).toBe(true);+ expect(sockets.length).toBe(2);+ expect(desyncs).toHaveLength(1);+ } finally {+ await sql.end({ timeout: 1 });+ }+ }, 30_000);++ test('a reserved connection that desyncs refuses every later statement with a typed connection error', async () => {+ assertSafeE2eDatabaseUrl(databaseUrl!);+ const url = new URL(databaseUrl!);+ const sockets: net.Socket[] = [];+ const desyncs: Desync[] = [];+ const sql = postgres(databaseUrl!, {+ max: 1, onnotice: () => {}, ondesync: (info: Desync) => desyncs.push(info),+ socket: () => { const s = net.connect(Number(url.port || 5432), url.hostname); sockets.push(s); return s; },+ } as postgres.Options<Record<string, never>>);+ try {+ const reserved = await sql.reserve();+ expect([...await reserved.unsafe('SELECT 5 AS n')] as unknown[]).toEqual([{ n: 5 }]);+ sockets[0]!.emit('data', strayCommandComplete());+ expect(desyncs).toEqual([{ message: 'C', connection: expect.any(Number), statement: 'SELECT 5 AS n' }]);+ const after = await reserved.unsafe('SELECT 6 AS n').then(() => 'resolved', (e: { code?: string }) => e.code);+ expect(after).toMatch(/^CONNECTION_(DESYNC|DESTROYED)$/);+ reserved.release();+ expect([...await sql.unsafe('SELECT 7 AS n')] as unknown[]).toEqual([{ n: 7 }]);+ expect(sockets.length).toBe(2);+ } finally {+ await sql.end({ timeout: 1 });+ }+ }, 30_000);++ test('LISTEN/NOTIFY, server notices and parameter changes never trip it', async () => {+ assertSafeE2eDatabaseUrl(databaseUrl!);+ const desyncs: Desync[] = [];+ const notices: string[] = [];+ const sql = postgres(databaseUrl!, { max: 2, onnotice: n => notices.push(String(n.message)), ondesync: (info: Desync) => desyncs.push(info) } as postgres.Options<Record<string, never>>);+ const channel = `driver_desync_${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}`;+ try {+ const received: string[] = [];+ const { unlisten } = await sql.listen(channel, payload => { received.push(payload); });+ for (let i = 0; i < 5; i++) await sql.notify(channel, `p${i}`);+ const deadline = Date.now() + 5_000;+ while (received.length < 5 && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));+ expect(received).toEqual(['p0', 'p1', 'p2', 'p3', 'p4']);+ await sql.unsafe("DO $$ BEGIN RAISE NOTICE 'driver desync notice'; END $$");+ await sql.unsafe("SET application_name = 'driver-desync-probe'");+ expect([...await sql.unsafe('SELECT 8 AS n')] as unknown[]).toEqual([{ n: 8 }]);+ await unlisten();+ expect(notices).toContain('driver desync notice');+ expect(desyncs).toEqual([]);+ } finally {+ await sql.end({ timeout: 1 });+ }+ }, 30_000);++ test("gbrain's pool hooks log one pg_connection_desync line per trip, by keyword and table, with no SQL text or parameters", async () => {+ assertSafeE2eDatabaseUrl(databaseUrl!);+ const url = new URL(databaseUrl!);+ const sockets: net.Socket[] = [];+ const counter = new PoolIncidentCounter();+ const sql = postgres(databaseUrl!, {+ max: 1, onnotice: () => {}, ...poolHealthOptions(counter.hooks('direct'), undefined),+ socket: () => { const s = net.connect(Number(url.port || 5432), url.hostname); sockets.push(s); return s; },+ } as postgres.Options<Record<string, never>>);+ const warn = console.warn;+ const lines: string[] = [];+ console.warn = (line: string) => { lines.push(String(line)); };+ try {+ await sql.unsafe("SELECT relname FROM pg_class WHERE relname = $1 AND 'literal-text' <> ''", ['param-value']);+ sockets[0]!.emit('data', strayCommandComplete());+ expect([...await sql.unsafe('SELECT 9 AS n')] as unknown[]).toEqual([{ n: 9 }]);+ } finally {+ console.warn = warn;+ await sql.end({ timeout: 1 });+ }+ const desync = lines.filter(l => l.includes('pg_connection_desync'));+ expect(desync).toHaveLength(1);+ expect(desync[0]).toMatch(/^\[gbrain\] warn code=pg_connection_desync pool=direct message=C connection=\d+ sql=SELECT_pg_class /);+ expect(desync[0]).not.toContain('literal-text');+ expect(desync[0]).not.toContain('param-value');+ expect(desync[0]).not.toContain('relname');+ expect(counter.desyncCount).toBe(1);+ }, 30_000);+});diff --git a/test/pool-health-6383.test.ts b/test/pool-health-6383.test.tsindex 3a9e194bab..b06e9c1fbc 100644--- a/test/pool-health-6383.test.ts+++ b/test/pool-health-6383.test.ts@@ -13,7 +13,7 @@import { describe, expect, test } from 'bun:test';import { gucMilliseconds, poolHealthOptions, resolveInflightTimeoutSeconds } from '../src/core/db.ts';import { withEnv } from './helpers/with-env.ts';-import { formatBuildFailureWarning, formatStuckConnectionWarning, PoolIncidentCounter } from '../src/core/pool-gauge.ts';+import { formatBuildFailureWarning, formatDesyncWarning, formatStuckConnectionWarning, PoolIncidentCounter } from '../src/core/pool-gauge.ts';import { driverPoolStats, poolHealthSnapshot } from '../src/core/postgres-engine/pool-stats.ts';import { formatPoolRecoveredInfo, formatPoolStalledWarning, PoolStallWatch } from '../src/core/postgres-engine/pool-stall-watch.ts';import { probeDeepHealth } from '../src/commands/serve-http-metrics.ts';@@ -51,8 +51,10 @@ describe('in-flight budget', () => {test('poolHealthOptions carries the hooks and the budget into postgres.js options', async () => {await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: undefined }, async () => {const onstuck = () => {};- const options = poolHealthOptions({ onstuck }, '5min');+ const ondesync = () => {};+ const options = poolHealthOptions({ onstuck, ondesync }, '5min');expect(options.onstuck).toBe(onstuck);+ expect(options.ondesync).toBe(ondesync);expect(options.onpoisoned).toBeUndefined();expect(options.inflight_timeout).toBe(330);expect(poolHealthOptions(undefined, undefined).inflight_timeout).toBeNull();@@ -74,6 +76,14 @@ describe('warn lines', () => {expect(formatBuildFailureWarning('read', 'weird code', 'SELECT 1')).toContain('error=BUILD_FAILED');});+ test('pg_connection_desync names the message type, the connection and the last statement by keyword and table only', () => {+ const line = formatDesyncWarning('read', { message: 'C', connection: 7, statement: "SELECT enabled FROM persistence_brain WHERE singleton = 1 AND note = 'secret'" });+ expect(line).toContain('[gbrain] warn code=pg_connection_desync pool=read message=C connection=7 sql=SELECT_persistence_brain');+ expect(line).toContain('docs=docs/ENGINES.md#pg-connection-desync');+ expect(line).not.toContain('secret');+ expect(formatDesyncWarning('direct', { message: '\n', connection: -1, statement: '' })).toContain('message=? connection=0');+ });+test('PoolIncidentCounter counts each kind once per report', () => {const counter = new PoolIncidentCounter();const warn = console.warn;@@ -83,6 +93,7 @@ describe('warn lines', () => {counter.recordStuck('read', { age_ms: 1, queued: 0, statement: 'SELECT 1' });counter.recordBuildFailure('read', 'UNDEFINED_VALUE', 'SELECT $1');counter.recordBuildFailure('direct', 'MAX_PARAMETERS_EXCEEDED', 'SELECT $1');+ counter.hooks('read').ondesync({ message: 'D', connection: 3, statement: 'SELECT 1' });} finally {console.warn = warn;}@@ -90,6 +101,8 @@ describe('warn lines', () => {expect(counter.buildFailureCount).toBe(2);expect(lines.filter(l => l.includes('pg_connection_stuck'))).toHaveLength(1);expect(lines.filter(l => l.includes('pg_statement_build_failed'))).toHaveLength(2);+ expect(counter.desyncCount).toBe(1);+ expect(lines.filter(l => l.includes('pg_connection_desync'))).toHaveLength(1);});});@@ -102,7 +115,7 @@ function fakeEngine(state: { busy: number; queued: number; completed: number; olpoolMax: 4,poisonedDiscards: 1,stuckDiscards: 2,- buildFailures: 3,+ buildFailures: 3, desyncDiscards: 4,prepare: false,pool: driverPoolStats({ pool: { max: 4, open: 4 - state.busy, busy: state.busy, full: 0, reserved: 0, connecting: 0, closed: 0, ended: 0, queued: state.queued, inflight_oldest_ms: state.oldest, completed: state.completed } }),}),@@ -112,7 +125,7 @@ function fakeEngine(state: { busy: number; queued: number; completed: number; oldescribe('poolHealthSnapshot', () => {test('joins the driver numbers with the engine counters, and is null for an engine without pool numbers', () => {const snapshot = poolHealthSnapshot(fakeEngine({ busy: 1, queued: 2, completed: 10, oldest: 250 }));- expect(snapshot).toEqual({ checked_out: 1, max: 4, waiters: 2, inflight_oldest_ms: 250, completed: 10, poisoned_discards: 1, stuck_discards: 2, build_failures: 3 });+ expect(snapshot).toEqual({ checked_out: 1, max: 4, waiters: 2, inflight_oldest_ms: 250, completed: 10, poisoned_discards: 1, stuck_discards: 2, build_failures: 3, desync_discards: 4 });expect(poolHealthSnapshot({ kind: 'pglite' })).toBeNull();expect(poolHealthSnapshot({ getPoolDiagnostics: () => { throw new Error('closed'); } })).toBeNull();});@@ -142,7 +155,7 @@ describe('PoolStallWatch', () => {now += 30_000;expect(watch.tick()).toBeNull();expect(lines).toHaveLength(3);- expect(lines[0]).toBe(formatPoolStalledWarning({ checked_out: 1, max: 4, waiters: 0, inflight_oldest_ms: 90_000, completed: 11, poisoned_discards: 1, stuck_discards: 2, build_failures: 3 }, 60_000));+ expect(lines[0]).toBe(formatPoolStalledWarning({ checked_out: 1, max: 4, waiters: 0, inflight_oldest_ms: 90_000, completed: 11, poisoned_discards: 1, stuck_discards: 2, build_failures: 3, desync_discards: 4 }, 60_000));expect(lines[0]).toContain('code=pg_pool_stalled checked_out=1 max=4 waiters=0 inflight_oldest_ms=90000 completed_delta=0 stalled_ms=60000');expect(lines[1]).toContain('stalled_ms=90000');expect(lines[2]).toBe(formatPoolRecoveredInfo(120_000, 1));diff --git a/test/postgres-driver-vendor.test.ts b/test/postgres-driver-vendor.test.tsindex 0f0213e563..636488561d 100644--- a/test/postgres-driver-vendor.test.ts+++ b/test/postgres-driver-vendor.test.ts@@ -35,6 +35,11 @@ describe('vendored Postgres driver packaging', () => {expect(index).toContain('completed.cancelPromise');expect(index).toContain('return poisoned(c)');expect(index).toContain('cancelActive(query, resolve, reject, Math.min(delay * 2, 1000))');+ expect(index).toContain('function ondesync(c, info)');+ const connection = readFileSync(new URL(`../vendor/postgres/${path}/connection.js`, import.meta.url), 'utf8');+ expect(connection).not.toContain('while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))');+ expect(connection).toContain('} else if (query.cancelled) {');+ expect(connection).toContain('function answersStatement(xs, x)');}});});diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.jsindex dd1590db54..2473a23172 100644--- a/vendor/postgres/cf/src/connection.js+++ b/vendor/postgres/cf/src/connection.js@@ -52,7 +52,7 @@ const errorFields = {82 : 'routine' // R}-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop, ondesync = noop } = {}) {const {sslnegotiation,ssl,@@ -103,6 +103,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, serverSignature = null, nextWriteTimer = null, lastWritten = null+ , lastExecuted = null, deferredRetries = [], terminated = false, incomings = null@@ -184,6 +185,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)lastWritten = q+ lastExecuted = qconst mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst@@ -553,6 +555,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {+ if (!query && !initial && !stream && answersStatement(xs, x)) {+ desynced(x)+ return+ }(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d@@ -583,6 +589,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}+ // GBrain: a message that answers a statement (its columns, rows, completion, parse/bind acknowledgements or a+ // statement error) arriving when no statement is waiting for one means the client and the server no longer+ // agree on which answer belongs to which statement: every later answer on this connection would be read for+ // the wrong query. The connection is retired and everything queued on it fails with CONNECTION_DESYNC.+ // Notices, parameter changes, notifications, ReadyForQuery and a FATAL/PANIC error legitimately arrive+ // without a statement and pass through.+ function answersStatement(xs, x) {+ if (x === 84 || x === 68 || x === 67 || x === 73 || x === 49 || x === 50 || x === 116 || x === 110)+ return true+ if (x !== 69)+ return false+ const fields = parseError(xs)+ const severity = fields.severity || fields.severity_local+ return severity !== 'FATAL' && severity !== 'PANIC'+ }++ function desynced(x) {+ const s = socket+ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ error(Errors.connection('CONNECTION_DESYNC', options, socket))+ query = null+ connection.inflightSince = 0+ ondesync(connection, info)+ terminate()+ if (s && !s.destroyed) {+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)+ t.unref && t.unref()+ }+ }+function DataRow(x) {let index = 7let length@@ -637,9 +673,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery.sharedTypes && options.shared_types.delete(query.typesKey)query.retried? errored(query.retried)- : query.prepared && retryRoutines.has(errorResponse.routine)+ : query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled? retry(query, errorResponse): errored(errorResponse)+ } else if (query.cancelled) {+ // GBrain: a query cancelled while it waited behind another one on this connection still gets the+ // server's answer to it; that answer is consumed here and the query rejects as cancelled.+ query.reject(Errors.generic('57014', 'canceling statement due to user request'))} else {query.resolve(results || result)}@@ -673,8 +713,14 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn}- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ if (sent.length) {+ query = sent.shift()+ query.active = true+ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ }flushRetries()diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.jsindex 81c46a3c8b..ae8b031749 100644--- a/vendor/postgres/cf/src/index.js+++ b/vendor/postgres/cf/src/index.js@@ -63,7 +63,7 @@ function Postgres(a, b) {, full = Queue(), queues = { connecting, reserved, closed, ended, open, busy, full }- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck, ondesync }))const sql = Sql(handler)@@ -576,6 +576,15 @@ function Postgres(a, b) {} catch (_) {}}+ // GBrain: a connection whose answers no longer match its statements leaves rotation before its socket closes.+ function ondesync(c, info) {+ c.queue !== ended && move(c, ended)+ c.reserved && c.reserved.reject && c.reserved.reject(Errors.generic('CONNECTION_DESYNC', 'The connection was retired: an answer arrived for no statement'))+ try {+ options.ondesync && options.ondesync(info)+ } catch (_) {}+ }+function poisoned(c) {if (c.queue === ended)return@@ -673,6 +682,7 @@ function parseOptions(a, b) {onpoisoned : o.onpoisoned,onstuck : o.onstuck,onbuilderror : o.onbuilderror,+ ondesync : o.ondesync,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.jsindex fd279e5d28..f4afd61d48 100644--- a/vendor/postgres/cjs/src/connection.js+++ b/vendor/postgres/cjs/src/connection.js@@ -50,7 +50,7 @@ const errorFields = {82 : 'routine' // R}-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop, ondesync = noop } = {}) {const {sslnegotiation,ssl,@@ -101,6 +101,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, serverSignature = null, nextWriteTimer = null, lastWritten = null+ , lastExecuted = null, deferredRetries = [], terminated = false, incomings = null@@ -182,6 +183,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)lastWritten = q+ lastExecuted = qconst mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst@@ -551,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {+ if (!query && !initial && !stream && answersStatement(xs, x)) {+ desynced(x)+ return+ }(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d@@ -581,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}+ // GBrain: a message that answers a statement (its columns, rows, completion, parse/bind acknowledgements or a+ // statement error) arriving when no statement is waiting for one means the client and the server no longer+ // agree on which answer belongs to which statement: every later answer on this connection would be read for+ // the wrong query. The connection is retired and everything queued on it fails with CONNECTION_DESYNC.+ // Notices, parameter changes, notifications, ReadyForQuery and a FATAL/PANIC error legitimately arrive+ // without a statement and pass through.+ function answersStatement(xs, x) {+ if (x === 84 || x === 68 || x === 67 || x === 73 || x === 49 || x === 50 || x === 116 || x === 110)+ return true+ if (x !== 69)+ return false+ const fields = parseError(xs)+ const severity = fields.severity || fields.severity_local+ return severity !== 'FATAL' && severity !== 'PANIC'+ }++ function desynced(x) {+ const s = socket+ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ error(Errors.connection('CONNECTION_DESYNC', options, socket))+ query = null+ connection.inflightSince = 0+ ondesync(connection, info)+ terminate()+ if (s && !s.destroyed) {+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)+ t.unref && t.unref()+ }+ }+function DataRow(x) {let index = 7let length@@ -635,9 +671,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery.sharedTypes && options.shared_types.delete(query.typesKey)query.retried? errored(query.retried)- : query.prepared && retryRoutines.has(errorResponse.routine)+ : query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled? retry(query, errorResponse): errored(errorResponse)+ } else if (query.cancelled) {+ // GBrain: a query cancelled while it waited behind another one on this connection still gets the+ // server's answer to it; that answer is consumed here and the query rejects as cancelled.+ query.reject(Errors.generic('57014', 'canceling statement due to user request'))} else {query.resolve(results || result)}@@ -671,8 +711,14 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn}- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ if (sent.length) {+ query = sent.shift()+ query.active = true+ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ }flushRetries()diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.jsindex abb4a15856..dc7e234da4 100644--- a/vendor/postgres/cjs/src/index.js+++ b/vendor/postgres/cjs/src/index.js@@ -62,7 +62,7 @@ function Postgres(a, b) {, full = Queue(), queues = { connecting, reserved, closed, ended, open, busy, full }- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck, ondesync }))const sql = Sql(handler)@@ -575,6 +575,15 @@ function Postgres(a, b) {} catch (_) {}}+ // GBrain: a connection whose answers no longer match its statements leaves rotation before its socket closes.+ function ondesync(c, info) {+ c.queue !== ended && move(c, ended)+ c.reserved && c.reserved.reject && c.reserved.reject(Errors.generic('CONNECTION_DESYNC', 'The connection was retired: an answer arrived for no statement'))+ try {+ options.ondesync && options.ondesync(info)+ } catch (_) {}+ }+function poisoned(c) {if (c.queue === ended)return@@ -672,6 +681,7 @@ function parseOptions(a, b) {onpoisoned : o.onpoisoned,onstuck : o.onstuck,onbuilderror : o.onbuilderror,+ ondesync : o.ondesync,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex f570aaab29..814037bc66 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -50,7 +50,7 @@ const errorFields = {82 : 'routine' // R}-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {+function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop, ondesync = noop } = {}) {const {sslnegotiation,ssl,@@ -101,6 +101,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose, serverSignature = null, nextWriteTimer = null, lastWritten = null+ , lastExecuted = null, deferredRetries = [], terminated = false, incomings = null@@ -182,6 +183,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosebuild(q)lastWritten = q+ lastExecuted = qconst mayPipeline = !q.options.onexecute || q.options.onexecute(connection)return write(toBuffer(q))&& !q.describeFirst@@ -551,6 +553,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose/* Handlers */function handle(xs, x = xs[0]) {+ if (!query && !initial && !stream && answersStatement(xs, x)) {+ desynced(x)+ return+ }(x === 68 ? DataRow : // Dx === 100 ? CopyData : // d@@ -581,6 +587,36 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose)(xs)}+ // GBrain: a message that answers a statement (its columns, rows, completion, parse/bind acknowledgements or a+ // statement error) arriving when no statement is waiting for one means the client and the server no longer+ // agree on which answer belongs to which statement: every later answer on this connection would be read for+ // the wrong query. The connection is retired and everything queued on it fails with CONNECTION_DESYNC.+ // Notices, parameter changes, notifications, ReadyForQuery and a FATAL/PANIC error legitimately arrive+ // without a statement and pass through.+ function answersStatement(xs, x) {+ if (x === 84 || x === 68 || x === 67 || x === 73 || x === 49 || x === 50 || x === 116 || x === 110)+ return true+ if (x !== 69)+ return false+ const fields = parseError(xs)+ const severity = fields.severity || fields.severity_local+ return severity !== 'FATAL' && severity !== 'PANIC'+ }++ function desynced(x) {+ const s = socket+ const info = { message: String.fromCharCode(x), connection: id, statement: lastExecuted ? statementText(lastExecuted) : '' }+ error(Errors.connection('CONNECTION_DESYNC', options, socket))+ query = null+ connection.inflightSince = 0+ ondesync(connection, info)+ terminate()+ if (s && !s.destroyed) {+ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)+ t.unref && t.unref()+ }+ }+function DataRow(x) {let index = 7let length@@ -635,9 +671,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosequery.sharedTypes && options.shared_types.delete(query.typesKey)query.retried? errored(query.retried)- : query.prepared && retryRoutines.has(errorResponse.routine)+ : query.prepared && retryRoutines.has(errorResponse.routine) && !query.cancelled? retry(query, errorResponse): errored(errorResponse)+ } else if (query.cancelled) {+ // GBrain: a query cancelled while it waited behind another one on this connection still gets the+ // server's answer to it; that answer is consumed here and the query rejects as cancelled.+ query.reject(Errors.generic('57014', 'canceling statement due to user request'))} else {query.resolve(results || result)}@@ -671,8 +711,14 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclosereturn}- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ // GBrain: the stock loop skipped a query cancelled while it waited behind another one, so the answer the+ // server still sent for it was read for the next query (the next query resolved with another statement's+ // rows, and the cancelled one never settled). The cancelled query stays current and absorbs its own answer.+ if (sent.length) {+ query = sent.shift()+ query.active = true+ query.cancelled && Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)+ }flushRetries()diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.jsindex 32efd8bf11..6718a17dd8 100644--- a/vendor/postgres/src/index.js+++ b/vendor/postgres/src/index.js@@ -62,7 +62,7 @@ function Postgres(a, b) {, full = Queue(), queues = { connecting, reserved, closed, ended, open, busy, full }- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))+ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck, ondesync }))const sql = Sql(handler)@@ -575,6 +575,15 @@ function Postgres(a, b) {} catch (_) {}}+ // GBrain: a connection whose answers no longer match its statements leaves rotation before its socket closes.+ function ondesync(c, info) {+ c.queue !== ended && move(c, ended)+ c.reserved && c.reserved.reject && c.reserved.reject(Errors.generic('CONNECTION_DESYNC', 'The connection was retired: an answer arrived for no statement'))+ try {+ options.ondesync && options.ondesync(info)+ } catch (_) {}+ }+function poisoned(c) {if (c.queue === ended)return@@ -672,6 +681,7 @@ function parseOptions(a, b) {onpoisoned : o.onpoisoned,onstuck : o.onstuck,onbuilderror : o.onbuilderror,+ ondesync : o.ondesync,shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),onparameter : o.onparameter,socket : o.socket,diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.tsindex 3623312172..53127d627f 100644--- a/vendor/postgres/types/index.d.ts+++ b/vendor/postgres/types/index.d.ts@@ -138,6 +138,11 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {* `statement` is its text with `$n` placeholders, never parameter values.*/onbuilderror: (code: string, statement: string) => void;+ /**+ * GBrain: called once per connection retired because a statement's answer arrived with no statement+ * waiting for it; `statement` is the last statement written on it, with `$n` placeholders.+ */+ ondesync: (desync: { message: string; connection: number; statement: string }) => void;/*** GBrain: share the parameter types of a described statement across this pool's* connections, so a connection running it for the first time skips the describe