Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(db): our own implementation of the #5946 fix (#5946)

time-attack3c58ed1f3196
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index f58f7bdf8d..a54247f703 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).
-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Parallel `--workers` child pools connect through `db.ts`'s `connectWorkerEngine` (`connectWithRetry` with `isRetryableWorkerConnectError`): the startup retry set plus postgres.js `CONNECT_TIMEOUT`, because the parent engine has already reached the same URL, so a timeout there is a starved handshake rather than a bad route (incremental sync's worker pools in `sync/imports.ts` do the same; `GBRAIN_NO_RETRY_CONNECT=1` opts out). Pinned by `test/worker-connect-retry.serial.test.ts`. A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).`runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.
+- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).`runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.
- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index 9221b0197f..c312aa3d90 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Single-source and `--all` deliver that intrinsic >100-file embed deferral the same way: a queued `embed-backfill` on a worker-backed engine with federated v2 on, a manual-drain outcome without a worker; an explicit `--no-embed` single-source run submits nothing. Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`. Managed single-source and `--all` CLI envelopes retain structured `failures`, `failure_codes`, `run_id`, `target_commit`, and `counts_scope: run_cumulative`; blocked results exit nonzero. `--retry-failed` requires explicit idle ordinary-source fresh admission with the same options; no managed `--skip-failed`. Google/GitHub API source kinds route before the managed Git cursor. Managed connector `--retry-failed` explicitly admits a linked replacement after authority, source/owner, cursor and idle-state checks; pending work and old terminal receipts are not replaced. Unsupported connector dry-run, Git filtering/working-tree/code and `--skip-failed` options refuse before credentials/network; bound sources keep file publication and unbound sources use explicit connector database authority.
Refactor wave 1 (W4 sync): `src/commands/sync.ts` is now the façade — it keeps the `SyncResult` / `SyncOpts` types, `runSync`, `resolveParallelism`, `syncOneSource` and re-exports every moved symbol, so importers need no change. The implementation described above lives in `src/commands/sync/` (next entry). Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file); the façade's ceiling dropped from 6,022 to 468 lines when the implementation moved.
-- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain with the CONNECT_TIMEOUT-tolerant worker connect retry; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.
+- `src/commands/sync/` — the `gbrain sync` implementation behind the `sync.ts` façade (refactor wave 1, W4 sync). `perform.ts` is `performSync` (dispatch, filesystem lock, writer lock). `incremental.ts` is `performSyncInner`, a short orchestrator that runs the phases in order and returns the first `partial` a drain produces: `preflight.ts` (repo, git root and scope, pull and HEAD — an abort of the sync signal or a process cleanup pass (SIGTERM/SIGHUP) stops the pull and returns partial `pull_timeout`, persisted `sync.exclude` / `sync.include_hidden` unions, gc'd-bookmark / first-sync / `--include-gitignored` full-sync fallbacks, checkpoint pin, working-tree scope and drift, the filtered delta, dry run — every exit before the checkpoint opens is `{ done }`, otherwise an immutable `SyncPlan`), `deletes.ts` (un-syncable-modified sweep, batched removed-file drain), `renames.ts` (rename drain, per-rename apply, reconcile fallback), `imports.ts` (concurrency and connection clamp, pacer, stall watchdog, `importOnePath`, serial / worker-pool drain whose pools connect with `retryConnectTimeout`, #5946; the #132 rule — never wrap the drain or its call in `engine.transaction()` — is pinned in `test/sync.test.ts` for both files) and `finalize.ts` (zero-change exit, final flush, pin-reachability gate, failure-ledger bookmark gate, ingest log, extract / facts / embed). `sync-run.ts` defines `SyncRun`, the state the phases share across awaits, and `SyncPlan`; mutable fields are accessed only as `run.<field>` and `@checkpoint` fields are written only by `sync-run.ts` (`createSyncRun`, `flushCheckpoint`, `markCompleted`, `maybeYield`, `registerCheckpointCleanup`, `partial`, `abortUnpersistedPin`) — enforced by `scripts/check-sync-run-state.ts` (docs/TESTING.md#syncrun-state-guard). `full.ts` is `performFullSync` (dry run, import, shared failure gate, reconcile of deleted files, stale embed); the hold settle and the delete reconcile reuse runImport's walk only when `reusableWalk` accepts it (complete, same root, identical strategy / include-gitignored / --include-hidden / --exclude), and a reconcile whose reused walk names any page stale decides deletions on a fresh walk, because the import walk can miss a file restored since. `run.ts` is the CLI body `runSyncInner` (break-lock, source resolution, `--skip-failed` pre-ack, `runSyncAll` fan-out, `runSingleSourceSync` / watch), with flag parsing and usage text in `args.ts` (`parseSyncFlags` before the `--break-lock` branch, `parseSyncFanoutFlags` after it, `printSyncHelp`). Helpers: `checkpoint.ts` (checkpoint keys, cadence env knobs), `rename-reconcile.ts` (tracked-slug liveness index, orphaned `<rename:…>` sentinel sweep), `connector.ts`, `trigger.ts` (`gbrain sync trigger`), `report.ts` (`printSyncResult`, nudges), `missing-path.ts`, `gitignore.ts`. Controlled-order interleavings (watchdog, caller abort, SIGTERM cleanup, checkpoint write, mid-run commit, gc'd bookmark) with durable state checked after a restart: `test/sync-run-ordering.serial.test.ts`; parallel worker completion on Postgres: `test/e2e/sync-run-workers-postgres.test.ts`. Adding a sync phase: add a module that takes `(run, Pick<SyncPlan, ...>, ...)` and returns `SyncResult | undefined`, and call it from `performSyncInner` in order.
- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index b493e760a5..db194d7cf9 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).
-- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`. `resolveUrlConnectTimeout(url)` supplies `connect_timeout` to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; `0`, junk or no parameter means 10s. Pinned by `test/db-connect-timeout.test.ts`.
+- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect(config, { onpoisoned })` passes the owner engine's poisoned-discard hook to the singleton pool and returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the CLI teardown contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`. `resolveUrlConnectTimeout(url)` supplies `connect_timeout` to the same four call sites from each pool's own URL query (postgres.js lets the explicit option win over the URL, so the URL value is honoured only through this resolver): whole seconds, capped at the runtime's 2^31-1 ms timer limit; `0`, junk or no parameter means 10s. Pinned by `test/db-connect-timeout.test.ts`. `connectWithRetry` retries the `isRetryableConnError` set (3 attempts, 1s/2s backoff; `GBRAIN_NO_RETRY_CONNECT=1` makes it one); `retryConnectTimeout: true` adds postgres.js `CONNECT_TIMEOUT` (`isConnectTimeoutError` in `retry-matcher.ts`) and is passed only by the per-worker pools of parallel import and incremental sync, whose URL the parent engine already reached (#5946), so a first connect still fails fast on a timeout. Pinned by `test/worker-pool-connect-retry.test.ts`.
- `src/core/degraded-engine.ts` + `src/core/degraded-marker.ts` — degraded-mode serve, STARTUP-SCOPED by design: when Postgres is unreachable at `gbrain serve` startup, serve boots on `createDegradedEngine` (a concrete object whose method set is enumerated from PostgresEngine's prototype at construction — no dynamic `get` trap; `kind` is an explicit getter, read synchronously at ~29 branch sites; `disconnect()` is a no-op while dead so shutdown never triggers a reconnect) instead of dying. Every tool call attempts ONE reconnect (single-flight across concurrent callers, min-interval gated ~5s — no connect storms against a dying pooler); calls inside the window throw the STORED original error (stale-but-honest, refreshed on every real attempt) so MCP dispatch classifies the REAL error shape into the `database_error` envelope + marker. The `reconnect` callback is the FULL deferred connectEngine (config merge, gateway, migrations — guarded in cli.ts: a vanished config.json throws instead of connectEngine's process.exit killing the live server); first success swaps in the live engine permanently and fires recovery callbacks (serve re-runs deferred boot + sends `tools/list_changed` — clients that handshook degraded hold the reduced gate-hidden catalog and must refresh; the callback is a no-op once shutdown has started) — but the TRIGGERING call gets `DegradedRecoveredRetryError`, never a result: its source scope was resolved under the degraded fallback, so one client retry buys scope correctness (no call ever executes under the fallback scope against a live engine). Callers waiting on an in-flight attempt are latency-capped (`callerWaitMs`, default 2s — they get the stored error while the attempt finishes in the background, so a timeout-class failure can't stall the MCP handshake). Prototype GETTERS delegate too (throw the stored error while dead — never a silent `undefined`); `DEGRADED_LAST_ERROR` is a read-only accessor for the stored diagnosis (drives the HTTP `/health` degraded reason without consuming a reconnect). Serve-side degraded posture: source scope honors a validated `GBRAIN_SOURCE` (tier `env`) before seed_default, and `stdioVisibleTools` fail-closes every gated op WITHOUT touching the engine. The degraded gate keys on the RESOLVED brain's engine (a PGLite mount on a postgres host keeps die-on-startup). Mid-session outages ride `PostgresEngine.reconnect()` + per-call classified envelopes — degraded mode adds no mid-session state; PGLite startup failures keep die-on-startup (single-writer lock makes a lazy proxy wrong there; that lane's repair is pglite-repair). Kill switch `GBRAIN_SERVE_DEGRADED=0` (or `false`); structured `[gbrain-serve] DEGRADED/RECOVERED` stderr lines. `degraded-marker.ts` is the dependency-free seam (`Symbol.for`-registered markers + `isEngineDegraded`/`onEngineRecovered`/`degradedLastError`) so server.ts/serve.ts/http-transport.ts can ask about degraded state without importing the heavy Postgres engine module.
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 9667a37fb0..46cb39afb6 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -353,7 +353,6 @@ test/upgrade.serial.test.ts R2 R2: mock.module(${repoRoot}src/core/binary-self-u
test/v0_28_5-fix-wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_PGLITE_SNAPSHOT)
test/v0_37_fix_wave.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_EMBEDDING_MODEL, GBRAIN_EMBEDDING_DIMENSIONS, OPENAI_API_KEY (+4 more))
test/v0_37_gap_fill.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_NON_INTERACTIVE)
-test/worker-connect-retry.serial.test.ts R2 R2: mock.module(../src/core/postgres-engine.ts) replaces modules for every file in the process
test/worker-lock-renewal-e2e.serial.test.ts R1 R1: mutates process.env (GBRAIN_AUDIT_DIR)
test/worker-registry.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/workspace-push.serial.test.ts R1 R1: mutates process.env (HOME, GBRAIN_HOME, GBRAIN_GIT_ALLOW_FILE_TRANSPORT, PATH (+1 more))
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 577d986ac4..b57e0f865b 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -844,7 +844,7 @@ export async function runImport(
}
} else {
const { PostgresEngine } = await import('../core/postgres-engine.ts');
- const { resolvePoolSize, connectWorkerEngine } = await import('../core/db.ts');
+ const { connectWithRetry, resolvePoolSize } = await import('../core/db.ts');
// Each child keeps the established two-connection pool. GBRAIN_POOL_SIZE
// controls the parent pool; GBRAIN_MAX_CONNECTIONS clamps the child
// count above so the combined footprint stays within the operator's cap.
@@ -860,7 +860,7 @@ export async function runImport(
for (let i = 0; i < actualWorkers; i++) {
if (signal?.aborted) break;
const eng = new PostgresEngine();
- await connectWorkerEngine(eng, { database_url: databaseUrl, poolSize: workerPoolSize });
+ await connectWithRetry(eng, { database_url: databaseUrl, poolSize: workerPoolSize }, { retryConnectTimeout: true });
workerEngines.push(eng);
}
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index 9043a30af0..db251bf19c 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -423,7 +423,7 @@ async function drainImports(
}
} else {
const { PostgresEngine } = await import('../../core/postgres-engine.ts');
- const { resolvePoolSize, connectWorkerEngine } = await import('../../core/db.ts');
+ const { connectWithRetry, resolvePoolSize } = await import('../../core/db.ts');
const workerPoolSize = Math.min(2, resolvePoolSize(2));
const workerCount = Math.min(effectiveConcurrency, importsToDo.length);
const databaseUrl = config.database_url;
@@ -439,7 +439,7 @@ async function drainImports(
// already-connected engines on any one failure.
for (let i = 0; i < workerCount; i++) {
const eng = new PostgresEngine();
- await connectWorkerEngine(eng, { database_url: databaseUrl, poolSize: workerPoolSize });
+ await connectWithRetry(eng, { database_url: databaseUrl, poolSize: workerPoolSize }, { retryConnectTimeout: true });
workerEngines.push(eng);
}
diff --git a/src/core/db.ts b/src/core/db.ts
index 366aa9e49f..390291f9f9 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -5,7 +5,7 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import type { BrainEngine } from './engine.ts';
import { verifySchema } from './schema-verify.ts';
-import { isRetryableConnError, isRetryableWorkerConnectError } from './retry-matcher.ts';
+import { isConnectTimeoutError, isRetryableConnError } from './retry-matcher.ts';
let sql: ReturnType<typeof postgres> | null = null;
let connectedUrl: string | null = null;
@@ -438,8 +438,16 @@ export interface ConnectWithRetryOpts {
baseDelayMs?: number;
noRetry?: boolean;
log?: (line: string) => void;
- /** Which errors earn another attempt. Defaults to `isRetryableDbConnectError`. */
- isRetryable?: (err: unknown) => boolean;
+ /**
+ * Also retry postgres.js CONNECT_TIMEOUT (#5946). Set it only when this
+ * process already holds a connection to the same database_url, as the
+ * per-worker pools of parallel import and incremental sync do: the route is
+ * then known to work, so a missed handshake timer means the handshake was
+ * starved (typically by a long synchronous stretch on this event loop), and
+ * no session existed yet, so dialing again is safe. Every other caller
+ * keeps failing fast on a timeout, which usually means a bad route.
+ */
+ retryConnectTimeout?: boolean;
}
export async function connectWithRetry(
@@ -459,7 +467,7 @@ export async function connectWithRetry(
return;
} catch (e: unknown) {
lastErr = e;
- const retryable = (opts.isRetryable ?? isRetryableDbConnectError)(e);
+ const retryable = isRetryableDbConnectError(e) || (opts.retryConnectTimeout === true && isConnectTimeoutError(e));
const isLast = i === attempts - 1;
if (!retryable || isLast) {
throw e;
@@ -473,19 +481,3 @@ export async function connectWithRetry(
// Unreachable, but TS needs the throw.
throw lastErr;
}
-
-/**
- * Connect one per-worker pool of a parallel `import` or incremental `sync`.
- * Each is a fresh TCP + TLS + auth handshake, and one that failed used to
- * abort the whole import (under `sync --all`, drop the whole source). Same
- * bounded retry as the CLI's startup connect (3 attempts, 1s/2s backoff;
- * GBRAIN_NO_RETRY_CONNECT=1 opts out), plus CONNECT_TIMEOUT: the parent engine
- * already reached this URL, so a timeout here is a starved handshake, not a
- * bad route (see isRetryableWorkerConnectError).
- */
-export function connectWorkerEngine(
- engine: BrainEngine,
- config: EngineConfig & { poolSize: number },
-): Promise<void> {
- return connectWithRetry(engine, config, { isRetryable: isRetryableWorkerConnectError });
-}
diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.ts
index cae9eee185..87699cb789 100644
--- a/src/core/retry-matcher.ts
+++ b/src/core/retry-matcher.ts
@@ -160,26 +160,20 @@ export function isConnectionEndedError(err: unknown): boolean {
}
/**
- * Is this a transient failure of a PER-WORKER pool's connect (the extra
- * PostgresEngine pools that parallel `import` and `sync` open, one per worker)?
+ * Did postgres.js abandon a connection handshake because its own
+ * `connect_timeout` timer fired? It reports that as code `CONNECT_TIMEOUT`
+ * with the message "write CONNECT_TIMEOUT <host>:<port>" (the host and port
+ * read "undefined:undefined" once the socket has been upgraded to TLS).
*
- * Everything `isRetryableConnError` accepts, plus postgres.js's library code
- * `CONNECT_TIMEOUT` ("write CONNECT_TIMEOUT host:port", or "undefined:undefined"
- * once the socket has been upgraded to TLS). The general matcher leaves that
- * code out on purpose: on a process's FIRST connect a timeout usually means
- * the host does not route (pg-access-classify's `network_unreachable`), and
- * the fix is the URL, not a retry.
- *
- * A worker pool is different by construction. It is opened only after the
- * parent engine has connected to the same `database_url`, so the route is
- * proven, and a handshake that misses `connect_timeout` there was starved
- * rather than misrouted: most often by the client's own event loop, held by a
- * synchronous stretch (a large repository walk) longer than the timeout. No
- * session was established, so a fresh attempt is safe.
+ * Kept OUT of `isRetryableConnError` on purpose: on a process's first connect
+ * a handshake timeout usually means the host does not route, which
+ * pg-access-classify reports as `network_unreachable`, and retrying cannot
+ * fix that. A caller that has already reached the same URL in this process
+ * opts in through connectWithRetry's `retryConnectTimeout`.
*/
-export function isRetryableWorkerConnectError(err: unknown): boolean {
- if (isRetryableConnError(err)) return true;
- return getCode(err) === 'CONNECT_TIMEOUT' || /CONNECT_TIMEOUT/.test(getMessage(err));
+export function isConnectTimeoutError(err: unknown): boolean {
+ if (getCode(err) === 'CONNECT_TIMEOUT') return true;
+ return /\bCONNECT_TIMEOUT\b/.test(getMessage(err));
}
/**
diff --git a/test/minions.test.ts b/test/minions.test.ts
index 51df16b930..0317b662ad 100644
--- a/test/minions.test.ts
+++ b/test/minions.test.ts
@@ -2743,30 +2743,6 @@ describe('connectWithRetry / isRetryableDbConnectError', () => {
).rejects.toThrow();
expect(attempts).toBe(1);
});
-
- test('connectWithRetry: isRetryable decides which errors earn another attempt; the default is unchanged', async () => {
- const { connectWithRetry } = await import('../src/core/db.ts');
- const { isRetryableWorkerConnectError } = await import('../src/core/retry-matcher.ts');
- const timeout = Object.assign(new Error('write CONNECT_TIMEOUT undefined:undefined'), { code: 'CONNECT_TIMEOUT' });
- let attempts = 0;
- const fakeEngine = {
- connect: async () => {
- attempts++;
- if (attempts === 1) throw timeout;
- },
- } as unknown as Parameters<typeof connectWithRetry>[0];
-
- await expect(
- connectWithRetry(fakeEngine, { database_url: 'postgres://x' }, { baseDelayMs: 1, log: () => {} })
- ).rejects.toBe(timeout);
- expect(attempts).toBe(1);
-
- attempts = 0;
- await connectWithRetry(fakeEngine, { database_url: 'postgres://x' }, {
- baseDelayMs: 1, log: () => {}, isRetryable: isRetryableWorkerConnectError,
- });
- expect(attempts).toBe(2);
- });
});
// ---------------------------------------------------------------------------
diff --git a/test/retry-matcher.test.ts b/test/retry-matcher.test.ts
index 24fda27eab..e0b916d722 100644
--- a/test/retry-matcher.test.ts
+++ b/test/retry-matcher.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, test } from 'bun:test';
import {
+ isConnectTimeoutError,
isStatementTimeoutError,
isLockTimeoutError,
isRetryableConnError,
isRetryableError,
- isRetryableWorkerConnectError,
} from '../src/core/retry-matcher.ts';
function pgError(code: string, message: string): Error & { code: string } {
@@ -136,39 +136,38 @@ describe('isRetryableError', () => {
});
});
-describe('isRetryableWorkerConnectError', () => {
- // The two shapes postgres.js 3.4.x builds for `Errors.connection('CONNECT_TIMEOUT', ...)`:
- // the TCP socket's host:port, or undefined:undefined once secure() has swapped
- // in the tls.connect() socket.
- const beforeTls = pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT db.example.test:5432');
- const afterTls = pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT undefined:undefined');
-
- test('retries CONNECT_TIMEOUT in both shapes, and via the message when a wrapper dropped the code', () => {
- expect(isRetryableWorkerConnectError(beforeTls)).toBe(true);
- expect(isRetryableWorkerConnectError(afterTls)).toBe(true);
- expect(isRetryableWorkerConnectError(new Error('write CONNECT_TIMEOUT db.example.test:5432'))).toBe(true);
- });
-
- test('accepts everything the general connection matcher accepts', () => {
- for (const err of [
- new Error('connection refused'),
- new Error('the database system is starting up'),
- pgError('CONNECTION_ENDED', 'write CONNECTION_ENDED'),
- pgError('53300', 'too many connections for role'),
- ]) {
- expect(isRetryableConnError(err)).toBe(true);
- expect(isRetryableWorkerConnectError(err)).toBe(true);
+describe('isConnectTimeoutError (#5946)', () => {
+ test.each([
+ ['the TCP-socket message with its code', pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT db.example.test:5432')],
+ ['the post-TLS message with its code', pgError('CONNECT_TIMEOUT', 'write CONNECT_TIMEOUT undefined:undefined')],
+ ['the code on a plain object without a message', { code: 'CONNECT_TIMEOUT' }],
+ ['the message after a wrapper dropped the code', new Error('worker 2: write CONNECT_TIMEOUT 10.0.0.5:6543')],
+ ])('matches %s', (_label, err) => {
+ expect(isConnectTimeoutError(err)).toBe(true);
+ });
+
+ test.each([
+ ['null', null],
+ ['undefined', undefined],
+ ['zero', 0],
+ ['NaN', Number.NaN],
+ ['an empty string', ''],
+ ['a longer token that only contains the name', new Error('metric CONNECT_TIMEOUTS_TOTAL rose')],
+ ['a lowercase mention', new Error('connect_timeout=10 in the URL')],
+ ['a TCP-level ETIMEDOUT', pgError('ETIMEDOUT', 'connect ETIMEDOUT 10.0.0.5:5432')],
+ ['a statement timeout', pgError('57014', 'canceling statement due to statement timeout')],
+ ['a lock timeout', pgError('55P03', 'could not obtain lock on relation')],
+ ['an ended connection', pgError('CONNECTION_ENDED', 'write CONNECTION_ENDED db.example.test:5432')],
+ ['a different code with an unrelated message', pgError('3D000', 'database "gbrain" does not exist')],
+ ])('does not match %s', (_label, err) => {
+ expect(isConnectTimeoutError(err)).toBe(false);
+ });
+
+ test('the general connection matcher still refuses CONNECT_TIMEOUT, so first connects fail fast', () => {
+ for (const where of ['db.example.test:5432', 'undefined:undefined']) {
+ const err = pgError('CONNECT_TIMEOUT', `write CONNECT_TIMEOUT ${where}`);
+ expect(isConnectTimeoutError(err)).toBe(true);
+ expect(isRetryableConnError(err)).toBe(false);
}
});
-
- test('still refuses permanent errors and statement / lock timeouts', () => {
- expect(isRetryableWorkerConnectError(pgError('3D000', 'database "gbrain" does not exist'))).toBe(false);
- expect(isRetryableWorkerConnectError(pgError('57014', 'canceling statement due to statement timeout'))).toBe(false);
- expect(isRetryableWorkerConnectError(pgError('55P03', 'could not obtain lock on row'))).toBe(false);
- });
-
- test('the general matcher is not widened: a first connect still fails fast on CONNECT_TIMEOUT', () => {
- expect(isRetryableConnError(beforeTls)).toBe(false);
- expect(isRetryableConnError(afterTls)).toBe(false);
- });
});
diff --git a/test/worker-connect-retry.serial.test.ts b/test/worker-connect-retry.serial.test.ts
deleted file mode 100644
index a15380a81c..0000000000
--- a/test/worker-connect-retry.serial.test.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * A per-worker pool connect survives one transient CONNECT_TIMEOUT.
- *
- * Parallel `import` (which `sync --full` runs) and incremental `sync` open one
- * PostgresEngine pool per worker, each a fresh TCP + TLS + auth handshake,
- * after the parent engine has already connected to the same URL. That connect
- * had no retry, and `isRetryableConnError` does not accept postgres.js's
- * `CONNECT_TIMEOUT` anyway, so one handshake that missed `connect_timeout`
- * threw out of the worker loop: the import failed, and under `sync --all` the
- * whole source was dropped. The usual cause is the client, not the server: a
- * long synchronous stretch in the same process (one source's repository walk)
- * holds the event loop while another source's handshake is in flight.
- *
- * Serial (`.serial.test.ts`): a top-level mock.module stands in for the worker
- * engines so each connect can be scripted to fail; nothing dials a database.
- */
-import { afterAll, beforeAll, beforeEach, expect, mock, spyOn, test } from 'bun:test';
-import { execFileSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import type { BrainEngine } from '../src/core/engine.ts';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import * as importFiles from '../src/core/import-file.ts';
-import * as sourceFilesystem from '../src/core/minions/source-filesystem.ts';
-import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';
-import { runImport } from '../src/commands/import.ts';
-import { performSync } from '../src/commands/sync.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-let connects = 0;
-let scriptedFailures: Error[] = [];
-
-mock.module('../src/core/postgres-engine.ts', () => ({
- PostgresEngine: class {
- readonly kind = 'postgres';
- async connect(): Promise<void> {
- connects += 1;
- const failure = scriptedFailures.shift();
- if (failure) throw failure;
- }
- async disconnect(): Promise<void> {}
- },
-}));
-
-/** The shape postgres.js throws when the connect timer fires after the TLS upgrade. */
-const connectTimeout = () =>
- Object.assign(new Error('write CONNECT_TIMEOUT undefined:undefined'), { code: 'CONNECT_TIMEOUT' });
-
-const home = mkdtempSync(join(tmpdir(), 'gbrain-worker-connect-retry-'));
-const emptyDir = join(home, 'empty-import');
-const repo = join(home, 'repo');
-let engine: PGLiteEngine;
-
-const isolated = (fn: () => Promise<void>) => withEnv({
- GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_MAX_CONNECTIONS: undefined,
- GBRAIN_POOL_SIZE: undefined, GBRAIN_NO_RETRY_CONNECT: undefined,
-}, fn);
-
-function git(...args: string[]): string {
- return execFileSync('git', ['-C', repo, '-c', 'user.name=Example', '-c', '[email protected]',
- '-c', 'core.hooksPath=/dev/null', ...args], { encoding: 'utf8' }).trim();
-}
-
-function writePage(name: string): void {
- writeFileSync(join(repo, `${name}.md`), `---\ntype: note\ntitle: ${name}\n---\n\nWorker connect fixture ${name}.\n`);
-}
-
-beforeAll(async () => isolated(async () => {
- mkdirSync(emptyDir);
- mkdirSync(repo);
- mkdirSync(join(home, '.gbrain'));
- writeFileSync(join(home, '.gbrain', 'config.json'),
- JSON.stringify({ engine: 'postgres', database_url: 'postgresql://example.invalid/gbrain_test' }));
- writePage('base');
- execFileSync('git', ['init', '-q', repo]);
- git('add', '.');
- git('commit', '-qm', 'base');
- engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
- await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);
-}), 60_000);
-
-afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); });
-
-beforeEach(() => {
- connects = 0;
- scriptedFailures = [];
-});
-
-/** Capture the retry line connectWithRetry writes to stderr. */
-async function withCapturedWarnings(fn: () => Promise<unknown>): Promise<string[]> {
- const lines: string[] = [];
- const warnSpy = spyOn(console, 'warn').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });
- try { await fn(); } finally { warnSpy.mockRestore(); }
- return lines;
-}
-
-test('import: a worker connect that times out once is retried, and the import completes', () => isolated(async () => {
- // The worker pools here are mocks; the import runs inside an already-held
- // fixture-root lock, as nested sync imports do (import-connection-budget's seam).
- const heldRoot = realpathSync(emptyDir);
- const lockSpy = spyOn(sourceFilesystem, 'hasSourceFilesystemLock').mockImplementation(path => path === heldRoot);
- const parent = { kind: 'postgres', executeRaw: async () => [], getConfig: async () => null } as unknown as BrainEngine;
- scriptedFailures = [connectTimeout()];
- try {
- const warnings = await withCapturedWarnings(() => runImport(parent, ['--no-embed', '--workers', '2', emptyDir]));
- expect(connects).toBe(3); // two workers, one of them on its second attempt
- expect(warnings.some(line => line.includes('CONNECT_TIMEOUT') && line.includes('retrying'))).toBe(true);
- } finally {
- lockSpy.mockRestore();
- }
-}));
-
-test('sync: a worker connect that times out once is retried, and the source still syncs', () => isolated(async () => {
- // First sync (serial, on PGLite) sets the bookmark; the next commit's two
- // pages then go through the incremental parallel drain.
- const first = await performSync(engine, { repoPath: repo, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true });
- expect(first.status).toBe('first_sync');
- writePage('alpha');
- writePage('beta');
- git('add', '.');
- git('commit', '-qm', 'two more pages');
-
- // The worker engines are mocks, so the per-file import is stubbed. The
- // parent is the PGLite engine reporting itself as Postgres; the real PGLite
- // engine holds the filesystem lock, and the caller-held scope stands in for
- // the per-source lease (`skipLock`), as in import-cancellation's harness.
- const importSpy = spyOn(importFiles, 'importFile').mockImplementation(async (_eng, _file, path) =>
- ({ status: 'imported', slug: path.slice(0, -3), chunks: 1 }));
- const parent = new Proxy(engine, { get(target, prop) {
- if (prop === 'kind') return 'postgres';
- const value = Reflect.get(target, prop); return typeof value === 'function' ? value.bind(target) : value;
- } }) as BrainEngine;
- scriptedFailures = [connectTimeout()];
- try {
- let result: Awaited<ReturnType<typeof performSync>> | undefined;
- const warnings = await withCapturedWarnings(async () => {
- result = await withSourceFilesystemLock(engine, repo, () => performSync(parent, {
- repoPath: repo, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, concurrency: 2, skipLock: true,
- }));
- });
- expect(result?.status).toBe('synced');
- expect(result?.added).toBe(2);
- expect(importSpy).toHaveBeenCalledTimes(2);
- expect(connects).toBe(3);
- expect(warnings.some(line => line.includes('CONNECT_TIMEOUT') && line.includes('retrying'))).toBe(true);
- } finally {
- importSpy.mockRestore();
- }
-}), 60_000);
diff --git a/test/worker-pool-connect-retry.test.ts b/test/worker-pool-connect-retry.test.ts
new file mode 100644
index 0000000000..b95038db93
--- /dev/null
+++ b/test/worker-pool-connect-retry.test.ts
@@ -0,0 +1,244 @@
+/**
+ * #5946: the per-worker Postgres pools of parallel import and incremental
+ * sync retry a handshake that missed postgres.js's connect timer.
+ *
+ * Those pools open only after the parent engine has connected to the same
+ * database_url, so a CONNECT_TIMEOUT there is a starved handshake, not a bad
+ * route. connectWithRetry takes that as an explicit opt-in
+ * (`retryConnectTimeout`); every other caller still fails fast on it.
+ *
+ * Three layers:
+ * 1. connectWithRetry's decision table against a scripted engine.
+ * 2. A real PostgresEngine against a TCP endpoint that accepts and never
+ * answers, so the error postgres.js actually throws is the one matched.
+ * 3. runImport --workers and the incremental sync drain, with the worker
+ * pools' connect() scripted through a prototype spy (no database).
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { runImport } from '../src/commands/import.ts';
+import { connectWithRetry } from '../src/core/db.ts';
+import { performSync } from '../src/commands/sync.ts';
+import * as importFiles from '../src/core/import-file.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { withSourceFilesystemLock } from '../src/core/minions/source-filesystem.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type AddressInfo, type Server, type Socket } from 'node:net';
+import { dirname, join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const handshakeTimeout = (where = 'undefined:undefined') =>
+ Object.assign(new Error(`write CONNECT_TIMEOUT ${where}`), { code: 'CONNECT_TIMEOUT' });
+const pgFailure = (code: string, message: string) => Object.assign(new Error(message), { code });
+
+/** An engine whose connect() replays `script` (an Error throws, undefined succeeds), then succeeds. */
+function scriptedEngine(script: Array<Error | undefined>) {
+ const calls = { n: 0 };
+ const engine = {
+ async connect() {
+ const step = script[calls.n++];
+ if (step) throw step;
+ },
+ } as unknown as BrainEngine;
+ return { engine, calls };
+}
+
+const CFG = { database_url: 'postgresql://worker.example.invalid/brain', poolSize: 2 };
+const quiet = { baseDelayMs: 1, log: () => {} };
+
+describe('connectWithRetry: retryConnectTimeout decides whether CONNECT_TIMEOUT earns another attempt', () => {
+ const noRetryUnset = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_NO_RETRY_CONNECT: undefined }, fn);
+
+ test('opted in: a single handshake timeout is retried and the connect succeeds', () => noRetryUnset(async () => {
+ const warned: string[] = [];
+ const { engine, calls } = scriptedEngine([handshakeTimeout('db.example.invalid:5432')]);
+ await connectWithRetry(engine, CFG, { baseDelayMs: 1, log: line => warned.push(line), retryConnectTimeout: true });
+ expect(calls.n).toBe(2);
+ expect(warned).toHaveLength(1);
+ expect(warned[0]).toContain('CONNECT_TIMEOUT');
+ }));
+
+ test('opted in: a timeout that keeps happening stops after three attempts with the last error', () => noRetryUnset(async () => {
+ const last = handshakeTimeout();
+ const { engine, calls } = scriptedEngine([handshakeTimeout(), handshakeTimeout(), last, undefined]);
+ await expect(connectWithRetry(engine, CFG, { ...quiet, retryConnectTimeout: true })).rejects.toBe(last);
+ expect(calls.n).toBe(3);
+ }));
+
+ const singleAttempt: Array<[string, Error, Record<string, unknown>]> = [
+ ['no option: the general startup policy still fails fast on a timeout', handshakeTimeout(), {}],
+ ['explicit false', handshakeTimeout(), { retryConnectTimeout: false }],
+ ['a truthy non-boolean is not an opt-in', handshakeTimeout(), { retryConnectTimeout: 1 }],
+ ['opted in, but noRetry wins', handshakeTimeout(), { retryConnectTimeout: true, noRetry: true }],
+ ['opted in, a missing database is permanent', pgFailure('3D000', 'database "brain" does not exist'), { retryConnectTimeout: true }],
+ ['opted in, a statement timeout is not a handshake timeout', pgFailure('57014', 'canceling statement due to statement timeout'), { retryConnectTimeout: true }],
+ ['opted in, a lock timeout is not a handshake timeout', pgFailure('55P03', 'could not obtain lock on relation'), { retryConnectTimeout: true }],
+ ];
+ for (const [name, failure, extra] of singleAttempt) {
+ test(`one attempt only: ${name}`, () => noRetryUnset(async () => {
+ const { engine, calls } = scriptedEngine([failure]);
+ await expect(connectWithRetry(engine, CFG, { ...quiet, ...extra })).rejects.toBe(failure);
+ expect(calls.n).toBe(1);
+ }));
+ }
+
+ test('opted in: GBRAIN_NO_RETRY_CONNECT=1 still makes it one attempt', () => withEnv({ GBRAIN_NO_RETRY_CONNECT: '1' }, async () => {
+ const failure = handshakeTimeout();
+ const { engine, calls } = scriptedEngine([failure]);
+ await expect(connectWithRetry(engine, CFG, { ...quiet, retryConnectTimeout: true })).rejects.toBe(failure);
+ expect(calls.n).toBe(1);
+ }));
+
+ test('opted in: the existing retryable class (a dropped connection) is still retried', () => noRetryUnset(async () => {
+ const { engine, calls } = scriptedEngine([new Error('connection refused')]);
+ await connectWithRetry(engine, CFG, { ...quiet, retryConnectTimeout: true });
+ expect(calls.n).toBe(2);
+ }));
+});
+
+describe('a real pool against an endpoint that never answers the handshake', () => {
+ let server: Server;
+ let dialed = 0;
+ const held: Socket[] = [];
+
+ beforeAll(async () => {
+ server = createServer(socket => { dialed += 1; held.push(socket); });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ });
+ afterAll(async () => {
+ for (const socket of held) socket.destroy();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ });
+
+ const silentUrl = () => `postgres://[email protected]:${(server.address() as AddressInfo).port}/brain?connect_timeout=1`;
+ const attempt = (opts: Parameters<typeof connectWithRetry>[2]) => withEnv({ GBRAIN_NO_RETRY_CONNECT: undefined }, async () => {
+ dialed = 0;
+ const engine = new PostgresEngine();
+ try {
+ return await connectWithRetry(engine, { database_url: silentUrl(), poolSize: 1 }, { baseDelayMs: 20, log: () => {}, ...opts })
+ .then(() => undefined, (e: unknown) => e);
+ } finally {
+ await engine.disconnect().catch(() => {});
+ }
+ });
+
+ test('opted in: postgres.js\'s own timeout is recognised and the pool dials three times', async () => {
+ const error = await attempt({ retryConnectTimeout: true });
+ expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');
+ expect(dialed).toBe(3);
+ }, 20_000);
+
+ test('not opted in: the same timeout ends after one dial', async () => {
+ const error = await attempt({});
+ expect((error as { code?: string }).code).toBe('CONNECT_TIMEOUT');
+ expect(dialed).toBe(1);
+ }, 20_000);
+});
+
+describe('both worker-pool call sites retry a starved handshake', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-worker-pool-retry-'));
+ const repo = join(home, 'notes');
+ let brain: PGLiteEngine;
+ let script: Array<Error | undefined> = [];
+ let workerConnects = 0;
+
+ const inHome = <T>(fn: () => Promise<T>) => withEnv({
+ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_MAX_CONNECTIONS: undefined, GBRAIN_POOL_SIZE: undefined, GBRAIN_NO_RETRY_CONNECT: undefined,
+ }, fn);
+ const note = (name: string) =>
+ writeFileSync(join(repo, `${name}.md`), `---\ntype: note\ntitle: ${name}\n---\n\nWorker pool fixture ${name}.\n`);
+ const gitIn = (...args: string[]) => execFileSync('git', ['-C', repo, '-c', 'user.name=Example', '-c',
+ '[email protected]', '-c', 'core.hooksPath=/dev/null', ...args], { encoding: 'utf8' });
+ /** The PGLite engine, presenting itself as Postgres so the parallel worker-pool branch runs. */
+ const asPostgres = () => new Proxy(brain, {
+ get: (target, key) => {
+ const member = key === 'kind' ? 'postgres' : Reflect.get(target, key);
+ return typeof member === 'function' ? member.bind(target) : member;
+ },
+ }) as BrainEngine;
+ const workerSpies = () => [
+ spyOn(PostgresEngine.prototype, 'connect').mockImplementation(async () => {
+ const step = script[workerConnects++];
+ if (step) throw step;
+ }),
+ spyOn(PostgresEngine.prototype, 'disconnect').mockImplementation(async () => {}),
+ spyOn(importFiles, 'importFile').mockImplementation(async (_eng, _file, relPath) =>
+ ({ status: 'imported', slug: relPath.replace(/\.md$/, ''), chunks: 1 })),
+ spyOn(console, 'warn').mockImplementation(() => {}),
+ ];
+
+ beforeAll(async () => {
+ brain = new PGLiteEngine();
+ await brain.connect({});
+ await brain.initSchema();
+ const configFile = join(home, '.gbrain', 'config.json');
+ mkdirSync(dirname(configFile), { recursive: true });
+ writeFileSync(configFile, JSON.stringify({ engine: 'postgres', database_url: CFG.database_url }));
+ mkdirSync(repo, { recursive: true });
+ note('seed');
+ execFileSync('git', ['init', '--quiet', repo]);
+ gitIn('add', '-A');
+ gitIn('commit', '--quiet', '-m', 'seed');
+ await brain.executeRaw('UPDATE sources SET local_path = $1 WHERE id = $2', [repo, 'default']);
+ }, 60_000);
+
+ afterAll(async () => {
+ await brain.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ afterEach(() => { script = []; workerConnects = 0; });
+
+ const importWithTwoWorkers = () => inHome(() =>
+ withSourceFilesystemLock(brain, repo, () => runImport(asPostgres(), ['--no-embed', '--workers', '2', repo])));
+
+ test('import --workers: the first pool times out once, is redialled, and the import completes', async () => {
+ const spies = workerSpies();
+ script = [handshakeTimeout()];
+ try {
+ await importWithTwoWorkers();
+ expect(workerConnects).toBe(3);
+ expect(spies[2]).toHaveBeenCalled();
+ } finally {
+ for (const spy of spies) spy.mockRestore();
+ }
+ }, 30_000);
+
+ test('import --workers: a permanent worker connect error is not retried', async () => {
+ const spies = workerSpies();
+ const permanent = pgFailure('3D000', 'database "brain" does not exist');
+ script = [permanent];
+ try {
+ await expect(importWithTwoWorkers()).rejects.toBe(permanent);
+ expect(workerConnects).toBe(1);
+ } finally {
+ for (const spy of spies) spy.mockRestore();
+ }
+ }, 30_000);
+
+ test('incremental sync: a starved worker handshake is redialled and the source still syncs', () => inHome(async () => {
+ const syncOf = { repoPath: repo, sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+ const seeded = await performSync(brain, syncOf);
+ expect(seeded.status).toBe('first_sync');
+ note('one');
+ note('two');
+ gitIn('add', '-A');
+ gitIn('commit', '--quiet', '-m', 'two notes');
+
+ const spies = workerSpies();
+ script = [undefined, handshakeTimeout('db.example.invalid:5432')];
+ try {
+ const result = await withSourceFilesystemLock(brain, repo, () =>
+ performSync(asPostgres(), { ...syncOf, concurrency: 2, skipLock: true }));
+ expect(result.status).toBe('synced');
+ expect(result.added).toBe(2);
+ expect(workerConnects).toBe(3);
+ } finally {
+ for (const spy of spies) spy.mockRestore();
+ }
+ }), 60_000);
+});