Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): connection-wait and loop-lag evidence on consumer phases (#5801)

garrytan184646b8db80
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 32b533e4e8..10c749b79f 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -582,8 +582,13 @@ checkpoint did not advance. The message names both errors (redacted, at most
the SQLSTATE (for example `53300` when a pooler's client limit is reached),
a write-error code, `storage_error`, or `deadline_exceeded` when the phase
overran its five-second budget. `message` is the redacted error text, one line,
-at most 200 characters. Unfinished work stays tracked and is retried; nothing
-is lost. Run `gbrain sources writer status --json` to see what is waiting. The
+at most 200 characters. Connection-wait evidence follows on Postgres:
+`first_conn_ms` is the time from phase start until the phase obtained a
+connection; `checkout=not_observed conn_wait_ms=<n>` means it had not obtained
+one after `n` milliseconds (a saturated pool or pooler, not a slow query); and
+`loop_lag_ms` is the longest event-loop delay during the phase (a busy or
+starved process). The same fields appear in the consumer's status snapshot
+under `phase`. Unfinished work stays tracked and is retried; nothing is lost. Run `gbrain sources writer status --json` to see what is waiting. The
line is rate-limited (one per second, one per phase and code every 30 seconds).
An idle consumer keeps one ordinary-pool connection for its work probe and
never holds a direct or session-pooler connection, so a
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 650311398c..8a9c914f2b 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -37,7 +37,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`). Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index a8c79d9ca0..998ce2a2d2 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/pool-budget.ts` + `src/core/persistence/pool-capacity.ts` — physical-pool shared long-hold ceilings retain one ordinary/control connection across engine clones; pool size one pauses canonical consumption with `writer_pool_capacity`. Publication concurrency is capped at two per actual Postgres pool and one per PGLite owner. `persistence/takes-prepare.ts` journals semantic takes with frozen dates/resolver identity and original/current holder ceilings; canonical row updates and receipt commit together. Publication retains the actual affected holders privately in authority JSON, so narrowed holder grants also hide committed/replayed receipts after input compaction.
-- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`.
+- `src/core/pool-gauge.ts` — `CheckoutGauge`: approximate in-flight counters at the engine's raw/direct/reserved/tx seams, surfaced via duck-typed `PostgresEngine.getPoolDiagnostics()` (no BrainEngine change, no PGLite stub). HONESTY CONTRACT in the module doc: tagged-template traffic is untracked; consumers must label counts as a subset and never derive waiter/available figures. Fail-open (clamped release, try/finally around sync-throwing runUnsafe). Consumed by db-probe.ts. Pinned by `test/pool-gauge.test.ts`. `PoisonedDiscardCounter` counts the driver's non-idle connection discards and writes one fixed-shape `pg_connection_poisoned` warn line each; the engine wires it into every pool it creates and reports it as `poisonedDiscards`. `onCheckout(listener)` (exposed as `PostgresEngine.onCheckout`) fires after a connection is actually obtained: signalled raw reserve resolution, transaction-callback entry and `withReservedConnection` reserve resolution; it never fires for a call still waiting (pinned by `test/e2e/postgres-checkout-observer.test.ts`).
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The package-private `#postgres` import maps directly to the shipped cancellation-capable `vendor/postgres` source (the same source is embedded by compiled builds); `vendor/README.md` and the hash-verifying updater own provenance and regeneration. `postgres-engine/cancellation.ts` shares actual reserved-owner capability detection, typed `postgres_cancellation_unavailable` errors, and abort-bounded reservation with late-owner release; unsignalled diagnostic queries remain usable. Signalled SQL must retain cancellation/discard safety, including through transaction-mode poolers. The migrated storage domains' methods are one-line delegations into `src/core/engine-sql/<domain>.ts` over the private `engineSql` getter (a fresh Postgres adapter over `this.sql` on every access; RLS-scoped reads brand the `withScopedReadTransaction` handle with `scopedRead`), Postgres-only code stays under `src/core/postgres-engine/`, and the façade keeps its full public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (an `unnest(${arr}::text[])` array-literal path would crash Postgres with "malformed array literal" on free text such as calendar/Zoom context) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` (in `src/core/engine-sql/chunks.ts`, both engines) uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. The chunk SQL below lives once in `src/core/engine-sql/chunks.ts`; the engine resolves the active column and source scope, owns the retry/transaction wrapper and the RLS scope transaction, and passes them in. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` routes text-embedding writes through the column registry (both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; so a registry-routed brain never writes with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap(conn)` BEFORE replaying SCHEMA_SQL — a one-line delegation to the shared `src/core/engine-sql/bootstrap.ts` (Postgres dialect hooks: `current_schema()` probes plus the Postgres-blob-only `dream_verdicts.expires_at` probe); the entire probe path runs on the DDL connection threaded from `initSchema` (so concurrent bootstraps cannot race on a Supabase pooler). `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-lifecycle.test.ts` (concurrent-connect ownership, `db.disconnect()` detaching the singleton before awaiting `end()`, and the instance-reconnect `_reconnecting` guard). `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` do not hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds do not pin the worker's shared read pool — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`. `getRawData` joins `pages` and adds `p.deleted_at IS NULL` unless `opts.includeDeleted` (the `alive` fragment next to `privacy` in all six branches) so raw session metadata follows the page soft-delete; PGLite mirrors it with one `where.push`; pinned by the standalone getRawData describe in `test/e2e/engine-parity.test.ts` (PGLite arm always runs; Postgres arm when DATABASE_URL is set). `includeDeleted` is NOT on the shared `PageReadScope` (only getRawData honors it) — it is declared per-method as `getRawData(slug, source?, opts?: PageReadScope & { includeDeleted?: boolean })` in engine.ts and both engines; resolved only by trusted callers (export, engine migration; the ingest probe passes it but only ever runs against a live page), never from MCP parameters (`get_raw_data` builds its scope from `readPolicyOpts(ctx)`).
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers every BrainEngine method whose SQL has not moved to `src/core/engine-sql/` (rows in `scripts/engine-sql-baseline.tsv`), written as parity twins of the PGLite methods (search arms, graph traversal caps, source-scoped stats and health, page lifecycle and soft delete, chunk writes, transaction routing). Migrated domains are one-line delegations over the private `engineSql` getter (a fresh adapter over `this.sql` on every access); reads that were RLS-scoped on master keep their own `withScopedReadTransaction` call and hand engine-sql `scopedRead(this.engineSqlOn(tx))`, an adapter over the scoped handle; `runUnsafe` forwards `prepare`/`simple` only when the engine-sql adapter sets them.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 1e2850d846..2fcac0478c 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -338,6 +338,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/fixture-reset-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/postgres-poisoned-connection.test.ts",
+ "test/e2e/postgres-checkout-observer.test.ts",
"test/e2e/db-lock-acquisition-token.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts",
@@ -524,7 +525,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/oauth-provider.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-oauth.test.ts", "test/e2e/token-usage-skip-locked.test.ts"],
// #5730: non-idle pooled connections are discarded by the vendored driver.
"vendor/postgres/**": ["test/e2e/postgres-poisoned-connection.test.ts", "test/e2e/persistence-chaos.test.ts"],
- "src/core/pool-gauge.ts": ["test/e2e/postgres-poisoned-connection.test.ts"],
+ "src/core/pool-gauge.ts": ["test/e2e/postgres-poisoned-connection.test.ts", "test/e2e/postgres-checkout-observer.test.ts"],
"src/core/oauth-grants.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-consent.test.ts"],
"src/core/grants/lifecycle.ts": ["test/e2e/oauth-grant-transactions.test.ts", "test/e2e/serve-http-consent.test.ts"],
"src/commands/serve-http-clients.ts": ["test/e2e/serve-http-consent.test.ts"],
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 787efa1833..57db0eae18 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -21,7 +21,7 @@ src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation;
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
src/core/operations.ts 331 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
src/core/pglite-engine.ts 3225 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); 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)
-src/core/postgres-engine.ts 3258 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)
+src/core/postgres-engine.ts 3263 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)
src/core/search/hybrid.ts 1584 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
src/core/types.ts 2105 ratchet +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
src/core/minions/queue.ts 2522 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
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 9546705db2..006f783c6b 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -11,6 +11,12 @@ import { runPersistenceEffects } from './effects.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { isWriteErrorCode } from './types.ts';
import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';
+
+type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };
+/** #5801: the phase a connection checkout belongs to, carried through its async chain. */
+const phaseScope = new AsyncLocalStorage<{ observation: PhaseObservation; startedAt: number }>();
/** #5233: one-line, redacted, length-capped error text for the consumer's stderr line. */
function errorDetail(error: unknown): string | undefined {
@@ -66,7 +72,11 @@ export class PersistenceConsumer {
private progressWake = false;
private lastError: { code: string; at: string; phase?: string } | undefined;
private abort = new AbortController();
- private phaseObservation: { name: string; started_at: string; deadline_exceeded: boolean; attempt: number } | undefined;
+ private phaseObservation: PhaseObservation | undefined;
+ private phaseStartedAt = 0;
+ private lastPhaseTiming: string | undefined;
+ private loopDelay: IntervalHistogram | null | undefined;
+ private unobserveCheckout: (() => void) | undefined;
private phaseAttempts = 0;
private lastLog: { key: string; at: number } | undefined;
private lastPhaseError: string | undefined;
@@ -77,6 +87,10 @@ export class PersistenceConsumer {
private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void } = {}) {
this.hostId = opts.hostId ?? localHostId();
}
+ private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {
+ const engine = this.engine as { onCheckout?: unknown };
+ return typeof engine.onCheckout === 'function' ? (engine.onCheckout as (listener: () => void) => () => void).bind(this.engine) : undefined;
+ }
start(): void { this.stopping = false; this.abort = new AbortController(); this.fullTickRequested = true; this.idleDelayMs = this.pollMs; this.schedule(0); }
/**
* Work admitted by this process: tick now instead of waiting out the idle
@@ -342,19 +356,49 @@ export class PersistenceConsumer {
return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,
sampled_at: new Date().toISOString(), observation_scope: 'current_process_reset_on_restart',
preparation_attempts: this.preparationAttempts,
- phase: this.phaseObservation ? { ...this.phaseObservation } : null,
+ phase: this.phaseObservation ? { ...this.phaseObservation, ...this.phaseTiming(this.phaseObservation, this.phaseStartedAt) } : null,
preparations: [...this.preparing.values()].map(value => ({ ...value })),
...(this.lastError ? { last_error: { ...this.lastError } } : {}) };
}
+ /**
+ * #5801: connection-wait and event-loop evidence for a phase. A checkout is
+ * observed only after a connection was obtained inside this phase's async
+ * chain; until then the phase reports how long it has been waiting.
+ */
+ private phaseTiming(observation: PhaseObservation, startedAt: number): { checkout?: 'not_observed'; conn_wait_ms?: number; loop_lag_ms?: number } {
+ let lag: number | undefined;
+ try { if (this.loopDelay) lag = Math.round(this.loopDelay.max / 1e6); } catch { /* fail-open */ }
+ return {
+ ...(this.unobserveCheckout && observation.first_conn_ms === undefined
+ ? { checkout: 'not_observed' as const, conn_wait_ms: Math.round(performance.now() - startedAt) } : {}),
+ ...(lag === undefined ? {} : { loop_lag_ms: lag }),
+ };
+ }
+ private timingText(observation: PhaseObservation, startedAt: number): string {
+ const fields: Record<string, unknown> = { first_conn_ms: observation.first_conn_ms, ...this.phaseTiming(observation, startedAt) };
+ return Object.entries(fields).filter(([, value]) => value !== undefined).map(([key, value]) => ` ${key}=${value}`).join('');
+ }
private async phase<T>(name: string, run: (signal?: AbortSignal) => Promise<T>): Promise<T> {
- const observation = { name, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.phaseAttempts };
+ const observation: PhaseObservation = { name, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.phaseAttempts };
+ const startedAt = performance.now();
this.phaseObservation = observation;
+ this.phaseStartedAt = startedAt;
+ this.unobserveCheckout ??= this.checkoutObservable?.(() => {
+ const scope = phaseScope.getStore();
+ if (scope && scope.observation.first_conn_ms === undefined) scope.observation.first_conn_ms = Math.round(performance.now() - scope.startedAt);
+ });
+ if (this.loopDelay === undefined) {
+ try { this.loopDelay = monitorEventLoopDelay({ resolution: 10 }); this.loopDelay.enable(); } catch { this.loopDelay = null; }
+ }
+ try { this.loopDelay?.reset(); } catch { /* fail-open */ }
const abort = new AbortController();
const stop = () => abort.abort(this.abort.signal.reason);
this.abort.signal.addEventListener('abort', stop, { once: true });
if (this.stopping) stop();
- const timer = setTimeout(() => { observation.deadline_exceeded = true; abort.abort(); this.log(name, 'deadline_exceeded'); }, this.opts.phaseMs ?? 5000);
- try { return await run(this.engine.kind === 'postgres' ? abort.signal : undefined); }
+ const timer = setTimeout(() => {
+ observation.deadline_exceeded = true; abort.abort(); this.log(name, 'deadline_exceeded', undefined, this.timingText(observation, startedAt));
+ }, this.opts.phaseMs ?? 5000);
+ try { return await phaseScope.run({ observation, startedAt }, () => run(this.engine.kind === 'postgres' ? abort.signal : undefined)); }
catch (error) {
const cancelled = error as { name?: unknown; code?: unknown; message?: unknown } | null;
if (this.stopping && abort.signal.aborted && abort.signal.reason === this.abort.signal.reason
@@ -363,7 +407,7 @@ export class PersistenceConsumer {
&& /^(?:57014: )?canceling statement due to user request$/.test(cancelled.message))) {
throw this.abort.signal.reason;
}
- this.lastPhaseError = name; throw error;
+ this.lastPhaseError = name; this.lastPhaseTiming = this.timingText(observation, startedAt); throw error;
}
finally { clearTimeout(timer); this.abort.signal.removeEventListener('abort', stop); this.phaseObservation = undefined; }
}
@@ -373,14 +417,15 @@ export class PersistenceConsumer {
this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),
...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };
if (this.opts.onError) this.opts.onError(error);
- else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error));
+ else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error), this.lastPhaseError ? this.lastPhaseTiming : undefined);
this.lastPhaseError = undefined;
+ this.lastPhaseTiming = undefined;
}
- private log(phase: string, code: string, detail?: string): void {
+ private log(phase: string, code: string, detail?: string, timing = ''): void {
const key = `${phase}:${code}`, at = Date.now();
if (this.lastLog && (at - this.lastLog.at < 1000 || this.lastLog.key === key && at - this.lastLog.at < 30_000)) return;
this.lastLog = { key, at };
- if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}`
+ if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}`
+ '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');
}
private async execute(row: WriteRequest): Promise<boolean> {
@@ -456,5 +501,9 @@ export class PersistenceConsumer {
await this.effectsWorker;
await this.topologyWorker;
await this.maintenanceWorker;
+ this.unobserveCheckout?.();
+ this.unobserveCheckout = undefined;
+ try { this.loopDelay?.disable(); } catch { /* fail-open */ }
+ this.loopDelay = undefined;
}
}
diff --git a/src/core/pool-gauge.ts b/src/core/pool-gauge.ts
index 3168873f6d..42ae42d820 100644
--- a/src/core/pool-gauge.ts
+++ b/src/core/pool-gauge.ts
@@ -33,6 +33,24 @@ export interface PoolGaugeSnapshot {
export class CheckoutGauge {
private counts: PoolGaugeSnapshot = { raw: 0, direct: 0, reserved: 0, tx: 0 };
+ private checkoutListeners = new Set<() => void>();
+
+ /**
+ * #5801: `listener` runs after a connection is actually obtained (reserve
+ * resolution or transaction-callback entry), never when a call merely starts
+ * waiting. Callers attribute the call to their own work (for example through
+ * AsyncLocalStorage); the gauge itself knows nothing about callers.
+ */
+ onCheckout(listener: () => void): () => void {
+ this.checkoutListeners.add(listener);
+ return () => { this.checkoutListeners.delete(listener); };
+ }
+
+ checkedOut(): void {
+ for (const listener of this.checkoutListeners) {
+ try { listener(); } catch { /* best-effort */ }
+ }
+ }
acquire(kind: GaugeKind): void {
this.counts[kind] += 1;
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index a199c9dd86..5cd62581b9 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -602,6 +602,7 @@ export class PostgresEngine implements BrainEngine {
if (!this._pageTransaction) this.checkoutGauge.acquire('tx');
try {
return await (conn.begin(async (handle) => {
+ if (!this._pageTransaction) this.checkoutGauge.checkedOut();
const tx = composablePostgresTransaction(handle);
// Create a scoped engine with tx as its connection, no shared state mutation
const txEngine = Object.create(this) as PostgresEngine;
@@ -642,6 +643,7 @@ export class PostgresEngine implements BrainEngine {
releasePermit();
throw e;
}
+ this.checkoutGauge.checkedOut();
try {
const conn: ReservedConnection = {
async executeRaw<R = Record<string, unknown>>(
@@ -681,6 +683,9 @@ export class PostgresEngine implements BrainEngine {
* it optionally, same pattern as `engine.reconnect`). Fail-open: returns
* null instead of throwing.
*/
+ /** #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 {
try {
const max = (this.sql as unknown as { options?: { max?: number } }).options?.max;
@@ -3030,7 +3035,7 @@ export class PostgresEngine implements BrainEngine {
signal?.addEventListener('abort', onAbort, { once: true });
try {
reserved = signal && typeof conn.reserve === 'function' ? await reserveWithCancellation(opts => conn.reserve(opts), signal) : undefined;
- if (reserved) conn = reserved;
+ if (reserved) { conn = reserved; this.checkoutGauge.checkedOut(); }
owner = reserved ?? conn as unknown as postgres.TransactionSql;
if (signal?.aborted) throw new DOMException('aborted', 'AbortError');
if (signal && !hasPostgresCancellationCapability(owner)) throw postgresCancellationUnavailable();
diff --git a/test/e2e/postgres-checkout-observer.test.ts b/test/e2e/postgres-checkout-observer.test.ts
new file mode 100644
index 0000000000..f1cdc8d8a6
--- /dev/null
+++ b/test/e2e/postgres-checkout-observer.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #5801: the engine's checkout observer fires only once a connection is
+ * actually obtained (reserve resolution or transaction-callback entry), never
+ * while a call is still waiting for a pool slot. The persistence consumer
+ * builds its first_conn_ms / checkout=not_observed evidence on this seam.
+ *
+ * Regression that fails it: firing at the gauge's acquire() (before the wait),
+ * or not firing on one of the three acquisition paths.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+let engine: PostgresEngine | undefined;
+afterEach(async () => { await engine?.disconnect(); engine = undefined; });
+
+async function connect(poolSize: number): Promise<{ engine: PostgresEngine; checkouts: () => number }> {
+ assertSafeE2eDatabaseUrl(url!);
+ engine = new PostgresEngine();
+ await engine.connect({ engine: 'postgres', database_url: url!, poolSize });
+ let count = 0;
+ engine.onCheckout(() => { count++; });
+ return { engine, checkouts: () => count };
+}
+
+describe.skipIf(!url)('#5801 engine checkout observer', () => {
+ test('fires once per acquisition on the signalled raw, transaction and reserved paths, never for unsignalled pooled queries', async () => {
+ const { engine, checkouts } = await connect(3);
+ await engine.executeRaw('SELECT 1');
+ expect(checkouts()).toBe(0);
+ await engine.executeRaw('SELECT 1', undefined, { signal: new AbortController().signal });
+ expect(checkouts()).toBe(1);
+ await engine.transaction(async tx => { expect(checkouts()).toBe(2); await tx.executeRaw('SELECT 1'); });
+ await engine.withReservedConnection(async conn => { expect(checkouts()).toBe(3); await conn.executeRaw('SELECT 1'); });
+ expect(checkouts()).toBe(3);
+ });
+
+ test('a call waiting for a pool slot is not observed until it obtains one', async () => {
+ const { engine, checkouts } = await connect(2);
+ const release = Promise.withResolvers<void>();
+ let held = 0;
+ const holding = Array.from({ length: 2 }, () => engine.transaction(async tx => {
+ await tx.executeRaw('SELECT 1'); held++; await release.promise;
+ }));
+ while (held < 2) await Bun.sleep(5);
+ expect(checkouts()).toBe(2);
+ const waiting = engine.executeRaw('SELECT 1', undefined, { signal: new AbortController().signal });
+ await Bun.sleep(200);
+ expect(checkouts()).toBe(2);
+ release.resolve();
+ await Promise.all(holding);
+ await waiting;
+ expect(checkouts()).toBe(3);
+ });
+});
diff --git a/test/persistence-consumer-log.test.ts b/test/persistence-consumer-log.test.ts
index c76209948b..31833014cc 100644
--- a/test/persistence-consumer-log.test.ts
+++ b/test/persistence-consumer-log.test.ts
@@ -2,10 +2,14 @@
* The resident consumer's stderr line is the only trace an operator gets when
* a phase fails or overruns. #5233: the line carried only an error code, so a
* pooler's "max clients reached" was invisible. It now carries a redacted,
- * one-line, length-capped message, a fix command and a docs anchor.
+ * one-line, length-capped message, a fix command and a docs anchor. #5801: it
+ * also says whether the phase ever obtained a connection (first_conn_ms, or
+ * checkout=not_observed with the time spent waiting) and the event-loop lag.
*
* Regression that fails it: dropping the message (or the redaction) from the
- * line. Existing coverage asserts consumer state, not this line.
+ * line, reporting a checkout that happened after the deadline or in another
+ * caller's async chain, or omitting the timing fields. Existing coverage
+ * asserts consumer state, not this line.
*/
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
@@ -26,7 +30,7 @@ function failingEngine(error: Error): BrainEngine {
return new Proxy({ kind: 'pglite' } as Record<string, unknown>, {
get(target, prop) {
if (prop in target) return target[prop as string];
- if (prop === 'then') return undefined;
+ if (prop === 'then' || prop === 'onCheckout') return undefined;
return async () => { throw error; };
},
}) as unknown as BrainEngine;
@@ -52,3 +56,68 @@ describe('persistence consumer stderr line', () => {
expect(line!.trimEnd().includes('\n')).toBe(false);
});
});
+
+function delayedCheckoutEngine(checkoutAfterMs: number, failAfterMs: number, error: Error) {
+ const listeners = new Set<() => void>();
+ const call = async () => {
+ await Bun.sleep(checkoutAfterMs);
+ for (const listener of listeners) listener();
+ await Bun.sleep(failAfterMs);
+ throw error;
+ };
+ const target: Record<string, unknown> = {
+ kind: 'postgres',
+ onCheckout: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; },
+ };
+ const engine = new Proxy(target, {
+ get(t, prop) {
+ if (prop in t) return t[prop as string];
+ if (prop === 'then') return undefined;
+ return call;
+ },
+ }) as unknown as BrainEngine;
+ return { engine, unrelatedCheckout: () => { for (const listener of listeners) listener(); } };
+}
+
+describe('#5801 connection-wait evidence on the consumer line', () => {
+ const failure = () => Object.assign(new Error('synthetic storage failure'), { code: '08006' });
+
+ test('a checkout that arrives after the deadline is reported as not_observed with the time waited', async () => {
+ const { engine } = delayedCheckoutEngine(200, 0, failure());
+ captureStderr();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw failure(); }, { hostId: crypto.randomUUID(), phaseMs: 100 });
+ try { await consumer.tick(); } finally { await consumer.stop(); }
+ const line = stderr.find(entry => entry.includes('reason=deadline_exceeded'));
+ expect(line).toBeDefined();
+ expect(line).toContain('checkout=not_observed');
+ expect(line).not.toContain('first_conn_ms=');
+ expect(Number(/conn_wait_ms=(\d+)/.exec(line!)![1])).toBeGreaterThanOrEqual(100);
+ expect(line).toMatch(/loop_lag_ms=\d+/);
+ });
+
+ test('a checkout inside the phase reports its real acquisition time', async () => {
+ const { engine } = delayedCheckoutEngine(150, 50, failure());
+ captureStderr();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw failure(); }, { hostId: crypto.randomUUID(), phaseMs: 2_000 });
+ try { await consumer.tick(); } finally { await consumer.stop(); }
+ const line = stderr.find(entry => entry.includes('reason=08006'));
+ expect(line).toBeDefined();
+ const firstConn = Number(/first_conn_ms=(\d+)/.exec(line!)![1]);
+ expect(firstConn).toBeGreaterThanOrEqual(140);
+ expect(firstConn).toBeLessThan(2_000);
+ expect(line).not.toContain('checkout=not_observed');
+ });
+
+ test('an unrelated checkout outside the phase cannot satisfy its observation', async () => {
+ const { engine, unrelatedCheckout } = delayedCheckoutEngine(300, 0, failure());
+ captureStderr();
+ const consumer = new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw failure(); }, { hostId: crypto.randomUUID(), phaseMs: 100 });
+ const ticking = consumer.tick();
+ await Bun.sleep(20);
+ unrelatedCheckout();
+ try { await ticking; } finally { await consumer.stop(); }
+ const line = stderr.find(entry => entry.includes('reason=deadline_exceeded'));
+ expect(line).toContain('checkout=not_observed');
+ expect(line).not.toContain('first_conn_ms=');
+ });
+});