Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.22.0 fix(pglite): honest close bound + opt-in out-of-band disconnect watchdog (#4284) (#4316)

Garry Tan1886e1970318
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 42a8f435d4..be188b5522 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 38f10d28c7..e5e817b537 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 826763aa44..88208cc76c 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.21.0 -->
+<!-- gbrain-runbook-stamp: 0.46.22.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e81c97a701..57b9c5bdd2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,74 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.22.0] - 2026-08-18
+
+**A wedged database shutdown can now die fast and loud instead of hanging
+forever.** Issue #4284 (analysis and measurements by @cheRoma — thank you)
+proved that the time-bound around the embedded database's close could never
+fire against the exact deadlock it was written for: a wedge starves the
+event loop, and no timer on a starved loop ever runs. The bound is now
+honest about what it covers, and a new opt-in out-of-band watchdog covers
+what it can't.
+
+### Fixed
+
+- **The in-loop close bound is now honest and correctly armed.** The timer
+ arms *before* the close begins (not after), stays referenced so a quiet
+ process can't exit before the warning and lock release fire, reads its
+ override per call, and clamps oversized values so a huge
+ `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` means a longer bound — never an instant
+ spurious timeout. Its warning now states plainly that a close which wedges
+ the event loop cannot be caught in-process, and names the watchdog knob
+ that can catch it. Code comments and docs describe the layered defense
+ truthfully: the pre-close drain *prevents* the known wedge, the in-loop
+ bound covers a close that still yields, and only the watchdog observes a
+ wedged one.
+- **The CLI teardown backstop now budgets the real close bound.** Raising
+ the close timeout widens the teardown deadline with it, instead of the
+ backstop force-exiting mid-honest-close against a stale hardcoded copy.
+- **Watchdog timer arithmetic can never overflow into an instant kill.**
+ Deadline, grace, and their sum are clamped below the platform timer
+ ceiling (an overflowed timer fires at ~1ms — for the kill timer that
+ would have meant SIGKILLing a healthy process), and a non-numeric grace
+ is coerced safely instead of arming a ~1ms kill.
+
+### Added
+
+- **Opt-in out-of-band disconnect watchdog** — a diagnostic instrument for
+ CI lanes and wedge hunts, off by default. Set
+ `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (and optionally
+ `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS`, default 30000; an explicit 0
+ means SIGKILL at the deadline) and a worker-thread watchdog arms around
+ each embedded-database disconnect: SIGTERM at the deadline, SIGKILL at
+ deadline+grace, firing even while the main event loop is completely
+ wedged — converting a silent 10-minute CI kill into a fast, loud,
+ attributed death. A drain-aware floor clamps a too-small deadline UP
+ (with a warning) so a units typo can never kill a healthy slow teardown,
+ garbage values warn instead of silently disarming, and the armed
+ breadcrumb re-fires whenever the effective deadline changes in a
+ long-lived process.
+- **A regression pin that genuinely wedges an event loop.** A new spawned-
+ fixture test suite starves a real Bun loop the way the measured incident
+ did, proving the watchdog SIGKILLs it at deadline+grace, that nothing
+ in-process can fire without the watchdog, and that a healthy disconnect
+ is never harmed. The heavy read-latency reproducer now arms the watchdog
+ as a canary.
+
+### To take advantage of v0.46.22.0
+
+- Nothing changes by default — teardown behavior with the env knobs unset
+ is the same layered defense that already shipped, now honestly
+ documented.
+- In CI lanes or when hunting a suspected shutdown wedge, export
+ `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS=30000` (optionally
+ `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS=10000`): a wedge then dies loudly
+ with a `pglite-disconnect-watchdog` stderr label at ~40s instead of
+ hanging until an outer timeout. Values below the safe floor are clamped
+ up with a warning, never applied literally.
+- If you previously raised `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, the CLI
+ teardown backstop now automatically widens to match — no action needed.
+
## [0.46.21.0] - 2026-08-18
**Fact extraction no longer requires an Anthropic key — and OpenAI defaults
@@ -427,7 +495,9 @@ open community PRs by @Masashi-Ono0611 — thank you.
shutdown permanently (observed as a 10-minute CI kill; a workload that
took 19 seconds before the regression). Both engines now settle in-flight
background work before closing, the close itself is time-bounded
- (override: `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`), and a clean CLI exit now
+ (override: `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`; the bound covers a close
+ that still yields to the event loop — a wedged close cannot be caught
+ in-process, see #4284), and a clean CLI exit now
also flushes buffered search telemetry — short-lived CLI calls finally
show up in `gbrain search stats`.
- **Mixed-case embedding model ids work.** `litellm:Qwen/Qwen3-Embedding-4B`
diff --git a/TODOS.md b/TODOS.md
index e36a41d7c0..42cdb9ab27 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -359,7 +359,19 @@
- [ ] **P3 — transcript.ts renderBlock still renders v2 gateway blocks as "Unknown block type".** The absorbed #4156 rekeyed the tool ledger to (message_idx, tool_use_id); teaching renderBlock the 'tool-call'/'tool-result' ChatBlock shapes is the remaining half so `gbrain agent logs` shows gateway-path tool use readably. Files: src/core/minions/transcript.ts, test/subagent-transcript.test.ts.
-- [ ] **P3 — consolidate the five hand-rolled bounded-wait copies.** Promise.race + setTimeout + clearTimeout now lives in hybrid.ts:151/:898, eval-capture.ts:203, supervisor.ts probeQueueState, telemetry's drain, and pglite-engine's bounded close. A shared `raceBounded(promise, ms)` helper would kill the copy-drift class. Sweep, don't rush — each copy has slightly different timeout/cleanup semantics to preserve.
+- [ ] **P3 — consolidate the five hand-rolled bounded-wait copies.** Promise.race + setTimeout + clearTimeout now lives in hybrid.ts:151/:898, eval-capture.ts:203, supervisor.ts probeQueueState, telemetry's drain, and pglite-engine's bounded close. A shared `raceBounded(promise, ms)` helper would kill the copy-drift class. Sweep, don't rush — each copy has slightly different timeout/cleanup semantics to preserve. NOTE (#4284): the pglite close copy's semantics are now deliberately divergent and load-bearing — timer armed BEFORE the awaited call starts, deliberately REF'D (no unref), delay clamped to 2^31−1 — and are pinned by structural tests in `test/fix-wave-structural.test.ts`; a sweep must preserve (or parameterize) all three, not normalize them away.
+- [ ] **P3 — enable the PGLite disconnect watchdog by default in gbrain's own CI lanes.**
+ **What:** set `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (~30s) + `..._GRACE_MS` in the serial/e2e
+ CI lanes (and consider `scripts/run-serial-tests.sh`) after a soak period, so any future
+ #4143-class wedge dies loudly with the `pglite-disconnect-watchdog` stderr label instead
+ of eating the lane's full timeout. **Why:** the watchdog is opt-in (a diagnostic
+ instrument); today only `tests/heavy/read_latency_under_sync.sh` arms it, and the heavy
+ lane runs nightly at best — PR CI wedges would still present as silent timeouts.
+ **Context:** shipped with the #4284 fix; the lethal-knob floor
+ (`max(5000, sinkCount*2000 + closeTimeout + 2000)`) already protects healthy slow
+ teardowns, so the main soak question is worker-spawn overhead per disconnect across
+ thousands of test teardowns, and whether any lane has legitimate >30s disconnects.
+ **Effort:** S. **Priority:** P3.
- [ ] **P2 — Heavy Tests lane gates nothing on in-repo branches.** #4143 shipped broken for a month because the lane comes back `skipped` on branch pushes and only a downstream fork ran it nightly. Either run a bounded subset (the read_latency workload at reduced params) in PR CI, or make the nightly failure page someone. Files: .github/workflows (heavy lane), tests/heavy/.
diff --git a/VERSION b/VERSION
index b13dfd0594..5cf6b8f5aa 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.21.0
\ No newline at end of file
+0.46.22.0
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index b9c7f3022d..419303d724 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -15,7 +15,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration replacing the `getAllSlugs()→getPage(slug)` N+1 (which silently defaulted to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; back-compatible — no opts gives prior behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, closing the planner-non-determinism class where a new index on `pages` could flip ranking on tied scores.
- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification.
-- `src/core/background-work.ts` (#1762/#1745/#1775) — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (#4143 — `'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` (#4143) is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4, #2095 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5, #4143 — `awaitPendingTelemetryFlush`: awaits the in-flight flush in both modes, flushes residual buckets only in `'exit'` mode so short-lived CLI calls land in `search_telemetry` on clean exit). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()` — closing the PGLite busy-loop where `db.close()` raced an in-flight job and pinned the single-writer lock (#1762). Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count. CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure — #1745); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op (#1775). Incorporates + hardens PR #1763 (@ElliotDrel). Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.test.ts`.
+- `src/core/background-work.ts` (#1762/#1745/#1775) — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (#4143 — `'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` (#4143) is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4, #2095 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5, #4143 — `awaitPendingTelemetryFlush`: awaits the in-flight flush in both modes, flushes residual buckets only in `'exit'` mode so short-lived CLI calls land in `search_telemetry` on clean exit). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()` — closing the PGLite busy-loop where `db.close()` raced an in-flight job and pinned the single-writer lock (#1762). Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count, plus the shared teardown budgets (#4284): `MAX_TIMER_DELAY_MS` (the 2^31−1 setTimeout ceiling; `process-watchdog.ts` aliases it as `MAX_WATCHDOG_TIMER_MS`), `SINK_DRAIN_TIMEOUT_MS` (the per-sink drain bound, used as the `runDrainers` default), and `pgliteCloseTimeoutMs()` (the env-tunable in-loop close bound, defined here so `cli-force-exit`'s computed deadline budgets the SAME bound the engine honors). CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure — #1745); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op (#1775). Incorporates + hardens PR #1763 (@ElliotDrel). Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.test.ts`.
- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate regression).
- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. Pinned by `test/search/explain-formatter.test.ts`.
- `src/core/search/mode.ts` — Named search-mode bundles + the search cache key. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds every result-shaping knob into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. Mid-deploy `query_cache` rows from before the upgrade hash differently — natural row segregation, clears within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain.
@@ -24,11 +24,11 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/watch.ts` — `gbrain watch` (#2095): the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.
- `src/commands/integrations.ts` — recipe install. The resolver-row install fence is keyed by `manifest.recipe` (`gbrain:<recipe>:resolver-rows`), so a second `copy-into-host-repo` recipe no longer writes a block mislabeled with the first recipe's name. Pinned by `test/integrations-install.test.ts`. Health-check DSL includes the staleness-aware `heartbeat_max_age` type (#2787): declares the sense's expected cadence (`max_age: 48h`), and `integrations doctor` FAILS when the newest heartbeat event is older — the only check type that catches a green-but-dead sense (all others are point-in-time). Not embedded-gated (reads only the local heartbeat file). Recipe frontmatter carries `output_paths` (repo-relative dirs the collector writes, e.g. calendar-to-brain → `daily/calendar/`); `getConfiguredCollectorOutputs()` surfaces them for the #2788 db_only-collision check/warning. Pinned by `test/integrations-heartbeat-max-age.test.ts`. Standalone integration recipe management (no DB needed). Exports `getRecipeDirs()` (trust-tagged recipe sources), SSRF helpers (`isInternalUrl`, `parseOctet`, `hostnameToOctets`, `isPrivateIpv4`). Only package-bundled recipes are `embedded=true`; `$GBRAIN_RECIPES_DIR` and cwd `./recipes/` are untrusted and cannot run `command`/`http`/string health checks.
- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive consolidating the hand-rolled audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Refactored onto it for parity: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts` (each module's public API preserved bit-for-bit). The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. One hand-rolled audit remains at `src/core/skillpack/audit.ts`. Pinned by `test/audit/audit-writer.test.ts`.
-- `src/core/cli-force-exit.ts` (#2084) — single owner of one-shot CLI exit + teardown, designed as a PAIR with the `import.meta.main` seam at the bottom of `src/cli.ts`. `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + sinks × 2s disconnect-drain bound + 5s PGLite-close bound + facts-abort grace + 2 × pool-end bound + slack, floor 10s — the two #4143 terms budget `engine.disconnect()`'s own drain pass and bounded close so the backstop can't fire while every component honored its own bound; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently reporting success on failure. The deadline arms at TEARDOWN start, never before the op handler (the pre-#2084 placement measured handler + teardown combined, so PgBouncer deployments paid a flat 10s force-exit tax on every query and any >10s op was killed mid-run with exit 0). All nine cli.ts disconnect sites route through it; the ONE process exit happens in cli.ts's `main().then/catch` via `flushThenExit(currentExitCode())`, gated by `shouldForceExitAfterMain()` (daemon list: `serve`) — the CLI never waits for Bun's event loop to drain, because `endPoolBounded` deliberately races past stuck PgBouncer sockets that would keep it alive. `flushThenExit(code)` fences stdout+stderr (`write('', cb)` raced with an unref'd guard, EPIPE-safe both sync and async) then holds a REF'D aliveness grace for non-TTY stdio before `process.exit` — Bun delivers queued pipe writes only while the process is alive (no flush API reaches `process.stdout`'s native queue; write callbacks fire on accept, not delivery), so the grace IS the flush (#1959 truncation class). Scope claim is deliberately cli.ts-only: command modules' mid-run engine lifecycles stay local (process-exit semantics inside them would be wrong) and are absorbed by the final explicit exit. Pinned by `test/cli-finish-teardown.test.ts`, `test/flush-then-exit-harness.test.ts` (real spawned-Bun pipe semantics), `test/cli-should-force-exit.test.ts`, `test/cli-pipe-truncation.test.ts` (real-CLI piped --tools-json byte-stable), `test/cli-exit-verdict-pin.test.ts`, the `#2084` describes in `test/fix-wave-structural.test.ts` + `test/e2e/pglite-cli-exit.serial.test.ts`, and `test/e2e/pgbouncer-teardown.test.ts` (CI transaction-mode pooler — the #1972/#2015/#2084 class, finally reproducible in CI).
+- `src/core/cli-force-exit.ts` (#2084) — single owner of one-shot CLI exit + teardown, designed as a PAIR with the `import.meta.main` seam at the bottom of `src/cli.ts`. `finishCliTeardown({engine, drainTimeoutMs?})` is teardown-ONLY (never exits on the clean path): arms a REF'D backstop (unref'd would let a hung teardown exit naturally, skipping the flush and exiting with whatever PGLite scribbled into `process.exitCode`) whose deadline is COMPUTED from the bounds it guards (`computeTeardownDeadlineMs` = sinks × drainTimeoutMs + sinks × `SINK_DRAIN_TIMEOUT_MS` disconnect-drain bound + the RESOLVED PGLite close bound (`pgliteCloseTimeoutMs()` from background-work.ts — an operator-raised `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` widens this backstop too, #4284, never a hardcoded copy of the default) + facts-abort grace + 2 × pool-end bound + slack, floor 10s — the #4143 terms budget `engine.disconnect()`'s own drain pass and bounded close so the backstop can't fire while every component honored its own bound; `GBRAIN_TEARDOWN_DEADLINE_MS` env override is the incident escape hatch), drains every background-work sink, disconnects the engine (a throw is warned + swallowed — the exit code reports the OPERATION, not the cleanup), then returns. The exit VERDICT lives in a gbrain-owned channel (`setCliExitVerdict`/`currentExitCode`; mirror-writes `process.exitCode` but NEVER reads it back) because PGLite's Emscripten runtime scribbles its own status into `process.exitCode` at arbitrary points mid-run — every writer that means to set the CLI exit code (op-dispatch catch, reindex, frontmatter, transcripts, brainstorm, autopilot, doctor's FAIL verdict, extract, and cli.ts's swept inner exits — friction, claw-test, smoke-test, the no-DB eval runners, status/status-thin, whoknows-thin) calls `setCliExitVerdict`; `test/cli-exit-verdict-pin.test.ts` greps src/ so the next raw `process.exitCode =` write fails CI instead of silently reporting success on failure. The deadline arms at TEARDOWN start, never before the op handler (the pre-#2084 placement measured handler + teardown combined, so PgBouncer deployments paid a flat 10s force-exit tax on every query and any >10s op was killed mid-run with exit 0). All nine cli.ts disconnect sites route through it; the ONE process exit happens in cli.ts's `main().then/catch` via `flushThenExit(currentExitCode())`, gated by `shouldForceExitAfterMain()` (daemon list: `serve`) — the CLI never waits for Bun's event loop to drain, because `endPoolBounded` deliberately races past stuck PgBouncer sockets that would keep it alive. `flushThenExit(code)` fences stdout+stderr (`write('', cb)` raced with an unref'd guard, EPIPE-safe both sync and async) then holds a REF'D aliveness grace for non-TTY stdio before `process.exit` — Bun delivers queued pipe writes only while the process is alive (no flush API reaches `process.stdout`'s native queue; write callbacks fire on accept, not delivery), so the grace IS the flush (#1959 truncation class). Scope claim is deliberately cli.ts-only: command modules' mid-run engine lifecycles stay local (process-exit semantics inside them would be wrong) and are absorbed by the final explicit exit. Pinned by `test/cli-finish-teardown.test.ts`, `test/flush-then-exit-harness.test.ts` (real spawned-Bun pipe semantics), `test/cli-should-force-exit.test.ts`, `test/cli-pipe-truncation.test.ts` (real-CLI piped --tools-json byte-stable), `test/cli-exit-verdict-pin.test.ts`, the `#2084` describes in `test/fix-wave-structural.test.ts` + `test/e2e/pglite-cli-exit.serial.test.ts`, and `test/e2e/pgbouncer-teardown.test.ts` (CI transaction-mode pooler — the #1972/#2015/#2084 class, finally reproducible in CI).
- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'recorded_on_clean_exit', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`: since #4143 a short-lived CLI call's buffer flushes during the bounded CLI teardown drain, so a CLEAN exit is recorded; hard kills, drains that exceed their bound, and anything buffered when an engine disconnects outside the CLI teardown path still drop — the disclosure is display-only and reads its truth from the telemetry module's single-source constants. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).
-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` (#4143) early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would reopen the #1337 race). `close()` itself is bounded at `GBRAIN_PGLITE_CLOSE_TIMEOUT_MS` (default 5000ms, floor 1s): a timed-out close degrades to a once-per-process stderr warning and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `disconnect()` (#4143) early-nulls the handle (so no NEW statement can reach it), then runs `drainBackgroundWorkBeforeDisconnect()` so statements ALREADY in flight settle against the still-open handle — PGLite's `close()` deadlocks permanently (close's promise AND the in-flight query's promise never settle) with a statement in flight; the ordering is load-bearing (drain above the null would reopen the #1337 race). Teardown defense is layered and honestly scoped (#4284): the drain PREVENTS the known wedge; the in-loop close bound (`GBRAIN_PGLITE_CLOSE_TIMEOUT_MS`, default 5000ms, floor 1s, ceiling 2^31−1, read per call) covers ONLY a close that still yields to the event loop — armed BEFORE `close()` is called and deliberately ref'd, a timed-out close degrades to a once-per-process stderr warning naming both env knobs and teardown proceeds (an abandoned close's later rejection is swallowed; the WAL-repair path covers a zombie instance on next open); a close that WEDGES the loop (blocked or microtask-starved, the #1762 re-pump class) can never be caught by any same-loop timer and is observable/killable only by the opt-in out-of-band watchdog — a diagnostic/incident instrument, not ambient production protection: `GBRAIN_PGLITE_CLOSE_WATCHDOG_MS` (unset/0 = off; a positive value clamps UP to `max(5000, registered-sink-count×2000 + close timeout + 2000)` with a warn so a units typo never SIGKILLs a healthy slow teardown) + `GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS` (default 30000) arm the shared `process-watchdog.ts` worker around a PGLite disconnect with a live handle (armed after the early-return, before the drain; disposed in a nested finally so a `releaseLock` throw can't leak it; SIGTERM at deadline, SIGKILL at deadline+grace; lock-only teardown and postgres pool teardown are out of scope). Pinned by `test/pglite-engine-disconnect.serial.test.ts` + `test/search-telemetry-disconnect-hang.serial.test.ts` + `test/pglite-disconnect-watchdog.serial.test.ts` (spawned fixture that genuinely starves the loop) + the `#4284` structural pins in `test/fix-wave-structural.test.ts`. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
- `src/core/pglite-embedded-assets.ts` + `src/core/pglite-embedded-asset-paths.ts` — PGLite runtime-asset supply for every run mode (compiled binary, source checkout, bun-global install). `pglite-embedded-asset-paths.ts` is the bundler ANCHOR: five literal `with { type: 'file' }` imports of the wasm/data/extension-tarball assets via repo-relative node_modules paths (the package's `exports` map hides `./dist/*`) — keep the specifiers literal and byte-stable, an expression or indirection silently stops the bytes embedding and the compiled binary regresses to the Bun-vfs ENOENT class (#1340). `resolvePgliteAssetPaths()` in `pglite-embedded-assets.ts` is the tiered resolver (#4116): tier 1 dynamically `import()`s the anchor (the rejection under a hoisted install — bun-global upgrades dedupe `@electric-sql/pglite` to the global root, making the anchor's specifiers unresolvable — is EXPECTED and routes to tier 2, which is why the anchor is not a static import); tier 2 derives the dist dir via module resolution of `@electric-sql/pglite` (`import.meta.resolve` then `createRequire` — the SAME specifier the engine imports, so assets can never come from a different pglite copy than the loaded JS); tier 3 throws one actionable error naming everything tried, with the canonical GitHub reinstall command (never the npm-registry name, which is squatted — see the README install warning). `getEmbeddedPgliteOptions()` memoizes one build per process and hands PGLite compiled `WebAssembly.Module`s + fs-bundle Blob + materialized extension tarballs via `PGliteOptions`. Pinned by `test/pglite-embedded-assets.test.ts` + `test/pglite-hoisted-install.serial.test.ts` (real `bun add -g`-shaped hoisted layout).
- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (ported from electric-sql/pglite PR #994 by @yestheboxer, Apache-2.0, rejected upstream as "should be a separate tool" — gbrain is that tool). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
@@ -188,7 +188,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/dry-fix.ts` — `gbrain doctor --fix` engine. `autoFixDryViolations(fixes, {dryRun})` rewrites inlined rules to `> **Convention:** see [path](path).` callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (`getWorkingTreeStatus()` 3-state `'clean' | 'dirty' | 'not_a_repo'`), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout. `execFileSync` array args (no shell, no injection surface). EOF newline preserved. Safety primitives are in `src/core/skill-fix-gates.ts` (back-compat re-exports preserved). `MISSING_RULE_PATTERNS` INSERT pattern type lives alongside REPLACE patterns — same auto-fix entry point + git-safety gates, but places a canonical callout at a target offset (`after-h1-paragraph` only). First INSERT pattern is `brain_first`, auto-inserting `> **Convention:** see [conventions/brain-first.md](../conventions/brain-first.md) for the lookup chain (search → query → get_page → external).` on any flagged SKILL.md whose verdict is `missing_brain_first`. Idempotent — re-runs detect the existing callout and skip.
- `src/core/backoff.ts` — Adaptive load-aware throttling: CPU/memory checks, exponential backoff, active hours multiplier.
- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter allowed near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).
-- `src/core/process-watchdog.ts` (#1633) — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+ (the reported incident). `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests. Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Reusable beyond sync (autopilot/cycle are follow-up adopters). Pinned by `test/process-watchdog.test.ts` (pure decision matrix + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).
+- `src/core/process-watchdog.ts` (#1633) — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+ (the reported incident). `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrix + clamp arithmetic + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).
- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time leaked a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (bun test runners died mid-suite when a test emitted a synthetic SIGTERM; the runner misread rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone left the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).
- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). Its previous local resolver returned GBRAIN_HOME directly, splitting one logical home across two roots (config at `$GBRAIN_HOME/.gbrain/config.json`, ledger at `$GBRAIN_HOME/migrations/`) — while claiming in its own comment to match gbrainPath. `copyForwardLegacyFile` migrates the pre-unification layout once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.
- `src/core/audit/batch-retry-audit.ts` — JSONL audit primitive for batch-retry events, built on `audit-writer.ts`. Schema: `{ts, site, batch_size, attempt, outcome: 'success' | 'exhausted', delay_ms, error_message_summary, error_code?}`. Privacy: NEVER logs slugs / page IDs / content (mirrors `shell-audit.ts`). `logBatchRetry` fires per successful retry recovery; `logBatchExhausted` fires when retries exhaust and rows are lost. `readRecentBatchRetryEvents(hours=24)` returns `{events, corrupted_lines, files_scanned, files_unreadable}` — corruption + permission errors surface to doctor, not silently swallowed. `pruneOldBatchRetryAuditFiles(daysToKeep=30)` deletes old files, called from `gbrain dream --phase purge`. File: `~/.gbrain/audit/batch-retry-YYYY-Www.jsonl` (honors `GBRAIN_AUDIT_DIR`). `summarizeError` routes error messages through the shared `redactConnectionInfo` helper from `src/core/audit/redact-connection-info.ts` BEFORE truncation so DSNs / hostnames / credentials / IPv4 octets can't leak into operator-shared JSONL dumps. Pinned by `test/audit/batch-retry-audit.test.ts` (12 cases) + `test/audit/batch-retry-redaction.test.ts` (3 privacy regressions).
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 9b817a6645..fd29c14ede 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 7c411f3433..4e2758eb79 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 129f60cd8a..349441e0c8 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 96cd4a2dc9..72513062e4 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 18 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 958c7b7223..dba4d1cdc6 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.22.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index ba3c09212f..359c60fa22 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 941d9d0470..7ce2db035a 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.46.21.0",
+ "version": "0.46.22.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 17 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 45cb9e3b60..d7b8ac6e01 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.22.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 9159021adf..ff90f0bb2c 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.21.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.22.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 75d781113b..4d8e80ee3b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -6,7 +6,7 @@
src/commands/doctor.ts 4291 ratchet peel target: containment sprint C8-C13; grown v0.46.x keyless not_configured state
src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
src/core/postgres-engine.ts 5816 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave
-src/core/pglite-engine.ts 5744 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave
+src/core/pglite-engine.ts 5859 ratchet peel target: containment sprint C15; grown v0.46.11.0 five-issue wave + retrieval wave + #4284 honest close bound/watchdog + its review-fix batch
src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
src/commands/sync.ts 4300 ratchet peel target: containment sprint C13-C14; grown v0.46.11.0 five-issue wave
src/core/ai/gateway.ts 4428 ratchet watchlist; merged: dream-wave turn permits + key-aware effective-model reconfigure + env-only worker refresh + discovery endpoint-trust docstring
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 8f9b1fdf4b..5ea786ef51 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -126,7 +126,7 @@ test/fix-wave-structural.test.ts v0.36.1.x #1090 — admin embed two-tier resolu
test/fix-wave-structural.test.ts v0.36.1.x #1124 — query --no-expand actually negates expand 1 readFileSync
test/fix-wave-structural.test.ts v0.41.37.0 #1605 — v0.11.0 phaseASchema routes in-process for ALL engines 2 readFileSync
test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifier 2 readFileSync
-test/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 8 readFileSync
+test/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 9 readFileSync
test/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 readFileSync
test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync
test/hook-command.serial.test.ts user-prompt 14 readFileSync
diff --git a/src/core/background-work.ts b/src/core/background-work.ts
index 449ecb9ff5..468d16aa29 100644
--- a/src/core/background-work.ts
+++ b/src/core/background-work.ts
@@ -54,6 +54,41 @@
*/
export type BackgroundWorkDrainMode = 'exit' | 'disconnect';
+/**
+ * Shared teardown budgets (#4284). This module is the natural home: it is the
+ * zero-import leaf that every teardown participant (both engines,
+ * cli-force-exit, process-watchdog) already imports, so budget numbers defined
+ * here cannot drift between the components that must agree on them.
+ */
+
+/**
+ * setTimeout delay ceiling: Node/Bun overflow-clamp anything above 2^31−1 to
+ * ~1ms (TimeoutOverflowWarning), so an oversized delay must be clamped to
+ * mean "longer bound", never an instant spurious fire.
+ */
+export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
+
+/** Per-sink bound for one drain pass (the `runDrainers` default below). */
+export const SINK_DRAIN_TIMEOUT_MS = 2000;
+
+/**
+ * #4143/#4284 — the in-loop bound for PGlite.close() inside disconnect().
+ * Read per call (not module load) so tests and incident responders can set
+ * GBRAIN_PGLITE_CLOSE_TIMEOUT_MS without subprocess gymnastics; floor 1s,
+ * ceiling 2^31−1. Lives here (not in the engine) so cli-force-exit's
+ * computed teardown deadline budgets the SAME bound the engine will actually
+ * honor — a hardcoded copy drifted the moment the bound became tunable.
+ * HONEST SCOPE lives at the close site in pglite-engine.ts: this bound
+ * catches a close that still YIELDS; a wedged loop needs the out-of-band
+ * watchdog.
+ */
+export function pgliteCloseTimeoutMs(): number {
+ return Math.min(
+ MAX_TIMER_DELAY_MS,
+ Math.max(1000, Number(process.env.GBRAIN_PGLITE_CLOSE_TIMEOUT_MS ?? '') || 5000),
+ );
+}
+
export interface BackgroundWorkDrainer {
/** Stable identity; also the Map key (idempotent registration). */
name: string;
@@ -122,7 +157,7 @@ export function __listDrainerNamesForTest(): string[] {
* the subsequent disconnect.
*/
export async function drainAllBackgroundWorkForCliExit(opts?: { timeoutMs?: number }): Promise<void> {
- await runDrainers(opts?.timeoutMs ?? 2000, { allowAbort: true, mode: 'exit' });
+ await runDrainers(opts?.timeoutMs ?? SINK_DRAIN_TIMEOUT_MS, { allowAbort: true, mode: 'exit' });
}
/**
@@ -141,7 +176,7 @@ export async function drainAllBackgroundWorkForCliExit(opts?: { timeoutMs?: numb
* hooks.
*/
export async function drainBackgroundWorkBeforeDisconnect(opts?: { timeoutMs?: number }): Promise<void> {
- await runDrainers(opts?.timeoutMs ?? 2000, { allowAbort: false, mode: 'disconnect' });
+ await runDrainers(opts?.timeoutMs ?? SINK_DRAIN_TIMEOUT_MS, { allowAbort: false, mode: 'disconnect' });
}
const warnedOnce = new Set<string>();
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index 2d67d4379c..258ca4cf2d 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -52,7 +52,12 @@
* every path directly (cli.ts is a script entrypoint).
*/
-import { drainAllBackgroundWorkForCliExit, backgroundWorkSinkCount } from './background-work.ts';
+import {
+ drainAllBackgroundWorkForCliExit,
+ backgroundWorkSinkCount,
+ pgliteCloseTimeoutMs,
+ SINK_DRAIN_TIMEOUT_MS,
+} from './background-work.ts';
import { POOL_END_TIMEOUT_SECONDS } from './db.ts';
import { parseGlobalFlags } from './cli-options.ts';
@@ -152,13 +157,16 @@ export function computeTeardownDeadlineMs(opts: {
// ×2 budgets the worst case of two sequential pool ends (direct + read).
const poolEndBoundMs = POOL_END_TIMEOUT_SECONDS * 1000 + 500;
// #4143: engine.disconnect() now runs its OWN drain pass (the
- // in-flight-settle drain, fixed at 2000ms/sink — see
+ // in-flight-settle drain, SINK_DRAIN_TIMEOUT_MS/sink — see
// drainBackgroundWorkBeforeDisconnect) AFTER the exit-mode drain above it
- // in finishCliTeardown, plus PGLite's 5s bounded close. Budget both, or
+ // in finishCliTeardown, plus PGLite's bounded close. Budget both, or
// the backstop fires while every component honored its own bound (the D9
- // false-backstop class this formula exists to kill).
- const disconnectDrainBoundMs = opts.sinkCount * 2000;
- const pgliteCloseBoundMs = 5000;
+ // false-backstop class this formula exists to kill). #4284: the close
+ // bound is env-tunable (its own warn text tells operators to raise it),
+ // so budget the RESOLVED bound, never a hardcoded copy of its default —
+ // a 60s GBRAIN_PGLITE_CLOSE_TIMEOUT_MS must widen this backstop too.
+ const disconnectDrainBoundMs = opts.sinkCount * SINK_DRAIN_TIMEOUT_MS;
+ const pgliteCloseBoundMs = pgliteCloseTimeoutMs();
const computed =
opts.sinkCount * opts.drainTimeoutMs +
disconnectDrainBoundMs +
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4f654378e1..33556110f9 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -10,18 +10,17 @@ import { join as joinPath, resolve as resolvePath, sep as pathSep } from 'node:p
// so a `bun build --compile` binary can serve a PGLite brain (Bun vfs #1340).
// The embedded `extensions` REPLACE the stock `{ vector, pg_trgm }` imports.
import { getEmbeddedPgliteOptions } from './pglite-embedded-assets.ts';
-import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';
-
-/**
- * #4143 — bound for PGlite.close() inside disconnect(). close() deadlocks
- * permanently when a statement is in flight; the drain above close() removes
- * the known trigger, this bound converts any residual instance into a 5s warn
- * instead of a wedged process. Env-overridable for incident response.
- */
-const PGLITE_CLOSE_TIMEOUT_MS = Math.max(
- 1000,
- Number(process.env.GBRAIN_PGLITE_CLOSE_TIMEOUT_MS ?? '') || 5000,
-);
+import {
+ drainBackgroundWorkBeforeDisconnect,
+ backgroundWorkSinkCount,
+ pgliteCloseTimeoutMs,
+ SINK_DRAIN_TIMEOUT_MS,
+ MAX_TIMER_DELAY_MS,
+} from './background-work.ts';
+// Engine-live path: static top-level import (no lazy `import()`). The opt-in
+// out-of-band disconnect watchdog (#4284) reuses the worker_threads watchdog
+// `gbrain sync` already validated against starved event loops (#1633).
+import { installProcessWatchdog } from './process-watchdog.ts';
import type {
BrainEngine,
BatchOpts,
@@ -116,6 +115,76 @@ import type { PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';
import * as salienceImpl from './pglite-engine/salience.ts';
import type { PgliteSalienceDeps } from './pglite-engine/salience.ts';
+/**
+ * #4284 — opt-in out-of-band watchdog for a PGLite disconnect with a live
+ * handle. OFF by default: a DIAGNOSTIC/INCIDENT instrument (CI lanes, heavy
+ * tests, wedge hunts), not ambient production protection. When armed it is
+ * the ONLY layer that can fire while the event loop is wedged (worker_threads
+ * — its timers live on a separate OS thread): stderr line + SIGTERM at the
+ * deadline, SIGKILL at deadline+grace, converting a silent 600s CI kill into
+ * a fast, loud, attributed death.
+ *
+ * (The in-loop close bound this backs up — `pgliteCloseTimeoutMs` — lives in
+ * background-work.ts so cli-force-exit's computed teardown deadline budgets
+ * the SAME bound the engine honors; its HONEST SCOPE is documented at the
+ * close site below.)
+ *
+ * Resolve ordering is OFF-check FIRST: unset/''/0/negative → inert (deadline
+ * 0) — but a SET-and-unparseable value ("30s", "5m") warns once before going
+ * inert, because a garbage value must not silently disarm the instrument an
+ * incident responder deliberately armed. Only a positive value proceeds to
+ * the lethal-knob floor
+ * max(5000, backgroundWorkSinkCount()*SINK_DRAIN_TIMEOUT_MS + closeTimeout + 2000)
+ * which budgets the serial pre-close drain plus the in-loop close bound, so a
+ * numeric units typo (`=30`, thinking seconds) clamps UP with a warn instead
+ * of SIGKILLing a HEALTHY slow teardown — `jobs work` daemons reconnect()
+ * through disconnect(). Mirrors the computed-deadline pattern in
+ * cli-force-exit.ts. Grace: explicit `0` is honored (SIGKILL at the
+ * deadline); unset → default 30000; garbage warns once and uses the default.
+ */
+function pgliteCloseWatchdogMs(): { deadlineMs: number; graceMs: number } {
+ const rawStr = process.env.GBRAIN_PGLITE_CLOSE_WATCHDOG_MS;
+ if (rawStr === undefined || rawStr === '') return { deadlineMs: 0, graceMs: 0 }; // OFF (default)
+ const raw = Number(rawStr);
+ if (!Number.isFinite(raw)) {
+ warnOncePerProcess(
+ 'pglite-close-watchdog-env-invalid',
+ `[pglite] GBRAIN_PGLITE_CLOSE_WATCHDOG_MS=${rawStr} is not a number — the disconnect watchdog is OFF, not armed. Use milliseconds (e.g. 30000).`,
+ );
+ return { deadlineMs: 0, graceMs: 0 };
+ }
+ if (raw <= 0) return { deadlineMs: 0, graceMs: 0 }; // deliberate off
+ const floor = Math.min(
+ MAX_TIMER_DELAY_MS,
+ Math.max(5000, backgroundWorkSinkCount() * SINK_DRAIN_TIMEOUT_MS + pgliteCloseTimeoutMs() + 2000),
+ );
+ const deadlineMs = Math.min(MAX_TIMER_DELAY_MS, Math.max(floor, Math.floor(raw)));
+ if (deadlineMs > raw) {
+ // Keyed by the computed deadline: in a long-lived daemon the floor GROWS
+ // as sinks register lazily, and the warn must re-fire when the effective
+ // deadline changes — otherwise the attribution surface lies about when
+ // the kill will land (#4284 red-team).
+ warnOncePerProcess(
+ `pglite-close-watchdog-floor:${deadlineMs}`,
+ `[pglite] GBRAIN_PGLITE_CLOSE_WATCHDOG_MS=${raw} is below this process's safe floor (drain budget + close timeout) — clamped up to ${deadlineMs}ms so a healthy slow teardown is never killed.`,
+ );
+ }
+ let graceMs = 30_000;
+ const rawGraceStr = process.env.GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS;
+ if (rawGraceStr !== undefined && rawGraceStr !== '') {
+ const g = Number(rawGraceStr);
+ if (Number.isFinite(g) && g >= 0) {
+ graceMs = Math.min(MAX_TIMER_DELAY_MS, Math.floor(g)); // explicit 0 = SIGKILL at deadline
+ } else {
+ warnOncePerProcess(
+ 'pglite-close-watchdog-grace-env-invalid',
+ `[pglite] Ignoring invalid GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS=${rawGraceStr}; using default 30000ms.`,
+ );
+ }
+ }
+ return { deadlineMs, graceMs };
+}
+
type PGLiteDB = PGlite;
// Tier 3 snapshot fast-restore. Reads a tar dump produced by
@@ -783,17 +852,46 @@ export class PGLiteEngine implements BrainEngine {
this._lock = null;
if (!db && !lock) return; // already disconnected — nothing to drain or close
- // #4143: drain in-flight background work AFTER the early-null and BEFORE
- // close(). PGLite's close() deadlocks PERMANENTLY — close's promise AND
- // the in-flight query's promise never settle — when any statement is in
- // flight (the trigger was the telemetry flush issuing two sequential
- // INSERTs). Ordering is load-bearing: the early-null means no NEW
- // statement can reach the raw handle (drainer writes fail fast with
- // 'PGLite not connected' and are swallowed — that is intended), while
- // statements ALREADY in flight settle against the still-open handle.
- // Reordering the drain above the null would reopen the #1337 race.
- await drainBackgroundWorkBeforeDisconnect();
+ // #4284 — out-of-band watchdog (opt-in; see pgliteCloseWatchdogMs). Armed
+ // ONLY when a live handle exists (a lock-only teardown has no close to
+ // wedge) and BEFORE the drain so a drain-side wedge is covered too.
+ // Scope: a PGLite disconnect with a live handle — nothing else. Disposed
+ // in the outer finally below, even when the drain or releaseLock throws.
+ let watchdog: { dispose(): void } | null = null;
+ if (db) {
+ const { deadlineMs, graceMs } = pgliteCloseWatchdogMs();
+ if (deadlineMs > 0) {
+ watchdog = installProcessWatchdog({
+ deadlineMs,
+ graceMs,
+ label: 'pglite-disconnect-watchdog',
+ });
+ // Keyed by the computed deadline (not once-per-process flat): in a
+ // long-lived daemon the drain-aware floor grows as sinks register, and
+ // this breadcrumb is the kill's attribution surface — it must re-fire
+ // when the effective deadline changes (#4284 red-team).
+ warnOncePerProcess(
+ `pglite-close-watchdog-armed:${deadlineMs}:${graceMs}`,
+ `[pglite] disconnect watchdog armed: SIGTERM at ${deadlineMs}ms, SIGKILL at ${deadlineMs + graceMs}ms (out-of-band worker thread — fires even if the event loop wedges; #4284).`,
+ );
+ }
+ }
+
try {
+ // #4143: drain in-flight background work AFTER the early-null and BEFORE
+ // close(). PGLite's close() deadlocks PERMANENTLY — close's promise AND
+ // the in-flight query's promise never settle — when any statement is in
+ // flight (the trigger was the telemetry flush issuing two sequential
+ // INSERTs). Ordering is load-bearing: the early-null means no NEW
+ // statement can reach the raw handle (drainer writes fail fast with
+ // 'PGLite not connected' and are swallowed — that is intended), while
+ // statements ALREADY in flight settle against the still-open handle.
+ // Reordering the drain above the null would reopen the #1337 race.
+ // Inside the try (#4284 red-team): the drain is contractually
+ // non-throwing, but the no-leaked-armed-worker guarantee must be
+ // structural, not contractual — a throw here still reaches the
+ // finally's releaseLock + dispose.
+ await drainBackgroundWorkBeforeDisconnect();
if (db) {
// Deliberately NOT wrapped in preservingProcessExitCode: close's
// status write (0) is long-standing baseline behavior that test-runner
@@ -802,27 +900,38 @@ export class PGLiteEngine implements BrainEngine {
// process.exitCode at all — it lives in the gbrain-owned channel
// (setCliExitVerdict/currentExitCode in cli-force-exit.ts).
//
- // #4143 backstop: bound close() so any residual instance of the
- // in-flight-statement deadlock degrades to a loud warning instead of
- // wedging the process until an outer 600s CI kill. A close-throw
- // still propagates (lock releases in finally, same as before). Note
- // for reconnect(): a timed-out close leaves a zombie instance briefly
+ // #4143/#4284 in-loop bound — HONEST SCOPE: catches a close that
+ // still YIELDS (slow, or promise-deadlocked with an idle loop). It
+ // can NEVER fire against a close that wedges the event loop (#4284):
+ // the timers phase doesn't run, so no same-loop timer wins this
+ // race. That class is prevented by the drain above; the opt-in
+ // watchdog is the only observer. The timer is armed BEFORE close()
+ // is called so close's pre-first-yield work runs with the bound
+ // already ticking, and it is deliberately REF'D (no unref): in the
+ // one case this bound can catch, an unref'd timer would let Bun exit
+ // before the warn and the lock release fire (precedent:
+ // cli-force-exit.ts adversarial F3, db-pacer.ts). Deliberately NOT
+ // timeout.ts:withTimeout — it unrefs its timer and rejects; this
+ // site needs a ref'd race that resolves a flag. A close-throw still
+ // propagates (lock releases in finally, same as before). Note for
+ // reconnect(): a timed-out close leaves a zombie instance briefly
// coexisting with a re-opened dataDir — the WAL-repair path covers
// the consequence on next open.
- const closePromise = db.close();
+ const timeoutMs = pgliteCloseTimeoutMs();
let timer: ReturnType<typeof setTimeout> | undefined;
try {
+ const timedOutPromise = new Promise<boolean>((resolve) => {
+ timer = setTimeout(() => resolve(true), timeoutMs);
+ });
+ const closePromise = db.close();
const timedOut = await Promise.race([
closePromise.then(() => false),
- new Promise<boolean>((resolve) => {
- timer = setTimeout(() => resolve(true), PGLITE_CLOSE_TIMEOUT_MS);
- timer.unref?.();
- }),
+ timedOutPromise,
]);
if (timedOut) {
warnOncePerProcess(
'pglite-close-timeout',
- `[pglite] db.close() did not settle within ${PGLITE_CLOSE_TIMEOUT_MS}ms — proceeding with teardown (a statement may still be in flight; #4143). Override with GBRAIN_PGLITE_CLOSE_TIMEOUT_MS.`,
+ `[pglite] db.close() did not settle within ${timeoutMs}ms — proceeding with teardown (a statement may still be in flight; #4143). Override with GBRAIN_PGLITE_CLOSE_TIMEOUT_MS. A close that WEDGES the event loop cannot be caught by this in-loop bound — arm GBRAIN_PGLITE_CLOSE_WATCHDOG_MS for the out-of-band watchdog (#4284).`,
);
// Abandoned close may reject later — never let it become an
// unhandled rejection.
@@ -833,8 +942,14 @@ export class PGLiteEngine implements BrainEngine {
}
}
} finally {
- if (lock?.acquired) {
- await releaseLock(lock);
+ try {
+ if (lock?.acquired) {
+ await releaseLock(lock);
+ }
+ } finally {
+ // #4284: dispose even when releaseLock throws — a leaked armed worker
+ // would SIGTERM/SIGKILL a process whose close already completed.
+ watchdog?.dispose();
}
}
}
diff --git a/src/core/process-watchdog.ts b/src/core/process-watchdog.ts
index 60b7b5c36d..fc0769c304 100644
--- a/src/core/process-watchdog.ts
+++ b/src/core/process-watchdog.ts
@@ -35,6 +35,8 @@
*/
import { Worker } from 'node:worker_threads';
+// Zero-import teardown-budget leaf — safe edge, no cycle (it imports nothing).
+import { MAX_TIMER_DELAY_MS } from './background-work.ts';
export type WatchdogAction = 'wait' | 'sigterm' | 'sigkill';
@@ -73,6 +75,35 @@ export interface WatchdogHandle {
const DEFAULT_GRACE_MS = 30_000;
+/**
+ * setTimeout delay ceiling (2^31−1): Node/Bun overflow-clamp larger delays to
+ * ~1ms, which for the deadline+grace SUM timer would mean SIGKILLing a healthy
+ * process almost immediately (#4284 hardening). Aliased from the shared
+ * teardown-budget constant so the ceiling cannot drift between modules.
+ */
+export const MAX_WATCHDOG_TIMER_MS = MAX_TIMER_DELAY_MS;
+
+/**
+ * Pure clamp for the two worker timers (#4284). The worker arms
+ * setTimeout(deadlineMs) AND setTimeout(deadlineMs + graceMs); BOTH delays
+ * must stay ≤ 2^31−1 or the overflowing one fires at ~1ms — for the sum
+ * timer that is an instant SIGKILL. Grace is clamped so the SUM fits, and a
+ * NON-FINITE grace is coerced to 0 (never NaN: setTimeout(deadline + NaN)
+ * fires at ~1ms — the exact failure this clamp exists to prevent). NaN
+ * deadline flows through as NaN so the caller's Number.isFinite inert-check
+ * still catches it; an INFINITE deadline clamps to the ceiling and ARMS
+ * (~24.8 days) rather than going inert — deliberate, matching the "oversized
+ * means longer bound" rule. Exported pure so unit tests verify the arithmetic
+ * without ever arming a real max-deadline worker in-suite (whose buggy
+ * overflow would SIGTERM the test runner itself).
+ */
+export function clampWatchdogTimers(deadlineMs: number, graceMs: number): { deadlineMs: number; graceMs: number } {
+ const d = Math.min(MAX_WATCHDOG_TIMER_MS, Math.floor(deadlineMs));
+ const safeGrace = Number.isFinite(graceMs) ? Math.max(0, Math.floor(graceMs)) : 0;
+ const g = Math.min(MAX_WATCHDOG_TIMER_MS - (Number.isFinite(d) ? Math.max(0, d) : 0), safeGrace);
+ return { deadlineMs: d, graceMs: g };
+}
+
function defaultWarn(msg: string): void {
try { process.stderr.write(msg + '\n'); } catch { /* stderr may be broken */ }
}
@@ -121,8 +152,7 @@ setTimeout(() => {
*/
export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandle {
const warn = opts.onWarn ?? defaultWarn;
- const deadlineMs = Math.floor(opts.deadlineMs);
- const graceMs = Math.max(0, Math.floor(opts.graceMs ?? DEFAULT_GRACE_MS));
+ const { deadlineMs, graceMs } = clampWatchdogTimers(opts.deadlineMs, opts.graceMs ?? DEFAULT_GRACE_MS);
// Sanitize label to a safe charset (defends the inline worker string + log lines).
const label = (opts.label ?? 'watchdog').replace(/[^A-Za-z0-9_.:-]/g, '').slice(0, 40) || 'watchdog';
const heartbeatMs = Math.max(0, Math.floor(opts.heartbeatMs ?? 0));
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 0b96982dbd..a0f796429a 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.46.21.0 -->
+<!-- gbrain-template-stamp: 0.46.22.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/fix-wave-structural.test.ts b/test/fix-wave-structural.test.ts
index 7a2d0701d1..2346eb2df7 100644
--- a/test/fix-wave-structural.test.ts
+++ b/test/fix-wave-structural.test.ts
@@ -222,6 +222,54 @@ describe('v0.42.20.0 — background-work registry drains every sink before disco
expect(drainIdx).toBeGreaterThan(nullIdx);
});
+ test('#4284 in-loop close bound arms BEFORE close, stays ref\'d; watchdog covers the whole drain+close window', () => {
+ // Neither half of the #4284 defect is observable behaviorally in-suite:
+ // something always keeps the test runner's loop alive (ref'd vs unref'd
+ // never differs), and the armed breadcrumb is deadline-keyed
+ // once-per-process (a second same-deadline arm is invisible). Source pins
+ // hold what tests can't. Anchors are unique statement literals,
+ // comment-proof (eng-review D13.2 discipline): a bare `db.close(` also
+ // matches doc comments, the connect()-time scratch-probe close, and the
+ // timeout warn string — all positioned BEFORE the disconnect site.
+ const pglite = readFileSync('src/core/pglite-engine.ts', 'utf8');
+ const earlyReturnIdx = pglite.indexOf('if (!db && !lock) return;');
+ const armIdx = pglite.indexOf("label: 'pglite-disconnect-watchdog'");
+ const drainIdx = pglite.indexOf('await drainBackgroundWorkBeforeDisconnect()');
+ const timerArmIdx = pglite.indexOf('timer = setTimeout(() => resolve(true), timeoutMs)');
+ const closeIdx = pglite.indexOf('const closePromise = db.close()');
+ const releaseIdx = pglite.indexOf('await releaseLock(lock)');
+ const disposeIdx = pglite.indexOf('watchdog?.dispose()');
+ expect(earlyReturnIdx).toBeGreaterThan(-1);
+ expect(armIdx).toBeGreaterThan(-1);
+ expect(drainIdx).toBeGreaterThan(-1);
+ expect(timerArmIdx).toBeGreaterThan(-1);
+ expect(closeIdx).toBeGreaterThan(-1);
+ expect(releaseIdx).toBeGreaterThan(-1);
+ expect(disposeIdx).toBeGreaterThan(-1);
+ // A no-op / lock-only disconnect never arms a worker (eng-review E4).
+ expect(earlyReturnIdx).toBeLessThan(armIdx);
+ // The watchdog covers a drain-side wedge too (OV-7).
+ expect(armIdx).toBeLessThan(drainIdx);
+ // Arm-before-close: the in-loop timer exists before close() starts
+ // (#4284 reason 1 — a timer armed after close's synchronous prefix
+ // misses it entirely).
+ expect(drainIdx).toBeLessThan(timerArmIdx);
+ expect(timerArmIdx).toBeLessThan(closeIdx);
+ // Dispose AFTER releaseLock inside the nested finally: a releaseLock
+ // throw must never leak an armed worker that later SIGKILLs a process
+ // whose close already completed (OV2-4). The nested-finally shape itself
+ // isn't index-checkable, but dispose-after-release plus the drain sitting
+ // inside the same try (drainIdx > the try that ends in this finally) pin
+ // the covered window.
+ expect(releaseIdx).toBeLessThan(disposeIdx);
+ // No unref on the close-bound timer: in the ONE case the in-loop bound
+ // can catch (never-settling close, idle loop), an unref'd timer lets the
+ // process exit before the warn and the lock release fire. Scoped to the
+ // disconnect region so unrelated timers may unref freely.
+ const disconnectRegion = pglite.slice(earlyReturnIdx, disposeIdx + 500);
+ expect(disconnectRegion).not.toContain('.unref');
+ });
+
test('cli-force-exit.ts daemon guard excludes "serve"', () => {
const src = readFileSync('src/core/cli-force-exit.ts', 'utf8');
expect(src).toMatch(/export function shouldForceExitAfterMain/);
diff --git a/test/fixtures/pglite-disconnect-watchdog-harness.ts b/test/fixtures/pglite-disconnect-watchdog-harness.ts
new file mode 100644
index 0000000000..c9393bbe29
--- /dev/null
+++ b/test/fixtures/pglite-disconnect-watchdog-harness.ts
@@ -0,0 +1,62 @@
+/**
+ * Fixture for test/pglite-disconnect-watchdog.serial.test.ts. Spawned via `bun`.
+ *
+ * Usage: bun pglite-disconnect-watchdog-harness.ts <mode>
+ * wedge-watchdog — monkeypatch close() into the measured #4284 wedge (a
+ * queueMicrotask re-pump that starves the timers phase,
+ * the #1762 shape), with the out-of-band watchdog armed by
+ * the parent's env. The watchdog's SIGKILL must end this
+ * process at deadline+grace.
+ * wedge-control — same wedge, NO watchdog env: pins #4284's measured claim
+ * that the in-loop close bound can never fire while the
+ * loop is starved (no warn, no post-disconnect marker;
+ * only the parent's cap ends it).
+ * clean-watchdog — real close with a deliberately-tiny watchdog env: proves
+ * the lethal-knob floor clamps up and a disposed watchdog
+ * never kills a healthy disconnect.
+ *
+ * Env knobs (GBRAIN_PGLITE_CLOSE_TIMEOUT_MS / _WATCHDOG_MS / _WATCHDOG_GRACE_MS)
+ * are set by the PARENT test per mode.
+ *
+ * Safety nets, stacked: the microtask spin self-bounds at 20s (after it stops
+ * the loop idles, the in-loop bound finally fires, and the process exits on
+ * its own), under the parent's marker-relative kill cap, under the parent's
+ * absolute failsafe. A failed kill can never hang CI.
+ */
+import { writeSync } from 'node:fs';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { backgroundWorkSinkCount } from '../../src/core/background-work.ts';
+
+const mode = process.argv[2] ?? 'wedge-control';
+
+// Mirror production: cli.ts installs SIGTERM cleanup handlers. With ANY JS
+// handler present, a starved event loop SURVIVES SIGTERM (the handler can
+// never run — signal dispatch to JS needs the loop), so the watchdog's
+// SIGKILL at deadline+grace is the real backstop. Without a handler the
+// KERNEL default would kill at the SIGTERM deadline and the SIGKILL path
+// would ship untested (#4284 eng outside-voice, empirically probed).
+process.on('SIGTERM', () => { /* no-op — a starved loop never runs this */ });
+
+const engine = new PGLiteEngine();
+await engine.connect({ engine: 'pglite' }); // in-memory; no initSchema — close is monkeypatched
+
+if (mode === 'wedge-watchdog' || mode === 'wedge-control') {
+ const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
+ eng._db!.close = () => {
+ const t0 = Date.now();
+ const spin = () => { if (Date.now() - t0 < 20_000) queueMicrotask(spin); };
+ spin();
+ return new Promise<void>(() => { /* never settles */ });
+ };
+}
+
+// fs.writeSync, NOT process.stdout.write: a stream write is a yield point and
+// would perturb the starvation under test (the #4143 instrumentation lesson).
+// SINKS lets the parent compute the expected lethal-knob floor dynamically
+// (floor = max(5000, sinks*2000 + closeTimeout + 2000)) instead of pinning a
+// number that silently drifts when a future sink joins this import graph.
+writeSync(1, `SINKS=${backgroundWorkSinkCount()}\n`);
+writeSync(1, 'ARMED\n');
+await engine.disconnect();
+writeSync(1, 'DISCONNECTED\n');
+process.exit(0);
diff --git a/test/pglite-disconnect-watchdog.serial.test.ts b/test/pglite-disconnect-watchdog.serial.test.ts
new file mode 100644
index 0000000000..14ff354c96
--- /dev/null
+++ b/test/pglite-disconnect-watchdog.serial.test.ts
@@ -0,0 +1,194 @@
+/**
+ * #4284 — Bun-pinned integration for the out-of-band PGLite disconnect
+ * watchdog, against a REAL wedged event loop.
+ *
+ * The issue's measured claim: a close() that starves the loop (queueMicrotask
+ * re-pump, the #1762 shape) can never lose a same-loop Promise.race — the
+ * timers phase never runs, so the in-loop close bound is structurally unable
+ * to fire. These tests spawn a harness that genuinely wedges its own loop and
+ * assert (a) the opt-in worker_threads watchdog kills it anyway, (b) without
+ * the watchdog nothing in-process ever fires (the #4284 regression pin), and
+ * (c) a healthy disconnect with a floored watchdog is never harmed.
+ *
+ * Signal semantics (eng outside-voice, empirically probed): the harness
+ * installs a no-op SIGTERM handler to mirror production (cli.ts cleanup
+ * handlers), so the starved child SURVIVES SIGTERM and dies by SIGKILL at
+ * deadline+grace — this suite is the only coverage of the SIGKILL backstop.
+ *
+ * Serial: real subprocesses + wall-clock timing + PGLite WASM cold starts.
+ */
+import { describe, test, expect } from 'bun:test';
+import { join } from 'node:path';
+
+const HARNESS = join(import.meta.dir, 'fixtures', 'pglite-disconnect-watchdog-harness.ts');
+
+/** Per-mode env; the close-timeout env also shapes the lethal-knob floor. */
+const CLOSE_TIMEOUT_MS = 1_000;
+const WATCHDOG_DEADLINE_MS = 5_000; // == the floor when sinks=0: max(5000, 0*2000 + 1000 + 2000)
+const WATCHDOG_GRACE_MS = 600;
+
+interface FixtureRun {
+ exitCode: number | null;
+ signalCode: string | null;
+ stdout: string;
+ stderr: string;
+ killedByTest: boolean;
+ /** wall-clock ms from the child's ARMED marker to exit; -1 if never armed */
+ sinceArmedMs: number;
+}
+
+/**
+ * Spawn the harness, kill-cap it relative to the child's ARMED marker (WASM
+ * cold-start varies wildly on loaded CI boxes — capping from spawn would
+ * flake), with a generous absolute failsafe behind it.
+ */
+async function runFixture(
+ mode: string,
+ env: Record<string, string | undefined>,
+ capAfterArmedMs: number,
+): Promise<FixtureRun> {
+ const cleanEnv: Record<string, string> = {};
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) {
+ if (v !== undefined) cleanEnv[k] = v;
+ }
+ const proc = Bun.spawn(['bun', HARNESS, mode], {
+ stdout: 'pipe',
+ stderr: 'pipe',
+ env: cleanEnv,
+ });
+ let killedByTest = false;
+ let armedAt = 0;
+ let markerCap: ReturnType<typeof setTimeout> | undefined;
+ // Both kill-caps no-op on an already-exited child: buffered stdout can
+ // arrive after proc.exited (arming markerCap on a stale closure), and a
+ // spurious late fire must not flip killedByTest or signal a dead PID.
+ const killIfAlive = () => {
+ if (proc.exitCode !== null) return;
+ killedByTest = true;
+ proc.kill('SIGKILL');
+ };
+ const failsafe = setTimeout(killIfAlive, 60_000);
+ let stdout = '';
+ const stdoutReader = (async () => {
+ const dec = new TextDecoder();
+ for await (const chunk of proc.stdout) {
+ stdout += dec.decode(chunk);
+ if (!armedAt && stdout.includes('ARMED')) {
+ armedAt = Date.now();
+ markerCap = setTimeout(killIfAlive, capAfterArmedMs);
+ }
+ }
+ })();
+ await proc.exited;
+ const exitAt = Date.now();
+ clearTimeout(failsafe);
+ // Drain the reader BEFORE clearing markerCap: buffered stdout (a fast clean
+ // exit's ARMED marker) can arrive after proc.exited resolves, and the
+ // reader is what arms markerCap — clearing first would leave a freshly
+ // armed timer dangling in the runner (maintainability review).
+ await stdoutReader;
+ if (markerCap) clearTimeout(markerCap);
+ const stderr = await new Response(proc.stderr).text();
+ return {
+ exitCode: proc.exitCode,
+ signalCode: (proc as unknown as { signalCode: string | null }).signalCode,
+ stdout,
+ stderr,
+ killedByTest,
+ sinceArmedMs: armedAt ? exitAt - armedAt : -1,
+ };
+}
+
+/** The harness prints SINKS=<n>; the expected floor derives from it. */
+function expectedFloor(stdout: string): number {
+ const m = stdout.match(/SINKS=(\d+)/);
+ expect(m).not.toBeNull();
+ const sinks = Number(m![1]);
+ return Math.max(5000, sinks * 2000 + CLOSE_TIMEOUT_MS + 2000);
+}
+
+describe('pglite disconnect watchdog vs a wedged event loop (#4284, Bun-pinned)', () => {
+ test('wedge-watchdog: the out-of-band watchdog SIGKILLs a loop-starved close at deadline+grace', async () => {
+ const r = await runFixture('wedge-watchdog', {
+ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: String(CLOSE_TIMEOUT_MS),
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: String(WATCHDOG_DEADLINE_MS),
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS: String(WATCHDOG_GRACE_MS),
+ }, 12_000);
+
+ // The watchdog — not this test — must be the killer, by SIGKILL: the
+ // harness's production-mirroring SIGTERM handler means only the kernel-
+ // level SIGKILL can end a starved loop. signalCode is the race-free pin
+ // (the worker's final stderr write could in principle lose to the kill).
+ expect(r.killedByTest).toBe(false);
+ expect(r.exitCode === 0).toBe(false);
+ expect(r.signalCode).toBe('SIGKILL');
+ expect(r.stdout).not.toContain('DISCONNECTED'); // the wedge never resolves
+
+ // Death lands near deadline+grace, measured from the child's ARMED marker
+ // (the floor for this env is exactly the deadline we armed — sinks=0).
+ expect(expectedFloor(r.stdout)).toBe(WATCHDOG_DEADLINE_MS);
+ expect(r.sinceArmedMs).toBeGreaterThanOrEqual(WATCHDOG_DEADLINE_MS - 500);
+ expect(r.sinceArmedMs).toBeLessThan(11_000);
+
+ // Attribution: the worker's stderr lines carry the label and fire even
+ // while the main thread is starved (worker_threads = separate OS thread).
+ expect(r.stderr).toContain('pglite-disconnect-watchdog');
+ expect(r.stderr).toContain('grace expired');
+
+ // ADVISORY (not asserted — OV-4): under starvation the in-loop warn should
+ // never appear; a future Bun that services timers under microtask pressure
+ // would change this. Logged for the human reading a red-adjacent run.
+ if (r.stderr.includes('did not settle')) {
+ console.log('[advisory] in-loop close-timeout warn fired under starvation — Bun timer semantics may have changed; re-evaluate #4284 assumptions');
+ }
+ }, 90_000);
+
+ test('wedge-control: WITHOUT the watchdog, nothing in-process fires — the #4284 regression pin', async () => {
+ const r = await runFixture('wedge-control', {
+ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: String(CLOSE_TIMEOUT_MS),
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: undefined,
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS: undefined,
+ }, 5_000);
+
+ // Anchor: the wedge actually ran. Without this, a pre-ARMED hang (e.g. a
+ // future connect() regression) would satisfy every negative assertion
+ // below against near-empty output and the regression pin would pass
+ // vacuously (testing-specialist finding).
+ expect(r.stdout).toContain('ARMED');
+ // Only the test's cap ends it: the wedge holds past 5x the in-loop bound.
+ expect(r.killedByTest).toBe(true);
+ expect(r.stdout).not.toContain('DISCONNECTED');
+ expect(r.stderr).not.toContain('pglite-disconnect-watchdog'); // off = off
+
+ // HARD assert — the direct pin of #4284's measured claim: the in-loop
+ // close-timeout warn NEVER appears while the loop is starved, because the
+ // timers phase never runs. If this fails after a Bun upgrade, the runtime
+ // now services timers under microtask starvation — that is a behavior
+ // IMPROVEMENT: re-evaluate whether the out-of-band watchdog is still the
+ // only wedge observer, do not paper over the red.
+ expect(r.stderr).not.toContain('did not settle');
+ }, 90_000);
+
+ test('clean-watchdog: a units-typo deadline clamps UP to the floor and a healthy disconnect is never killed', async () => {
+ const r = await runFixture('clean-watchdog', {
+ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: String(CLOSE_TIMEOUT_MS),
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: '100', // "100", thinking seconds — the units-typo footgun
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS: String(WATCHDOG_GRACE_MS),
+ }, 30_000);
+
+ // Healthy disconnect: clean exit, marker printed, nothing killed anything.
+ expect(r.killedByTest).toBe(false);
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain('DISCONNECTED');
+ expect(r.stderr).not.toContain('deadline reached'); // worker never fired
+ expect(r.stderr).not.toContain('grace expired');
+
+ // The lethal-knob floor: 100ms clamps UP (never down, never refuse-to-arm),
+ // the clamp warns, and the armed breadcrumb names the FLOORED deadline.
+ const floor = expectedFloor(r.stdout);
+ expect(r.stderr).toContain('below this process\'s safe floor');
+ expect(r.stderr).toContain(`SIGTERM at ${floor}ms`);
+ // Once per process: exactly one armed breadcrumb.
+ expect(r.stderr.split('disconnect watchdog armed').length - 1).toBe(1);
+ }, 90_000);
+});
diff --git a/test/pglite-engine-disconnect.serial.test.ts b/test/pglite-engine-disconnect.serial.test.ts
index 360c73e513..8f234131d1 100644
--- a/test/pglite-engine-disconnect.serial.test.ts
+++ b/test/pglite-engine-disconnect.serial.test.ts
@@ -37,6 +37,24 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { __registerDrainerForTest } from '../src/core/background-work.ts';
+import { _resetWarnOnceForTests } from '../src/core/utils.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+/**
+ * Capture console.warn lines for the duration of `fn` (warnOncePerProcess
+ * routes through console.warn). Restores in finally.
+ */
+async function captureWarns<T>(fn: () => Promise<T>): Promise<{ result: T; warns: string[] }> {
+ const warns: string[] = [];
+ const orig = console.warn;
+ console.warn = (...args: unknown[]) => { warns.push(args.map(String).join(' ')); };
+ try {
+ const result = await fn();
+ return { result, warns };
+ } finally {
+ console.warn = orig;
+ }
+}
function newTempDataDir(): string {
return mkdtempSync(join(tmpdir(), 'gbrain-disconnect-test-'));
@@ -264,29 +282,201 @@ describe('PGLiteEngine.disconnect() — v0.41.8.0 lifecycle invariants', () => {
test('#7 BOUNDED CLOSE (#4143): a close() that never settles cannot wedge disconnect, and the lock still releases', async () => {
const dataDir = newTempDataDir();
try {
+ // env floor is 1000ms — shaving ~4s off the default 5s bound per run.
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '1000' }, async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ await engine.initSchema();
+
+ // Force the deadlock shape directly: close() never settles.
+ const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
+ eng._db!.close = () => new Promise<void>(() => { /* never settles */ });
+
+ const started = Date.now();
+ await engine.disconnect(); // must resolve via the bounded race (~1s), not hang
+ const elapsed = Date.now() - started;
+ expect(elapsed).toBeLessThan(4_000); // 1s bound + generous slack
+
+ // Lock released despite the abandoned close: a fresh engine can
+ // connect to the SAME dataDir without lock contention.
+ const engine2 = new PGLiteEngine();
+ await engine2.connect({ database_path: dataDir });
+ const result = await engine2.executeRaw<{ ok: number }>('SELECT 1 AS ok');
+ expect(result[0].ok).toBe(1);
+ await engine2.disconnect();
+ });
+ } finally {
+ rmSync(dataDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ // ───────────────────────────────────────────────────────────────
+ // #4284 — the in-loop close bound, made honest. These pin the arm-
+ // before-close rework, the env floor/ceiling, the warn text, and the
+ // abandoned-close rejection swallow. The wedged-loop case (where NO
+ // in-loop timer can fire) lives in the spawned-fixture suite:
+ // test/pglite-disconnect-watchdog.serial.test.ts.
+ // ───────────────────────────────────────────────────────────────
+
+ test('#8 TIMEOUT WARN (#4284): a timed-out close warns once, names both env knobs, and teardown proceeds', async () => {
+ const dataDir = newTempDataDir();
+ try {
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '1000' }, async () => {
+ _resetWarnOnceForTests(); // 'pglite-close-timeout' is burned by test #7 in this process
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir });
+ const eng = engine as unknown as {
+ _db: { close: () => Promise<void> } | null;
+ _lock: { lockDir: string; acquired: boolean } | null;
+ };
+ const { existsSync } = await import('fs');
+ const lockDir = eng._lock!.lockDir;
+ expect(existsSync(lockDir)).toBe(true);
+ eng._db!.close = () => new Promise<void>(() => { /* never settles */ });
+
+ const started = Date.now();
+ const { warns } = await captureWarns(() => engine.disconnect());
+ const elapsed = Date.now() - started;
+ expect(elapsed).toBeLessThan(2_500); // resolved via the 1000ms bound
+
+ const timeoutWarns = warns.filter((w) => w.includes('did not settle within 1000ms'));
+ expect(timeoutWarns.length).toBe(1);
+ // The warn is the operator runbook: it must name the override AND the
+ // out-of-band watchdog (an in-loop bound cannot catch a wedged close).
+ expect(timeoutWarns[0]).toContain('GBRAIN_PGLITE_CLOSE_TIMEOUT_MS');
+ expect(timeoutWarns[0]).toContain('GBRAIN_PGLITE_CLOSE_WATCHDOG_MS');
+
+ // Lock released despite the abandoned close.
+ expect(existsSync(lockDir)).toBe(false);
+ });
+ } finally {
+ rmSync(dataDir, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ test('#9 ABANDONED-CLOSE REJECTION (#4284): a close that rejects after the timeout never becomes an unhandledRejection', async () => {
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '1000' }, async () => {
+ _resetWarnOnceForTests();
const engine = new PGLiteEngine();
- await engine.connect({ database_path: dataDir });
- await engine.initSchema();
+ await engine.connect({ engine: 'pglite' }); // in-memory
+ const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
+ // Rejects 200ms AFTER the 1000ms bound fires — the abandoned-promise path.
+ eng._db!.close = () =>
+ new Promise<void>((_resolve, reject) =>
+ setTimeout(() => reject(new Error('late synthetic close failure')), 1_200));
+
+ const unhandled: unknown[] = [];
+ const onUnhandled = (err: unknown) => { unhandled.push(err); };
+ process.on('unhandledRejection', onUnhandled);
+ try {
+ await captureWarns(() => engine.disconnect()); // resolves ~1s via the bound
+ // Let the late rejection actually fire, then a settle tick.
+ await new Promise((r) => setTimeout(r, 600));
+ await new Promise((r) => setTimeout(r, 50));
+ expect(unhandled).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', onUnhandled);
+ }
+ });
+ }, 30_000);
- // Force the deadlock shape directly: close() never settles.
+ test('#10 OVERFLOW CLAMP (#4284): a huge env value means a longer bound, never a ~1ms spurious fire — with a positive control', async () => {
+ // Phase 1: absurd env. Pre-clamp, setTimeout(9.9e13) overflow-fires at
+ // ~1ms and the bound would spuriously abandon a healthy 50ms close.
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '99999999999999' }, async () => {
+ _resetWarnOnceForTests(); // burned by earlier tests — without this the assert is vacuous
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' });
+ const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
+ const realClose = eng._db!.close.bind(eng._db!);
+ eng._db!.close = () => new Promise<void>((resolve) => setTimeout(() => resolve(realClose()), 50));
+
+ const { warns } = await captureWarns(() => engine.disconnect());
+ expect(warns.filter((w) => w.includes('did not settle')).length).toBe(0);
+ });
+
+ // Phase 2 (positive control): prove this rig CAN see the warn — same spy,
+ // same reset, a bound that genuinely fires.
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '1000' }, async () => {
+ _resetWarnOnceForTests();
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' });
const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
eng._db!.close = () => new Promise<void>(() => { /* never settles */ });
- const started = Date.now();
- await engine.disconnect(); // must resolve via the bounded race (~5s), not hang
- const elapsed = Date.now() - started;
- expect(elapsed).toBeLessThan(9_000); // 5s bound + generous slack
+ const { warns } = await captureWarns(() => engine.disconnect());
+ expect(warns.filter((w) => w.includes('did not settle within 1000ms')).length).toBe(1);
+ });
+ }, 30_000);
- // Lock released despite the abandoned close: a fresh engine can
- // connect to the SAME dataDir without lock contention.
- const engine2 = new PGLiteEngine();
- await engine2.connect({ database_path: dataDir });
- const result = await engine2.executeRaw<{ ok: number }>('SELECT 1 AS ok');
- expect(result[0].ok).toBe(1);
- await engine2.disconnect();
- } finally {
- rmSync(dataDir, { recursive: true, force: true });
+ test('#12 WATCHDOG ENV MATRIX (#4284): off-variants stay off, garbage warns, grace 0 is honored', async () => {
+ const { backgroundWorkSinkCount } = await import('../src/core/background-work.ts');
+ // The engine-only import graph registers no sinks, so with close-timeout
+ // 1000 the lethal-knob floor is max(5000, sinks*2000 + 1000 + 2000).
+ const floor = Math.max(5000, backgroundWorkSinkCount() * 2000 + 1000 + 2000);
+ const DEADLINE = String(floor + 1000); // above the floor: no clamp warn expected
+
+ async function healthyDisconnect(env: Record<string, string | undefined>): Promise<string[]> {
+ return withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '1000', ...env }, async () => {
+ _resetWarnOnceForTests();
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' });
+ const { warns } = await captureWarns(() => engine.disconnect());
+ return warns;
+ });
}
+
+ // Deliberate OFF spellings: no arm, no complaint.
+ for (const off of ['0', '-5']) {
+ const warns = await healthyDisconnect({ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: off });
+ expect(warns.filter((w) => w.includes('watchdog')).length).toBe(0);
+ }
+
+ // Garbage ("30s" units typo) must NOT silently disarm: loud warn, still off.
+ {
+ const warns = await healthyDisconnect({ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: '30s' });
+ expect(warns.filter((w) => w.includes('is not a number')).length).toBe(1);
+ expect(warns.filter((w) => w.includes('watchdog armed')).length).toBe(0);
+ }
+
+ // Explicit grace 0 is honored: SIGKILL lands AT the deadline.
+ {
+ const warns = await healthyDisconnect({
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: DEADLINE,
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS: '0',
+ });
+ const armed = warns.filter((w) => w.includes('watchdog armed'));
+ expect(armed.length).toBe(1);
+ expect(armed[0]).toContain(`SIGTERM at ${DEADLINE}ms, SIGKILL at ${DEADLINE}ms`);
+ }
+
+ // Garbage grace warns and falls back to the 30000 default.
+ {
+ const warns = await healthyDisconnect({
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS: DEADLINE,
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS: 'oops',
+ });
+ expect(warns.filter((w) => w.includes('Ignoring invalid GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS')).length).toBe(1);
+ const armed = warns.filter((w) => w.includes('watchdog armed'));
+ expect(armed.length).toBe(1);
+ expect(armed[0]).toContain(`SIGKILL at ${Number(DEADLINE) + 30_000}ms`);
+ }
+ }, 60_000);
+
+ test('#11 FLOOR BRANCH (#4284): env below the 1000ms floor is floored, not applied literally', async () => {
+ await withEnv({ GBRAIN_PGLITE_CLOSE_TIMEOUT_MS: '10' }, async () => {
+ _resetWarnOnceForTests(); // burned by earlier tests — without this the assert is vacuous
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' });
+ const eng = engine as unknown as { _db: { close: () => Promise<void> } | null };
+ const realClose = eng._db!.close.bind(eng._db!);
+ // Settles at ~300ms: under a literal 10ms bound the timer wins and warns;
+ // under the floored 1000ms bound the close wins and nothing warns.
+ eng._db!.close = () => new Promise<void>((resolve) => setTimeout(() => resolve(realClose()), 300));
+
+ const { warns } = await captureWarns(() => engine.disconnect());
+ expect(warns.filter((w) => w.includes('did not settle')).length).toBe(0);
+ });
}, 30_000);
});
diff --git a/test/process-watchdog.test.ts b/test/process-watchdog.test.ts
index 380ae6d338..af75f34647 100644
--- a/test/process-watchdog.test.ts
+++ b/test/process-watchdog.test.ts
@@ -4,7 +4,7 @@
* test/process-watchdog.serial.test.ts (Bun-pinned, real processes).
*/
import { describe, test, expect } from 'bun:test';
-import { watchdogDecision, installProcessWatchdog } from '../src/core/process-watchdog.ts';
+import { watchdogDecision, installProcessWatchdog, clampWatchdogTimers, MAX_WATCHDOG_TIMER_MS } from '../src/core/process-watchdog.ts';
describe('watchdogDecision', () => {
const deadline = 1000;
@@ -59,3 +59,59 @@ describe('installProcessWatchdog (handle contract)', () => {
h.dispose();
});
});
+
+describe('clampWatchdogTimers (#4284 joint-overflow clamp)', () => {
+ // Pure-function tests ONLY: setTimeout overflow-fires above 2^31−1, so a
+ // buggy clamp armed on a REAL worker would SIGTERM this test process at
+ // ~1ms (process.kill(process.pid)). Never arm a max-deadline worker here.
+ test('normal values pass through floored', () => {
+ expect(clampWatchdogTimers(5000.9, 600.2)).toEqual({ deadlineMs: 5000, graceMs: 600 });
+ });
+
+ test('a max deadline forces grace to zero so the SUM timer cannot overflow', () => {
+ const { deadlineMs, graceMs } = clampWatchdogTimers(MAX_WATCHDOG_TIMER_MS, 30_000);
+ expect(deadlineMs).toBe(MAX_WATCHDOG_TIMER_MS);
+ expect(graceMs).toBe(0);
+ expect(deadlineMs + graceMs).toBeLessThanOrEqual(MAX_WATCHDOG_TIMER_MS);
+ });
+
+ test('an oversized deadline clamps to the ceiling; the sum still fits', () => {
+ const { deadlineMs, graceMs } = clampWatchdogTimers(Number.MAX_SAFE_INTEGER, 30_000);
+ expect(deadlineMs).toBe(MAX_WATCHDOG_TIMER_MS);
+ expect(deadlineMs + graceMs).toBeLessThanOrEqual(MAX_WATCHDOG_TIMER_MS);
+ });
+
+ test('a near-ceiling deadline trims grace to exactly fit the sum', () => {
+ const { deadlineMs, graceMs } = clampWatchdogTimers(MAX_WATCHDOG_TIMER_MS - 10_000, 30_000);
+ expect(deadlineMs).toBe(MAX_WATCHDOG_TIMER_MS - 10_000);
+ expect(graceMs).toBe(10_000);
+ });
+
+ test('negative grace clamps to zero; NaN deadline flows through for the inert-check', () => {
+ expect(clampWatchdogTimers(5000, -1).graceMs).toBe(0);
+ // installProcessWatchdog's Number.isFinite inert-check must still see NaN.
+ expect(Number.isFinite(clampWatchdogTimers(Number.NaN, 100).deadlineMs)).toBe(false);
+ });
+
+ test('NaN grace is coerced to 0, never armed as a ~1ms overflow SIGKILL', () => {
+ // setTimeout(deadline + NaN) = setTimeout(NaN) fires at ~1ms — the exact
+ // failure class this clamp exists to prevent (multi-specialist finding).
+ const { deadlineMs, graceMs } = clampWatchdogTimers(5000, Number.NaN);
+ expect(deadlineMs).toBe(5000);
+ expect(graceMs).toBe(0);
+ });
+
+ test('Infinity deadline clamps to the ceiling and arms (documented contract)', () => {
+ // Deliberate: "oversized means longer bound" — an infinite deadline
+ // becomes ~24.8 days armed, not inert (see the clamp docstring).
+ const { deadlineMs, graceMs } = clampWatchdogTimers(Number.POSITIVE_INFINITY, 30_000);
+ expect(deadlineMs).toBe(MAX_WATCHDOG_TIMER_MS);
+ expect(deadlineMs + graceMs).toBeLessThanOrEqual(MAX_WATCHDOG_TIMER_MS);
+ });
+
+ test('installProcessWatchdog stays inert on NaN and non-positive deadlines post-clamp', () => {
+ const h = installProcessWatchdog({ deadlineMs: Number.NaN });
+ expect(h.active).toBe(false);
+ h.dispose();
+ });
+});
diff --git a/tests/heavy/read_latency_under_sync.sh b/tests/heavy/read_latency_under_sync.sh
index eee7bb0399..01b1c6cdd7 100755
--- a/tests/heavy/read_latency_under_sync.sh
+++ b/tests/heavy/read_latency_under_sync.sh
@@ -46,6 +46,10 @@ echo "[read_latency] running baseline + under-load workload..."
unset DATABASE_URL || true
set +e
+# #4284 canary: arm the out-of-band disconnect watchdog. The drain keeps it
+# silent on a healthy run; a regression of the #4143 wedge class dies loudly
+# at ~30s (SIGTERM 20s + SIGKILL +10s) instead of the 600s deadline kill —
+# and the stderr log names the wedge via the pglite-disconnect-watchdog label.
timeout 600s env \
BRAIN_PAGES="${BRAIN_PAGES:-500}" \
NUM_QUERIES="${NUM_QUERIES:-200}" \
@@ -53,6 +57,8 @@ timeout 600s env \
WRITES_PER_WRITER="${WRITES_PER_WRITER:-25}" \
STRICT="${STRICT_LATENCY:-0}" \
THRESHOLD_PCT="${THRESHOLD_PCT:-50}" \
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_MS="${GBRAIN_PGLITE_CLOSE_WATCHDOG_MS:-20000}" \
+ GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS="${GBRAIN_PGLITE_CLOSE_WATCHDOG_GRACE_MS:-10000}" \
bun run tests/heavy/_read_latency_workload.ts > "$WORKLOAD_OUT" 2>>"$LOG_DIR/heavy-read_latency-stderr-$TS.log"
WORKLOAD_RC=$?
set -e