Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(pool-health): env through withEnv; raise postgres-engine ceiling for the pool incident hooks; regenerate the driver patch

garrytan68b79ec66942
diff --git a/patches/[email protected] b/patches/[email protected]
index a19fcc0d79..ea31f44910 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,8 +1,21 @@
diff --git a/cjs/src/connection.js b/cjs/src/connection.js
-index 07f6716..ec88b7c 100644
+index 07f6716..813790c 100644
--- a/cjs/src/connection.js
+++ b/cjs/src/connection.js
-@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -49,7 +49,7 @@ const errorFields = {
+ 82 : 'routine' // R
+ }
+
+-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {
+ const {
+ sslnegotiation,
+ ssl,
+@@ -75,9 +75,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ , idleTimer = timer(end, options.idle_timeout)
+ , lifeTimer = timer(end, options.max_lifetime)
+ , connectTimer = timer(connectTimedOut, options.connect_timeout)
++ , inflightTimer = timer(inflightTimedOut, options.inflight_timeout)
let socket = null
, cancelMessage
@@ -12,7 +25,21 @@ index 07f6716..ec88b7c 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -143,11 +146,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -105,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ , ended = null
+ , nonce = null
+ , query = null
++ , queryStart = 0
+ , final = null
+
+ const connection = {
+ queue: queues.closed,
+ idleTimer,
++ inflightSince: 0,
+ connect(query) {
+ initial = query
+ reconnect()
+@@ -143,11 +149,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -28,21 +55,102 @@ index 07f6716..ec88b7c 100644
} catch (error) {
reject(error)
}
-@@ -170,11 +175,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
- : (query = q, query.active = true)
+@@ -163,25 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ if (q.cancelled)
+ return
+
++ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to
++ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an
++ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and
++ // every later reply on the socket was delivered one statement late until the process restarted.
++ let bytes
+ try {
+ q.state = backend
++ build(q)
++ bytes = toBuffer(q)
++ } catch (error) {
++ if (!query) {
++ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.
++ query = q
++ query.active = true
++ write(Sync)
++ armInflight()
++ }
++ options.onbuilderror && reportBuildError(q, error)
++ queryError(q, error)
++ return true
++ }
++
++ try {
+ query
+ ? sent.push(q)
+- : (query = q, query.active = true)
++ : (query = q, query.active = true, armInflight())
- build(q)
+- build(q)
+- return write(toBuffer(q))
+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
- return write(toBuffer(q))
++ return write(bytes)
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
- && (!q.options.onexecute || q.options.onexecute(connection))
+ && mayPipeline
} catch (error) {
- sent.length === 0 && write(Sync)
- errored(error)
-@@ -235,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+- sent.length === 0 && write(Sync)
+- errored(error)
++ if (query === q) {
++ sent.length === 0 && write(Sync)
++ errored(error)
++ } else {
++ sent.remove(q)
++ queryError(q, error)
++ }
+ return true
+ }
+ }
+
++ function reportBuildError(q, error) {
++ try {
++ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))
++ } catch (_) {}
++ }
++
++ // The statement's text with $n placeholders, never its parameter values.
++ function statementText(q) {
++ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
++ return String(q.string || strings.reduce((a, s, i) => a + '$' + i + s)).replace(/\s+/g, ' ').trim().slice(0, 200)
++ }
++
++ // GBrain (#6383): the head statement's clock. It starts when a statement becomes the head, restarts on every
++ // byte the server sends and stops at ReadyForQuery. A statement that outlives options.inflight_timeout with
++ // nothing coming back (a desynced connection, a pooler that swallowed a CancelRequest, a dead peer) has no
++ // server-side timeout left to save it: the connection is retired instead of holding its queue forever.
++ function armInflight() {
++ queryStart = connection.inflightSince = performance.now()
++ inflightTimer.start()
++ }
++
++ function inflightTimedOut() {
++ if (!query)
++ return
++ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }
++ const s = socket
++ error(Errors.connection('CONNECTION_STUCK', options, socket))
++ query = null
++ connection.inflightSince = 0
++ onstuck(connection, stuck)
++ terminate()
++ if (s && !s.destroyed) {
++ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)
++ t.unref && t.unref()
++ }
++ }
++
+ function toBuffer(q) {
+ if (q.parameters.length >= 65534)
+ throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
+@@ -235,10 +306,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -60,7 +168,7 @@ index 07f6716..ec88b7c 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,7 +306,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -295,10 +371,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* c8 ignore next 3 */
function drain() {
@@ -69,7 +177,11 @@ index 07f6716..ec88b7c 100644
}
function data(x) {
-@@ -379,6 +390,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
++ query && inflightTimer.start()
+ if (incomings) {
+ incomings.push(x)
+ remaining -= x.length
+@@ -379,6 +456,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function error(err) {
@@ -78,7 +190,7 @@ index 07f6716..ec88b7c 100644
if (connection.queue === queues.connecting && options.host[retries + 1])
return
-@@ -388,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -388,6 +467,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function errored(err) {
@@ -87,7 +199,7 @@ index 07f6716..ec88b7c 100644
stream && (stream.destroy(err), stream = null)
query && queryError(query, err)
initial && (queryError(initial, err), initial = null)
-@@ -438,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -438,19 +519,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
clearImmediate(nextWriteTimer)
@@ -98,7 +210,11 @@ index 07f6716..ec88b7c 100644
socket.removeListener('data', data)
socket.removeListener('connect', connected)
idleTimer.cancel()
-@@ -447,10 +466,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ lifeTimer.cancel()
+ connectTimer.cancel()
++ inflightTimer.cancel()
++ connection.inflightSince = 0
+
socket.removeAllListeners()
socket = null
@@ -123,19 +239,29 @@ index 07f6716..ec88b7c 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -533,8 +565,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,8 +633,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
++ connection.inflightSince = 0
if (query) {
++ options.shared.completed++
if (errorResponse) {
+ // GBrain: a failed statement describes again next time instead of trusting shared parameter types.
+ query.sharedTypes && options.shared_types.delete(query.typesKey)
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
-@@ -564,10 +599,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -550,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ query = results = errorResponse = null
+ result = new Result()
+ connectTimer.cancel()
++ inflightTimer.cancel()
+
+ if (initial) {
+ if (target_session_attrs) {
+@@ -564,23 +670,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -150,7 +276,13 @@ index 07f6716..ec88b7c 100644
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +617,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
+
+ if (query)
+- return // Consider opening if able and sent.length < 50
++ return armInflight() // Consider opening if able and sent.length < 50
+
+ connection.reserved
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -159,7 +291,7 @@ index 07f6716..ec88b7c 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,6 +667,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -630,6 +738,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -169,7 +301,7 @@ index 07f6716..ec88b7c 100644
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
-@@ -767,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -767,14 +878,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
async function fetchArrayTypes() {
needsTypes = false
@@ -200,15 +332,26 @@ index 07f6716..ec88b7c 100644
}
diff --git a/cjs/src/index.js b/cjs/src/index.js
-index f09c61c..694550b 100644
+index f09c61c..abb4a15 100644
--- a/cjs/src/index.js
+++ b/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() {
+@@ -62,10 +62,34 @@ function Postgres(a, b) {
+ , full = Queue()
+ , queues = { connecting, reserved, closed, ended, open, busy, full }
+
+- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))
++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))
+
+ const sql = Sql(handler)
+
++ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317). A property
++ // getter, not an Object.assign member: Object.assign reads a getter once and copies its value, which froze
++ // these numbers at construction (#6383). `inflight_oldest_ms` is the age of the oldest head statement across
++ // the pool's connections and `completed` counts every ReadyForQuery that settled a statement.
++ Object.defineProperty(sql, 'pool', {
++ enumerable: false,
++ get() {
++ const now = performance.now()
+ return {
+ max: options.max,
+ open: open.length,
@@ -218,13 +361,17 @@ index f09c61c..694550b 100644
+ connecting: connecting.length,
+ closed: closed.length,
+ ended: ended.length,
-+ queued: queries.length
++ queued: queries.length,
++ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),
++ completed: options.shared.completed
+ }
-+ },
++ }
++ })
++
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
- subscribe,
- CLOSE,
-@@ -200,40 +214,134 @@ function Postgres(a, b) {
+@@ -200,40 +224,134 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -378,7 +525,7 @@ index f09c61c..694550b 100644
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +357,13 @@ function Postgres(a, b) {
+@@ -249,9 +367,13 @@ function Postgres(a, b) {
}
async function scope(c, fn, name) {
@@ -392,7 +539,7 @@ index f09c61c..694550b 100644
let uncaughtError
, result
-@@ -281,6 +393,8 @@ function Postgres(a, b) {
+@@ -281,6 +403,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -401,7 +548,7 @@ index f09c61c..694550b 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +404,16 @@ function Postgres(a, b) {
+@@ -290,18 +414,16 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -424,7 +571,7 @@ index f09c61c..694550b 100644
}
}
-@@ -351,7 +463,7 @@ function Postgres(a, b) {
+@@ -351,7 +473,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -433,7 +580,7 @@ index f09c61c..694550b 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +474,25 @@ function Postgres(a, b) {
+@@ -362,6 +484,25 @@ function Postgres(a, b) {
})
}
@@ -459,7 +606,7 @@ index f09c61c..694550b 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +529,14 @@ function Postgres(a, b) {
+@@ -398,7 +539,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -475,10 +622,19 @@ index f09c61c..694550b 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +556,32 @@ function Postgres(a, b) {
+@@ -418,12 +566,41 @@ function Postgres(a, b) {
: move(c, full)
}
++ // GBrain (#6383): a connection the in-flight watchdog retired leaves rotation before its socket closes, so no
++ // statement is routed to it in between; onclose then returns it to `closed` like any other dropped connection.
++ function onstuck(c, info) {
++ c.queue !== ended && move(c, ended)
++ try {
++ options.onstuck && options.onstuck(info)
++ } catch (_) {}
++ }
++
+ function poisoned(c) {
+ if (c.queue === ended)
+ return
@@ -509,15 +665,40 @@ index f09c61c..694550b 100644
}
}
-@@ -491,6 +649,8 @@ function parseOptions(a, b) {
+@@ -444,7 +621,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')
+
+- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']
++ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']
+ const defaults = {
+ max : globalThis.Cloudflare ? 3 : 10,
+ ssl : false,
+@@ -453,6 +630,7 @@ function parseOptions(a, b) {
+ connect_timeout : 30,
+ max_lifetime : max_lifetime,
+ max_pipeline : 100,
++ inflight_timeout: null,
+ backoff : backoff,
+ keep_alive : 60,
+ prepare : true,
+@@ -491,11 +669,15 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
++ onstuck : o.onstuck,
++ onbuilderror : o.onbuilderror,
+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
+ parameters : {},
+- shared : { retries: 0, typeArrayMap: {} },
++ shared : { retries: 0, typeArrayMap: {}, completed: 0 },
+ ...mergeUserTypes(o.types)
+ }
+ }
diff --git a/cjs/src/query.js b/cjs/src/query.js
index 45327f2..1d09250 100644
--- a/cjs/src/query.js
@@ -575,10 +756,23 @@ index 8438f5d..c444310 100644
const out = xs[index++]
diff --git a/src/connection.js b/src/connection.js
-index 1b1cccd..c4d90e6 100644
+index 1b1cccd..a2e2deb 100644
--- a/src/connection.js
+++ b/src/connection.js
-@@ -78,6 +78,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -49,7 +49,7 @@ const errorFields = {
+ 82 : 'routine' // R
+ }
+
+-function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
++function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop, onstuck = noop } = {}) {
+ const {
+ sslnegotiation,
+ ssl,
+@@ -75,9 +75,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ , idleTimer = timer(end, options.idle_timeout)
+ , lifeTimer = timer(end, options.max_lifetime)
+ , connectTimer = timer(connectTimedOut, options.connect_timeout)
++ , inflightTimer = timer(inflightTimedOut, options.inflight_timeout)
let socket = null
, cancelMessage
@@ -588,7 +782,21 @@ index 1b1cccd..c4d90e6 100644
, errorResponse = null
, result = new Result()
, incoming = Buffer.alloc(0)
-@@ -143,11 +146,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -105,11 +109,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ , ended = null
+ , nonce = null
+ , query = null
++ , queryStart = 0
+ , final = null
+
+ const connection = {
+ queue: queues.closed,
+ idleTimer,
++ inflightSince: 0,
+ connect(query) {
+ initial = query
+ reconnect()
+@@ -143,11 +149,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
async function cancel({ pid, secret }, resolve, reject) {
@@ -604,21 +812,102 @@ index 1b1cccd..c4d90e6 100644
} catch (error) {
reject(error)
}
-@@ -170,11 +175,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
- : (query = q, query.active = true)
+@@ -163,25 +171,88 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ if (q.cancelled)
+ return
+
++ // GBrain (#6383): a statement is built and serialized before it joins this connection's queue. It used to
++ // join first, so a statement that failed to build (UNDEFINED_VALUE, MAX_PARAMETERS_EXCEEDED) behind an
++ // in-flight one rejected that head statement with its error, stayed queued with nothing on the wire, and
++ // every later reply on the socket was delivered one statement late until the process restarted.
++ let bytes
+ try {
+ q.state = backend
++ build(q)
++ bytes = toBuffer(q)
++ } catch (error) {
++ if (!query) {
++ // An idle connection owns the ReadyForQuery its Sync produces, exactly as a failed head statement did.
++ query = q
++ query.active = true
++ write(Sync)
++ armInflight()
++ }
++ options.onbuilderror && reportBuildError(q, error)
++ queryError(q, error)
++ return true
++ }
++
++ try {
+ query
+ ? sent.push(q)
+- : (query = q, query.active = true)
++ : (query = q, query.active = true, armInflight())
- build(q)
+- build(q)
+- return write(toBuffer(q))
+ const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
- return write(toBuffer(q))
++ return write(bytes)
&& !q.describeFirst
&& !q.cursorFn
&& sent.length < max_pipeline
- && (!q.options.onexecute || q.options.onexecute(connection))
+ && mayPipeline
} catch (error) {
- sent.length === 0 && write(Sync)
- errored(error)
-@@ -235,10 +241,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+- sent.length === 0 && write(Sync)
+- errored(error)
++ if (query === q) {
++ sent.length === 0 && write(Sync)
++ errored(error)
++ } else {
++ sent.remove(q)
++ queryError(q, error)
++ }
+ return true
+ }
+ }
+
++ function reportBuildError(q, error) {
++ try {
++ options.onbuilderror(error && error.code ? error.code : 'BUILD_FAILED', statementText(q))
++ } catch (_) {}
++ }
++
++ // The statement's text with $n placeholders, never its parameter values.
++ function statementText(q) {
++ const strings = Array.isArray(q.strings) ? q.strings : [String(q.strings)]
++ return String(q.string || strings.reduce((a, s, i) => a + '$' + i + s)).replace(/\s+/g, ' ').trim().slice(0, 200)
++ }
++
++ // GBrain (#6383): the head statement's clock. It starts when a statement becomes the head, restarts on every
++ // byte the server sends and stops at ReadyForQuery. A statement that outlives options.inflight_timeout with
++ // nothing coming back (a desynced connection, a pooler that swallowed a CancelRequest, a dead peer) has no
++ // server-side timeout left to save it: the connection is retired instead of holding its queue forever.
++ function armInflight() {
++ queryStart = connection.inflightSince = performance.now()
++ inflightTimer.start()
++ }
++
++ function inflightTimedOut() {
++ if (!query)
++ return
++ const stuck = { age_ms: Math.round(performance.now() - queryStart), queued: sent.length, statement: statementText(query) }
++ const s = socket
++ error(Errors.connection('CONNECTION_STUCK', options, socket))
++ query = null
++ connection.inflightSince = 0
++ onstuck(connection, stuck)
++ terminate()
++ if (s && !s.destroyed) {
++ const t = setTimeout(() => s.destroyed || s.destroy(), 1000)
++ t.unref && t.unref()
++ }
++ }
++
+ function toBuffer(q) {
+ if (q.parameters.length >= 65534)
+ throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded')
+@@ -235,10 +306,15 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
q.onlyDescribe && (delete statements[q.signature])
q.parameters = q.parameters || parameters
q.prepared = q.prepare && q.signature in statements
@@ -636,7 +925,7 @@ index 1b1cccd..c4d90e6 100644
typeof options.debug === 'function' && options.debug(id, string, parameters, types)
}
-@@ -295,7 +306,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -295,10 +371,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* c8 ignore next 3 */
function drain() {
@@ -645,7 +934,11 @@ index 1b1cccd..c4d90e6 100644
}
function data(x) {
-@@ -379,6 +390,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
++ query && inflightTimer.start()
+ if (incomings) {
+ incomings.push(x)
+ remaining -= x.length
+@@ -379,6 +456,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function error(err) {
@@ -654,7 +947,7 @@ index 1b1cccd..c4d90e6 100644
if (connection.queue === queues.connecting && options.host[retries + 1])
return
-@@ -388,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -388,6 +467,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function errored(err) {
@@ -663,7 +956,7 @@ index 1b1cccd..c4d90e6 100644
stream && (stream.destroy(err), stream = null)
query && queryError(query, err)
initial && (queryError(initial, err), initial = null)
-@@ -438,6 +453,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -438,19 +519,38 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
remaining = 0
incomings = null
clearImmediate(nextWriteTimer)
@@ -674,7 +967,11 @@ index 1b1cccd..c4d90e6 100644
socket.removeListener('data', data)
socket.removeListener('connect', connected)
idleTimer.cancel()
-@@ -447,10 +466,23 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ lifeTimer.cancel()
+ connectTimer.cancel()
++ inflightTimer.cancel()
++ connection.inflightSince = 0
+
socket.removeAllListeners()
socket = null
@@ -699,19 +996,29 @@ index 1b1cccd..c4d90e6 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -533,8 +565,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,8 +633,13 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
+ connection.status = x[5]
++ connection.inflightSince = 0
if (query) {
++ options.shared.completed++
if (errorResponse) {
+ // GBrain: a failed statement describes again next time instead of trusting shared parameter types.
+ query.sharedTypes && options.shared_types.delete(query.typesKey)
query.retried
? errored(query.retried)
: query.prepared && retryRoutines.has(errorResponse.routine)
-@@ -564,10 +599,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -550,6 +655,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ query = results = errorResponse = null
+ result = new Result()
+ connectTimer.cancel()
++ inflightTimer.cancel()
+
+ if (initial) {
+ if (target_session_attrs) {
+@@ -564,23 +670,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -726,7 +1033,13 @@ index 1b1cccd..c4d90e6 100644
}
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
-@@ -580,7 +617,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
+
+ if (query)
+- return // Consider opening if able and sent.length < 50
++ return armInflight() // Consider opening if able and sent.length < 50
+
+ connection.reserved
? !connection.reserved.release && x[5] === 73 // I
? ending
? terminate()
@@ -735,7 +1048,7 @@ index 1b1cccd..c4d90e6 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,6 +667,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -630,6 +738,9 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -745,7 +1058,7 @@ index 1b1cccd..c4d90e6 100644
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
}
-@@ -767,14 +807,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -767,14 +878,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
async function fetchArrayTypes() {
needsTypes = false
@@ -776,15 +1089,26 @@ index 1b1cccd..c4d90e6 100644
}
diff --git a/src/index.js b/src/index.js
-index c7fba3d..fc9f766 100644
+index c7fba3d..32efd8b 100644
--- a/src/index.js
+++ b/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() {
+@@ -62,10 +62,34 @@ function Postgres(a, b) {
+ , full = Queue()
+ , queues = { connecting, reserved, closed, ended, open, busy, full }
+
+- const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose }))
++ const connections = [...Array(options.max)].map(() => Connection(options, queues, { onopen, onend, onclose, onstuck }))
+
+ const sql = Sql(handler)
+
++ // GBrain: the pool's own queue lengths, read-only, for the consumer's pool diagnostics (#6317). A property
++ // getter, not an Object.assign member: Object.assign reads a getter once and copies its value, which froze
++ // these numbers at construction (#6383). `inflight_oldest_ms` is the age of the oldest head statement across
++ // the pool's connections and `completed` counts every ReadyForQuery that settled a statement.
++ Object.defineProperty(sql, 'pool', {
++ enumerable: false,
++ get() {
++ const now = performance.now()
+ return {
+ max: options.max,
+ open: open.length,
@@ -794,13 +1118,17 @@ index c7fba3d..fc9f766 100644
+ connecting: connecting.length,
+ closed: closed.length,
+ ended: ended.length,
-+ queued: queries.length
++ queued: queries.length,
++ inflight_oldest_ms: connections.reduce((age, c) => c.inflightSince ? Math.max(age, Math.round(now - c.inflightSince)) : age, 0),
++ completed: options.shared.completed
+ }
-+ },
++ }
++ })
++
+ Object.assign(sql, {
+ get parameters() { return options.parameters },
largeObject: largeObject.bind(null, sql),
- subscribe,
- CLOSE,
-@@ -200,40 +214,134 @@ function Postgres(a, b) {
+@@ -200,40 +224,134 @@ function Postgres(a, b) {
return await sql`select pg_notify(${ channel }, ${ '' + payload })`
}
@@ -954,7 +1282,7 @@ index c7fba3d..fc9f766 100644
let savepoints = 0
, connection
, prepare = null
-@@ -249,9 +357,13 @@ function Postgres(a, b) {
+@@ -249,9 +367,13 @@ function Postgres(a, b) {
}
async function scope(c, fn, name) {
@@ -968,7 +1296,7 @@ index c7fba3d..fc9f766 100644
let uncaughtError
, result
-@@ -281,6 +393,8 @@ function Postgres(a, b) {
+@@ -281,6 +403,8 @@ function Postgres(a, b) {
return result
function savepoint(name, fn) {
@@ -977,7 +1305,7 @@ index c7fba3d..fc9f766 100644
if (name && Array.isArray(name.raw))
return savepoint(sql => sql.apply(sql, arguments))
-@@ -290,18 +404,16 @@ function Postgres(a, b) {
+@@ -290,18 +414,16 @@ function Postgres(a, b) {
function handler(q) {
q.catch(e => uncaughtError || (uncaughtError = e))
@@ -1000,7 +1328,7 @@ index c7fba3d..fc9f766 100644
}
}
-@@ -351,7 +463,7 @@ function Postgres(a, b) {
+@@ -351,7 +473,7 @@ function Postgres(a, b) {
return new Promise((resolve, reject) => {
query.state
? query.active
@@ -1009,7 +1337,7 @@ index c7fba3d..fc9f766 100644
: query.cancelled = { resolve, reject }
: (
queries.remove(query),
-@@ -362,6 +474,25 @@ function Postgres(a, b) {
+@@ -362,6 +484,25 @@ function Postgres(a, b) {
})
}
@@ -1035,7 +1363,7 @@ index c7fba3d..fc9f766 100644
async function end({ timeout = null } = {}) {
if (ending)
return ending
-@@ -398,7 +529,14 @@ function Postgres(a, b) {
+@@ -398,7 +539,14 @@ function Postgres(a, b) {
move(c, ended)
}
@@ -1051,10 +1379,19 @@ index c7fba3d..fc9f766 100644
if (queries.length === 0)
return move(c, open)
-@@ -418,12 +556,32 @@ function Postgres(a, b) {
+@@ -418,12 +566,41 @@ function Postgres(a, b) {
: move(c, full)
}
++ // GBrain (#6383): a connection the in-flight watchdog retired leaves rotation before its socket closes, so no
++ // statement is routed to it in between; onclose then returns it to `closed` like any other dropped connection.
++ function onstuck(c, info) {
++ c.queue !== ended && move(c, ended)
++ try {
++ options.onstuck && options.onstuck(info)
++ } catch (_) {}
++ }
++
+ function poisoned(c) {
+ if (c.queue === ended)
+ return
@@ -1085,15 +1422,40 @@ index c7fba3d..fc9f766 100644
}
}
-@@ -491,6 +649,8 @@ function parseOptions(a, b) {
+@@ -444,7 +621,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')
+
+- const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive']
++ const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'inflight_timeout']
+ const defaults = {
+ max : globalThis.Cloudflare ? 3 : 10,
+ ssl : false,
+@@ -453,6 +630,7 @@ function parseOptions(a, b) {
+ connect_timeout : 30,
+ max_lifetime : max_lifetime,
+ max_pipeline : 100,
++ inflight_timeout: null,
+ backoff : backoff,
+ keep_alive : 60,
+ prepare : true,
+@@ -491,11 +669,15 @@ function parseOptions(a, b) {
onnotice : o.onnotice,
onnotify : o.onnotify,
onclose : o.onclose,
+ onpoisoned : o.onpoisoned,
++ onstuck : o.onstuck,
++ onbuilderror : o.onbuilderror,
+ shared_types : o.shared_types === false ? null : o.shared_types instanceof Map ? o.shared_types : new Map(),
onparameter : o.onparameter,
socket : o.socket,
transform : parseTransform(o.transform || { undefined: undefined }),
+ parameters : {},
+- shared : { retries: 0, typeArrayMap: {} },
++ shared : { retries: 0, typeArrayMap: {}, completed: 0 },
+ ...mergeUserTypes(o.types)
+ }
+ }
diff --git a/src/query.js b/src/query.js
index 0d44a15..9696778 100644
--- a/src/query.js
@@ -1151,10 +1513,10 @@ index c4ef971..8fba891 100644
const out = xs[index++]
diff --git a/types/index.d.ts b/types/index.d.ts
-index 13c3432..03f1ddf 100644
+index 13c3432..3623312 100644
--- a/types/index.d.ts
+++ b/types/index.d.ts
-@@ -119,6 +119,18 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
+@@ -119,6 +119,32 @@ interface BaseOptions<T extends Record<string, postgres.PostgresType>> {
*/
publications: string
onclose: (connId: number) => void;
@@ -1164,6 +1526,20 @@ index 13c3432..03f1ddf 100644
+ */
+ onpoisoned: (status: string) => void;
+ /**
++ * GBrain: seconds a head statement may wait for the server with nothing coming back
++ * before the connection is retired and every statement queued on it rejects with
++ * `CONNECTION_STUCK`. Null disables the watchdog.
++ * @default null
++ */
++ inflight_timeout: number | null;
++ /** GBrain: called once per connection the in-flight watchdog retired. */
++ onstuck: (stuck: { age_ms: number; queued: number; statement: string }) => void;
++ /**
++ * GBrain: called when a statement fails to build (`UNDEFINED_VALUE`, `MAX_PARAMETERS_EXCEEDED`);
++ * `statement` is its text with `$n` placeholders, never parameter values.
++ */
++ onbuilderror: (code: string, statement: string) => void;
++ /**
+ * GBrain: share the parameter types of a described statement across this pool's
+ * connections, so a connection running it for the first time skips the describe
+ * round trip and keeps pipelining. Only built-in types are shared.
@@ -1173,7 +1549,7 @@ index 13c3432..03f1ddf 100644
backoff: boolean | ((attemptNum: number) => number);
max_lifetime: number | null;
keep_alive: number | null;
-@@ -605,7 +617,7 @@ declare namespace postgres {
+@@ -605,7 +631,7 @@ declare namespace postgres {
writable(): Promise<Writable>;
execute(): this;
@@ -1182,7 +1558,7 @@ index 13c3432..03f1ddf 100644
/**
* @deprecated `.stream` has been renamed to `.forEach`
-@@ -659,6 +671,7 @@ declare namespace postgres {
+@@ -659,6 +685,7 @@ declare namespace postgres {
| Fragment[]
interface UnsafeQueryOptions {
@@ -1190,16 +1566,16 @@ index 13c3432..03f1ddf 100644
/**
* When executes query as prepared statement.
* @default false
-@@ -705,6 +718,8 @@ declare namespace postgres {
+@@ -705,6 +732,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 };
++ pool: { max: number; open: number; busy: number; full: number; reserved: number; connecting: number; closed: number; ended: number; queued: number; inflight_oldest_ms: number; completed: number };
end(options?: { timeout?: number | undefined } | undefined): Promise<void>;
-@@ -717,10 +732,11 @@ declare namespace postgres {
+@@ -717,10 +746,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>>;
@@ -1212,7 +1588,7 @@ index 13c3432..03f1ddf 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 +744,7 @@ declare namespace postgres {
+@@ -728,6 +758,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 df40047a15..4cf14643b8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2049 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 342 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 3007 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)
-src/core/postgres-engine.ts 3002 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)
+src/core/postgres-engine.ts 3009 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); +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
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 2250 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move)
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/pool-gauge.ts b/src/core/pool-gauge.ts
index 6b0b257230..b8d4950c5e 100644
--- a/src/core/pool-gauge.ts
+++ b/src/core/pool-gauge.ts
@@ -112,6 +112,11 @@ export class PoolIncidentCounter {
return this.buildFailures;
}
+ /** The driver hooks of one pool, bound to this counter (what an engine passes as `PoolHealthHooks`). */
+ hooks(pool: 'read' | 'direct'): { onstuck: (info: { age_ms: number; queued: number; statement: string }) => void; onbuilderror: (code: string, statement: string) => void } {
+ return { onstuck: (info) => this.recordStuck(pool, info), onbuilderror: (code, statement) => this.recordBuildFailure(pool, code, statement) };
+ }
+
recordStuck(pool: 'read' | 'direct', info: { age_ms: number; queued: number; statement: string }): void {
this.stuck += 1;
try { console.warn(formatStuckConnectionWarning(pool, info)); } catch { /* best-effort */ }
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 7329d368a3..a387dd25b1 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -209,10 +209,7 @@ export class PostgresEngine implements BrainEngine {
private readonly onPoisoned = (pool: 'read' | 'direct', status: string) => this.poisonedDiscards.record(pool, status);
/** #6383: stuck-connection retirements and build failures, per engine, with their warn lines. */
private poolIncidents = new PoolIncidentCounter();
- private readonly poolHealth = (pool: 'read' | 'direct') => ({
- onstuck: (info: db.StuckConnectionInfo) => this.poolIncidents.recordStuck(pool, info),
- onbuilderror: (code: string, statement: string) => this.poolIncidents.recordBuildFailure(pool, code, statement),
- });
+ private readonly poolHealth = (pool: 'read' | 'direct') => this.poolIncidents.hooks(pool);
/**
* #1471: module-singleton OWNERSHIP token. `true` only for the engine whose
* connect() actually created the shared db.ts `sql` singleton (returned
diff --git a/test/pool-health-6383.test.ts b/test/pool-health-6383.test.ts
index 0975e39cbe..3a9e194bab 100644
--- a/test/pool-health-6383.test.ts
+++ b/test/pool-health-6383.test.ts
@@ -10,19 +10,15 @@
* while an earlier deep probe is still pending, and 200 with the pool block
* otherwise.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'bun:test';
import { gucMilliseconds, poolHealthOptions, resolveInflightTimeoutSeconds } from '../src/core/db.ts';
+import { withEnv } from './helpers/with-env.ts';
import { formatBuildFailureWarning, formatStuckConnectionWarning, PoolIncidentCounter } from '../src/core/pool-gauge.ts';
import { driverPoolStats, poolHealthSnapshot } from '../src/core/postgres-engine/pool-stats.ts';
import { formatPoolRecoveredInfo, formatPoolStalledWarning, PoolStallWatch } from '../src/core/postgres-engine/pool-stall-watch.ts';
import { probeDeepHealth } from '../src/commands/serve-http-metrics.ts';
import type { BrainEngine } from '../src/core/engine.ts';
-const previousGrace = process.env.GBRAIN_PG_STUCK_GRACE_MS;
-afterEach(() => {
- if (previousGrace === undefined) delete process.env.GBRAIN_PG_STUCK_GRACE_MS; else process.env.GBRAIN_PG_STUCK_GRACE_MS = previousGrace;
-});
-
describe('in-flight budget', () => {
test('gucMilliseconds reads every statement_timeout unit and treats a bare number as milliseconds', () => {
expect(gucMilliseconds('5min')).toBe(300_000);
@@ -35,33 +31,32 @@ describe('in-flight budget', () => {
expect(gucMilliseconds('soon')).toBeNull();
});
- test('resolveInflightTimeoutSeconds is statement_timeout plus a 30 s default grace, in whole seconds', () => {
- delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
- expect(resolveInflightTimeoutSeconds('5min')).toBe(330);
- expect(resolveInflightTimeoutSeconds('1800000')).toBe(1830);
- process.env.GBRAIN_PG_STUCK_GRACE_MS = '500';
- expect(resolveInflightTimeoutSeconds('500ms')).toBe(1);
- });
-
- test('the watchdog is off without a statement timeout and with grace 0 or off', () => {
- delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
- expect(resolveInflightTimeoutSeconds(undefined)).toBeNull();
- process.env.GBRAIN_PG_STUCK_GRACE_MS = '0';
- expect(resolveInflightTimeoutSeconds('5min')).toBeNull();
- process.env.GBRAIN_PG_STUCK_GRACE_MS = 'off';
- expect(resolveInflightTimeoutSeconds('5min')).toBeNull();
- process.env.GBRAIN_PG_STUCK_GRACE_MS = 'nonsense';
- expect(resolveInflightTimeoutSeconds('5min')).toBe(330);
- });
-
- test('poolHealthOptions carries the hooks and the budget into postgres.js options', () => {
- delete process.env.GBRAIN_PG_STUCK_GRACE_MS;
- const onstuck = () => {};
- const options = poolHealthOptions({ onstuck }, '5min');
- expect(options.onstuck).toBe(onstuck);
- expect(options.onpoisoned).toBeUndefined();
- expect(options.inflight_timeout).toBe(330);
- expect(poolHealthOptions(undefined, undefined).inflight_timeout).toBeNull();
+ test('resolveInflightTimeoutSeconds is statement_timeout plus a 30 s default grace, in whole seconds', async () => {
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: undefined }, async () => {
+ expect(resolveInflightTimeoutSeconds('5min')).toBe(330);
+ expect(resolveInflightTimeoutSeconds('1800000')).toBe(1830);
+ });
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: '500' }, async () => {
+ expect(resolveInflightTimeoutSeconds('500ms')).toBe(1);
+ });
+ });
+
+ test('the watchdog is off without a statement timeout and with grace 0 or off', async () => {
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: undefined }, async () => { expect(resolveInflightTimeoutSeconds(undefined)).toBeNull(); });
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: '0' }, async () => { expect(resolveInflightTimeoutSeconds('5min')).toBeNull(); });
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: 'off' }, async () => { expect(resolveInflightTimeoutSeconds('5min')).toBeNull(); });
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: 'nonsense' }, async () => { expect(resolveInflightTimeoutSeconds('5min')).toBe(330); });
+ });
+
+ test('poolHealthOptions carries the hooks and the budget into postgres.js options', async () => {
+ await withEnv({ GBRAIN_PG_STUCK_GRACE_MS: undefined }, async () => {
+ const onstuck = () => {};
+ const options = poolHealthOptions({ onstuck }, '5min');
+ expect(options.onstuck).toBe(onstuck);
+ expect(options.onpoisoned).toBeUndefined();
+ expect(options.inflight_timeout).toBe(330);
+ expect(poolHealthOptions(undefined, undefined).inflight_timeout).toBeNull();
+ });
});
});