Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): pool numbers from the vendored driver, claim owner nonce and last_sql on the claim stamp (#6317 lane 2, C1/C3)

garrytanbc4e367f20d4
diff --git a/patches/[email protected] b/patches/[email protected]
index e7dee3d8ff..be27516e38 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,5 +1,5 @@
diff --git a/cjs/src/connection.js b/cjs/src/connection.js
-index 07f6716702ac888215c86ad6e0071aaf55ae519c..f6d76e59ab690dc0a92986f90ade8839bc0470d4 100644
+index 07f67167..f6d76e59 100644
--- a/cjs/src/connection.js
+++ b/cjs/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -146,10 +146,31 @@ index 07f6716702ac888215c86ad6e0071aaf55ae519c..f6d76e59ab690dc0a92986f90ade8839
}
diff --git a/cjs/src/index.js b/cjs/src/index.js
-index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3e5eb9ff7 100644
+index f09c61c7..28dbe40c 100644
--- a/cjs/src/index.js
+++ b/cjs/src/index.js
-@@ -200,40 +200,134 @@ function Postgres(a, b) {
+@@ -68,6 +68,20 @@ function Postgres(a, b) {
+
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
++ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
++ get pool() {
++ return {
++ max: options.max,
++ open: open.length,
++ busy: busy.length,
++ full: full.length,
++ reserved: reserved.length,
++ connecting: connecting.length,
++ closed: closed.length,
++ ended: ended.length,
++ queued: queries.length
++ }
++ },
+ largeObject: largeObject.bind(null, sql),
+ subscribe,
+ CLOSE,
+@@ -200,40 +214,134 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -303,7 +324,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +343,13 @@ function Postgres(a, b) {
+@@ -249,9 +357,13 @@ function Postgres(a, b) {
}
async function scope(c, fn, name) {
@@ -317,7 +338,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
let uncaughtError
, result
-@@ -281,6 +379,8 @@ function Postgres(a, b) {
+@@ -281,6 +393,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -326,7 +347,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +390,16 @@ function Postgres(a, b) {
+@@ -290,18 +404,16 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -349,7 +370,42 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
}
}
-@@ -398,7 +496,14 @@ function Postgres(a, b) {
+@@ -351,7 +463,7 @@ function Postgres(a, b) {
+ return new Promise((resolve, reject) => {
+ query.state
+ ? query.active
+- ? Connection(options).cancel(query.state, resolve, reject)
++ ? cancelActive(query, resolve, reject)
+ : query.cancelled = { resolve, reject }
+ : (
+ queries.remove(query),
+@@ -362,6 +474,25 @@ function Postgres(a, b) {
+ })
+ }
+
++ function cancelActive(query, resolve, reject, delay = 50) {
++ Connection(options).cancel(query.state, () => {
++ if (!query.active)
++ return resolve()
++ let waiting = true
++ const timer = setTimeout(next, delay)
++ Promise.prototype.then.call(query, next, next)
++ function next() {
++ if (!waiting)
++ return
++ waiting = false
++ clearTimeout(timer)
++ query.active
++ ? cancelActive(query, resolve, reject, Math.min(delay * 2, 1000))
++ : resolve()
++ }
++ }, reject)
++ }
++
+ async function end({ timeout = null } = {}) {
+ if (ending)
+ return ending
+@@ -398,7 +529,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -365,7 +421,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +523,32 @@ function Postgres(a, b) {
+@@ -418,12 +556,32 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -399,7 +455,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
}
}
-@@ -491,6 +616,8 @@ function parseOptions(a, b) {
+@@ -491,6 +649,8 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -409,7 +465,7 @@ index f09c61c7e998f411560b95c9a8e1ed6a97972c11..a58dbb6c1e27094bb10e461d354af8c3
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/cjs/src/query.js b/cjs/src/query.js
-index 45327f2fabcdbf8f8ec5020675012c310c04fee6..1d092504ac1ce1fdac78cb0c4ef3a8aa957676e4 100644
+index 45327f2f..1d092504 100644
--- a/cjs/src/query.js
+++ b/cjs/src/query.js
@@ -23,11 +23,12 @@ const Query = module.exports.Query = class Query extends Promise {
@@ -453,7 +509,7 @@ index 45327f2fabcdbf8f8ec5020675012c310c04fee6..1d092504ac1ce1fdac78cb0c4ef3a8aa
this.execute()
return promise
diff --git a/cjs/src/queue.js b/cjs/src/queue.js
-index 8438f5da92cf7637d98a33491d75c75b1c817c25..c444310ff87b0ac81fd19cd3170a0ba607a66781 100644
+index 8438f5da..c444310f 100644
--- a/cjs/src/queue.js
+++ b/cjs/src/queue.js
@@ -15,6 +15,7 @@ function Queue(initial = []) {
@@ -465,7 +521,7 @@ index 8438f5da92cf7637d98a33491d75c75b1c817c25..c444310ff87b0ac81fd19cd3170a0ba6
const out = xs[index++]
diff --git a/src/connection.js b/src/connection.js
-index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..792c83d36a32b8181a438e0b0e91e0a7db8083ca 100644
+index 1b1cccde..792c83d3 100644
--- a/src/connection.js
+++ b/src/connection.js
@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
@@ -612,10 +668,31 @@ index 1b1cccde43b4570d5d071d6ffaab2669b3c2065a..792c83d36a32b8181a438e0b0e91e0a7
}
diff --git a/src/index.js b/src/index.js
-index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda0c1ea466 100644
+index c7fba3da..060e7b84 100644
--- a/src/index.js
+++ b/src/index.js
-@@ -200,40 +200,134 @@ function Postgres(a, b) {
+@@ -68,6 +68,20 @@ function Postgres(a, b) {
+
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
++ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
++ get pool() {
++ return {
++ max: options.max,
++ open: open.length,
++ busy: busy.length,
++ full: full.length,
++ reserved: reserved.length,
++ connecting: connecting.length,
++ closed: closed.length,
++ ended: ended.length,
++ queued: queries.length
++ }
++ },
+ largeObject: largeObject.bind(null, sql),
+ subscribe,
+ CLOSE,
+@@ -200,40 +214,134 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -769,7 +846,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +343,13 @@ function Postgres(a, b) {
+@@ -249,9 +357,13 @@ function Postgres(a, b) {
}
async function scope(c, fn, name) {
@@ -783,7 +860,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
let uncaughtError
, result
-@@ -281,6 +379,8 @@ function Postgres(a, b) {
+@@ -281,6 +393,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -792,7 +869,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +390,16 @@ function Postgres(a, b) {
+@@ -290,18 +404,16 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -815,7 +892,42 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
}
}
-@@ -398,7 +496,14 @@ function Postgres(a, b) {
+@@ -351,7 +463,7 @@ function Postgres(a, b) {
+ return new Promise((resolve, reject) => {
+ query.state
+ ? query.active
+- ? Connection(options).cancel(query.state, resolve, reject)
++ ? cancelActive(query, resolve, reject)
+ : query.cancelled = { resolve, reject }
+ : (
+ queries.remove(query),
+@@ -362,6 +474,25 @@ function Postgres(a, b) {
+ })
+ }
+
++ function cancelActive(query, resolve, reject, delay = 50) {
++ Connection(options).cancel(query.state, () => {
++ if (!query.active)
++ return resolve()
++ let waiting = true
++ const timer = setTimeout(next, delay)
++ Promise.prototype.then.call(query, next, next)
++ function next() {
++ if (!waiting)
++ return
++ waiting = false
++ clearTimeout(timer)
++ query.active
++ ? cancelActive(query, resolve, reject, Math.min(delay * 2, 1000))
++ : resolve()
++ }
++ }, reject)
++ }
++
+ async function end({ timeout = null } = {}) {
+ if (ending)
+ return ending
+@@ -398,7 +529,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -831,7 +943,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +523,32 @@ function Postgres(a, b) {
+@@ -418,12 +556,32 @@ function Postgres(a, b) {
: move(c, full)
}
@@ -865,7 +977,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
}
}
-@@ -491,6 +616,8 @@ function parseOptions(a, b) {
+@@ -491,6 +649,8 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
@@ -875,7 +987,7 @@ index c7fba3dace20173f4cb13f3f138bb6d213b43683..58b370bb3482de2ab6c86246cd63dfda
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
diff --git a/src/query.js b/src/query.js
-index 0d44a15cd9e42beaf11d4be6ccde60223e09508a..96967780bdb55671bdcdda0fd0bb6e718e0a0e78 100644
+index 0d44a15c..96967780 100644
--- a/src/query.js
+++ b/src/query.js
@@ -23,11 +23,12 @@ export class Query extends Promise {
@@ -919,7 +1031,7 @@ index 0d44a15cd9e42beaf11d4be6ccde60223e09508a..96967780bdb55671bdcdda0fd0bb6e71
this.execute()
return promise
diff --git a/src/queue.js b/src/queue.js
-index c4ef97164f057db99dce1b9af3401dbb1af37e31..8fba891b879e8f5c7fdb03ea0590753663c824c3 100644
+index c4ef9716..8fba891b 100644
--- a/src/queue.js
+++ b/src/queue.js
@@ -15,6 +15,7 @@ function Queue(initial = []) {
@@ -931,7 +1043,7 @@ index c4ef97164f057db99dce1b9af3401dbb1af37e31..8fba891b879e8f5c7fdb03ea05907536
const out = xs[index++]
diff --git a/types/index.d.ts b/types/index.d.ts
-index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..d7ba214bc614097fddbf2951127c5685d7c8e643 100644
+index 13c3432f..96cba0e0 100644
--- a/types/index.d.ts
+++ b/types/index.d.ts
@@ -119,6 +119,18 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
@@ -970,7 +1082,16 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..d7ba214bc614097fddbf2951127c5685
/**
* When executes query as prepared statement.
* @default false
-@@ -717,10 +730,11 @@ declare namespace postgres {
+@@ -705,6 +718,8 @@ declare namespace postgres {
+
+ options: ParsedOptions<TTypes>;
+ parameters: ConnectionParameters;
++ /** GBrain: the pool's own queue lengths at this instant (`queued` = queries waiting for a connection). */
++ pool: { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number };
+
+ end(options?: { timeout?: number | undefined } | undefined): Promise<void>;
+
+@@ -717,10 +732,11 @@ declare namespace postgres {
begin<T>(cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
begin<T>(options: string, cb: (sql: TransactionSql<TTypes>) => T | Promise<T>): Promise<UnwrapPromiseArray<T>>;
@@ -983,7 +1104,7 @@ index 13c3432f761e2c2ee5b7dc1bdafe93e49f993dc7..d7ba214bc614097fddbf2951127c5685
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 +742,7 @@ declare namespace postgres {
+@@ -728,6 +744,7 @@ declare namespace postgres {
}
interface ReservedSql<TTypes extends Record<string, unknown> = {}> extends Sql<TTypes> {
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d6a91a0fd..c68483eb58 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2202 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 340 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
src/core/pglite-engine.ts 2998 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)
-src/core/postgres-engine.ts 2953 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)
+src/core/postgres-engine.ts 2955 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); +2 #6317: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts)
src/core/search/hybrid.ts 1615 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts
src/core/types.ts 2239 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index 205f1c21f3..7dad670df9 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -25,9 +25,13 @@
* and the ceiling. Without a deadline (switch off, a clock from an older
* caller) or on PGLite (one in-process connection, no other session to wait
* on) the engine is returned as it is.
+ *
+ * #6317 (C1): the same wrapper records each statement's label on the clock
+ * (`recordClaimSql`) before issuing it, so the claim stamp's `last_sql` names
+ * the read a parked preparation is waiting on.
*/
import type { BrainEngine } from '../engine.ts';
-import type { ClaimPhaseClock } from './claim-phase.ts';
+import { recordClaimSql, type ClaimPhaseClock } from './claim-phase.ts';
import { registerEngineView, viewedEngine } from './switches.ts';
/** The SQLSTATEs a bounded read ends with when its server-side bound passes. */
@@ -54,6 +58,7 @@ export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undef
if (deadlineAt === undefined || engine.kind !== 'postgres') return engine;
return registerEngineView(new Proxy(engine, { get(target, key) {
if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) => {
+ recordClaimSql(clock, sql);
if (opts?.signal) return target.executeRaw(sql, params, opts);
try {
// The clock's signal ends only the wait for a free connection (a saturated pool); the statement itself ends at the bound.
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 78abdff319..38788b9a00 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -28,9 +28,19 @@
* running-overdue verdict (`preparation_overdue`) writer status and doctor
* attach as `claim.stall`; the terminal give-up is the `preparation_stalled`
* receipt, so the two never share a name.
+ *
+ * #6317 adds the process identity and the last statement: the owner is
+ * `{kind, pid, nonce, pid_ns, version}` (a per-process nonce, because
+ * containers sharing one home reuse pids; `isOwnerThisProcess` compares the
+ * nonce whenever the stamp has one), and `recordClaimSql` keeps the label of
+ * the last raw statement a preparer issued (first keyword plus table, never
+ * text or parameters; `boundedReads` records it), stamped as `last_sql` so
+ * writer status, the drain's stall line and the consumer's log lines
+ * (`claimTripleText`) name the same step / waiting_on / last_sql triple.
*/
import type { BrainEngine } from '../engine.ts';
import { VERSION } from '../../version.ts';
+import { consumerIdentity } from './consumer-heartbeat.ts';
export type ClaimPhaseName = 'preparing' | 'publishing';
export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'unknown'] as const;
@@ -57,9 +67,13 @@ export interface ClaimPhaseClock {
* Absent with the deadlines switch off.
*/
deadlineAt?: number;
+ /** #6317: the last raw statement the preparation issued (label only) and when. */
+ lastSql?: { label: string; at: number };
}
-/** The process that holds a claim, as the stamp records it. */
-export interface ClaimOwner { kind: string; pid: number; version: string }
+/** The process that holds a claim, as the stamp records it (`nonce`/`pid_ns` absent on stamps from an owner older than #6317). */
+export interface ClaimOwner { kind: string; pid: number; version: string; nonce?: string; pid_ns?: string | null }
+/** #6317: the step / waiting_on / last_sql triple of a claim, as stamped and as read back. */
+export interface ClaimLastSql { label: string; age_ms: number | null }
export function startClaimPhase(now = Date.now(), signal?: AbortSignal, budgetMs?: number): ClaimPhaseClock {
return { phase: 'preparing', claimedAt: now, since: now, step: null, stepSince: now, waitingOn: 'unknown', ...(signal ? { signal } : {}),
@@ -86,6 +100,28 @@ export function enterClaimStep(clock: ClaimPhaseClock | undefined, step: string,
if (clock.step !== step) { clock.step = step; clock.stepSince = now; }
clock.waitingOn = waitingOn;
}
+/** #6317: the label of a raw statement for the stamp: its first keyword and the first table it names; never text or parameters. */
+export function sqlLabel(sql: string): string {
+ const text = sql.replace(/\s+/g, ' ').trim();
+ const keyword = /^[A-Za-z]+/.exec(text)?.[0]?.toUpperCase() ?? 'SQL';
+ const table = /\b(?:FROM|INTO|UPDATE|JOIN)\s+(?:ONLY\s+)?("?[A-Za-z_][\w.]*"?)/i.exec(text)?.[1]?.replaceAll('"', '');
+ return table ? `${keyword} ${table}` : keyword;
+}
+/** #6317: records the statement a preparer is about to issue on its clock (`boundedReads` calls it at every raw read). */
+export function recordClaimSql(clock: ClaimPhaseClock | undefined, sql: string, now = Date.now()): void {
+ if (clock) clock.lastSql = { label: sqlLabel(sql), at: now };
+}
+/** #6317: the ` step=… waiting_on=… last_sql=…` text every `[persistence]` cut-off and hold line carries (C3). */
+export function claimTripleText(clock: Pick<ClaimPhaseClock, 'step' | 'waitingOn' | 'lastSql'> | undefined, now = Date.now()): string {
+ if (!clock) return ' step=none waiting_on=unknown last_sql=none';
+ const last = clock.lastSql ? `${clock.lastSql.label.replaceAll(' ', '_')}@${Math.round((now - clock.lastSql.at) / 1000)}s` : 'none';
+ return ` step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn} last_sql=${last}`;
+}
+/** #6317: whether a stamped owner is this process: the pid, and the nonce when the stamp carries one (a reused pid is another process). */
+export function isOwnerThisProcess(owner: Pick<ClaimOwner, 'pid' | 'nonce'> | null | undefined): boolean {
+ if (!owner || owner.pid !== process.pid) return false;
+ return owner.nonce === undefined || owner.nonce === consumerIdentity().nonce;
+}
const OWNER_COMMANDS = new Set(['sync', 'serve', 'jobs', 'autopilot', 'mcp', 'dream', 'cycle', 'sources', 'migrate-graduation', 'put', 'import']);
let ownerOverride: ClaimOwner | undefined;
@@ -93,7 +129,8 @@ let ownerOverride: ClaimOwner | undefined;
export function claimOwner(): ClaimOwner {
if (ownerOverride) return ownerOverride;
const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));
- return { kind: command && OWNER_COMMANDS.has(command) ? command : 'cli', pid: process.pid, version: VERSION };
+ const identity = consumerIdentity();
+ return { kind: command && OWNER_COMMANDS.has(command) ? command : 'cli', pid: process.pid, version: VERSION, nonce: identity.nonce, pid_ns: identity.pid_ns };
}
/** Test seam. */
export function setClaimOwnerForTest(owner: ClaimOwner | undefined): void { ownerOverride = owner; }
@@ -101,7 +138,8 @@ export function setClaimOwnerForTest(owner: ClaimOwner | undefined): void { owne
/** The `claim_phase` jsonb a renewal (or a claim, or a group's dispatch mark) stores for the claim holding `token`. */
export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null, owner: ClaimOwner = claimOwner()): string {
return JSON.stringify({ phase: clock.phase, claimed_at: new Date(clock.claimedAt).toISOString(), since: new Date(clock.since).toISOString(), token,
- step: clock.step, step_since: new Date(clock.stepSince).toISOString(), waiting_on: clock.waitingOn, owner });
+ step: clock.step, step_since: new Date(clock.stepSince).toISOString(), waiting_on: clock.waitingOn, owner,
+ last_sql: clock.lastSql ? { label: clock.lastSql.label, at: new Date(clock.lastSql.at).toISOString() } : null });
}
/**
@@ -154,6 +192,8 @@ export interface ClaimState {
waiting_on: WaitingOn;
/** The process holding the claim, when its stamp recorded one. */
owner: ClaimOwner | null;
+ /** #6317: the last raw statement the owner's preparation issued (label and age), null when none was recorded. */
+ last_sql: ClaimLastSql | null;
/** Whether the same request continues without anyone acting (after its lease lapses or its transaction ends). */
resumes_on_its_own: boolean;
why: string;
@@ -174,7 +214,13 @@ const age = (at: unknown, now: number): number | null => {
function stampOwner(raw: unknown): ClaimOwner | null {
const owner = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
if (!owner || typeof owner.kind !== 'string' || typeof owner.pid !== 'number' || typeof owner.version !== 'string') return null;
- return { kind: owner.kind, pid: owner.pid, version: owner.version };
+ return { kind: owner.kind, pid: owner.pid, version: owner.version, ...(typeof owner.nonce === 'string' ? { nonce: owner.nonce } : {}),
+ ...(typeof owner.pid_ns === 'string' || owner.pid_ns === null ? { pid_ns: owner.pid_ns } : {}) };
+}
+/** #6317: the stamp's `last_sql` read back with its age; null when the stamp has none (an owner older than #6317 included). */
+export function stampLastSql(raw: unknown, now: number): ClaimLastSql | null {
+ const last = raw && typeof raw === 'object' ? raw as Record<string, unknown> : null;
+ return last && typeof last.label === 'string' ? { label: last.label, age_ms: age(last.at, now) } : null;
}
export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null {
@@ -186,7 +232,7 @@ export function claimStateOf(row: ClaimRow, now = Date.now()): ClaimState | null
const step = own && typeof stamp!.step === 'string' ? stamp!.step : null;
const detail = { step, step_age_ms: step ? age(stamp!.step_since, now) : null,
waiting_on: own && (WAITING_ON as readonly unknown[]).includes(stamp!.waiting_on) ? stamp!.waiting_on as WaitingOn : 'unknown' as const,
- owner: own ? stampOwner(stamp!.owner) : null };
+ owner: own ? stampOwner(stamp!.owner) : null, last_sql: own ? stampLastSql(stamp!.last_sql, now) : null };
if (row.publication_started) return { phase: 'file_publication', claim_age_ms: claimAge, phase_age_ms: null, ...detail, resumes_on_its_own: false,
why: 'Its files were being published; the publication recovery path restores or finishes them when the owning process scans its roots again (after a restart if it hung).' };
if (row.claim_lapsed) return { phase: 'publication_transaction', claim_age_ms: claimAge, phase_age_ms: null, ...detail, resumes_on_its_own: true,
diff --git a/src/core/persistence/consumer-heartbeat.ts b/src/core/persistence/consumer-heartbeat.ts
new file mode 100644
index 0000000000..26f1d36899
--- /dev/null
+++ b/src/core/persistence/consumer-heartbeat.ts
@@ -0,0 +1,84 @@
+/**
+ * #6317 (B3): the per-process consumer heartbeat table, `persistence_consumers`.
+ *
+ * LANE 2 STUB. Lane 1 owns this module, its migration and the heartbeat
+ * writer; this file carries only the read side lane 2 (the drain's
+ * wedged-owner check and the movement reader) depends on, under the names
+ * the plan fixes, so the integrator keeps lane 1's file and drops this one.
+ * Every read answers null or an empty list when the table does not exist yet
+ * (a brain older than the migration, PGLite without it), so no caller treats
+ * a missing row as evidence of anything.
+ *
+ * One row per consumer-bearing process: `(host_id, pid, nonce)` identifies a
+ * process across pid reuse and pid namespaces; `mode` says whether it claims
+ * (`full`, `promoted`) or only waits (`probing`, `waiter_only`); `renewed_at`
+ * is its liveness (live within 30 s, lapsed at 60 s); `restart_required` and
+ * `root_barrier_age_ms` are the owner's own verdict on itself (a zombie at
+ * the cap, an abandoned root barrier), from which `wedged` derives.
+ */
+import { randomUUID } from 'node:crypto';
+import { readlinkSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+
+export const CONSUMER_LIVE_MS = 30_000;
+export const CONSUMER_LAPSED_MS = 60_000;
+export const RESIDENT_CONSUMER_KINDS: readonly string[] = ['serve', 'sync', 'jobs', 'autopilot', 'mcp'];
+
+export type ConsumerMode = 'probing' | 'full' | 'waiter_only' | 'promoted';
+export interface ConsumerRow {
+ host_id: string;
+ pid: number;
+ nonce: string;
+ pid_ns: string | null;
+ kind: string;
+ mode: ConsumerMode;
+ started_at: string;
+ renewed_at: string;
+ restart_required: boolean;
+ root_barrier_age_ms: number | null;
+ pool: { checked_out: number; max: number; waiters: number } | null;
+ host_json_path: string | null;
+ persistence_home: string | null;
+ minted_under: Record<string, unknown> | null;
+ version: string | null;
+}
+export interface ConsumerIdentity { pid: number; nonce: string; pid_ns: string | null }
+
+const NONCE = randomUUID();
+let pidNamespace: string | null | undefined;
+/** This process's identity for claim stamps and heartbeat rows: pid, a per-process nonce, and the pid namespace inode where readable. */
+export function consumerIdentity(): ConsumerIdentity {
+ if (pidNamespace === undefined) {
+ try { pidNamespace = /pid:\[(\d+)\]/.exec(readlinkSync('/proc/self/ns/pid'))?.[1] ?? null; } catch { pidNamespace = null; }
+ }
+ return { pid: process.pid, nonce: NONCE, pid_ns: pidNamespace };
+}
+
+/** Whether `row` was renewed within the live window (`now` on this clock; renewed_at is the database's). */
+export function consumerLive(row: Pick<ConsumerRow, 'renewed_at'>, now = Date.now()): boolean {
+ const at = Date.parse(row.renewed_at);
+ return Number.isFinite(at) && now - at <= CONSUMER_LIVE_MS;
+}
+/** A consumer whose own status says it stopped making progress: at the zombie cap, or holding a root barrier past the ceiling. */
+export function consumerWedged(row: Pick<ConsumerRow, 'restart_required' | 'root_barrier_age_ms'>, ceilingMs: number): boolean {
+ return row.restart_required || (row.root_barrier_age_ms !== null && row.root_barrier_age_ms > ceilingMs);
+}
+
+/** Every heartbeat row of `hostId`, newest renewal first; empty when the table is absent or the read fails. */
+export async function listHostConsumers(engine: Pick<BrainEngine, 'executeRaw'>, hostId: string): Promise<ConsumerRow[]> {
+ try {
+ return await engine.executeRaw<ConsumerRow>(
+ `SELECT host_id::text AS host_id, pid, nonce, pid_ns, kind, mode, started_at::text AS started_at, renewed_at::text AS renewed_at,
+ restart_required, root_barrier_age_ms, pool, host_json_path, persistence_home, minted_under, version
+ FROM persistence_consumers WHERE host_id = $1::uuid ORDER BY renewed_at DESC`, [hostId]);
+ } catch {
+ return [];
+ }
+}
+
+/** The live, full, resident-kind, not-wedged row on `hostId` that is not `self`, or null (B1a's probe). */
+export async function probeLiveFullConsumer(engine: Pick<BrainEngine, 'executeRaw'>, hostId: string, self: ConsumerIdentity, ceilingMs = 600_000): Promise<ConsumerRow | null> {
+ const rows = await listHostConsumers(engine, hostId);
+ return rows.find(row => (row.mode === 'full' || row.mode === 'promoted') && RESIDENT_CONSUMER_KINDS.includes(row.kind)
+ && !(row.pid === self.pid && row.nonce === self.nonce) && consumerLive(row) && !consumerWedged(row, ceilingMs)) ?? null;
+}
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 7a17031a8f..e85361f631 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -6,7 +6,7 @@ import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
import { preparationConfigView } from './config-snapshot.ts';
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
-import { claimPhaseStamp, claimStateOf, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';
+import { claimPhaseStamp, claimStateOf, claimTripleText, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';
import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, preparationKind, startPreparation, type PreparationPolicy } from './preparation-budget.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { ownerExceptionLogText } from './publication-failure.ts';
@@ -689,7 +689,7 @@ export class PersistenceConsumer {
this.zombies.set(row.id, { request_id: row.request_id, operation: row.operation, step: clock.step, waiting_on: clock.waitingOn,
claimed_at: new Date(clock.claimedAt).toISOString(), abandoned_at: at, outlived_ceiling_at: at });
void settled.then(() => { this.zombies.delete(row.id); });
- this.log('preparation', 'ceiling_exceeded', `request ${row.request_id} step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn}${this.restartRequired() ? ' restart_required' : ''}`);
+ this.log('preparation', 'ceiling_exceeded', `request ${row.request_id}${claimTripleText(clock)}${this.restartRequired() ? ' restart_required' : ''}`);
await floorPreparationAttempts(this.engine, row.id, this.policy.maxAttempts).catch(error => this.report(error));
});
}
@@ -711,7 +711,7 @@ export class PersistenceConsumer {
try {
const previous = claimStateOf({ state: 'running', claim_phase: row.previous_claim_phase, execution_token: previousToken(row.previous_claim_phase) });
const done = await finishPreparationStalled(this.engine, row, { step: previous?.step ?? null, waiting_on: previous?.waiting_on ?? 'unknown', limit: policy.maxAttempts }, false);
- this.log('preparation', 'preparation_stalled', failureLogText(done));
+ this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText({ step: previous?.step ?? null, waitingOn: previous?.waiting_on ?? 'unknown' })}`);
return this.settled(done);
} finally { this.preparing.delete(row.id); this.executing.delete(row.id); }
}
@@ -722,7 +722,7 @@ export class PersistenceConsumer {
return this.prepare(this.engine.kind === 'postgres' && singleWrite(row)
&& await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,
row, this.config, budget !== undefined && preparationKind(row) === 'foreground' ? signal : undefined, clock);
- }, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded'); } });
+ }, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded', `request ${row.request_id}${claimTripleText(clock)}`); } });
const stop = () => prep.abort({ code: 'consumer_stopping' });
this.abort.signal.addEventListener('abort', stop, { once: true });
const lease = startClaimLease(
@@ -738,7 +738,7 @@ export class PersistenceConsumer {
if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }
if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {
const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);
- this.log('preparation', 'preparation_stalled', failureLogText(done));
+ this.log('preparation', 'preparation_stalled', `${failureLogText(done)}${claimTripleText(clock)}`);
return this.settled(done);
}
await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 108f27a595..10899abc8d 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -45,6 +45,7 @@ import {
} from './retry.ts';
import { isConnectionEndedError } from './retry-matcher.ts';
import { CheckoutGauge, PoisonedDiscardCounter, type PoolGaugeSnapshot } from './pool-gauge.ts';
+import { driverPoolStats, type DriverPoolStats } from './postgres-engine/pool-stats.ts';
import {
valueHash,
normalizeDimension,
@@ -702,13 +703,14 @@ export class PostgresEngine implements BrainEngine {
/** #5801: observe connection acquisition (see CheckoutGauge.onCheckout). Duck-typed like getPoolDiagnostics. */
onCheckout(listener: () => void): () => void { return this.checkoutGauge.onCheckout(listener); }
- getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number } | null {
+ getPoolDiagnostics(): { tracked: PoolGaugeSnapshot; poolMax: number | null; poisonedDiscards: number; pool: DriverPoolStats | null } | null {
try {
const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;
return {
tracked: this.checkoutGauge.snapshot(),
poolMax: typeof max === 'number' ? max : null,
poisonedDiscards: this.poisonedDiscards?.count ?? 0,
+ pool: driverPoolStats(this.sql),
};
} catch {
return null;
diff --git a/src/core/postgres-engine/pool-stats.ts b/src/core/postgres-engine/pool-stats.ts
new file mode 100644
index 0000000000..455422d045
--- /dev/null
+++ b/src/core/postgres-engine/pool-stats.ts
@@ -0,0 +1,37 @@
+/**
+ * #6317 (C1): the ordinary pool's real numbers, read from the vendored
+ * driver's own queues (`sql.pool`, a GBrain addition to postgres.js: the
+ * `open`, `busy`, `full`, `reserved`, `connecting` connection queues and the
+ * queries waiting for any connection). This is the figure `pool-gauge.ts`
+ * refuses to invent: a connection is checked out when it is executing
+ * (`busy`, `full`), owned by a reservation or transaction (`reserved`) or
+ * being opened for a waiting query (`connecting`); `waiters` is the driver's
+ * query queue, which a transaction-mode pooler cannot see. Every reader
+ * duck-types the engine and gets null when the engine is not Postgres or the
+ * driver predates the accessor, never a guess.
+ */
+
+export interface DriverPoolStats {
+ checked_out: number;
+ max: number;
+ waiters: number;
+}
+
+interface DriverQueues { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number }
+
+/** The pool numbers of one driver instance, or null when it exposes none. */
+export function driverPoolStats(sql: unknown): DriverPoolStats | null {
+ const pool = (sql as { pool?: DriverQueues } | null)?.pool;
+ if (!pool || typeof pool.max !== 'number') return null;
+ return { checked_out: pool.busy + pool.full + pool.reserved + pool.connecting, max: pool.max, waiters: pool.queued };
+}
+
+/** The ordinary pool of an engine that reports one (`getPoolDiagnostics().pool`), else null. */
+export function enginePoolStats(engine: unknown): DriverPoolStats | null {
+ try {
+ const diagnostics = (engine as { getPoolDiagnostics?: () => { pool?: DriverPoolStats | null } | null } | null)?.getPoolDiagnostics?.();
+ return diagnostics?.pool ?? null;
+ } catch {
+ return null;
+ }
+}
diff --git a/vendor/postgres/cf/src/index.js b/vendor/postgres/cf/src/index.js
index 9993ca5837..0b27a51673 100644
--- a/vendor/postgres/cf/src/index.js
+++ b/vendor/postgres/cf/src/index.js
@@ -69,6 +69,20 @@ function Postgres(a, b) {
Object.assign(sql, {
get parameters() { return options.parameters },
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
+ get pool() {
+ return {
+ max: options.max,
+ open: open.length,
+ busy: busy.length,
+ full: full.length,
+ reserved: reserved.length,
+ connecting: connecting.length,
+ closed: closed.length,
+ ended: ended.length,
+ queued: queries.length
+ }
+ },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
diff --git a/vendor/postgres/cjs/src/index.js b/vendor/postgres/cjs/src/index.js
index 65dd5d1e07..28dbe40c56 100644
--- a/vendor/postgres/cjs/src/index.js
+++ b/vendor/postgres/cjs/src/index.js
@@ -68,6 +68,20 @@ function Postgres(a, b) {
Object.assign(sql, {
get parameters() { return options.parameters },
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
+ get pool() {
+ return {
+ max: options.max,
+ open: open.length,
+ busy: busy.length,
+ full: full.length,
+ reserved: reserved.length,
+ connecting: connecting.length,
+ closed: closed.length,
+ ended: ended.length,
+ queued: queries.length
+ }
+ },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
diff --git a/vendor/postgres/src/index.js b/vendor/postgres/src/index.js
index b715f5bb7d..060e7b842c 100644
--- a/vendor/postgres/src/index.js
+++ b/vendor/postgres/src/index.js
@@ -68,6 +68,20 @@ function Postgres(a, b) {
Object.assign(sql, {
get parameters() { return options.parameters },
+ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317).
+ get pool() {
+ return {
+ max: options.max,
+ open: open.length,
+ busy: busy.length,
+ full: full.length,
+ reserved: reserved.length,
+ connecting: connecting.length,
+ closed: closed.length,
+ ended: ended.length,
+ queued: queries.length
+ }
+ },
largeObject: largeObject.bind(null, sql),
subscribe,
CLOSE,
diff --git a/vendor/postgres/types/index.d.ts b/vendor/postgres/types/index.d.ts
index d7ba214bc6..96cba0e03b 100644
--- a/vendor/postgres/types/index.d.ts
+++ b/vendor/postgres/types/index.d.ts
@@ -718,6 +718,8 @@ declare namespace postgres {
options: ParsedOptions<TTypes>;
parameters: ConnectionParameters;
+ /** GBrain: the pool's own queue lengths at this instant (`queued` = queries waiting for a connection). */
+ pool: { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number };
end(options?: { timeout?: number | undefined } | undefined): Promise<void>;