Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(persistence): send the protocol declaration with BEGIN behind a transaction-mode pooler (GBRA-156)

garrytan11b4aff56b89
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 1a4b2bb8a0..16a2cfc28d 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -44,7 +44,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection. A lock holder that is not a serve and answers no owner socket (a concurrent CLI call) is not a resident owner: `maybeDelegateLocalOperation` returns unhandled and the engine path waits for the PGLite lock instead of answering `owner_unavailable`; a serve holder or an answering socket keeps every failure final. Owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. For an op that owns a `source` param (`opOwnsSource`, `src/core/ops/contract.ts`), `params.source` stays on the wire as the op's own value (provenance) and routing comes from the ambient tiers, as on the direct and thin-client CLI routes (`test/cli-op-owned-source.test.ts`). The production provider dispatches the trusted `local_cli` principal's allow-listed skill-administration ops with the `'stdio'` locality marker, so the four `localOnly` ones (`get_skill_retention`, `prune_skill_revisions`, `retain_skill_revision`, `import_skill_proposal`) work while a serve owns the brain, as do `takes_remove` and `takes_rebuild` (`LOCAL_CLI_LOCAL_ONLY_OPS`) for the `local_cli` principal (write scope still checked; `gbrain takes remove` and `gbrain takes rebuild` defer their engine like the other takes verbs); other local calls keep no marker (`test/persistence-local-only-ops.test.ts`). `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` (over 24 MiB: `body-digests.ts`) and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. FENCE REPAIR RECEIPT: `fence_repair` is a reserved `put_page` param; `preparePageAdmission` refuses it (`invalid_params`) on every operation unless the call is a trusted local (`ctx.remote === false`) `put_page` whose value `parseFenceRepairReceipt` accepts; `page-prepare.ts` re-parses it from the stored intent, returns it in the outcome as `fence_repair` and gives the page's file target the `fenceRepairCommit` note for its source-relative path. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode` and `commit`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
-- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).
+- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`). GBRA-156: `isPersistenceDeclaration` accepts exactly these declarations (transaction-local `set_config` calls and the brain row FOR SHARE). Admission, the FIFO claim, the effect claims and source guards, the receipt true-up and `publicationTransaction` pass it as `TransactionOptions.pipelineFirst`, so behind a transaction-mode pooler the declaration goes out with BEGIN (one round trip less per transaction) while every later statement still waits for BEGIN's answer; if BEGIN fails, only the declaration has run, in autocommit, where it changes nothing. Tests: `test/persistence-pipeline-first.test.ts` (the predicate and the reviewed call sites), `test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`.
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (`mayReprepare`: `revision_conflict` or, #5385 [R13], `revision_required`, both only when the caller named no `expected_revision`); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The `add_timeline_entry` receipt carries `bullet`, the rendered Markdown line (#5970): there is no update/remove verb because the page is the system of record, so the caller corrects an entry by editing that line with `edit_page` and the row follows the page (both timeline op descriptions say so; `test/timeline-correction-path-5970.test.ts`). #5251: `add_tag` / `remove_tag` prepare with `deferEmbedding: true` (a tag change leaves every chunk's text as it was, so no `embedding` effect is queued and `embedding_state` reads `deferred`; the stale sweep still covers any chunk the republication left without a vector); the full page republication they ride stays, so the issue stays open. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
diff --git a/patches/[email protected] b/patches/[email protected]
index 3151eaef9b..988d1eaeaa 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -684,7 +684,7 @@ index 07f6716..2978d0b 100644
seconds = typeof seconds === 'function' ? seconds() : seconds
if (!seconds)
diff --git a/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
-index f09c61c..97d3e55 100644
+index f09c61c..4709ad4 100644
--- a/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -62,10 +62,36 @@ function Postgres(a, b) {
@@ -725,7 +725,7 @@ index f09c61c..97d3e55 100644
Object.assign(sql, {
get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
-@@ -200,40 +226,181 @@ function Postgres(a, b) {
+@@ -200,58 +226,233 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -923,10 +923,49 @@ index f09c61c..97d3e55 100644
async function begin(options, fn) {
!fn && (fn = options, options = '')
- const queries = Queue()
++ // GBrain (#6930): `{ first }` opts one transaction in to sending its first statement right behind BEGIN, before
++ // BEGIN's answer, on a pool that pipelines inside transactions (transaction_pipeline). Only that one statement, and
++ // only when `first(text)` accepts its text: if BEGIN fails it runs in autocommit, so the caller's test must accept
++ // nothing but a read or a transaction-local set_config (a no-op outside a transaction), never a write. Every
++ // other statement, the first one too when the test refuses it, waits for BEGIN's answer as before, and a failed
++ // BEGIN rejects them unsent. The transaction still settles only after `fn` does.
++ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
++ ? options.first
++ : null
++ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +416,14 @@ function Postgres(a, b) {
++ , opening = null
++ , firstSeen = false
++ , written
+
+ try {
+- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
+- return await Promise.race([
++ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
++ if (!first) {
++ await begun
++ return await Promise.race([
++ scope(connection, fn),
++ new Promise((_, reject) => connection.onclose = reject)
++ ])
++ }
++ await Promise.race([new Promise(resolve => written = resolve), begun])
++ opening = begun.then(() => { opening = null })
++ opening.catch(() => { /* each held statement rejects with BEGIN's error */ })
++ const ran = Promise.race([
+ scope(connection, fn),
+ new Promise((_, reject) => connection.onclose = reject)
+ ])
++ const [opened, result] = await Promise.allSettled([begun, ran])
++ if (opened.status === 'rejected')
++ throw opened.reason
++ if (result.status === 'rejected')
++ throw result.reason
++ return result.value
+ } catch (error) {
+ throw error
}
async function scope(c, fn, name) {
@@ -941,7 +980,7 @@ index f09c61c..97d3e55 100644
let uncaughtError
, result
-@@ -281,6 +453,8 @@ function Postgres(a, b) {
+@@ -281,6 +482,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -950,7 +989,7 @@ index f09c61c..97d3e55 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +464,16 @@ function Postgres(a, b) {
+@@ -290,18 +493,29 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -959,6 +998,18 @@ index f09c61c..97d3e55 100644
- : c.execute(q) || move(c, full)
+ if (!reservation || c.reserved !== reservation)
+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
++ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
++ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
++ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
++ if (opening) {
++ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
++ const early = !firstSeen
++ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
++ && first(strings.reduce((a, s, i) => a + '$' + i + s))
++ firstSeen = true
++ if (!early)
++ return opening.then(() => handler(q), q.reject)
++ }
+ reservation.enqueue(q)
}
}
@@ -970,10 +1021,11 @@ index f09c61c..97d3e55 100644
- ? c.execute(queries.shift())
- : move(c, reserved)
+ own(c)
++ written && written()
}
}
-@@ -351,7 +523,7 @@ function Postgres(a, b) {
+@@ -351,7 +565,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -982,7 +1034,7 @@ index f09c61c..97d3e55 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +534,25 @@ function Postgres(a, b) {
+@@ -362,6 +576,25 @@ function Postgres(a, b) {
})
}
@@ -1008,7 +1060,7 @@ index f09c61c..97d3e55 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +589,14 @@ function Postgres(a, b) {
+@@ -398,7 +631,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -1024,7 +1076,7 @@ index f09c61c..97d3e55 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +616,50 @@ function Postgres(a, b) {
+@@ -418,12 +658,50 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -1076,7 +1128,7 @@ index f09c61c..97d3e55 100644
}
}
-@@ -444,7 +680,7 @@ function parseOptions(a, b) {
+@@ -444,7 +722,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-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
@@ -1085,7 +1137,7 @@ index f09c61c..97d3e55 100644
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
-@@ -453,6 +689,10 @@ function parseOptions(a, b) {
+@@ -453,6 +731,10 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
@@ -1096,7 +1148,7 @@ index f09c61c..97d3e55 100644
backoff : backoff,
keep_alive : 60,
prepare : true,
-@@ -491,11 +731,19 @@ function parseOptions(a, b) {
+@@ -491,11 +773,19 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -1872,7 +1924,7 @@ index 1b1cccd..28f3e50 100644
seconds = typeof seconds === 'function' ? seconds() : seconds
if (!seconds)
diff --git a/src/index.js b/vendor/postgres/src/index.js
-index c7fba3d..36e1db3 100644
+index c7fba3d..abf09ed 100644
--- a/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -62,10 +62,36 @@ function Postgres(a, b) {
@@ -1913,7 +1965,7 @@ index c7fba3d..36e1db3 100644
Object.assign(sql, {
get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
-@@ -200,40 +226,181 @@ function Postgres(a, b) {
+@@ -200,58 +226,233 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -2111,10 +2163,49 @@ index c7fba3d..36e1db3 100644
async function begin(options, fn) {
!fn && (fn = options, options = '')
- const queries = Queue()
++ // GBrain (#6930): `{ first }` opts one transaction in to sending its first statement right behind BEGIN, before
++ // BEGIN's answer, on a pool that pipelines inside transactions (transaction_pipeline). Only that one statement, and
++ // only when `first(text)` accepts its text: if BEGIN fails it runs in autocommit, so the caller's test must accept
++ // nothing but a read or a transaction-local set_config (a no-op outside a transaction), never a write. Every
++ // other statement, the first one too when the test refuses it, waits for BEGIN's answer as before, and a failed
++ // BEGIN rejects them unsent. The transaction still settles only after `fn` does.
++ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
++ ? options.first
++ : null
++ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +416,14 @@ function Postgres(a, b) {
++ , opening = null
++ , firstSeen = false
++ , written
+
+ try {
+- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
+- return await Promise.race([
++ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
++ if (!first) {
++ await begun
++ return await Promise.race([
++ scope(connection, fn),
++ new Promise((_, reject) => connection.onclose = reject)
++ ])
++ }
++ await Promise.race([new Promise(resolve => written = resolve), begun])
++ opening = begun.then(() => { opening = null })
++ opening.catch(() => { /* each held statement rejects with BEGIN's error */ })
++ const ran = Promise.race([
+ scope(connection, fn),
+ new Promise((_, reject) => connection.onclose = reject)
+ ])
++ const [opened, result] = await Promise.allSettled([begun, ran])
++ if (opened.status === 'rejected')
++ throw opened.reason
++ if (result.status === 'rejected')
++ throw result.reason
++ return result.value
+ } catch (error) {
+ throw error
}
async function scope(c, fn, name) {
@@ -2129,7 +2220,7 @@ index c7fba3d..36e1db3 100644
let uncaughtError
, result
-@@ -281,6 +453,8 @@ function Postgres(a, b) {
+@@ -281,6 +482,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -2138,7 +2229,7 @@ index c7fba3d..36e1db3 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +464,16 @@ function Postgres(a, b) {
+@@ -290,18 +493,29 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -2147,6 +2238,18 @@ index c7fba3d..36e1db3 100644
- : c.execute(q) || move(c, full)
+ if (!reservation || c.reserved !== reservation)
+ return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
++ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
++ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
++ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
++ if (opening) {
++ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
++ const early = !firstSeen
++ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
++ && first(strings.reduce((a, s, i) => a + '$' + i + s))
++ firstSeen = true
++ if (!early)
++ return opening.then(() => handler(q), q.reject)
++ }
+ reservation.enqueue(q)
}
}
@@ -2158,10 +2261,11 @@ index c7fba3d..36e1db3 100644
- ? c.execute(queries.shift())
- : move(c, reserved)
+ own(c)
++ written && written()
}
}
-@@ -351,7 +523,7 @@ function Postgres(a, b) {
+@@ -351,7 +565,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -2170,7 +2274,7 @@ index c7fba3d..36e1db3 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +534,25 @@ function Postgres(a, b) {
+@@ -362,6 +576,25 @@ function Postgres(a, b) {
})
}
@@ -2196,7 +2300,7 @@ index c7fba3d..36e1db3 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +589,14 @@ function Postgres(a, b) {
+@@ -398,7 +631,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -2212,7 +2316,7 @@ index c7fba3d..36e1db3 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +616,50 @@ function Postgres(a, b) {
+@@ -418,12 +658,50 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -2264,7 +2368,7 @@ index c7fba3d..36e1db3 100644
}
}
-@@ -444,7 +680,7 @@ function parseOptions(a, b) {
+@@ -444,7 +722,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-line
query.sslrootcert === 'system' && (query.ssl = 'verify-full')
@@ -2273,7 +2377,7 @@ index c7fba3d..36e1db3 100644
const defaults = {
max : globalThis.Cloudflare ? 3 : 10,
ssl : false,
-@@ -453,6 +689,10 @@ function parseOptions(a, b) {
+@@ -453,6 +731,10 @@ function parseOptions(a, b) {
connect_timeout : 30,
max_lifetime : max_lifetime,
max_pipeline : 100,
@@ -2284,7 +2388,7 @@ index c7fba3d..36e1db3 100644
backoff : backoff,
keep_alive : 60,
prepare : true,
-@@ -491,11 +731,19 @@ function parseOptions(a, b) {
+@@ -491,11 +773,19 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -2375,7 +2479,7 @@ index 7c7c2b9..d462498 100644
return '$' + (types.push(
diff --git a/types/index.d.ts b/vendor/postgres/types/index.d.ts
-index 13c3432..aedfb29 100644
+index 13c3432..03a1023 100644
--- a/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -119,6 +119,63 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
@@ -2468,9 +2572,16 @@ index 13c3432..aedfb29 100644
end(options?: { timeout?: number | undefined } | undefined): Promise<void>;
-@@ -717,10 +777,12 @@ declare namespace postgres {
+@@ -716,11 +776,19 @@ 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>>;
++ /**
++ * GBrain (#6930): with transaction_pipeline in force, the first statement `first` accepts (its text, `$n` for
++ * parameters) is sent behind BEGIN before BEGIN's answer. If BEGIN fails it runs in autocommit, so `first` must
++ * accept only a read or a transaction-local set_config, never a write.
++ */
++ begin<T>(options: { mode?: string; first?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
- reserve(): Promise<ReservedSql<TTypes>>
+ reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>
@@ -2482,7 +2593,7 @@ index 13c3432..aedfb29 100644
savepoint<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
savepoint<T>(name: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
-@@ -728,6 +790,8 @@ declare namespace postgres {
+@@ -728,6 +796,8 @@ 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.tsv
index ad2fe6989d..9d025279b3 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
+src/core/engine.ts 2838 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+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 nullable
src/core/operations.ts 242 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); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)
src/core/pglite-engine.ts 3085 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; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)
-src/core/postgres-engine.ts 3108 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 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (a statement sent ahead of COMMIT without waiting, page-state/transactions.ts withCommitChecks); an engine method cannot move
+src/core/postgres-engine.ts 3110 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 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (a statement sent ahead of COMMIT without waiting, page-state/transactions.ts withCommitChecks); an engine method cannot move; +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +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); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +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); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)
src/core/minions/queue.ts 2533 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); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 154bd6c9c5..a36a977b27 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -139,6 +139,13 @@ export interface BatchOpts {
*/
export interface TransactionOptions {
signal?: AbortSignal;
+ /**
+ * GBRA-156: Postgres behind a transaction-mode pooler (transaction pipelining on) sends the transaction's first
+ * statement with BEGIN instead of a round trip later, when this accepts its text. If BEGIN fails that statement runs
+ * in autocommit, so pass only a test that accepts a read or a transaction-local set_config, never a write
+ * (`isPersistenceDeclaration`). Ignored by PGLite and inside a transaction.
+ */
+ pipelineFirst?: (statement: string) => boolean;
}
/** Input row for addLinksBatch. Optional fields default to '' (matches NOT NULL DDL). */
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index fcd955bd74..35cda9f79c 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -12,7 +12,7 @@ import { recordChronicleDecision } from '../chronicle/ledger.ts';
import { isFactsExtractionEnabled } from '../facts/extract.ts';
import { loadConfig } from '../config.ts';
import { resolveDefaultVisibility } from '../facts/visibility.ts';
-import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { declarePersistenceProtocol, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { EXPIRED_PREPARING_CHARGE_SQL } from './claim-phase.ts';
import { refreshFenceClear } from './worktree-refresh-schema.ts';
import { pageBatchChildRequestIds } from './page-batch-id.ts';
@@ -143,7 +143,7 @@ export async function claimPersistenceEffect(engine: BrainEngine, hostId: string
const [claimed] = await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 RETURNING *`, [candidate.id, randomUUID()]);
return claimed;
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
}
/** #5530: an effect that commits exactly one recorded file (not a withdrawal walk or a source scan). */
@@ -249,7 +249,7 @@ export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: stri
UPDATE persistence_effects p SET state='running',execution_token=gen_random_uuid(),
claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now()
FROM ready WHERE p.id=ready.id RETURNING p.*`, [hostId, worktreeId, limit]);
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
return rows.sort((a, b) => Number(a.id) - Number(b.id));
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 99a9a6ee15..55eb6b527d 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -6,7 +6,7 @@ import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targ
import { existsSync, statSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import type { GBrainConfig } from '../config.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -789,7 +789,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);
if (blocked.length) throw recoveryFirst(effect);
}
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);
if (effect.kind === 'git' || effect.kind === 'embedding') attempt.gate = (await mirrorGates(engine, [effect.request_id])).get(effect.request_id);
if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts, attempt);
@@ -924,7 +924,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef
const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);
if (blocked.length) throw recoveryFirst(effect);
return null;
- }).catch(error => error ?? new Error('effect guard failed')));
+ }, { pipelineFirst: isPersistenceDeclaration }).catch(error => error ?? new Error('effect guard failed')));
if (guards.get(key)) throw guards.get(key);
if (!binding.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); continue; }
if (!mirrors.has(effect.source_id)) mirrors.set(effect.source_id, await sourceMirrorReadOnly(engine, effect.source_id));
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 69633168b0..db2414b663 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -25,7 +25,7 @@ import { classifyHolderLiveness, syncLockId } from '../db-lock.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { catalogueError } from '../error-catalogue.ts';
import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';
-import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
+import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, declarePersistenceProtocol, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertGraduationAdmission } from './graduation-custody.ts';
import { schemaAdmissionRefusal } from './schema-admission.ts';
import { CAPACITY_VERIFY } from './capacity-verify.ts';
@@ -241,7 +241,7 @@ export function assertReplayIntent(row: WriteRequest, expectedDigest: string): W
return row;
}
export async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>,
- transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn)): Promise<WriteRequest> {
+ transaction: <T>(fn: (tx: BrainEngine) => Promise<T>) => Promise<T> = fn => engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration })): Promise<WriteRequest> {
const { requestId, apply } = await prepareAdmission(engine, input, overrides);
// #6355: a lent connection (the consumer's warm lane) whose session dropped is dead for every later attempt, so the
// re-run takes a transaction from the engine's pool after the pool itself is rebuilt.
@@ -250,7 +250,7 @@ export async function admitWrite(engine: BrainEngine, input: WriteAdmission, ove
const brain = await declareDurablePersistence(tx, `${Math.min(100, remaining)}ms`, `${remaining}ms`);
if (input.brainId !== undefined && brain !== input.brainId) throw new PreadmitBrainChanged();
return apply(tx);
- }), undefined, async error => { run = fn => engine.transaction(fn); await engine.reconnect({ error }); });
+ }), undefined, async error => { run = fn => engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration }); await engine.reconnect({ error }); });
}
/** Caller owns the transaction and retries its entire unit of work after rollback. */
export async function admitWriteInTransaction(tx: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {
@@ -731,7 +731,7 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM
CASE WHEN ${SYNC_KIND('persistence_requests')} THEN (SELECT max(sequence) FROM persistence_requests)::text END AS seen_sequence`,
[row.id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);
return claimed ? { ...claimed, previous_claim_phase: row.claim_phase } : null;
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
}
/**
* #5984 lanes: claims the head of the next admitted group of lane run `run` in
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index 25bc855184..61e857aad2 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -45,6 +45,19 @@ export async function declareDurablePersistence(tx: SqlEngine, lockTimeout = '1s
return row?.brain ?? null;
}
+const LOCAL_SETTING = String.raw`set_config\('[a-z_.]+',(?:\$\d+|'[^']*'),true\)`;
+const DECLARATION = new RegExp(`^SELECT ${LOCAL_SETTING}(?:,\\s*${LOCAL_SETTING})*(?:,\\s*${BRAIN_SHARE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})?$`);
+/**
+ * GBRA-156: whether `statement` is a declaration this module sends: one SELECT of transaction-local set_config calls,
+ * optionally with the brain row FOR SHARE. Run outside a transaction it changes nothing (a local setting ends with its
+ * statement, and so does the share lock), so a transaction whose first statement it is may send it before BEGIN's
+ * answer (`TransactionOptions.pipelineFirst`): if BEGIN fails, only this statement runs, in autocommit. It accepts no
+ * other text, writes included, and nothing containing `;` (a simple-protocol query may hold several statements).
+ */
+export function isPersistenceDeclaration(statement: string): boolean {
+ return !statement.includes(';') && DECLARATION.test(statement.trim());
+}
+
export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";
export function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | 'protocol_version'>): void {
diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.ts
index 3316df94da..8b7588df82 100644
--- a/src/core/persistence/publication-deadline.ts
+++ b/src/core/persistence/publication-deadline.ts
@@ -21,7 +21,7 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import type { BrainEngine } from '../engine.ts';
import { gucMilliseconds, resolveSessionTimeouts } from '../db.ts';
-import { declareDurablePersistence } from './protocol.ts';
+import { declareDurablePersistence, isPersistenceDeclaration } from './protocol.ts';
export const PUBLICATION_CEILING_KEY = 'persistence.publication_ceiling_ms';
/** `persistence.publication_ceiling_ms`' default (60000 to 3600000 accepted). */
@@ -92,14 +92,15 @@ export async function declarePublication(tx: BrainEngine, bound: Pick<BrainEngin
/**
* `engine.transaction`, passing the current publication's signal on as `{ signal }`. An aborted transaction rejects
* while its body may still be parked, so a rejection waits for the body to settle first: nothing (recovery included)
- * acts on the publication while the body can still rename a file.
+ * acts on the publication while the body can still rename a file. Its bodies open with `declarePublication`, which
+ * goes out with BEGIN (GBRA-156); a body that opens with anything else waits for BEGIN's answer.
*/
export async function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
const signal = signals.getStore();
- if (!signal) return engine.transaction(fn);
+ if (!signal) return engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration });
let body: Promise<unknown> = Promise.resolve();
try {
- return await engine.transaction(tx => { const run = fn(tx); body = run; return run; }, { signal });
+ return await engine.transaction(tx => { const run = fn(tx); body = run; return run; }, { signal, pipelineFirst: isPersistenceDeclaration });
} catch (error) {
await body.then(() => undefined, () => undefined);
const closed = (error as { cause?: { code?: unknown } })?.cause?.code;
diff --git a/src/core/persistence/receipt-true-up.ts b/src/core/persistence/receipt-true-up.ts
index d465e143fd..9c64a1af8c 100644
--- a/src/core/persistence/receipt-true-up.ts
+++ b/src/core/persistence/receipt-true-up.ts
@@ -20,7 +20,7 @@
import type { BrainEngine } from '../engine.ts';
import { lockCounters } from './journal.ts';
import { principalKey, type WriteRequest } from './model.ts';
-import { declarePersistenceProtocol } from './protocol.ts';
+import { declarePersistenceProtocol, isPersistenceDeclaration } from './protocol.ts';
import { EFFECT_BYTES_SQL, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';
type Candidate = Pick<WriteRequest, 'id' | 'intent' | 'authority' | 'outcome' | 'error_message' | 'error_detail' | 'client_request_id'
@@ -61,7 +61,7 @@ export async function trueUpRequests(engine: BrainEngine, requestIds: Iterable<s
SELECT COALESCE(SUM(freed),0)::text AS freed FROM done`,
[shrink.map(s => s.row.id), shrink.map(s => s.old), shrink.map(s => s.kept), shrink.map(s => s.row.effect_bytes)]);
return Number(freed?.freed ?? 0);
- });
+ }, { pipelineFirst: isPersistenceDeclaration });
}
/** Config row: the sequence the one-shot compacted-receipt sweep has walked through (`done` once it reached the end). */
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index b1043d5d20..cce1bc7e53 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -665,7 +665,9 @@ export class PostgresEngine implements BrainEngine {
// .begin), which would skip a chained .finally and leak the counter.
if (!this._pageTransaction) this.checkoutGauge.acquire('tx');
try {
- return await withCommitChecks(checks => withTransactionAbort(opts?.signal, attach => withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => conn.begin(async (handle) => {
+ // GBRA-156: the pool's begin takes `first`; a nested transaction's begin (a savepoint) takes only the callback.
+ const begin = (run: (handle: unknown) => Promise<unknown>) => opts?.pipelineFirst && !this._pageTransaction ? conn.begin({ first: opts.pipelineFirst }, run) : conn.begin(run);
+ return await withCommitChecks(checks => withTransactionAbort(opts?.signal, attach => withHeldPageKeys(this._pageTransaction ? this._heldPageKeys : null, held => begin(async (handle) => {
attach(handle as Discardable);
if (!this._pageTransaction) this.checkoutGauge.checkedOut();
const tx = composablePostgresTransaction(handle);
diff --git a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
index aa826a7268..ceb1b0d0c0 100644
--- a/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
+++ b/test/e2e/pgbouncer-transaction-pipeline-6930.test.ts
@@ -22,6 +22,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import postgres from '#postgres';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { declarePersistenceProtocol, isPersistenceDeclaration } from '../../src/core/persistence/protocol.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { readSqlTrace, type StatementRecord } from '../helpers/statement-counter.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -149,3 +150,131 @@ describe.skipIf(!(pooled && pooledAdmin))('#6930 transaction pipelining through
expect(sentBeforeAnswer(records, /AS switched_off$/)).toEqual([false, false, false]);
}, 60_000);
});
+
+describe.skipIf(!(pooled && pooledAdmin))('GBRA-156: a transaction\'s first statement goes out with BEGIN when the caller opts in', () => {
+ const table = `txn_first_${crypto.randomUUID().replace(/-/g, '').slice(0, 8)}`;
+ const declaration = "SELECT set_config('gbrain.persistence_protocol','2',true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain";
+ beforeAll(async () => {
+ if (!(pooled && pooledAdmin)) return;
+ const admin = postgres(pooledUrl('?prepare=false'), { max: 1, prepare: false, onnotice: () => {} });
+ try {
+ await admin.unsafe('CREATE TABLE IF NOT EXISTS persistence_brain (singleton int PRIMARY KEY, brain_id uuid NOT NULL)');
+ await admin.unsafe("INSERT INTO persistence_brain VALUES (1, gen_random_uuid()) ON CONFLICT DO NOTHING");
+ await admin.unsafe(`CREATE TABLE ${table} (n int)`);
+ } finally { await admin.end(); }
+ }, 60_000);
+ const rows = async (engine: PostgresEngine) => Number((await engine.sql.unsafe(`SELECT count(*)::int AS c FROM ${table}`))[0]!.c);
+
+ test('the declaration is sent before BEGIN\'s answer, the next statement only after it, and both run in the transaction', async () => {
+ let seen: Array<{ protocol: string | null; xid: string; pid: number }> = [];
+ const records = await traced('first-declared', 1, async engine => {
+ seen = await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ return tx.executeRaw<{ protocol: string | null; xid: string; pid: number }>(
+ "SELECT current_setting('gbrain.persistence_protocol', true) AS protocol, txid_current()::text AS xid, pg_backend_pid() AS pid /* after declaration */");
+ }, { pipelineFirst: isPersistenceDeclaration });
+ });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const declared = records.find(r => r.sql === declaration)!;
+ const after = records.find(r => /after declaration \*\/$/.test(r.sql))!;
+ expect(declared.t < end(begin)).toBe(true);
+ expect(after.t >= end(begin)).toBe(true);
+ expect(seen.map(r => r.protocol)).toEqual(['2']);
+ }, 60_000);
+
+ test('a first statement the test refuses (a write) waits for BEGIN\'s answer', async () => {
+ const records = await traced('first-refused', 1, async engine => {
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`INSERT INTO ${table} VALUES (0) /* refused first */`);
+ await tx.executeRaw(`DELETE FROM ${table} WHERE n=0`);
+ }, { pipelineFirst: isPersistenceDeclaration });
+ });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const insert = records.find(r => /refused first \*\/$/.test(r.sql))!;
+ expect(insert.t >= end(begin)).toBe(true);
+ }, 60_000);
+
+ test('a BEGIN that fails runs at most the accepted declaration, in autocommit: no write runs, and the transaction rejects with BEGIN\'s error', async () => {
+ let declaredFirst: string | undefined;
+ let writeFirst: string | undefined;
+ let ranDeclaration = false;
+ let count = -1;
+ let after: unknown;
+ await traced('first-begin-fails', 1, async engine => {
+ // `isolation level bogus` survives begin()'s mode filter and makes the server refuse BEGIN (42601) on a live connection.
+ declaredFirst = await engine.sql.begin({ mode: 'isolation level bogus', first: isPersistenceDeclaration }, async tx => {
+ await tx.unsafe(declaration);
+ ranDeclaration = true;
+ await tx.unsafe(`INSERT INTO ${table} VALUES (1)`);
+ }).then(() => 'none', (e: { code?: string }) => e.code);
+ writeFirst = await engine.sql.begin({ mode: 'isolation level bogus', first: isPersistenceDeclaration }, async tx => {
+ await tx.unsafe(`INSERT INTO ${table} VALUES (2)`);
+ }).then(() => 'none', (e: { code?: string }) => e.code);
+ count = await rows(engine);
+ after = (await engine.sql.unsafe('SELECT 42 AS after_failed_begin'))[0]!.after_failed_begin;
+ });
+ expect(declaredFirst).toBe('42601');
+ expect(ranDeclaration).toBe(true);
+ expect(writeFirst).toBe('42601');
+ expect(count).toBe(0);
+ expect(after).toBe(42);
+ }, 60_000);
+
+ test('accepted text whose argument is a fragment (SQL, not a value) waits for BEGIN\'s answer', async () => {
+ const records = await traced('first-fragment', 1, async engine => {
+ await engine.sql.begin({ first: isPersistenceDeclaration }, async tx => {
+ await tx`SELECT set_config('lock_timeout',${tx.unsafe("(SELECT '1s' FROM pg_sleep(0))")},true)`;
+ await tx.unsafe('SELECT 1 AS after_fragment');
+ });
+ });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const fragment = records.find(r => /pg_sleep\(0\)/.test(r.sql))!;
+ expect(isPersistenceDeclaration("SELECT set_config('lock_timeout',$1,true)")).toBe(true);
+ expect(fragment.t >= end(begin)).toBe(true);
+ }, 60_000);
+
+ test('a callback that swallows a held statement\'s rejection after a failed BEGIN still gets BEGIN\'s error, and nothing past the declaration reaches the socket', async () => {
+ let outcome: string | undefined;
+ let swallowed: unknown;
+ let count = -1;
+ const records = await traced('first-swallowed', 1, async engine => {
+ outcome = await engine.sql.begin({ mode: 'isolation level bogus', first: isPersistenceDeclaration }, async tx => {
+ await tx.unsafe(declaration);
+ swallowed = await tx.unsafe(`INSERT INTO ${table} VALUES (3) /* swallowed */`).then(() => 'sent', (e: { code?: string }) => e.code);
+ return 'returned';
+ }).then(value => `resolved:${String(value)}`, (e: { code?: string }) => e.code);
+ count = await rows(engine);
+ });
+ expect(outcome).toBe('42601');
+ // Rejected unsent: held behind the failed BEGIN (42601), or issued after the failed transaction released its connection.
+ expect(['42601', 'CONNECTION_CLOSED']).toContain(swallowed as string);
+ expect(count).toBe(0);
+ const begin = records.findIndex(r => /^begin isolation level bogus/i.test(r.sql));
+ const next = records.slice(begin + 1).filter(r => r.conn === records[begin]!.conn).map(r => r.sql);
+ expect(next[0]).toBe(declaration);
+ expect(next.slice(1).filter(sql => /swallowed|^commit|^rollback/i.test(sql))).toEqual([]);
+ }, 60_000);
+
+ test('GBRAIN_PG_TXN_PIPELINE=0 keeps the declaration behind BEGIN\'s answer', async () => {
+ const records = await traced('first-off', 1, async engine => {
+ await engine.transaction(tx => declarePersistenceProtocol(tx), { pipelineFirst: isPersistenceDeclaration });
+ }, { GBRAIN_PG_TXN_PIPELINE: '0' });
+ const begin = records.find(r => /^begin\s*$/i.test(r.sql))!;
+ const declared = records.find(r => r.sql === declaration)!;
+ expect(declared.t >= end(begin)).toBe(true);
+ }, 60_000);
+
+ test('a failed single-statement bounded read rolls back at its pipelined COMMIT without an error of its own, and leaves no transaction behind', async () => {
+ let failed: string | undefined;
+ let next: Array<{ timeout: string; fresh: boolean }> = [];
+ const records = await traced('bounded-failed', 1, async engine => {
+ failed = await engine.executeRaw('SELECT 1/0 AS bounded_failure', [], { timeoutMs: 5000 }).then(() => 'none', (e: { code?: string }) => e.code);
+ next = await engine.sql.unsafe("SELECT current_setting('statement_timeout') AS timeout, now() = statement_timestamp() AS fresh") as unknown as typeof next;
+ });
+ expect(sentBeforeAnswer(records, /^BEGIN; SET LOCAL statement_timeout|^SELECT 1\/0 AS bounded_failure$|^COMMIT$/, 3)).toEqual([true, true]);
+ expect(failed).toBe('22012');
+ expect(next.map(r => r.fresh)).toEqual([true]);
+ expect(next[0]!.timeout).not.toBe('5s');
+ }, 60_000);
+});
+
diff --git a/test/persistence-pipeline-first.test.ts b/test/persistence-pipeline-first.test.ts
new file mode 100644
index 0000000000..3d030d182e
--- /dev/null
+++ b/test/persistence-pipeline-first.test.ts
@@ -0,0 +1,74 @@
+/**
+ * GBRA-156: a transaction opted in with `pipelineFirst: isPersistenceDeclaration` sends its first statement with
+ * BEGIN, before BEGIN's answer. If BEGIN fails that statement runs in autocommit, so the test must accept the
+ * declarations protocol.ts sends (transaction-local set_config, the brain row FOR SHARE) and nothing else. The
+ * driver behaviour is proven through PgBouncer by test/e2e/pgbouncer-transaction-pipeline-6930.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { declareDurablePersistence, declarePersistenceProtocol, isPersistenceDeclaration } from '../src/core/persistence/protocol.ts';
+import { declarePublication } from '../src/core/persistence/publication-deadline.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+function recorder(kind = 'postgres'): { engine: BrainEngine; sent: string[] } {
+ const sent: string[] = [];
+ const engine = { kind, executeRaw: async (sql: string) => { sent.push(sql); return [{ brain: null }]; } } as unknown as BrainEngine;
+ return { engine, sent };
+}
+
+describe('isPersistenceDeclaration', () => {
+ test('accepts every declaration protocol.ts and the publication send', async () => {
+ const { engine, sent } = recorder();
+ await declarePersistenceProtocol(engine);
+ await declareDurablePersistence(engine);
+ await declareDurablePersistence(engine, '100ms', '5000ms', '30000ms');
+ await declarePublication(engine);
+ expect(sent.length).toBe(4);
+ expect(sent.map(isPersistenceDeclaration)).toEqual([true, true, true, true]);
+ });
+
+ test('refuses writes, session settings, other locks and anything after the declaration', () => {
+ const share = '(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR SHARE) AS brain';
+ for (const statement of [
+ 'INSERT INTO persistence_requests DEFAULT VALUES',
+ "SELECT set_config('gbrain.persistence_protocol','2',false)",
+ "SELECT set_config('gbrain.persistence_protocol','2',true); DELETE FROM persistence_requests",
+ "SELECT set_config('gbrain.persistence_protocol','2',true),(SELECT brain_id::text FROM persistence_brain WHERE singleton=1 FOR UPDATE) AS brain",
+ "WITH gone AS (DELETE FROM persistence_requests RETURNING 1) SELECT set_config('lock_timeout','1s',true)",
+ "SELECT set_config('lock_timeout',(SELECT 'x'),true)",
+ "SELECT set_config('lock_timeout','1s;',true)",
+ "SELECT set_config('lock_timeout','1s',true);",
+ `SELECT set_config('gbrain.persistence_protocol','2',true),${share},(SELECT 1)`,
+ 'SELECT 1',
+ ]) expect({ statement, accepted: isPersistenceDeclaration(statement) }).toEqual({ statement, accepted: false });
+ });
+});
+
+describe('pipelineFirst call sites', () => {
+ // Each of these opens its transaction with a protocol declaration (journal admitWrite and claimNextWrite, the effect
+ // claims and source guards, the receipt true-up, publicationTransaction). A new opt-in is reviewed here first.
+ test('only the reviewed persistence call sites opt in, and only with isPersistenceDeclaration', () => {
+ const root = join(import.meta.dir, '..', 'src');
+ const found: Record<string, number> = {};
+ const walk = (dir: string): void => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) { walk(path); continue; }
+ if (!name.endsWith('.ts')) continue;
+ const text = readFileSync(path, 'utf8');
+ const uses = text.match(/pipelineFirst:\s*[^,}\s]+/g) ?? [];
+ if (uses.length) found[relative(root, path)] = uses.length;
+ for (const use of uses) expect({ path, use }).toEqual({ path, use: 'pipelineFirst: isPersistenceDeclaration' });
+ }
+ };
+ walk(root);
+ expect(found).toEqual({
+ 'core/persistence/effect-journal.ts': 2,
+ 'core/persistence/effects.ts': 2,
+ 'core/persistence/journal.ts': 3,
+ 'core/persistence/publication-deadline.ts': 2,
+ 'core/persistence/receipt-true-up.ts': 1,
+ });
+ });
+});
diff --git a/test/postgres-driver-vendor-6930.test.ts b/test/postgres-driver-vendor-6930.test.ts
index 7a6c139fde..667f232eb8 100644
--- a/test/postgres-driver-vendor-6930.test.ts
+++ b/test/postgres-driver-vendor-6930.test.ts
@@ -18,9 +18,17 @@ describe('vendored Postgres driver #6930 patch', () => {
const index = readFileSync(new URL('../vendor/postgres/' + path + '/index.js', import.meta.url), 'utf8');
expect(index).toContain("'max_pipeline', 'transaction_pipeline', 'backoff'");
expect(index).toContain('array_types : o.array_types || null,');
+ // GBRA-156: only an opted-in first statement its test accepts goes out before BEGIN's answer, and only with transaction_pipeline on.
+ expect(index).toContain("const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline");
+ expect(index).toContain('const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]');
+ expect(index).toContain('&& q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))');
+ expect(index).toContain("&& first(strings.reduce((a, s, i) => a + '$' + i + s))");
+ expect(index).toMatch(/if \(!early\)\n\s+return opening\.then\(\(\) => handler\(q\), q\.reject\)/);
+ expect(index).toMatch(/const \[opened, result\] = await Promise\.allSettled\(\[begun, ran\]\)\n\s+if \(opened\.status === 'rejected'\)\n\s+throw opened\.reason/);
}
const types = readFileSync(new URL('../vendor/postgres/types/index.d.ts', import.meta.url), 'utf8');
expect(types).toContain('transaction_pipeline: number;');
+ expect(types).toContain('begin<T>(options: { mode?: string; first?: (statement: string) => boolean }');
expect(types).toContain('array_types: { rows: Array<[number, number]> | null } | null;');
});
});
diff --git a/vendor/README.md b/vendor/README.md
index 210ea6f00f..24966fd75f 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -103,6 +103,16 @@ statements never reach that server connection. Default 0 (stock behaviour);
GBrain sets 100 on transaction-mode URLs (#6930,
`test/e2e/pgbouncer-transaction-pipeline-6930.test.ts`).
+With `transaction_pipeline` in force, `sql.begin({ first }, fn)` sends the
+transaction's first statement behind BEGIN before BEGIN's answer when
+`first(text)` accepts its text; every later statement, and a first one the
+test refuses, waits for that answer as stock `begin` does. If BEGIN fails,
+the early statement has run in autocommit and the rest are rejected unsent,
+so the test must accept only a read or a transaction-local `set_config`.
+GBrain passes `isPersistenceDeclaration` (`src/core/persistence/protocol.ts`)
+from the persistence transactions that open with the protocol declaration
+(GBRA-156, same test file).
+
Each statement's row count resets at its ReadyForQuery. Stock postgres.js
resets it only at CommandComplete. A statement that streams rows and then fails
never gets there: a runtime error after its first rows, or a cancel or timeout
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index 4de46d392a..518178f046 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -402,16 +402,45 @@ function Postgres(a, b) {
async function begin(options, fn) {
!fn && (fn = options, options = '')
+ // GBrain (#6930): `{ first }` opts one transaction in to sending its first statement right behind BEGIN, before
+ // BEGIN's answer, on a pool that pipelines inside transactions (transaction_pipeline). Only that one statement, and
+ // only when `first(text)` accepts its text: if BEGIN fails it runs in autocommit, so the caller's test must accept
+ // nothing but a read or a transaction-local set_config (a no-op outside a transaction), never a write. Every
+ // other statement, the first one too when the test refuses it, waits for BEGIN's answer as before, and a failed
+ // BEGIN rejects them unsent. The transaction still settles only after `fn` does.
+ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
+ ? options.first
+ : null
+ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
+ , opening = null
+ , firstSeen = false
+ , written
try {
- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- return await Promise.race([
+ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
+ if (!first) {
+ await begun
+ return await Promise.race([
+ scope(connection, fn),
+ new Promise((_, reject) => connection.onclose = reject)
+ ])
+ }
+ await Promise.race([new Promise(resolve => written = resolve), begun])
+ opening = begun.then(() => { opening = null })
+ opening.catch(() => { /* each held statement rejects with BEGIN's error */ })
+ const ran = Promise.race([
scope(connection, fn),
new Promise((_, reject) => connection.onclose = reject)
])
+ const [opened, result] = await Promise.allSettled([begun, ran])
+ if (opened.status === 'rejected')
+ throw opened.reason
+ if (result.status === 'rejected')
+ throw result.reason
+ return result.value
} catch (error) {
throw error
}
@@ -467,6 +496,18 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
+ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
+ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
+ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ if (opening) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ const early = !firstSeen
+ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
+ && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ firstSeen = true
+ if (!early)
+ return opening.then(() => handler(q), q.reject)
+ }
reservation.enqueue(q)
}
}
@@ -475,6 +516,7 @@ function Postgres(a, b) {
connection = c
move(c, reserved)
own(c)
+ written && written()
}
}
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index 97d3e55406..4709ad4bd9 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -401,16 +401,45 @@ function Postgres(a, b) {
async function begin(options, fn) {
!fn && (fn = options, options = '')
+ // GBrain (#6930): `{ first }` opts one transaction in to sending its first statement right behind BEGIN, before
+ // BEGIN's answer, on a pool that pipelines inside transactions (transaction_pipeline). Only that one statement, and
+ // only when `first(text)` accepts its text: if BEGIN fails it runs in autocommit, so the caller's test must accept
+ // nothing but a read or a transaction-local set_config (a no-op outside a transaction), never a write. Every
+ // other statement, the first one too when the test refuses it, waits for BEGIN's answer as before, and a failed
+ // BEGIN rejects them unsent. The transaction still settles only after `fn` does.
+ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
+ ? options.first
+ : null
+ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
+ , opening = null
+ , firstSeen = false
+ , written
try {
- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- return await Promise.race([
+ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
+ if (!first) {
+ await begun
+ return await Promise.race([
+ scope(connection, fn),
+ new Promise((_, reject) => connection.onclose = reject)
+ ])
+ }
+ await Promise.race([new Promise(resolve => written = resolve), begun])
+ opening = begun.then(() => { opening = null })
+ opening.catch(() => { /* each held statement rejects with BEGIN's error */ })
+ const ran = Promise.race([
scope(connection, fn),
new Promise((_, reject) => connection.onclose = reject)
])
+ const [opened, result] = await Promise.allSettled([begun, ran])
+ if (opened.status === 'rejected')
+ throw opened.reason
+ if (result.status === 'rejected')
+ throw result.reason
+ return result.value
} catch (error) {
throw error
}
@@ -466,6 +495,18 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
+ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
+ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
+ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ if (opening) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ const early = !firstSeen
+ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
+ && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ firstSeen = true
+ if (!early)
+ return opening.then(() => handler(q), q.reject)
+ }
reservation.enqueue(q)
}
}
@@ -474,6 +515,7 @@ function Postgres(a, b) {
connection = c
move(c, reserved)
own(c)
+ written && written()
}
}
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index 36e1db33d8..abf09edaa7 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -401,16 +401,45 @@ function Postgres(a, b) {
async function begin(options, fn) {
!fn && (fn = options, options = '')
+ // GBrain (#6930): `{ first }` opts one transaction in to sending its first statement right behind BEGIN, before
+ // BEGIN's answer, on a pool that pipelines inside transactions (transaction_pipeline). Only that one statement, and
+ // only when `first(text)` accepts its text: if BEGIN fails it runs in autocommit, so the caller's test must accept
+ // nothing but a read or a transaction-local set_config (a no-op outside a transaction), never a write. Every
+ // other statement, the first one too when the test refuses it, waits for BEGIN's answer as before, and a failed
+ // BEGIN rejects them unsent. The transaction still settles only after `fn` does.
+ const first = typeof options === 'object' && options.first && sql.options.transaction_pipeline > sql.options.max_pipeline
+ ? options.first
+ : null
+ typeof options === 'object' && (options = options.mode || '')
let savepoints = 0
, connection
, prepare = null
+ , opening = null
+ , firstSeen = false
+ , written
try {
- await sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
- return await Promise.race([
+ const begun = sql.unsafe('begin ' + options.replace(/[^a-z ]/ig, ''), [], { onexecute }).execute()
+ if (!first) {
+ await begun
+ return await Promise.race([
+ scope(connection, fn),
+ new Promise((_, reject) => connection.onclose = reject)
+ ])
+ }
+ await Promise.race([new Promise(resolve => written = resolve), begun])
+ opening = begun.then(() => { opening = null })
+ opening.catch(() => { /* each held statement rejects with BEGIN's error */ })
+ const ran = Promise.race([
scope(connection, fn),
new Promise((_, reject) => connection.onclose = reject)
])
+ const [opened, result] = await Promise.allSettled([begun, ran])
+ if (opened.status === 'rejected')
+ throw opened.reason
+ if (result.status === 'rejected')
+ throw result.reason
+ return result.value
} catch (error) {
throw error
}
@@ -466,6 +495,18 @@ function Postgres(a, b) {
q.catch(e => uncaughtError || (uncaughtError = e))
if (!reservation || c.reserved !== reservation)
return q.reject(Errors.generic('CONNECTION_CLOSED', 'Transaction connection is no longer owned'))
+ // GBrain (#6930): while BEGIN is unanswered only an accepted first statement is sent; the rest wait, in order. It
+ // is accepted on its text (`$n` for each argument, as statementText builds it) only when every argument is a
+ // parameter value: a fragment (a query, a helper, an identifier) would carry SQL the test never saw.
+ if (opening) {
+ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
+ const early = !firstSeen
+ && q.args.every(x => !(x instanceof Query || x instanceof Builder || x instanceof Identifier || Array.isArray(x) && x.some(y => y instanceof Query)))
+ && first(strings.reduce((a, s, i) => a + '$' + i + s))
+ firstSeen = true
+ if (!early)
+ return opening.then(() => handler(q), q.reject)
+ }
reservation.enqueue(q)
}
}
@@ -474,6 +515,7 @@ function Postgres(a, b) {
connection = c
move(c, reserved)
own(c)
+ written && written()
}
}
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index aedfb29b2c..03a10236da 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -776,6 +776,12 @@ declare namespace postgres {
begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
+ /**
+ * GBrain (#6930): with transaction_pipeline in force, the first statement `first` accepts (its text, `$n` for
+ * parameters) is sent behind BEGIN before BEGIN's answer. If BEGIN fails it runs in autocommit, so `first` must
+ * accept only a read or a transaction-local set_config, never a write.
+ */
+ begin<T>(options: { mode?: string; first?: (statement: string) => boolean }, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
reserve(options?: { signal?: AbortSignal }): Promise<ReservedSql<TTypes>>
}