Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): honest stalls, drain restart_required, superseded pass checkpoints (GBRA-133 PR 3a lane T)

garrytane11997e84ad1
diff --git a/docs/architecture/key-files/commit-notifier.md b/docs/architecture/key-files/commit-notifier.md
index 0a6bf8b886..2d991a323e 100644
--- a/docs/architecture/key-files/commit-notifier.md
+++ b/docs/architecture/key-files/commit-notifier.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/commit-notifier.ts` — the notifier core, pure over its seams (store, git reads, the runner). One loop per resident: claims the host lease every heartbeat (`GBRAIN_NOTIFIER_HEARTBEAT_MS`, default 10 s, lease two heartbeats; PGLite has no lease and the brain's holder owns), re-reads `sync.on_commit` and `sync.on_commit.sources` every 30 s (`parseOnCommit` is the one parser), lists the host's sources every 60 s, reads HEAD every poll (`GBRAIN_NOTIFIER_POLL_MS`, 3 s; a watch only nudges), and scans wanted markers every 15 s or on a nudge, with the flag off too. Starts on the leading edge of a quiet HEAD move (no rebase/merge/cherry-pick marker, no `index.lock`), then a 400 ms trailing window (`GBRAIN_NOTIFIER_QUIET_MS`). Per-source single flight under a host cap, least recently started first. Keeps a source due across refused starts, failed or blocked runs and resumable stops; retries at `RETRY_BACKOFF_MS` (5 s, 15 s, 1 min, 5 min) and reports `notifier_stalled` past the last tier without progress; `operator_blocked` waits for HEAD to move. Checks the fence before each start. Every decision is recorded (`decisions`) for tests; state and coverage rows are written on change only. Managed sources never take pull markers. Tests: `test/serve-head-watcher.test.ts` (memory store, `test/helpers/notifier-memory-store.ts`).
+- `src/core/commit-notifier.ts` — the notifier core, pure over its seams (store, git reads, the runner). One loop per resident: claims the host lease every heartbeat (`GBRAIN_NOTIFIER_HEARTBEAT_MS`, default 10 s, lease two heartbeats; PGLite has no lease and the brain's holder owns), re-reads `sync.on_commit` and `sync.on_commit.sources` every 30 s (`parseOnCommit` is the one parser), lists the host's sources every 60 s, reads HEAD every poll (`GBRAIN_NOTIFIER_POLL_MS`, 3 s; a watch only nudges), and scans wanted markers every 15 s or on a nudge, with the flag off too. Starts on the leading edge of a quiet HEAD move (no rebase/merge/cherry-pick marker, no `index.lock`), then a 400 ms trailing window (`GBRAIN_NOTIFIER_QUIET_MS`). Per-source single flight under a host cap, least recently started first. Keeps a source due across refused starts, failed or blocked runs and resumable stops; retries at `RETRY_BACKOFF_MS` (5 s, 15 s, 1 min, 5 min) and reports `notifier_stalled` past the last tier without progress (GBRA-133 PR 3a: a run whose status says `committed` is progress even before `last_commit` moves, and a drain-lease holder that `drainHeld` reports `stalled` is a failed attempt, `drain_holder_stalled`, instead of a silent defer; `test/honest-stalls-gbra133.test.ts`); `operator_blocked` waits for HEAD to move. Checks the fence before each start. Every decision is recorded (`decisions`) for tests; state and coverage rows are written on change only. Managed sources never take pull markers. Tests: `test/serve-head-watcher.test.ts` (memory store, `test/helpers/notifier-memory-store.ts`).
- `src/core/notifier/store.ts` — the durable rows (migration `v262-commit-notifier.ts`): `sync_wanted_markers` (source + intent freshness|pull|full, `generation` bumped on every upsert, `first_due_at` kept), `sync_notifier_leases` (one owner per host, fence bumped on takeover, release expires it now), `sync_notifier_sources` (state, retry schedule, last error and trace path, classic syncer host, coverage record). A drainer deletes only `WHERE generation =` the value it read (`clearMarker`, `settleMarkers`); freshness is due while `wanted_head IS DISTINCT FROM last_commit` (no ancestry assumption). `recordLocalSyncer` runs where `writeSyncAnchor` advances `last_commit`: records the syncer host and prunes satisfied markers (the CLI's re-check). `missingTable` lets callers on a pre-v262 brain read "nothing monitored".
- `src/core/notifier/resident.ts` + `src/core/notifier/detect.ts` — production seams and the one start path for every resident (`startResidentNotifier`: serve, serve --http through `src/core/serve-head-watcher.ts`, `gbrain jobs work`, the autopilot daemon). Never awaits: the first pass runs in the background. `GBRAIN_NOTIFIER=0` turns it off per process. Lists managed sources whose worktree this host owns and classic sources whose recorded syncer is this host (or `GBRAIN_NOTIFIER_CLASSIC_SOURCES`), skipping the rest with a reason. Starts syncs through the in-process delegated runner. Trace per source at `<gbrain home>/notifier/<source>.jsonl`. `detect.ts` resolves `--absolute-git-dir` / `--git-common-dir` (linked worktrees) and the quiet predicate. Tests: `test/pathological/s-notifier-classic-serve.test.ts`, `test/pathological/s-notifier-residents.test.ts`.
- `src/core/notifier/nudge.ts` + `src/core/notifier/handoff.ts` + `src/commands/sync/trigger.ts` — submitters and drainers of wanted markers. `recordTriggerMarker` picks the intent (managed: freshness at the checkout HEAD; classic: pull) and `recordSyncNudge` answers the versioned, acknowledged `sync_nudge` IPC kind (`src/core/context/sync-ipc.ts`, `resolve-ipc.ts`, bound in `src/mcp/resolve-ipc-binding.ts`). `handoff.ts` is the post-run re-check of the `sync` job handler and the serve's delegated runner: read before the run, settle after, at most one follow-up (a queued job with `maxWaiting: 1`, or a nudge); a lock-busy skip records a marker and completes. `gbrain sync trigger` answers queued / coalesced (`maxPending: 1`) / nudged, exit 0, with the `no_resident` notice when no resident watches the source; on PGLite a live serve takes it over IPC (`maybeTriggerThroughServe` in `src/commands/sync-delegate.ts`, which also records a busy delegated sync). The GitHub push webhook (`submitGitHubPush` in `src/commands/serve-http-webhooks.ts`) records the pushed sha first; a managed source answers 409 `refresh_required`. Tests: `test/pathological/s-notifier-marker-handoff.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 231da5febb..c3e54981ad 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -11,7 +11,7 @@
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. An unchanged per-tick refresh writes nothing: the registry directory and records are chmodded only when their mode differs and the directory is fsynced only when a record changed (`root-registry-idle-chmod-5297.test.ts`). The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints; an update that changes only embedding, telemetry or write-attribution columns of facts/takes is a physical projection and passes without the coordinator. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
-- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
+- **`src/core/persistence/sync-drain.ts`** — #5984: drains a managed sync in one invocation. `runDrain` re-enters the single-pass `performManagedSync` (which keeps returning `partial / writer_pending | writer_yield`) until the cursor is done, the caller's signal stops it, a strict registered run deadline is about 15 s away (`forward-progress.ts` `registerRunDeadline`, set by `cli.ts` when it arms the sync watchdog), a writer head needs intervention (`recovery_required`, `owner_unavailable`, unexpected bytes), or the no-progress detector sees the awaited request and its worktree head unchanged for 30 s and 3 passes with nothing claimable here. It retries only `worktree_refreshing` (its `retry_after_ms`), `database_contention`, connection errors and statement timeouts (3 attempts). Every page commit notes forward progress, so the progress-aware watchdog never stops a progressing drain. The result carries `drain: { outcome: synced | resumable | blocked, stop_reason, written, waived, remaining, rate_pages_per_min, eta_seconds, stall }`; `drainNext` builds `next` for the CLI from the shared `syncResumeCommand` (`sync-reconcile.ts`). The CLI (`sync/run.ts` single source, `--all`, `--watch`), serve's delegated runner and the `sync` job handler (#6706, bounded by `SyncOpts.deadlineAtMs`) set `SyncOpts.drain`; the PGLite owner delegate uses `runDrain` over IPC; the cycle, `sync-administration.ts` and `worktree-refresh.ts` keep their own loops. #6706: `runDrain` takes a caller `deadlineAtMs` (the earlier of it and the strict run deadline wins; a past deadline makes zero passes; a far one re-arms past the 2^31−1 ms timer limit), reports `resumable / deadline` when the deadline lands in a retry backoff, abandons a pass still running `DEADLINE_PASS_GRACE_MS` after it, and `deadlinePassed` stops the extra pass and the next stage; `jobDisposition` classifies a drained result for jobs (`synced`, `continue` when `drainNext` is safe to loop, `needs_operator`). `src/core/minions/handlers/sync-job-drain.ts` runs it in the `sync` job: `planJobDrain` (`drain`, `lanes: 1`, a deadline from `job.deadlineAtMs` or the row's wall-clock limit via `WALL_CLOCK_THRESHOLD_MS_SQL`, at most an hour, less 60 s; job-data controls only from trusted submitters; `sync.job_drain=false` turns it off), throttled progress, and `settleJobDrain` (the CLI's `outcome`/`drain`/`next`, `incomplete`, at most one continuation on a worker-backed brain, priority ≥ 5, whose `next` then observes it). A sync job that finds another live sync job on its source skips `sync_in_progress` (`sync-handler-drain-6706.test.ts`). `readManagedSyncBacklog` reads unfinished cursors' `progress` window (stamped by `sync-run.ts` on each advance, reset per drain) for `gbrain doctor` (`managed_sync_backlog`) and `sources status`, with `resume_args` built by `sync-reconcile.ts` `managedSyncResumeArgs`. #6278: the no-progress fingerprint keys on state, blocked reason, head id/state and the head claim's phase/step/since (`drainClaimOf`), never on lease columns, so a renewed-forever claim reads as no progress; a live preparation is allowed its budget plus `STALL_GRACE_MS` (budgets read from `persistence.*_preparation_ms` / `preparation_ceiling_ms`), a lapsed claim keeps the plain window (`stall.cause: owner_missing`), a preparation this process's pid owns past its allowance ends `resumable` / `preparation_abandoned`, and `SyncResult.breaker` ends `blocked` / `preparation_systemic`; `stall` carries `phase`, `step`, `waiting_on`, `cause`, and a timer prints `stalled <N>s on <step>` while nothing commits: between passes from the fingerprint's claim, inside a pass (a grouped publish parked in preparation never returns to the loop) from `StallProbe.head`, a 2 s-bounded read of the source's oldest running (else queued) request that prints nothing when no write is unfinished (B6). B7: a pass refused for write capacity (`isWriteCapacityWait`, `admission-retry.ts`: a `queue_capacity` whose `detail` is `outstanding=N limit=M`) is retried with backoff up to 5 s apart while the drain prints `waiting for write capacity (N outstanding of M)`; past the no-progress window it ends `blocked` / `write_capacity` with `drain.capacity` and writer status as `next`, keeping the last pass's result (or an empty one) for the report; a cumulative cap still throws. A pass that finishes one cursor and yields for a scheduled re-screen starts a new run on the next pass, and the report sums the page counts of every run it finished. GBRA-133 PR 3a: only page and checkpoint commits are committed progress (a legacy-sweep slice just keeps the governor's quiet clock fresh); an abandoned pass's late progress events are dropped; a stop whose head owner reports `restart_required` is cause `owner_restart_required` (`owner_row`, `drainNext` names the process). Tests: `test/sync-drain.test.ts`, `test/sync-drain-claims.test.ts`, `test/managed-sync-drain.test.ts`, `test/sync-drain-write-capacity.test.ts`.
- **`src/core/persistence/sync-window.ts`** — #5984 admit-ahead for draining managed Postgres syncs. While the cursor's `group` publishes, `admitAhead` (`sync-run.ts`) freezes and admits the next group and records it in the cursor's `window` (at most one group), so the consumer claims it as soon as the publishing group commits under the unchanged per-worktree FIFO claim. Window members name the previous group's last request in `intent.after`. #6712 (one page, one fate): a window group publishes whatever its predecessor became; nothing is cancelled for another page's failure, and dependency edges (`sync-group.ts` `dependencyKeys`, `freezeFollowers`' `taken`) keep two changes of one page out of the same group and out of the window while one is in flight. Publication validation (`sync-prepare.ts`) re-checks the predecessor once per transaction and reads the cursor `FOR KEY SHARE`, accepting `pending`, `group` and `window` members, so the drain's cursor saves never wait for the publishing group. After a failed page the members after it stay admitted at the head of the window, so every admitted request's identity stays in the cursor until its own receipt is read (`groupStep`, `promoteWindow`). Nothing is admitted ahead while foreground writes are recent (one was queued on the worktree in the last minute, `FOREGROUND_RECENT_MS`) or when the next entry is not groupable. Older binaries refuse a window member they did not admit (cursor membership), so a mixed-version drain fails closed instead of publishing twice; finish a drain before downgrading. A claimed head is ordered by `claimedPredecessorState`: a group member follows the member before it in its own group (its `after` names only the previous group), anything else follows `after`. `claimedHeadOrder` (the consumer, before claiming followers) only orders: under lanes a member whose predecessor member is unfinished releases its claim and waits; a predecessor that ended, committed or not, lets it publish (#6712). `WINDOW_CANCEL_MESSAGE` and `laneFaultCancelMessage` stay only so older receipts still read as legacy knock-ons. Test: `test/sync-group-member-order.test.ts`.
- **`src/core/persistence/sync-lanes.ts`** + **`worktree-lease.ts`** — #5984 lanes. The drain opens a lane policy for its worktree (`openLanes`, keyed by a per-drain run id that lane groups carry as `intent.lane`; `closeLaneRun` at drain end stops new lane claims and waits up to 90 s for the lane tasks still running, counted from the head's claim by `laneTask`). While it is open, this process's consumer claims the next admitted lane group head out of FIFO order (`claimNextLaneHead` in journal.ts: every earlier request claimed, any unfinished one a running request of the same run) up to the effective lane count (`laneRoots`), and runs it as a lane (`executeClaimedGroup` with `lane`). Lane publications share the worktree's native lock in this process (`acquireWorktreeShared` / `worktree-lease.ts`; one lane acquires the lock while lanes arriving meanwhile wait and join, and a lease stays registered until its lock is released); every exclusive `acquireWorktree` first yields the lease (marks it draining and wounded, waits up to its budget), and a lease drains for new claims after `LEASE_TURN_MS` of continuous holding. Lane transactions begin in manifest order (`awaitLaneBegin`) and commit in manifest order (`awaitLaneTurn`, inside the transaction before the counters: the predecessor `intent.after` must have ended, committed or not (#6712); a requeued or unadmitted one releases it, a wounded lease or 60 s rolls it back). Publication validation accepts a lane group whose predecessor is still queued or running (`windowPredecessorAllows`). `laneFallback` in group-publish.ts releases or falls back to the single path (#6712: never cancels), and a lock or statement timeout steps the lane count down (`stepDownLanes`). Lane settings (`--lanes`/`--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, clamped to the pool's long-hold capacity minus 3) resolve in `resolveBulkSettings` (sync-group.ts); with lanes the drain keeps twice the lane count of groups admitted ahead (`admitAhead`).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. A completed discovery that finds nothing to do (`up_to_date`) stamps only `sources.last_sync_at`, inside `withCoordinatedWrite` and guarded by source id and incarnation, so a quiet managed source stays fresh in doctor and a run that outlived a re-added source stamps nothing; dry runs and partial runs do not stamp. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. #6712 PR 1: a resume inherits the cursor's processing opt-outs OR-wise (`adoptCursor`, one CAS that also stamps the resumer's validated authority) and reports a flag it overrode in `inherited_options`; nothing refuses over processing options, and `explicitProcessing` is gone. Admitted requests keep their own intent principal: they are read under it (`admittedBy`), and a writer change drops only unadmitted frozen entries. Every managed pass runs under the source's drain lease (`withDrainLease`, `src/core/persistence/sync-lease.ts`), whose token fences admission, the settled/held CAS, fan-in and the cursor CAS (`assertDrainLease`). Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts, also when the run has a recorded failure and its pending write already committed before the cursor advanced; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. Content holds (#5988, `sync-screen.ts`): `freezeEntry` screens each import (company-profile cursors and `sync.holds=fail` excepted); a refused file becomes a hold written in the same transaction as the cursor step (`saveCursor`'s `inTx`), with no request admitted, and an over-bound pinned blob is held by size before it is read. A cursor whose pending request failed with a content refusal (`isContentRefusal`, old message shapes included) converts in place with its stored options: held, or re-frozen once per distinct bytes (`converted`), so a refusal the screen misses stays blocked without minting receipts. #6188: a failed fence refusal (`fenceReceiptLocation`: the durable `error_detail.fence`, the message, or an older release's message) holds the same bytes even when the screen admits them (`prepareTimeFenceHold`, reason `prepare_time`); a compacted `invalid_params` / `take_row_collision` receipt converts only when the re-screen holds. A page request of the run that fails with a fence refusal is held in the same invocation at the terminal-failure branch (single path and a bulk group's failed member) after the source's other requests settle within the run's wait budget, else the run returns `partial`; it is converted once, gets no failure-ledger row and is logged as a conversion. `sync.holds=fail` and company-profile cursors keep blocking with the typed refusal. #6278: a `preparation_stalled` receipt (the owner gave up preparing a member) is converted the same way by both converters: an import holds by its bytes, a delete as a delete hold (`meta.deleted`, `upstream_version` null), the checkpoint never holds; `preparationStalledHold` (sync-screen.ts) records the receipt's step and the resume arguments. Both converters write their hold through `holdUnderGate`, the narrowed gate: the failed entry's admitted suffix (window, later group members, this run's queued lane rows) is cancelled first, then the hold waits only for active suffix descendants and unfinished requests naming the entry's page (`UNFINISHED_PAGE_REQUEST_SQL`, now matching path and origin too), evaluated inside the transaction that writes the hold under the page-key → cursor lock order; its doc comment states the invariant the old source-wide wait protected. The cursor's `breaker` counts the run's stalled receipts (identities and streak, saved with each CAS): `holdsEscalated`'s rule over the run's screened imports or `BREAKER_STREAK` (5) in a row trips it, the run stops `blocked_by_failures` with `SyncResult.breaker` (drain `preparation_systemic`), and the next run's `convertBlockedCursor` re-freezes the entry and schedules the run's stalled holds for a re-screen instead of holding; a committed page resets the streak. `sameContentAtOrigin` and the waiver screens race the sync preparer against `persistence.sync_preparation_ms` (`raceSyncBudget`, sync-waivers.ts) and fail open. Tests: `test/managed-sync-preparation-stalled-holds.test.ts`, `test/sync-waiver-budget.test.ts`. Results carry this run's holds, the outstanding total, escalation, `converted_from_failed` and `recovered_frontmatter` (`buildHoldReport`); dry runs list `would_hold` / `screen_skipped`. After the checkpoint commits the pass stamps drain step `finish` and emits `managed_sync.finish`; then (unless `noExtract`) the owner derives links for the source's stale pages through `links-maintenance.ts` under `FINISH_BUDGET_MS` (pages left over stay stale for `gbrain extract --stale`), so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync. #6278 (B7): when the checkpoint commits while `sources retry-held` re-screens are scheduled for the source (scheduled against a backlog, or while this cursor ran), the pass returns `partial` / `writer_yield` instead of `synced`, so the drain's next pass retires the finished cursor and discovers again, taking them; a `queue_capacity` refused for outstanding requests (`isWriteCapacityWait`) is left out of the failure ledger because the drain waits it out. #6696: the cursor key comes from `selectManagedCursor` (`sync-cursor-key.ts`), which every managed caller crosses: a run without `--strategy` and without a company plan keys a fresh cursor with the source's configured strategy, while an unfinished cursor under the raw key keeps resuming under it, so its admitted requests keep matching. `SyncOpts.embedDeferred` (the cost gate's auto-defer) is frozen on the intent and treated as `noEmbed` by preparation, never as a processing option a resume adopts or compares (`test/persistence-sync-cursor-strategy-6696.test.ts`).
@@ -23,7 +23,7 @@
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. `partialFenceRuns` finds the fence runs a forced segment cut splits. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
-- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6712 PR 1: the wire still validates an older CLI's `explicitProcessing` list by shape, then ignores it (`WIRE_SKEW_WINDOWS.explicitProcessing` in `src/core/wire-skew.ts`, floor 0.60.255.0, accepted until 2026-11-14); the cursor's opt-outs are inherited (`test/sync-owner-lane-processing-6696.test.ts`). #6712 PR 2: the owner lane's flag tables are views of `SYNC_FLAGS` (`src/core/sync-flags.ts`); `--lanes N`/`--no-lanes` are accepted and not sent, and a dropped retired field prints `retiredWireNotice`.
+- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. GBRA-133 PR 3a: only an advanced cursor or a pass that committed pages is progress; a run that committed nothing stops as `sync_deadline_stalled` (exit 1). Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6712 PR 1: the wire still validates an older CLI's `explicitProcessing` list by shape, then ignores it (`WIRE_SKEW_WINDOWS.explicitProcessing` in `src/core/wire-skew.ts`, floor 0.60.255.0, accepted until 2026-11-14); the cursor's opt-outs are inherited (`test/sync-owner-lane-processing-6696.test.ts`). #6712 PR 2: the owner lane's flag tables are views of `SYNC_FLAGS` (`src/core/sync-flags.ts`); `--lanes N`/`--no-lanes` are accepted and not sent, and a dropped retired field prints `retiredWireNotice`.
- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`. #6946: `fence-write.ts` returns `legacyFallback: true, databaseOnlyReason: 'url_clone'` for a gbrain-owned `--url` clone on an unmanaged brain, and the backstop does not warn `facts:fence-write-unexpected-fallback` for it.
- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain is never fenced (`skipped_url_clone`); its rows stay database-only.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index fe96221aba..9d56daef13 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -28,9 +28,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.
-- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`.
+- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. GBRA-133 PR 3a: `progressSignal: 'committed'` forwards only `noteCommittedProgress()` notes, and a run that reaches its deadline having committed nothing stops at once (the `progressed` argument of `progressDeadlineDecision` is false) and writes `stallNotice` instead of `stopNotice`; the sync watchdog uses it, so screening and legacy-sweep slices never extend the deadline. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`. The stall notice of a run that committed nothing (`syncDeadlineStallNotice`: `code=sync_deadline_stalled`, why, a read-only `gbrain sync status` fix) is pinned by `test/honest-stalls-gbra133.test.ts`.
-- `src/core/forward-progress.ts` — process-wide forward-progress signal, zero imports. `noteForwardProgress()` records that a unit of work completed (called by every `progress.ts` tick); `onForwardProgress(listener)` subscribes and returns the unsubscribe; `lastForwardProgressAt()` reads the last note. Consumers are deadlines that must never stop a run that is still progressing: the sync watchdog (`process-watchdog.ts`, `progressWindowMs`) and the `gbrain serve` boot deadline. Heartbeats are not progress.
+- `src/core/forward-progress.ts` — process-wide forward-progress signal, zero imports. `noteForwardProgress()` records that a unit of work completed (called by every `progress.ts` tick); `onForwardProgress(listener)` subscribes and returns the unsubscribe; `lastForwardProgressAt()` reads the last note. Consumers are deadlines that must never stop a run that is still progressing: the sync watchdog (`process-watchdog.ts`, `progressWindowMs`) and the `gbrain serve` boot deadline. Heartbeats are not progress. GBRA-133 PR 3a: `noteCommittedProgress()` records committed work (a page written, deleted or renamed, a cursor advanced; the sync import, delete and rename loops, the drain's page commits and checkpoint, and a followed drain holder whose committed count rose) and is also a forward note; `onCommittedProgress` / `lastCommittedProgressAt` read it. The sync watchdog listens to committed notes only.
- `src/core/spawn.ts` — the one module in `src/` that launches subprocesses with `windowsHide` defaulted (#4992, contributed by @rokas-tarasevicius in PR #6105). A `detached: true` child on Windows has no console, so every console program it launches without `windowsHide` opens a visible console window that takes focus; the Stop-hook push, the backup check, the job supervisor, its worker and every job child run that way. Wraps `spawn`, `spawnSync`, `exec`, `execSync`, `execFile`, `execFileSync` (Node's overloads and `util.promisify.custom` kept) plus `bunSpawn` / `bunSpawnSync`, each defaulting `windowsHide: true` and keeping an explicit `false` (only `openBrowser` in `creds/redirect.ts`). Calls go through `child_process` and `Bun` at call time, so `spyOn` in tests still intercepts them. Trade-off: with every stdio stream piped or ignored, libuv turns the flag into CREATE_NO_WINDOW and the child gets a windowless console of its own, so a program that prompts on the console directly prompts invisibly; gbrain's networked git calls set `GIT_TERMINAL_PROMPT=0` (git-remote.ts also `SSH_ASKPASS_REQUIRE=never`), and inherited-stdio launches still attach to the terminal. `scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`) is a RATCHET: a new runtime `child_process` import or `Bun.spawn*` in `src/` fails unless the file is in its `NOT_YET_MIGRATED` list (the minions supervisor/worker/child/readiness/isolation/registry/shell handler, `workspace-push.ts`, `cli/main.ts`, `context/hook-heartbeat.ts`, the backup check, `cli-force-exit.ts`, `cli-preflight.ts`, `autopilot-lock.ts`, the autopilot commands and `bounded-child-exec.ts` are migrated; the rest, wave-13-claimed files included, are listed and lose the entry when they move), and a listed file that stops launching directly fails as stale. Pinned by `test/spawn-windows-hide.test.ts` (argument shapes; the detached supervisor, worker and push-git sites), `test/scripts/windows-hide-guard.test.ts` (forms, allowlist, ratchet, stale entries, the repository) and, natively on the test.yml `security-regressions` Windows row, `test/windows-hidden-console.test.ts` (a compiled console probe launched from a console-less detached process: the unhidden CONTROL launch must show a window or the run fails as `windows_console_gate_unsupported`; then the worker, the push's git and every seam launcher show none).
- `src/core/embed-stale-progress.ts` — `StaleChunkProgress` (#5968, wave 15 P2.6 [R28]): the exact tally behind `embed --stale` progress. Unit: stale chunks. `total` starts at the census and only grows: `listed(rows)` raises it to the rows actually listed (a writer adding stale rows behind the keyset cursor), `reentered(remaining)` to what a paced re-entry will relist, and `pageDone(census, handled)` by the heal delta when one oversized stored chunk became several, in the same step that adds the page's rows to `done` (failed, filtered and quarantined rows included), so `done <= total` at every callback and a finished run reads 100%. Pinned by `test/embed-stale-progress-5968.serial.test.ts`.
- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. `setTotal(total)` (optional on the interface; #5968) replaces a running phase's total once the exact amount of work is known, so a caller whose work grows mid-phase (a heal split, a re-entry) never reports past 100%. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Every `tick` calls `noteForwardProgress()`, so bulk work feeds the progress-aware deadlines; its only import is that zero-import leaf. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape. JSON `tick` events carry `cpu_ms`, the main thread's CPU time since the phase started (`process.threadCpuUsage()`); the scale tier's PGLite import-rate gate (`scripts/scale/gates.ts`) judges on it.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index aa08e90a46..3eb9b84733 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1091,6 +1091,16 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu
More: [docs/guides/troubleshooting.md#doctor-ops-tier](../../docs/guides/troubleshooting.md#doctor-ops-tier)
+### drain_holder_stalled
+
+<a id="drain_holder_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The commit notifier did not wait on a source's drain lease because the process holding it has made no commit or cursor save for 5 minutes; it counts as a failed attempt. | Waiting on a holder that commits nothing kept the source due forever with nothing reported. Counting it as a failed attempt runs the notifier's retry tiers (5 s, 15 s, 1 min, 5 min), so the source reaches notifier_stalled with the sync-now fix in sync status and doctor; a foreground sync follows the holder and takes the source over when its lease lapses. | Read gbrain sync status --source <id> --json (the notifier block and drain_holder name the holder), stop that process if it is wedged, then run gbrain sync --source <id> --no-pull. | agent | `repeat the read that failed` | 1 | yes |
+
+More: [docs/guides/on-commit-sync.md#notifier-stalled](../../docs/guides/on-commit-sync.md#notifier-stalled)
+
### drain_stalled
<a id="drain_stalled"></a>
@@ -1099,7 +1109,7 @@ More: [docs/guides/troubleshooting.md#doctor-ops-tier](../../docs/guides/trouble
|---|---|---|---|---|---|---|
| A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window. | A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which. | Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |
-Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`.
+Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`, `owner_restart_required`.
More: [docs/guides/write-refusals.md#drain-stalled](../../docs/guides/write-refusals.md#drain-stalled)
@@ -3905,6 +3915,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish. | The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict. | Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source. | agent | `repeat the read that failed` | 1 | no |
+### sync_deadline_stalled
+
+<a id="sync_deadline_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A gbrain sync reached its progress-aware deadline having committed nothing (no page written, deleted or renamed, no cursor advanced), so it stopped as a stall instead of extending. | The deadline extends only while a run commits work. Screening unchanged files, held files and legacy-sweep slices are not progress, so a run that spends its whole deadline on them reports a stall with its cause instead of "still progressing" or a clean resumable stop; rerunning the same way commits nothing again. | Run gbrain sync status --source <id> --json (read-only): it names the step, holds and last error the source is stuck on. Fix what it names, then rerun the same sync. Run: gbrain sync status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |
+
### sync_drain_lease_held
<a id="sync_drain_lease_held"></a>
@@ -3967,6 +3985,14 @@ Reasons: `content_directory`.
|---|---|---|---|---|---|---|
| Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug. | The upgrade invariant says a newer reader never refuses bytes an older one imported; with `GBRAIN_SYNC_PARSER_REGRESSION=stop` set for the process that syncs (the default holds the file), the run stops without advancing rather than hide a regression. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull. | host_admin | `gbrain doctor --json` | 1 | no |
+### sync_pass_superseded
+
+<a id="sync_pass_superseded"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A sync pass's checkpoint did not publish because the pass that admitted it no longer holds the source (it ended, or another pass started); the next pass stamps its own checkpoint. | A pass's checkpoint is bound to its drain lease and pass row, so it can never publish after that pass ends. Its receipt is a conflict that records no managed-sync failure and reads superseded in gbrain sources writer failures; a pass that stops with the checkpoint still pending reports disposition superseded instead of a request to resume. | Nothing to repair or resubmit: the pages the pass committed stand. Let the next sync pass run (gbrain sync --source <id> --no-pull), and read gbrain sync status --source <id> --json to confirm the source converges. | agent | `repeat the read that failed` | 1 | no |
+
### tail_changed
<a id="tail_changed"></a>
diff --git a/docs/guides/on-commit-sync.md b/docs/guides/on-commit-sync.md
index 6bd51b57e6..b01cc51066 100644
--- a/docs/guides/on-commit-sync.md
+++ b/docs/guides/on-commit-sync.md
@@ -172,6 +172,13 @@ sync status names the last error and the trace file
gbrain sync --source <id> --no-pull to see the error in the foreground, fix it,
and the notifier resumes on its next retry.
+A run that committed pages counts as progress even before the source's last
+synced commit moves. When the last error is drain_holder_stalled, another
+process holds the source's drain lease and has made no commit or cursor save
+for five minutes; the notifier does not wait on it silently. sync status names
+the holder: stop it if it is wedged, then run the foreground sync, which follows
+the holder and takes the source over when its lease lapses.
+
<a id="refresh-required"></a>
## refresh_required
diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.ts
index 8f02e134f6..c3571238ed 100644
--- a/src/commands/sync-persistence-delegate.ts
+++ b/src/commands/sync-persistence-delegate.ts
@@ -19,8 +19,8 @@ import { buildSingleSyncJsonEnvelope } from '../core/sync-embed-backfill.ts';
import { printManagedSyncDiagnostic } from './sync-diagnostics.ts';
import { parseDurationSeconds } from '../core/sync-concurrency.ts';
import { runDrain, drainJsonFields, formatDrainSummary, syncOutcome } from '../core/persistence/sync-drain.ts';
-import { resolveStallAbortSeconds, resolveSyncHardDeadline, syncResumeCommand } from '../core/sync-reconcile.ts';
-import { noteForwardProgress } from '../core/forward-progress.ts';
+import { resolveStallAbortSeconds, resolveSyncHardDeadline, syncDeadlineStallNotice, syncResumeCommand } from '../core/sync-reconcile.ts';
+import { noteCommittedProgress } from '../core/forward-progress.ts';
const invalid=(message:string,suggestion:string)=>opError('invalid_params',message,suggestion,
{fix:readFix('Prints the gbrain sync flags.',{argv:['gbrain','sync','--help']})});
@@ -66,9 +66,11 @@ export function delegatedProgressWindowMs(args:string[],env:Record<string,string
/**
* The client-side stop for a delegated sync. Past `timeoutMs` a progress-aware
- * deadline extends to one progress window after the last slice that made
- * progress (a company cursor that advanced, or a pass that settled paths), and
- * stops only after a full window without progress.
+ * deadline extends to one progress window after the last slice that committed
+ * work (a cursor that advanced, or a pass that wrote, deleted or renamed pages),
+ * and stops only after a full window without it. GBRA-133 PR 3a: a run that
+ * committed nothing never extends; its stop is a stall (`stalled`), and a pass
+ * that only settled paths (screened them unchanged) is not progress.
*/
export class DelegatedSyncDeadline {
readonly stop=new AbortController();
@@ -77,6 +79,9 @@ export class DelegatedSyncDeadline {
private lastIndex=-1;
private timer:ReturnType<typeof setTimeout>|undefined;
private extended=false;
+ private progressed=false;
+ /** True when the deadline stopped a run that committed nothing (`sync_deadline_stalled`). */
+ stalled=false;
constructor(timeoutMs:number,private readonly progressWindowMs:number|undefined,private readonly log:(line:string)=>void=line=>console.error(line)) {
this.lastProgressAt=performance.now();
this.at=timeoutMs>0?this.lastProgressAt+timeoutMs:Infinity;
@@ -93,13 +98,14 @@ export class DelegatedSyncDeadline {
const remainingMs=Math.max(this.at-performance.now(),this.progressWindowMs??0);
return Math.max(1,Math.ceil(remainingMs/1000));
}
- /** Call with each slice's result; an advanced cursor index, or a pass that settled paths, is progress. */
- noteSlice(slice:Pick<SyncResult,'managedCursor'|'pass'>):void {
+ /** Call with each slice's result; an advanced cursor index, or a pass that committed pages, is progress. */
+ noteSlice(slice:Pick<SyncResult,'managedCursor'|'pass'|'added'|'modified'|'deleted'|'renamed'>):void {
const index=slice.managedCursor?.index;
if(index!==undefined&&index>this.lastIndex)this.lastIndex=index;
- else if(!slice.pass?.settled)return;
+ else if(!slice.pass||slice.added+slice.modified+slice.deleted+(slice.renamed??0)===0)return;
+ this.progressed=true;
this.lastProgressAt=performance.now();
- noteForwardProgress();
+ noteCommittedProgress();
}
dispose():void { if(this.timer)clearTimeout(this.timer); }
private arm():void {
@@ -109,12 +115,13 @@ export class DelegatedSyncDeadline {
}
private check():void {
const now=performance.now();
- if(this.progressWindowMs&&now-this.lastProgressAt<this.progressWindowMs) {
+ if(this.progressWindowMs&&this.progressed&&now-this.lastProgressAt<this.progressWindowMs) {
this.at=this.lastProgressAt+this.progressWindowMs;
- if(!this.extended){this.extended=true;this.log(`[sync] past the delegated deadline and still progressing; extends while the owner keeps committing pages (stops after ${Math.round(this.progressWindowMs/1000)}s without progress).`);}
+ if(!this.extended){this.extended=true;this.log(`[sync] past the delegated deadline and still committing; extends while the owner keeps committing pages (stops after ${Math.round(this.progressWindowMs/1000)}s without a commit).`);}
this.arm();
return;
}
+ if(this.progressWindowMs&&!this.progressed){this.stalled=true;this.log('[sync] code=sync_deadline_stalled: the delegated deadline passed and the owner committed nothing (no page written and no cursor advanced); stopping as a stall.');}
this.stop.abort();
}
}
@@ -144,15 +151,19 @@ export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|nul
} finally { deadline.dispose(); }
const sourceId=result.source_id??params.options.sourceId??'default';
const resume=syncResumeCommand(args,getCliOptions().brain);
+ // GBRA-133 PR 3a: a deadline that stopped a run which committed nothing is a stall (code, why, fix), never a clean resumable stop.
+ const stall=deadline.stalled?syncDeadlineStallNotice(args,{deadlineMs:params.timeoutSeconds*1000,graceMs:0,reason:'delegated deadline'}):null;
+ if(stall)setCliExitVerdict(1);
if(args.includes('--json')) {
await writeStdoutFinal(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId,result),
- ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result,resume,sourceId) })+'\n');
+ ...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result,resume,sourceId), ...(stall ? { deadline_stall: JSON.parse(stall) } : {}) })+'\n');
printManagedSyncDiagnostic(result, process.stderr);
for(const line of formatDrainSummary(result,resume,sourceId))process.stderr.write(line+'\n');
}
else {
(await import('./sync.ts')).printSyncResult(result);
for(const line of formatDrainSummary(result,resume,sourceId))process.stdout.write(line+'\n');
+ if(stall)process.stdout.write(stall+'\n');
if(!params.options.dryRun&&!params.options.noEmbed&&result.added+result.modified>0) {
console.error('[sync] embeds deferred — the owner drains them using its configured provider and keys.');
}
diff --git a/src/commands/sync/deletes.ts b/src/commands/sync/deletes.ts
index bfb9deff8e..a009a0ae91 100644
--- a/src/commands/sync/deletes.ts
+++ b/src/commands/sync/deletes.ts
@@ -17,6 +17,7 @@ import { unsyncableReason, isPoisonedPath, DEFAULT_SOURCE_ID } from '../../core/
import type { SyncResult } from '../sync.ts';
import { partial, markCompleted, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';
+import { noteCommittedProgress } from '../../core/forward-progress.ts';
export async function sweepUnsyncableModified(
engine: BrainEngine,
@@ -189,6 +190,7 @@ export async function runDeletesPhase(
// lookups.
pagesAffected.push(...deleted);
for (const s of deleted) deletedSlugs.add(s);
+ if (deleted.length) noteCommittedProgress();
// v0.42.x (#1794): the whole batch is handled (soft-deleted,
// already gone, or refused above); checkpoint every path so a
// resume skips it.
@@ -203,6 +205,7 @@ export async function runDeletesPhase(
for (let j = 0; j < slugs.length; j++) {
try {
await softDeleteSyncPages(engine, [slugs[j]], deleteScopedOpts);
+ noteCommittedProgress();
pagesAffected.push(slugs[j]);
deletedSlugs.add(slugs[j]);
await markCompleted(run, deletable[j]);
@@ -240,6 +243,7 @@ export async function runDeletesPhase(
// optional-opts deletePage call applied on this legacy lane
// (opts.sourceId is undefined here by construction).
await softDeleteSyncPages(engine, [slug], { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID });
+ noteCommittedProgress();
pagesAffected.push(slug);
deletedSlugs.add(slug);
await markCompleted(run, path);
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index 602278afbb..4bd7b91a65 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -34,6 +34,7 @@ import { clearLegacyHold, holdClassicFile, holdRefusedImport, noteScreenedImport
import { classifyClassicFile } from '../../core/classic-file-holds.ts';
import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';
+import { noteCommittedProgress } from '../../core/forward-progress.ts';
type ImportPlan = Pick<SyncPlan, 'opts' | 'filtered' | 'lastCommit' | 'pin' | 'company' | 'gitContextRoot' | 'syncImportRoot' | 'syncActivePack' | 'holds'>;
@@ -371,6 +372,7 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
// much actually landed before --timeout fired.
run.filesImported++;
run.itemRun.succeed();
+ noteCommittedProgress();
await clearLegacyHold(eng, holds, path);
// v0.42.x (#1794): checkpoint this path so a kill banks it.
await markCompleted(run, path);
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index ea7e06922b..8ea49c4e7b 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -35,6 +35,7 @@ import { clearLegacyHold, holdRefusedImport, holdRenameDestination, noteScreened
import { classifyItemFailure } from '../../core/item-failure.ts';
import { partial, noteTypeWarning, markCompleted } from './sync-run.ts';
import type { SyncPlan, SyncRun, SyncProgress } from './sync-run.ts';
+import { noteCommittedProgress } from '../../core/forward-progress.ts';
import { recordFallbackRename } from '../../core/belief/identity.ts';
import { markBeliefCommits } from '../../core/belief/append.ts';
@@ -353,7 +354,7 @@ async function applyRename(
// banking `to` would make the resume filter skip this rename on the
// retry run — a permanent duplicate (reconcile) or a permanently
// unimported target (import error) — the exact bug class being fixed.
- if (!reconcileFailed && !importErrored) await markCompleted(run, to);
+ if (!reconcileFailed && !importErrored) { await markCompleted(run, to); noteCommittedProgress(); }
progress.tick(1, newSlug);
return undefined;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index c860518a7a..827f161554 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1062,6 +1062,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.344.0', text: 'On a transaction-mode pooler URL (PgBouncer or Supabase port 6543, `prepare=false`, or `GBRAIN_PREPARE=false`), gbrain now pipelines the statements of one transaction on the server connection the pooler pins for it, instead of waiting one round trip per statement, so a sync or write over a slow link finishes in fewer round trips. It still never sends a statement behind one that may end the transaction (COMMIT, ROLLBACK, END, ABORT, PREPARE TRANSACTION), never pipelines autocommit statements on such a URL, and keeps prepared statements off, so the pooler cannot hand a statement to another client\'s connection. Set `GBRAIN_PG_TXN_PIPELINE=0` to send one statement per round trip again.' },
{ since: '0.60.344.0', text: 'Doctor `managed_sync_latency` now grades the commit that is still waiting, not only commits that already synced: with `sync.on_commit` on or `sync.freshness_target_seconds` set, a source whose checkout HEAD has waited past the target (default 300 s) warns and past one hour fails, dated from the reflog entry that moved HEAD or the notifier\'s recorded first_due_at, and a waiting commit it cannot date (no reflog, rewritten history) warns as unknown. It grades classic sources the same way and reports keyword-visible and embedded freshness per source (`details.freshness_by_source`). `gbrain sources status` compares HEAD only (an uncommitted edit is no longer lag) and dates a behind source\'s lag from when the commit landed instead of from the last no-op sync.' },
{ since: '0.60.344.0', text: '`gbrain sources mirror-readonly <id> --dry-run` and `gbrain sources mirror-writable <id> --dry-run` now print the change they would make with a `(dry-run; no side effects)` banner and write nothing (#7086); before, both ignored `--dry-run` and set or cleared the read-only mirror flag.' },
+ { since: 'TBD', text: 'The `gbrain sync` hard deadline now extends only while the run commits work (a page written, deleted or renamed, or a sync cursor advanced). Screening unchanged files, held files and legacy-sweep slices no longer count, so a run that reaches its default or env deadline having committed nothing stops as a stall: it prints `code=sync_deadline_stalled` with a why and a read-only `gbrain sync status` fix (one JSON object under `--json`) instead of extending as "still progressing". A run delegated to a PGLite owner does the same, adds `deadline_stall` to its JSON and exits 1.' },
+ { since: 'TBD', text: 'A managed sync drain stopped by its governor drops the abandoned pass\'s late progress events (no late `[sync] N processed` line, no count added after the stop), and a stop whose head owner reports restart_required now says so: `drain.stall.cause` is `owner_restart_required` with the owner\'s heartbeat row, and `next` tells the host admin to restart that process, then rerun (it used to read `publication_overdue` or `no_progress`).' },
+ { since: 'TBD', text: 'The commit notifier counts a resumable sync that committed pages as progress even while `last_commit` has not moved yet (a long managed catch-up no longer reads `notifier_stalled`), and a source whose drain-lease holder has committed nothing for 5 minutes is no longer deferred silently: it counts as a failed attempt (`drain_holder_stalled`), so the retry tiers run and sync status and doctor show the sync-now fix.' },
+ { since: 'TBD', text: 'A sync pass\'s checkpoint that its pass can no longer publish (the pass ended, or another pass started) is now refused `sync_pass_superseded` instead of `revision_conflict`: it records no managed-sync failure, reads `superseded` in `gbrain sources writer failures` and does not count as an unresolved terminal failure, and a pass that stops with its checkpoint still pending reports `managedWrite.disposition: superseded` instead of "Re-run the same sync options to resume this request".' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/commit-notifier.ts b/src/core/commit-notifier.ts
index e30627b26d..82b05bfadd 100644
--- a/src/core/commit-notifier.ts
+++ b/src/core/commit-notifier.ts
@@ -59,7 +59,8 @@ export interface NotifierSource {
}
export interface SkippedSource { sourceId: string; reason: string }
export type StartResult = { jobId: string } | { busy: true } | { refused: string };
-export interface JobStatus { state: 'running' | 'aborting' | 'done' | 'error'; outcome?: 'synced' | 'resumable' | 'blocked'; reason?: string; error?: string }
+/** `committed`: the run wrote pages or advanced its cursor (GBRA-133 PR 3a), which is progress even while `last_commit` stays put. */
+export interface JobStatus { state: 'running' | 'aborting' | 'done' | 'error'; outcome?: 'synced' | 'resumable' | 'blocked'; reason?: string; error?: string; committed?: boolean }
export interface StartRequest { intent: MarkerIntent; sliceSeconds: number | null; first: boolean }
/** A recorded scheduling decision (tests and the notifier block read these instead of wall-clock timing). */
@@ -109,7 +110,8 @@ export interface CommitNotifierOptions {
revParse: (root: string) => Promise<string>;
quiet?: (source: NotifierSource) => boolean;
syncRunning?: () => boolean | Promise<boolean>;
- drainHeld?: (sourceId: string) => Promise<boolean>;
+ /** Whether another process holds the source's drain lease; `stalled` when that holder made no commit or cursor save for the stall window. */
+ drainHeld?: (sourceId: string) => Promise<boolean | 'stalled'>;
startSync: (sourceId: string, req: StartRequest) => Promise<StartResult>;
jobStatus: (jobId: string) => JobStatus | null;
watch?: (source: NotifierSource, onChange: () => void) => (() => void) | null;
@@ -210,6 +212,8 @@ function notifierKit(opts: CommitNotifierOptions) {
logged.add(key);
log(line);
};
+ /** A source that made progress logs its next stall again. */
+ const forgetLog = (key: string) => { logged.delete(key); };
const guard = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {
try { return await fn(); } catch (error) {
const message = error instanceof Error ? error.message : String(error);
@@ -222,7 +226,7 @@ function notifierKit(opts: CommitNotifierOptions) {
decisions.push({ at: now(), source, decision, ...extra });
if (decisions.length > DECISIONS_CAP) decisions.splice(0, decisions.length - DECISIONS_CAP);
};
- return { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, guard, decisions, decide };
+ return { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, forgetLog, guard, decisions, decide };
}
const closeWatch = (rt: Rt) => { if (rt.watchClose) { try { rt.watchClose(); } catch { /* best effort */ } rt.watchClose = null; } };
@@ -298,7 +302,7 @@ async function readOwedMarkers(opts: CommitNotifierOptions, guard: ReturnType<ty
}
export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier {
- const { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, guard, decisions, decide } = notifierKit(opts);
+ const { pollMs, quietMs, heartbeatMs, leaseMs, cap, now, pid, ownerId, forcePoll, setTimer, clearTimer, log, logOnce, forgetLog, guard, decisions, decide } = notifierKit(opts);
let enabled = false;
let excluded = new Set<string>();
@@ -416,7 +420,8 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
if (!rt) return;
const lastCommit = await guard(`reading the last synced commit of ${rt.sourceId}`, () => opts.lastCommit(rt.sourceId), rt.lastCommit);
rt.lastCommit = lastCommit;
- const progressed = lastCommit !== job.lastCommit;
+ const progressed = lastCommit !== job.lastCommit || st?.committed === true;
+ if (progressed) forgetLog(`stalled\u0000${rt.sourceId}`);
if (st?.state === 'done' && st.outcome === 'blocked') {
rt.blockedKey = markerKey(rt);
const tracePath = trace(rt, { event: 'blocked', reason: st.reason ?? null });
@@ -475,7 +480,9 @@ export function startCommitNotifier(opts: CommitNotifierOptions): CommitNotifier
decide(rt.sourceId, 'converged', { detail: 'covered by another run' });
continue;
}
- if (opts.drainHeld && await guard(`reading the drain lease of ${rt.sourceId}`, () => opts.drainHeld!(rt.sourceId), true)) { decide(rt.sourceId, 'defer_drain_lease'); continue; }
+ // GBRA-133 PR 3a: a holder that commits nothing is a failed attempt, so the retry tiers run to notifier_stalled (a foreground sync follows it and takes over).
+ const held = opts.drainHeld ? await guard(`reading the drain lease of ${rt.sourceId}`, () => opts.drainHeld!(rt.sourceId), true) : false;
+ if (held) { if (held === 'stalled') await failure(rt, 'drain_holder_stalled', 'the process holding the drain lease has made no commit or cursor save for 5 minutes', false); else decide(rt.sourceId, 'defer_drain_lease'); continue; }
if (opts.syncRunning && await opts.syncRunning()) { decide(rt.sourceId, 'defer_busy'); return; }
if (leased && fence !== null && !await guard('checking the notifier lease', () => opts.store.holdsLease(opts.hostId, ownerId, fence!), false)) {
owner = false; fence = null; decide(rt.sourceId, 'not_owner');
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2196438189..4d70803c1a 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -223,10 +223,15 @@ export const CODES = {
demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },
derived_cap_exhausted: { class: 'server', summary: "Paid work stopped at the cost cap derived from its estimate; the run is resumable." },
destination_not_ready: { class: 'host_only', summary: "The destination brain is not initialized for this operation." },
+ // GBRA-133 PR 3a: the commit notifier's failure code for a source whose drain-lease holder commits nothing.
+ drain_holder_stalled: { class: 'retryable', actor: 'agent', summary: "The commit notifier did not wait on a source's drain lease because the process holding it has made no commit or cursor save for 5 minutes; it counts as a failed attempt.",
+ why: "Waiting on a holder that commits nothing kept the source due forever with nothing reported. Counting it as a failed attempt runs the notifier's retry tiers (5 s, 15 s, 1 min, 5 min), so the source reaches notifier_stalled with the sync-now fix in sync status and doctor; a foreground sync follows the holder and takes the source over when its lease lapses.",
+ docs: 'docs/guides/on-commit-sync.md#notifier-stalled',
+ suggestion: 'Read gbrain sync status --source <id> --json (the notifier block and drain_holder name the holder), stop that process if it is wedged, then run gbrain sync --source <id> --no-pull.' },
drain_stalled: { class: 'server', retryable: false, actor: 'host_admin',
summary: "A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window.",
why: "A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which.",
- reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress'],
+ reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress', 'owner_restart_required'],
// #6712 PR 2: a pass that admits nothing with no unfinished request stops `no_progress`; an older build wrote `no_admission` for it.
retired_reasons: { no_admission: '0.60.266.0' },
docs: 'docs/guides/write-refusals.md#drain-stalled',
@@ -660,6 +665,11 @@ export const CODES = {
fix: { argv: ['gbrain', 'config', 'set', 'sync.admission', 'normal'], consent: [], actor: 'user', requires_exclusive: false,
why: 'Restores the default; the owner chose the restriction, so only they lift it, and gbrain never runs this on its own.',
verify: { argv: ['gbrain', 'doctor', '--only', 'sync_admission_restricted', '--json'] } } },
+ // GBRA-133 PR 3a: the sync watchdog's stop of a run that committed nothing before its progress-aware deadline (sync-reconcile.ts).
+ sync_deadline_stalled: { class: 'server', retryable: false, actor: 'agent', summary: "A gbrain sync reached its progress-aware deadline having committed nothing (no page written, deleted or renamed, no cursor advanced), so it stopped as a stall instead of extending.",
+ why: "The deadline extends only while a run commits work. Screening unchanged files, held files and legacy-sweep slices are not progress, so a run that spends its whole deadline on them reports a stall with its cause instead of \"still progressing\" or a clean resumable stop; rerunning the same way commits nothing again.",
+ suggestion: 'Run gbrain sync status --source <id> --json (read-only): it names the step, holds and last error the source is stuck on. Fix what it names, then rerun the same sync.',
+ fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: the source's state, holds, last error and the next step.", requires_exclusive: false } },
sync_drain_lease_held: { class: 'retryable', actor: 'provider',
summary: "Another process holds the source's drain lease and is still committing pages; this run followed it until its own budget ended, or lost the lease mid-pass, and stopped `resumable`.",
why: "One managed drainer per source: two drainers on one cursor raced each other's checkpoints. A follower counts the holder's commits as its own progress, takes the lease when the holder releases it, and stops `drain_stalled` (cause `no_progress`) instead when the holder commits nothing for 5 minutes, so a wedged holder never reads as a clean exit.",
@@ -686,6 +696,10 @@ export const CODES = {
sync_cursor_replaced: { class: 'caller', summary: "Another sync run of the source replaced the managed-sync cursor before this checkpoint published, so the checkpoint had nothing left to publish.",
why: "The replacing run (a rediscovery that retried a recorded failure, or a newer sync of the source) covers the source from its own discovery; the superseded checkpoint's receipt is a conflict, no managed-sync failure is recorded for it, and the run that awaited it goes on with the winning cursor. A same-run index lag still reports revision_conflict.",
suggestion: 'Nothing to repair: let the current sync finish. gbrain sync status --source <id> --json shows the cursor that now covers the source.' },
+ // GBRA-133 PR 3a: a live pass's checkpoint refused because its pass ended or another pass started (sync-checkpoint-replaced.ts).
+ sync_pass_superseded: { class: 'caller', summary: "A sync pass's checkpoint did not publish because the pass that admitted it no longer holds the source (it ended, or another pass started); the next pass stamps its own checkpoint.",
+ why: "A pass's checkpoint is bound to its drain lease and pass row, so it can never publish after that pass ends. Its receipt is a conflict that records no managed-sync failure and reads superseded in gbrain sources writer failures; a pass that stops with the checkpoint still pending reports disposition superseded instead of a request to resume.",
+ suggestion: 'Nothing to repair or resubmit: the pages the pass committed stand. Let the next sync pass run (gbrain sync --source <id> --no-pull), and read gbrain sync status --source <id> --json to confirm the source converges.' },
sync_parser_regression: { class: 'server', summary: "Sync stopped because gbrain would hold a file whose exact bytes imported before; this is a gbrain bug.", why: "The upgrade invariant says a newer reader never refuses bytes an older one imported; with `GBRAIN_SYNC_PARSER_REGRESSION=stop` set for the process that syncs (the default holds the file), the run stops without advancing rather than hide a regression.", suggestion: 'Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then run gbrain sync --source <id> --no-pull.' },
tail_changed: { class: 'caller', summary: "The end of the page no longer has the sha256 the append expected, so nothing was appended.", why: "append_page's expected_tail_sha256 binds an append to the tail its caller read; another write changed it, and appending anyway could interleave text with a tail the caller never saw.", suggestion: "Read the page again (get_page body: 'none' returns tail_sha256), check whether the text is still missing, and append against the current tail with a new request_id.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the current revision and tail_sha256.", requires_exclusive: false } },
tail_exposure_approval: { class: 'caller', summary: "A fence on a world-visible page has no end marker and prose follows its table; closing it after the last row is safe for the table but makes those lines visible to remote readers, so the content-repair lane previews the close and waits for a hash-bound approval instead of applying it unattended.", why: "Everything after an unpaired begin marker is hidden by the privacy boundary. The repair model read the tail as prose (not rows), so the only judgment left is whether those exact lines may become visible, and that is the user's: the preview prints them and the hash binds them. On a private page nothing new is disclosed and the lane closes the fence by itself.", actor: 'user', docs: 'docs/guides/write-refusals.md#tail_exposure_approval', suggestion: 'Show the user the preview\'s exposed lines (gbrain repair content --source <id> --only <path>, read-only), then run the printed gbrain repair content --source <id> --only <path> --apply --expect <hash> only after they agree; a changed tail invalidates the hash. By hand: add the end marker directly after the last table row and move the trailing text where it belongs, commit, then gbrain sync --source <id> --no-pull.' },
diff --git a/src/core/forward-progress.ts b/src/core/forward-progress.ts
index cf71e07573..3900a3bb38 100644
--- a/src/core/forward-progress.ts
+++ b/src/core/forward-progress.ts
@@ -32,6 +32,34 @@ export function onForwardProgress(listener: ForwardProgressListener): () => void
return () => { listeners.delete(listener); };
}
+const committedListeners = new Set<ForwardProgressListener>();
+
+/**
+ * GBRA-133 PR 3a: record committed work (a page written, deleted or renamed, or a sync cursor advanced). Screening a
+ * file that is unchanged, a held file and a legacy-sweep slice are forward progress at most, never committed work. A
+ * committed note is also a forward-progress note. The sync hard deadline extends only on these, so a run that screens
+ * for an hour and commits nothing stops as a stall instead of reading as "still progressing".
+ */
+let lastCommittedAt = 0;
+export function noteCommittedProgress(): void {
+ noteForwardProgress();
+ lastCommittedAt = lastProgressAt;
+ for (const listener of committedListeners) {
+ try { listener(); } catch { /* a listener must never break the work loop */ }
+ }
+}
+
+/** Wall-clock ms of the most recent committed-progress note in this process (0 = none yet). */
+export function lastCommittedProgressAt(): number {
+ return lastCommittedAt;
+}
+
+/** Subscribe to committed-progress notes; returns the unsubscribe function. */
+export function onCommittedProgress(listener: ForwardProgressListener): () => void {
+ committedListeners.add(listener);
+ return () => { committedListeners.delete(listener); };
+}
+
/** Wall-clock ms of the most recent progress note in this process (0 = none yet). */
export function lastForwardProgressAt(): number {
return lastProgressAt;
diff --git a/src/core/notifier/resident.ts b/src/core/notifier/resident.ts
index 0754b76787..5310405481 100644
--- a/src/core/notifier/resident.ts
+++ b/src/core/notifier/resident.ts
@@ -143,10 +143,15 @@ export function runnerStart(engine: BrainEngine): Pick<CommitNotifierOptions, 's
jobStatus: (jobId) => {
const s = runner?.getDelegatedSyncStatus(jobId);
if (!s || !s.ok || !s.state) return null;
- return { state: s.state, ...(s.drain ? { outcome: s.drain.outcome, ...(s.drain.stop_reason ? { reason: s.drain.stop_reason } : {}) } : {}), ...(s.jobError ? { error: s.jobError } : {}) };
+ return { state: s.state, ...(s.drain ? { outcome: s.drain.outcome, committed: s.drain.written + s.drain.waived > 0, ...(s.drain.stop_reason ? { reason: s.drain.stop_reason } : {}) } : {}),
+ ...(s.jobError ? { error: s.jobError } : {}) };
},
syncRunning: async () => (await load()).isDelegatedSyncRunning(),
- drainHeld: async (sourceId) => (await (await import('../persistence/sync-lease.ts')).readDrainHolder(engine, sourceId)) !== null,
+ drainHeld: async (sourceId) => {
+ const { holderStalled, readDrainHolder } = await import('../persistence/sync-lease.ts');
+ const holder = await readDrainHolder(engine, sourceId);
+ return holder === null ? false : holderStalled(holder) ? 'stalled' : true;
+ },
};
}
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 5a0a4e452c..b51ae26ef3 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -44,7 +44,7 @@ import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-gu
import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';
import { CANONICAL_FILE_MISSING, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';
-import { SYNC_CURSOR_REPLACED } from './sync-checkpoint-replaced.ts';
+import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import { fenceFailureDetail } from '../fence-repair/refusal.ts';
import { withdrawalFailureDetail } from '../facts/withdrawal.ts';
import { faultPoint, withFaultPoints } from './fault-points.ts';
@@ -213,7 +213,7 @@ function requestError(error: unknown): PublicationFailure {
if (code === 'revision_backfill_pending' && error instanceof Error) return { code, message: error.message };
return ownerExceptionFailure(error);
}
-function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed',SYNC_CURSOR_REPLACED].includes(code); }
+function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed',SYNC_CURSOR_REPLACED,SYNC_PASS_SUPERSEDED].includes(code); }
/** The terminal state of an unpublished failure: `admission_paused` (#6712 PR 4b, a destructive write `sync.admission` paused at publication) is `cancelled`. */
function failureState(code: string): 'conflict' | 'failed' | 'cancelled' { return code === 'admission_paused' ? 'cancelled' : conflictCode(code) ? 'conflict' : 'failed'; }
export function transientDatabaseFailure(error: unknown): boolean {
diff --git a/src/core/persistence/sync-checkpoint-replaced.ts b/src/core/persistence/sync-checkpoint-replaced.ts
index 9f370eddda..2fde387fbe 100644
--- a/src/core/persistence/sync-checkpoint-replaced.ts
+++ b/src/core/persistence/sync-checkpoint-replaced.ts
@@ -10,6 +10,14 @@
import type { WriteRequest } from './model.ts';
export const SYNC_CURSOR_REPLACED = 'sync_cursor_replaced';
+/**
+ * GBRA-133 PR 3a: a live pass's checkpoint (its stamp) is bound to the drain lease and pass row that admitted it. Once that pass
+ * ended (its lease released) or another pass started, the checkpoint can never publish: the next pass re-reads the source and
+ * stamps its own. Its refusal is `sync_pass_superseded` (receipt state `conflict`), it records no failure, and the terminal-failure
+ * readers classify it `superseded`. A pass that stops while its checkpoint is still pending says so (`disposition: 'superseded'`),
+ * never "resume this request".
+ */
+export const SYNC_PASS_SUPERSEDED = 'sync_pass_superseded';
/**
* The classification of a checkpoint whose durable cursor names another run: the refusal code with its receipt message
@@ -21,7 +29,7 @@ export function checkpointCursorReplaced(p: { kind: string; runId: string }, cur
cause: `Another sync run of ${sourceId} replaced the cursor this checkpoint belongs to, so the checkpoint had nothing left to publish; the replacing run covers the source.` };
}
-/** The terminal receipt of a checkpoint another run superseded: nothing to record, nothing to convert. */
+/** The terminal receipt of a checkpoint another run or pass superseded: nothing to record, nothing to convert. */
export function checkpointSuperseded(pending: { intent: { kind: string } }, done: Pick<WriteRequest, 'error_code'>): boolean {
- return pending.intent.kind === 'managed_sync_checkpoint' && done.error_code === SYNC_CURSOR_REPLACED;
+ return pending.intent.kind === 'managed_sync_checkpoint' && (done.error_code === SYNC_CURSOR_REPLACED || done.error_code === SYNC_PASS_SUPERSEDED);
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 29615a2a52..88ffcfbddb 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -17,7 +17,7 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { OperationError } from '../ops/contract.ts';
import { getCode, getMessage, isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';
-import { currentRunDeadline, noteForwardProgress } from '../forward-progress.ts';
+import { currentRunDeadline, noteCommittedProgress } from '../forward-progress.ts';
import { serr } from '../console-prefix.ts';
import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
@@ -117,8 +117,10 @@ export interface DrainStall {
* #6317: `owner_wedged_here` is a live same-host owner whose preparation passed the ceiling, or whose own heartbeat row says it is wedged
* (`restart_required`, a root barrier past the ceiling); `preparation_overdue` is kept for an owner on another host.
* #6712 PR 2: a pass that admitted nothing and left no unfinished request is `no_progress` too (`no_admission` is retired).
+ * GBRA-133 PR 3a: `owner_restart_required` is a head whose owner's own heartbeat row reports restart_required when the drain
+ * stops it (in a pass or between passes): only restarting that process ends it, so `owner_row` names it and `next` says so.
*/
- cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'head_blocked';
+ cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'head_blocked' | 'owner_restart_required';
/** #6405/#6423: the in-pass governor ended a pass that never returned (the pass was aborted and its late result is ignored). */
in_pass?: boolean;
/** #6317: the head owner as the stamp names it, so the stop can say which process to restart. */
@@ -381,7 +383,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
let lanes: { effective: number; stepDown: string | null; overlapped: number; fallbacks: number } | null = null;
// #6317: `extended` marks the one extra window a lapsed head gets while a consumer here can reclaim it; `ownerAt`/`owner` throttle the owner-row read to one per progress interval.
let stall: { key: string; since: number; passes: number; claim: DrainClaim | null; stallInfo: Omit<DrainStall, 'stalled_seconds'>; extended?: boolean; ownerAt?: number; owner?: DrainOwnerRow | null } | null = null;
- let lastCommitAt = startedAt, inPass = false, readingHead = false;
+ let lastCommitAt = startedAt, lastSweptAt = startedAt, inPass = false, readingHead = false;
// #6278 (B7): a pass refused for write capacity keeps the last pass's result for the report; `capacity` spans the refusals since the last pass that ran.
let last: SyncResult | undefined, capacity: { since: number; attempts: number } | null = null;
// #6278 (B7): a pass may finish one run and yield for the next (re-screens scheduled while it ran); the counts of finished runs carry into the report.
@@ -423,14 +425,12 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (event.phase === 'managed_sync.group' && typeof event.group === 'number') { groups++; groupedPages += event.group; largestGroup = Math.max(largestGroup, event.group); }
if (event.phase === 'managed_sync.group_ahead') admittedAhead += typeof event.group === 'number' ? 1 : 0;
if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped, fallbacks: event.lanes.fallbacks };
- // #6696 C4: the checkpoint commit is a commit; the tail after it is governed by its own budget.
- if (event.phase === 'managed_sync.finish') { lastCommitAt = clock(); drops = 0; noteForwardProgress(); return; }
- // GBRA-108: a pass's committed legacy-sweep slice (sync-pass-apply.ts) is progress, though it publishes no page.
- if (event.phase === 'managed_sync.legacy_swept') { lastCommitAt = clock(); noteForwardProgress(); return; }
+ // #6696 C4: the checkpoint commit is a commit. GBRA-108: a legacy-sweep slice keeps the governor from calling the pass hung; GBRA-133 PR 3a: it is no commit.
+ if (event.phase === 'managed_sync.finish') { lastCommitAt = clock(); drops = 0; noteCommittedProgress(); return; } else if (event.phase === 'managed_sync.legacy_swept') { lastSweptAt = clock(); return; }
if (event.phase !== 'managed_sync.page_committed') return;
if (event.waived) waived++; else written++;
lastCommitAt = clock(); drops = 0;
- noteForwardProgress();
+ noteCommittedProgress();
if (input.announce && clock() - lastLine >= PROGRESS_EVERY_MS) {
lastLine = clock();
const estimate = drainEstimate(remaining(), written + waived, clock() - startedAt);
@@ -442,28 +442,28 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
// rejects, an admission parked behind a transaction pooler) was never stopped. The governor runs whether or not the drain
// announces, races the pass so the drain settles even when the hung promise never does, bounds its own head read, and owns
// the abandoned pass: its signal is aborted (the pass's step boundaries throw, so it admits and writes nothing more) and its
- // late result or rejection is dropped.
- const noProgressMs = input.noProgressMs ?? IN_PASS_NO_PROGRESS_MS, ceilingMs = input.publicationCeilingMs ?? PUBLICATION_CEILING_DEFAULT_MS;
+ // late result or rejection is dropped, and (GBRA-133 PR 3a) its late progress events too: none reaches the report, a line or a deadline.
+ const noProgressMs = input.noProgressMs ?? IN_PASS_NO_PROGRESS_MS, ceilingMs = input.publicationCeilingMs ?? PUBLICATION_CEILING_DEFAULT_MS, governBound = Math.min(GOVERN_PROBE_MS, noProgressMs);
const governedPass = (): Promise<{ result: SyncResult } | { stall: DrainStall } | { deadline: true }> => {
const controller = new AbortController(), passStartedAt = clock();
const passSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
clearDrainStep();
- const running = Promise.resolve().then(() => input.pass(passSignal, onProgress));
+ let live = true; const running = Promise.resolve().then(() => input.pass(passSignal, event => { if (live) onProgress(event); }));
let timer: ReturnType<typeof setInterval> | null = null, probing = false, key: string | null = null, keySince = passStartedAt, blockedKey: string | null = null;
const governEvery = input.governMs ?? Math.min(every, GOVERN_EVERY_MS), blockerAfter = input.governMs ?? GOVERN_EVERY_MS;
const stopped = new Promise<{ stall: DrainStall }>(resolve => {
- const stop = (stall: DrainStall) => { if (timer) clearInterval(timer); timer = null; markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };
+ const stop = (stall: DrainStall) => { live = false; if (timer) clearInterval(timer); timer = null; markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };
timer = setInterval(() => {
- const quietSince = Math.max(lastCommitAt, passStartedAt);
+ const quietSince = Math.max(lastCommitAt, lastSweptAt, passStartedAt);
if (probing || clock() - quietSince < Math.min(noProgressMs, ceilingMs, blockerAfter)) return;
probing = true;
const head = input.probe?.head
? Promise.race([Promise.resolve().then(() => input.probe!.head!()), new Promise<never>((_, reject) => setTimeout(() => reject(new Error('head read timed out')), Math.min(GOVERN_PROBE_MS, noProgressMs)).unref?.())])
.then(value => ({ ok: true as const, value }), () => ({ ok: false as const }))
: Promise.resolve({ ok: true as const, value: null });
- void head.then(read => {
+ void head.then(async read => {
if (!timer) return;
- const now = clock(), quiet = now - Math.max(lastCommitAt, passStartedAt);
+ const now = clock(), quiet = now - Math.max(lastCommitAt, lastSweptAt, passStartedAt);
const head = read.ok ? read.value : null, claim = head?.claim ?? null;
const step = readDrainStep();
const base = { request_id: head?.request_id ?? 'none', state: head?.head_state ?? 'none', blocked_reason: null, head_request_id: head?.request_id ?? null,
@@ -479,20 +479,22 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (claim && !claim.lapsed && claim.phase === 'publishing') {
const age = claim.step_age_ms ?? quiet;
if (age < ceilingMs) return;
- stop({ ...base, stalled_seconds: Math.round(age / 1000), phase: 'publishing', step: claim.step, waiting_on: claim.waiting_on, cause: 'publication_overdue',
- owner_pid: claim.owner_pid, owner_kind: claim.owner_kind, owner_nonce: claim.owner_nonce, last_sql: claim.last_sql, ceiling_ms: ceilingMs });
+ const overdue = await withOwnerRestart(input.probe, claim, { ...base, stalled_seconds: Math.round(age / 1000), phase: 'publishing', step: claim.step, waiting_on: claim.waiting_on,
+ cause: 'publication_overdue', owner_pid: claim.owner_pid, owner_kind: claim.owner_kind, owner_nonce: claim.owner_nonce, last_sql: claim.last_sql, ceiling_ms: ceilingMs }, governBound);
+ if (timer) stop(overdue);
return;
}
// A live preparation is bounded by its own budget and the preparation ceiling (#6298), which settle the pass.
if (claim && !claim.lapsed && claim.phase === 'preparing') { key = null; return; }
const print = read.ok ? head ? `${head.head_state}|${claim?.phase ?? ''}|${claim?.step ?? ''}|${claim?.lapsed ?? ''}` : 'none' : 'unreadable';
if (print !== key) { key = print; keySince = now; }
- const elapsed = now - Math.max(keySince, lastCommitAt, passStartedAt);
+ const elapsed = now - Math.max(keySince, lastCommitAt, lastSweptAt, passStartedAt);
if (quiet < noProgressMs || elapsed < noProgressMs && key !== 'none') return;
const sql = step?.last_sql ? { label: step.last_sql.label, age_ms: now - step.last_sql.at } : claim?.last_sql ?? null;
- stop({ ...base, stalled_seconds: Math.round(quiet / 1000), phase: claim?.phase ?? null, step: head ? claim?.step ?? null : step?.step ?? null,
+ const quietStall = await withOwnerRestart(input.probe, claim, { ...base, stalled_seconds: Math.round(quiet / 1000), phase: claim?.phase ?? null, step: head ? claim?.step ?? null : step?.step ?? null,
waiting_on: claim?.waiting_on ?? null, cause: claim?.lapsed ? 'owner_missing' : 'no_progress',
- owner_pid: claim?.owner_pid ?? null, owner_kind: claim?.owner_kind ?? null, owner_nonce: claim?.owner_nonce ?? null, last_sql: sql });
+ owner_pid: claim?.owner_pid ?? null, owner_kind: claim?.owner_kind ?? null, owner_nonce: claim?.owner_nonce ?? null, last_sql: sql }, governBound);
+ if (timer) stop(quietStall);
}).finally(() => { probing = false; });
}, governEvery);
timer.unref?.();
@@ -502,11 +504,11 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
// stalled pass (its signal aborted, its late result dropped), so the drain still reports before the caller's hard deadline.
let graceTimer: ReturnType<typeof setTimeout> | undefined, onDeadline: (() => void) | undefined;
const expired = coop.signal ? new Promise<{ deadline: true }>(resolve => {
- onDeadline = () => { graceTimer = setTimeout(() => { markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned('deadline')); resolve({ deadline: true }); }, input.deadlineGraceMs ?? DEADLINE_PASS_GRACE_MS); graceTimer.unref?.(); };
+ onDeadline = () => { graceTimer = setTimeout(() => { live = false; markPassAbandoned(passSignal); controller.abort(new DrainPassAbandoned('deadline')); resolve({ deadline: true }); }, input.deadlineGraceMs ?? DEADLINE_PASS_GRACE_MS); graceTimer.unref?.(); };
if (coop.signal!.aborted) onDeadline(); else coop.signal!.addEventListener('abort', onDeadline, { once: true });
}) : null;
return Promise.race([running.then(result => ({ result })), stopped, ...(expired ? [expired] : [])]).finally(() => {
- if (timer) clearInterval(timer); timer = null; inPass = false;
+ live = false; if (timer) clearInterval(timer); timer = null; inPass = false;
clearTimeout(graceTimer); if (onDeadline) coop.signal?.removeEventListener('abort', onDeadline);
});
};
@@ -657,7 +659,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
return finish(result, 'blocked', 'drain_stalled', { stall: { ...detail, cause: 'owner_wedged_here', owner_row: stall.owner ?? null, past_ceiling: pastCeiling, ceiling_ms: claim.ceiling_ms },
retry_after_ms: Math.max(0, claim.ceiling_ms - age) });
}
- } else return finish(result, 'blocked', 'drain_stalled', { stall: detail });
+ } else return finish(result, 'blocked', 'drain_stalled', { stall: await withOwnerRestart(input.probe, claim, detail, GOVERN_PROBE_MS) });
}
}
}
@@ -697,6 +699,17 @@ function ownerPid(stamp: Record<string, unknown>): number | null {
const pid = owner && typeof owner.pid === 'number' ? owner.pid : stamp.pid;
return typeof pid === 'number' ? pid : null;
}
+/**
+ * GBRA-133 PR 3a: a stop whose head owner's own heartbeat row reports restart_required becomes `owner_restart_required` with that row
+ * (the owner read bounded by `boundMs`); any other stop, a lapsed claim's included, is returned as it is.
+ */
+async function withOwnerRestart(probe: StallProbe | undefined, claim: DrainClaim | null, stall: DrainStall, boundMs: number): Promise<DrainStall> {
+ if (!claim || claim.owner_pid === null || !probe?.owner || stall.cause === 'owner_missing') return stall;
+ let bound: ReturnType<typeof setTimeout> | undefined;
+ const row = await Promise.race([probe.owner(claim).catch(() => null), new Promise<null>(resolve => { bound = setTimeout(() => resolve(null), boundMs); bound.unref?.(); })]);
+ clearTimeout(bound);
+ return row?.restart_required ? { ...stall, cause: 'owner_restart_required', owner_row: row } : stall;
+}
/** The preparation budgets the drain's allowance reads (Lane A defines and validates the keys; defaults are the documented ones). */
async function readPreparationBudgets(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ syncMs: number; maintenanceMs: number; ceilingMs: number }> {
const read = async (key: string, fallback: number) => { const n = Number((await engine.getConfig(key).catch(() => null))?.trim()); return Number.isInteger(n) && n > 0 ? n : fallback; };
@@ -1036,6 +1049,19 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
return { ...headBlockedNext(d.stall.blocked_by, d.stall.head_request_id, d.stall.stalled_seconds, sourceId, resumeCommand), ...estimate, code: 'drain_stalled', cause: 'head_blocked',
docs: ERROR_CATALOGUE.sync_drain_head_blocked.docs };
}
+ // GBRA-133 PR 3a: the head's owner reports restart_required: it claims nothing until it restarts and holds its root until it exits.
+ if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'owner_restart_required') {
+ const stall = d.stall, owner = `the gbrain ${stall.owner_row?.kind ?? stall.owner_kind ?? 'owner'} process (pid ${stall.owner_row?.pid ?? stall.owner_pid ?? '?'})`;
+ const status = ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'];
+ return { command: status.join(' '), safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'drain_stalled', cause: 'owner_restart_required',
+ why: `The write at the head of this source (${stall.head_request_id ?? stall.request_id}) is held by ${owner} on this host${stall.phase ? `, ${stall.phase}${stall.step ? ` at step ${stall.step}` : ''}` : ''}, `
+ + 'and that process reports restart_required: it claims no write until it restarts, and the root it holds stays held until it exits, so waiting or rerunning does not clear it. '
+ + `Nothing failed and the cursor is intact. Restart that process, then rerun: ${resumeCommand}`,
+ fix: renderAction({ argv: status, consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'Status names the request, its step and the owner process that reports restart_required, read-only.',
+ user_message: `Restart ${owner} on this host (it reports restart_required), then run: ${resumeCommand}`,
+ verify: { argv: ['gbrain', 'sources', 'writer', 'movement', sourceId, '--json'] } }, cliRenderContext()), ...(docs ? { docs } : {}) };
+ }
// #6317 (B2): a live same-host owner stopped the drain at the ceiling or on its own wedged verdict; the fix is to wait for the ceiling
// (the root is freed there and the next pass holds the entry) or, past it, to restart the named process.
if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'owner_wedged_here') {
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 8c5101a0e5..306473c345 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -36,7 +36,7 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncResult } from '../../commands/sync.ts';
import type { Action } from '../agent-output.ts';
import { inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';
-import { currentRunDeadline, lastForwardProgressAt, noteForwardProgress } from '../forward-progress.ts';
+import { currentRunDeadline, lastForwardProgressAt, noteCommittedProgress, noteForwardProgress } from '../forward-progress.ts';
import { faultPoint } from './fault-points.ts';
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { VERSION } from '../../version.ts';
@@ -257,9 +257,13 @@ export async function withDrainLease(engine: BrainEngine, sourceId: string, opts
const holder = await readDrainHolder(engine, sourceId).catch(() => null);
if (seen === undefined) { opts.announce?.(holder, 'start'); reportedAt = Date.now(); }
else if (Date.now() - reportedAt >= (opts.tty ? FOLLOW_REPORT_TTY_MS : FOLLOW_REPORT_MS)) { opts.announce?.(holder, 'progress'); reportedAt = Date.now(); }
- // The holder's commits and cursor saves are this run's forward progress: the progress-aware watchdog window extends with them.
+ // The holder's commits are this run's committed progress (the progress-aware watchdog window extends with them); a cursor
+ // save alone (GBRA-133 PR 3a: a legacy-sweep slice saves the pass row) is forward progress only.
const now = `${holder?.started_at ?? ''}|${holder?.progress?.committed ?? ''}|${holder?.progress?.last_progress_at ?? ''}`;
- if (seen !== undefined && now !== seen) noteForwardProgress();
+ if (seen !== undefined && now !== seen) {
+ const [startedNow, committedNow] = now.split('|'), [startedSeen, committedSeen] = seen.split('|');
+ if (startedNow === startedSeen && Number(committedNow) > Number(committedSeen)) noteCommittedProgress(); else noteForwardProgress();
+ }
seen = now;
if (holder && holderStalled(holder)) return leaseStalledResult(sourceId, holder, { remote: opts.remote });
const stopAt = followStopAt(startedAt, follow.deadlineAtMs);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 5070960e65..1e85100623 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -48,7 +48,7 @@ import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';
import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';
import { checkpointRetryCommand, findIncompleteSyncReceipt, findOpenPassWork, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { CURSOR_CHANGED_REFUSAL_MESSAGE, SYNC_CURSOR_FENCE_ORIGIN } from './sync-knock-on.ts';
-import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';
+import { checkpointCursorReplaced, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import { recordPassTail, recordSyncTail } from './sync-tail-record.ts';
import { readPassRow, writePassRow, OPEN_AT_STAMP_CAP, type ManagedSyncPassValue } from './sync-pass-row.ts';
import { admissionAllows, readSyncAdmission } from './sync-admission.ts';
@@ -511,7 +511,7 @@ async function applyPassCheckpoint(tx: BrainEngine, row: WriteRequest, p: SyncIn
const stamp = p.stamp!;
const lease = await tx.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE', [syncLockId(row.source_id), stamp.leaseToken]);
const pass = lease.length ? await readPassRow(tx, row.source_id, stamp.incarnation) : null;
- if (!pass || pass.value.lease_token !== stamp.leaseToken || pass.value.telemetry.pass_id !== p.passId) throw syncPublicationRefusal('revision_conflict', PASS_LEASE_LOST_MESSAGE, row, p,
+ if (!pass || pass.value.lease_token !== stamp.leaseToken || pass.value.telemetry.pass_id !== p.passId) throw syncPublicationRefusal(SYNC_PASS_SUPERSEDED, PASS_LEASE_LOST_MESSAGE, row, p,
`The pass that admitted checkpoint ${row.request_id} of ${row.source_id} lost the source's drain lease, or another pass started since, so nothing was stamped.`);
const open = await findOpenPassWork(tx, row.worktree_id!, row.request_id);
if (open) throw opError('recovery_required', `An unfinished sync request (request ${open}) still blocks the sync checkpoint.`,
@@ -559,7 +559,7 @@ export async function publishPassStamp(tx: BrainEngine, row: WriteRequest, p: Sy
Object.assign(value.obligations, { not_converged_streak: 0, mismatch: {}, faults: {}, stuck_since: null });
value.telemetry = { ...value.telemetry, outcome: 'synced', stop_reason: stamp.configured ? null : 'selection_scoped', ended_at: at, remaining: 0,
duration_ms: Date.parse(at) - Date.parse(value.telemetry.started_at) };
- if (!await writePassRow(tx, value)) throw syncPublicationRefusal('revision_conflict', PASS_LEASE_LOST_MESSAGE, row, p,
+ if (!await writePassRow(tx, value)) throw syncPublicationRefusal(SYNC_PASS_SUPERSEDED, PASS_LEASE_LOST_MESSAGE, row, p,
`Another pass of ${row.source_id} started while checkpoint ${row.request_id} published, so nothing was stamped.`);
return { status: 'synced', source_id: row.source_id, pass_id: p.passId, configured: stamp.configured };
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index e6a1b9a6c5..cc545d4503 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -90,7 +90,7 @@ export interface ManagedSyncWriteDiagnostic {
write_request: WriteReceipt;
line_endings?: 'crlf_lf_only';
ledger_recorded?: boolean;
- detail?: string;
+ detail?: string; /** GBRA-133 PR 3a: a pass checkpoint the pass's end superseded (sync-checkpoint-replaced.ts). */ disposition?: 'superseded';
docs?: string;
}
@@ -783,8 +783,8 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
if (converted === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };
if (converted && 'tripped' in converted) return { result: breakerResult(converted.tripped, pending, done, remote) };
if (converted) { input.assertActive(); return { cursor: converted }; }
- // #6513: a checkpoint another run superseded records nothing; this run goes on with the winning cursor as it stands.
- if (checkpointSuperseded(pending, done)) return { cursor: await currentCursor(engine, key, cursor) };
+ // #6513: a checkpoint another run superseded records nothing; this run goes on with the winning cursor (GBRA-133 PR 3a: a pass's ends; the next pass stamps).
+ if (checkpointSuperseded(pending, done)) return pending.intent.passId ? { result: result(cursor, 'partial', 'writer_pending') } : { cursor: await currentCursor(engine, key, cursor) };
const rootCause = await syncRootCause(engine, cursor, pending, done);
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.ts
index 67e24e80f5..0537b3edaa 100644
--- a/src/core/persistence/sync-write-diagnostic.ts
+++ b/src/core/persistence/sync-write-diagnostic.ts
@@ -15,6 +15,7 @@ import { checkpointRetryCommand } from './checkpoint-validation.ts';
import { readSyncFile } from './sync-discovery.ts';
import { sha256 } from './digest.ts';
import { classifyTerminal } from './terminal-classify.ts';
+import { SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: string; processingOptions?: SyncProcessingOptions; syncOptions: SyncCursorOptions | null },
pending: { slug: string; intent: SyncIntent }, row: WriteRequest): ManagedSyncWriteDiagnostic {
@@ -23,7 +24,13 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: str
const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',
'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes',
'preparation_deadline', 'group_member_waiting', 'lane_lock_timeout', 'lane_statement_timeout'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';
- const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {
+ // GBRA-133 PR 3a: a live pass's checkpoint (its stamp) publishes only under the pass that admitted it. A pass that stops with it
+ // pending has ended, so the next pass supersedes it: nothing to resume, nothing failed.
+ const superseded = pending.intent.kind === 'managed_sync_checkpoint' && !!pending.intent.passId && (!terminal || code === SYNC_PASS_SUPERSEDED);
+ const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : superseded ? {
+ reason: blockedReason, message: 'This pass ended before its checkpoint published, so the checkpoint is superseded: it is bound to the pass that admitted it and never publishes after it.',
+ suggestion: 'Nothing to resume and nothing failed: the pages this pass committed stand, and the next sync pass re-reads the source and stamps its own checkpoint. Do not resubmit or cancel this request.',
+ } : {
reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',
suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',
};
@@ -32,12 +39,12 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: str
error_detail: row.error_detail ?? null, recovery: row.recovery, blocked_reason: row.blocked_reason, compacted: row.compacted, publication_started: row.publication_started,
error_message: row.error_message, intent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null }) : null;
const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,
- path: pending.intent.path, write_error: code, ...detail, ...(verdict ? { category: verdict.category, public_category: verdict.public_category } : {}),
+ path: pending.intent.path, write_error: code, ...detail, ...(verdict ? { category: verdict.category, public_category: verdict.public_category } : {}), ...(superseded ? { disposition: 'superseded' as const } : {}),
write_request: publicWriteReceipt(receiptFor(row)) };
// #6194: an import that lost to a database write the hold could not prove; the retry re-imports the Git version unless discovery's drift guard holds it.
if (terminal && code === 'revision_conflict' && pending.intent.kind === 'managed_sync_import') diagnostic.suggestion = `The page changed in the database after this import was frozen. `
+ `Before retrying, compare the file and the page with gbrain sources reconcile ${cursor.sourceId} ${pending.slug} --preview (it writes nothing): a retry re-imports the Git version over the database one. ${diagnostic.suggestion}`;
- if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to retry it under a new request. Skipping failures cannot bypass a managed write.`;
+ if (terminal && !superseded) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to retry it under a new request. Skipping failures cannot bypass a managed write.`;
if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {
try {
const bytes = readSyncFile(cursor.root, pending.intent.path);
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index 8017345c02..5d92a5e68e 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -26,6 +26,7 @@ import { isStatementTimeout } from './bounded-reads.ts';
import { readSchemaBehind } from './schema-admission.ts';
import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
+import { SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import type { PublicCategory } from './public-category.ts';
import { classifyTerminal, dispositionOf, driftSinceAction, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
@@ -143,7 +144,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
WHERE (${RECOVERY('r')} OR (${TERMINAL('r')} AND ${ENDED('r')} > now()-($1::int*interval '1 day')))
AND ($2::text[] IS NULL OR r.source_id=ANY($2::text[]))
), resolved AS (
- SELECT r.id FROM base r WHERE NOT r.has_recovery AND EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')})
+ SELECT r.id FROM base r WHERE NOT r.has_recovery AND (r.error_code='${SYNC_PASS_SUPERSEDED}' OR EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')}))
), tagged AS (
SELECT b.*, (x.id IS NOT NULL) AS resolved, (b.has_recovery OR b.ended_at > now()-($3::int*interval '1 day')) AS in_window, ${HISTORICAL_BY_BUILD('b')} AS historical_build
FROM base b LEFT JOIN resolved x ON x.id=b.id
@@ -342,7 +343,8 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
scanned++;
cursor = row.sequence;
const v = verdictOf(row, schemaBehind);
- const disposition = dispositionOf(row.later_state ? { state: row.later_state, same_intent: row.same_intent === true } : null);
+ // GBRA-133 PR 3a: a pass checkpoint whose pass ended is superseded by construction (the next pass stamps its own).
+ const disposition = row.error_code === SYNC_PASS_SUPERSEDED ? 'superseded' : dispositionOf(row.later_state ? { state: row.later_state, same_intent: row.same_intent === true } : null);
const historical = !row.has_recovery && (disposition !== 'unknown' || v.historical);
const matches = (!q.category || v.category === q.category) && (!q.code || v.code === q.code)
&& (q.origin === undefined || (v.origin ?? NO_ORIGIN) === q.origin) && (state === 'all' || !historical);
diff --git a/src/core/process-watchdog.ts b/src/core/process-watchdog.ts
index da9db8a354..1d9e4287e6 100644
--- a/src/core/process-watchdog.ts
+++ b/src/core/process-watchdog.ts
@@ -37,7 +37,7 @@
import { Worker } from 'node:worker_threads';
// Zero-import teardown-budget leaf — safe edge, no cycle (it imports nothing).
import { MAX_TIMER_DELAY_MS } from './background-work.ts';
-import { lastForwardProgressAt, onForwardProgress } from './forward-progress.ts';
+import { lastCommittedProgressAt, lastForwardProgressAt, onCommittedProgress, onForwardProgress } from './forward-progress.ts';
export type WatchdogAction = 'wait' | 'sigterm' | 'sigkill';
@@ -62,16 +62,17 @@ export type ProgressDeadlineAction = 'wait' | 'extend' | 'stop';
* stopped: once the deadline passes, the deadline extends for as long as the
* last progress note is younger than `windowMs`, and stops the run only after
* a full window with no progress. `windowMs <= 0` keeps the plain wall-clock
- * deadline.
+ * deadline. GBRA-133 PR 3a: `progressed` false (a run that must commit to
+ * count, and has committed nothing) never extends: the deadline stops it.
* elapsed < deadline -> 'wait'
* deadline passed, progress within window -> 'extend'
* deadline passed, no progress for window -> 'stop' (SIGTERM, then SIGKILL after grace)
*/
export function progressDeadlineDecision(
- elapsedMs: number, deadlineMs: number, sinceProgressMs: number, windowMs: number,
+ elapsedMs: number, deadlineMs: number, sinceProgressMs: number, windowMs: number, progressed = true,
): ProgressDeadlineAction {
if (elapsedMs < deadlineMs) return 'wait';
- if (windowMs > 0 && sinceProgressMs < windowMs) return 'extend';
+ if (windowMs > 0 && progressed && sinceProgressMs < windowMs) return 'extend';
return 'stop';
}
@@ -100,6 +101,15 @@ export interface ProcessWatchdogOpts {
* stderr line and an exit status.
*/
stopNotice?: string;
+ /**
+ * GBRA-133 PR 3a: which notes count as progress. `committed` listens to
+ * `noteCommittedProgress()` only (pages written, a cursor advanced), and a
+ * run that reaches its deadline having committed nothing stops at once
+ * instead of getting a window; `stallNotice` is then written instead of
+ * `stopNotice`. Default `forward`.
+ */
+ progressSignal?: 'forward' | 'committed';
+ stallNotice?: string;
}
export interface WatchdogHandle {
@@ -158,12 +168,13 @@ const INERT: WatchdogHandle = { dispose() {}, get active() { return false; } };
const WORKER_SRC = `
const { parentPort, workerData } = require('node:worker_threads');
const { writeSync } = require('node:fs');
-const { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice } = workerData;
+const { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice, stallNotice, requireProgress } = workerData;
const t0 = Date.now();
let lastProgress = t0;
+let progressed = !requireProgress;
let extended = false;
function w(m) { try { writeSync(2, '[' + label + '] ' + m + '\\n'); } catch (e) {} }
-if (progressWindowMs > 0 && parentPort) parentPort.on('message', () => { lastProgress = Date.now(); });
+if (progressWindowMs > 0 && parentPort) parentPort.on('message', () => { lastProgress = Date.now(); progressed = true; });
if (heartbeatMs > 0) {
const hb = setInterval(() => {
const elapsed = Math.round((Date.now() - t0) / 1000);
@@ -181,6 +192,16 @@ if (heartbeatMs > 0) {
if (typeof hb.unref === 'function') hb.unref();
}
function stop() {
+ if (!progressed) {
+ w('deadline reached (' + Math.round(deadlineMs/1000) + 's) and the run committed nothing — a stall, not progress; sending SIGTERM for graceful shutdown');
+ if (stallNotice) { try { writeSync(1, stallNotice + '\\n'); } catch (e) {} }
+ try { process.kill(process.pid, 'SIGTERM'); } catch (e) {}
+ setTimeout(() => {
+ w('grace expired — sending SIGKILL (event loop was starved; this is the orphan-pileup backstop)');
+ try { process.kill(process.pid, 'SIGKILL'); } catch (e) {}
+ }, graceMs);
+ return;
+ }
if (progressWindowMs > 0) {
w('deadline reached (' + Math.round(deadlineMs/1000) + 's) and no progress for ' + Math.round((Date.now() - lastProgress) / 1000) + 's — sending SIGTERM for graceful shutdown');
} else {
@@ -198,7 +219,7 @@ function check() {
const since = now - lastProgress;
// mirrors progressDeadlineDecision
if (now - t0 < deadlineMs) { setTimeout(check, deadlineMs - (now - t0)); return; }
- if (progressWindowMs > 0 && since < progressWindowMs) {
+ if (progressWindowMs > 0 && progressed && since < progressWindowMs) {
if (!extended) w('deadline reached (' + Math.round(deadlineMs/1000) + 's) but the run is still progressing (last progress ' + Math.round(since / 1000) + 's ago) — extending; it stops after ' + Math.round(progressWindowMs / 1000) + 's without progress');
extended = true;
setTimeout(check, progressWindowMs - since);
@@ -227,13 +248,15 @@ export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandl
const heartbeatMs = Math.max(0, Math.floor(opts.heartbeatMs ?? 0));
const progressWindowMs = Math.min(MAX_WATCHDOG_TIMER_MS, Math.max(0, Math.floor(Number.isFinite(opts.progressWindowMs) ? opts.progressWindowMs! : 0)));
const stopNotice = opts.stopNotice ?? '';
+ const committed = opts.progressSignal === 'committed';
+ const stallNotice = opts.stallNotice ?? stopNotice;
if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) return INERT;
try {
const worker = new Worker(WORKER_SRC, {
eval: true,
- workerData: { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice },
+ workerData: { deadlineMs, graceMs, label, heartbeatMs, progressWindowMs, stopNotice, stallNotice, requireProgress: committed && progressWindowMs > 0 },
});
// Don't let the watchdog keep the process alive past clean completion.
(worker as unknown as { unref?: () => void }).unref?.();
@@ -244,7 +267,7 @@ export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandl
// traffic when the worker only compares against a window of minutes.
const throttleMs = Math.max(10, Math.min(1000, Math.floor(progressWindowMs / 4)));
let lastPost = 0;
- const unsubscribe = progressWindowMs > 0 ? onForwardProgress(() => {
+ const unsubscribe = progressWindowMs > 0 ? (committed ? onCommittedProgress : onForwardProgress)(() => {
const now = Date.now();
if (now - lastPost < throttleMs) return;
lastPost = now;
@@ -272,14 +295,17 @@ export function installProcessWatchdog(opts: ProcessWatchdogOpts): WatchdogHandl
let term: ReturnType<typeof setTimeout>;
const check = () => {
const now = Date.now();
- const since = now - Math.max(t0, lastForwardProgressAt());
- const action = progressDeadlineDecision(now - t0, deadlineMs, since, progressWindowMs);
+ const last = committed ? lastCommittedProgressAt() : lastForwardProgressAt();
+ const progressed = !committed || progressWindowMs <= 0 || last > t0;
+ const since = now - Math.max(t0, last);
+ const action = progressDeadlineDecision(now - t0, deadlineMs, since, progressWindowMs, progressed);
if (action !== 'stop') {
term = setTimeout(check, action === 'wait' ? deadlineMs - (now - t0) : progressWindowMs - since);
(term as unknown as { unref?: () => void }).unref?.();
return;
}
- if (stopNotice) { try { process.stdout.write(stopNotice + '\n'); } catch { /* */ } }
+ const notice = progressed ? stopNotice : stallNotice;
+ if (notice) { try { process.stdout.write(notice + '\n'); } catch { /* */ } }
try { process.kill(process.pid, 'SIGTERM'); } catch { /* */ }
kill = setTimeout(() => { killed = true; try { process.kill(process.pid, 'SIGKILL'); } catch { /* */ } }, graceMs);
(kill as unknown as { unref?: () => void }).unref?.();
diff --git a/src/core/serve-head-watcher.ts b/src/core/serve-head-watcher.ts
index 39a20c4252..d4a5cf3f85 100644
--- a/src/core/serve-head-watcher.ts
+++ b/src/core/serve-head-watcher.ts
@@ -52,7 +52,7 @@ export interface ServeHeadWatcherOptions {
revParse?: (root: string) => Promise<string>;
quiet?: (source: WatchedSource) => boolean;
syncRunning?: () => boolean | Promise<boolean>;
- drainHeld?: (sourceId: string) => Promise<boolean>;
+ drainHeld?: (sourceId: string) => Promise<boolean | 'stalled'>;
startSync?: (sourceId: string, req: StartRequest) => Promise<OnCommitStart>;
jobStatus?: (jobId: string) => OnCommitJobStatus | null;
watch?: (gitDir: string, onChange: () => void) => (() => void) | null;
diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.ts
index 3b8a7c16b2..e7076e7869 100644
--- a/src/core/sync-reconcile.ts
+++ b/src/core/sync-reconcile.ts
@@ -295,14 +295,14 @@ export function resolveSyncHardDeadline(
* and the stderr line announcing it.
*/
export function syncWatchdogPlan(args: string[], res: HardDeadlineResolution): {
- watchdog: { deadlineMs: number; graceMs: number; label: string; heartbeatMs: number; progressWindowMs?: number; stopNotice: string };
+ watchdog: { deadlineMs: number; graceMs: number; label: string; heartbeatMs: number; progressWindowMs?: number; stopNotice: string; progressSignal: 'committed'; stallNotice: string };
armedLine: string;
} {
return {
watchdog: { deadlineMs: res.deadlineMs, graceMs: res.graceMs, label: 'sync-watchdog', heartbeatMs: 60_000,
- progressWindowMs: res.progressWindowMs, stopNotice: syncDeadlineStopNotice(args, res) },
+ progressWindowMs: res.progressWindowMs, stopNotice: syncDeadlineStopNotice(args, res), progressSignal: 'committed', stallNotice: syncDeadlineStallNotice(args, res) },
armedLine: `[sync-watchdog] hard deadline armed: ${Math.round(res.deadlineMs / 1000)}s + ${Math.round(res.graceMs / 1000)}s grace (${res.reason})` +
- (res.progressWindowMs ? `; extends while the sync keeps progressing (stops after ${Math.round(res.progressWindowMs / 1000)}s without progress)` : '') +
+ (res.progressWindowMs ? `; extends while the sync keeps committing pages (stops after ${Math.round(res.progressWindowMs / 1000)}s without a commit)` : '') +
'; disable with --no-hard-deadline\n',
};
}
@@ -351,6 +351,30 @@ export function syncDeadlineStopNotice(args: string[], res: HardDeadlineResoluti
return `gbrain sync stopped (code=sync_deadline_stop): ${cause}. ${fix}`;
}
+/**
+ * GBRA-133 PR 3a: the stdout notice the sync watchdog prints when a progress-aware deadline passes and the run committed
+ * nothing (no page written, deleted or renamed, no cursor advanced; screening unchanged files and legacy-sweep slices do
+ * not count). The run is a stall, not progress: `code`, `why` and an agent-operator `fix` (read-only sync status, which
+ * names what the run is stuck on) instead of the resume line, since rerunning the same way commits nothing again.
+ */
+export function syncDeadlineStallNotice(args: string[], res: HardDeadlineResolution): string {
+ const deadlineSec = Math.round(res.deadlineMs / 1000);
+ const source = args.find((_, i) => args[i - 1] === '--source');
+ const status = ['gbrain', 'sync', 'status', ...(source ? ['--source', source] : []), '--json'];
+ const resume = syncResumeCommand(args);
+ const message = `The ${deadlineSec}s sync deadline (${res.reason}) passed and the run committed nothing.`;
+ const why = 'No page was written, deleted or renamed and no sync cursor advanced before the deadline (screening unchanged files and legacy-sweep slices '
+ + 'are not progress), so the run stopped as a stall instead of extending. Rerunning the same way is unlikely to commit either; sync status names what '
+ + `the source is stuck on (read-only). Fix what it names, then rerun: ${resume}`;
+ const fix = { next: 'run', argv: status, command: status.join(' '), actor: 'agent', consent: [], requires_exclusive: false,
+ why: 'Read-only: the source\'s state, holds, last error and the next step.', verify: { argv: status } };
+ if (args.includes('--json')) {
+ return JSON.stringify({ status: 'stalled', code: 'sync_deadline_stalled', message, why, reason: res.reason, deadline_seconds: deadlineSec, committed: 0,
+ resume_command: resume, docs: 'docs/guides/error-codes.md#sync_deadline_stalled', fix });
+ }
+ return `gbrain sync stopped (code=sync_deadline_stalled): ${message} ${why} Fix: ${fix.command}`;
+}
+
/**
* Compose 1..N AbortSignals into one (CQ2). Undefined inputs are dropped; the
* result aborts when ANY input aborts. Returns a single signal directly (no
diff --git a/test/error-registry-6317-contract.test.ts b/test/error-registry-6317-contract.test.ts
index 9f63a33f35..12a2ee65a6 100644
--- a/test/error-registry-6317-contract.test.ts
+++ b/test/error-registry-6317-contract.test.ts
@@ -95,7 +95,8 @@ describe('#6317 codes are registered with a full envelope', () => {
describe('drain_stalled: the same-host stop has a cause vocabulary and a filled writer-status fix', () => {
test('owner_wedged_here is a registered reason beside the earlier causes, and the row says what changed', () => {
const entry = CODES.drain_stalled as CodeEntry;
- expect(entry.reasons).toEqual(['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress']);
+ // GBRA-133 PR 3a: `owner_restart_required` is a stop whose head owner's own heartbeat row reports restart_required.
+ expect(entry.reasons).toEqual(['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress', 'owner_restart_required']);
// #6712 PR 2: the in-pass governor's no-admission stop (#6423) is `no_progress` now; the retired reason keeps its tombstone.
expect(entry.retired_reasons).toEqual({ no_admission: '0.60.266.0' });
expect(entry.why).toContain('owner_wedged_here');
diff --git a/test/fixtures/watchdog-harness.ts b/test/fixtures/watchdog-harness.ts
index 7f8bcd2f31..476ba4dbe2 100644
--- a/test/fixtures/watchdog-harness.ts
+++ b/test/fixtures/watchdog-harness.ts
@@ -32,10 +32,17 @@
* after the last progress note, after printing the
* STOP-NOTICE stop notice on stdout.
*
+ * Committed-progress modes (GBRA-133 PR 3a) — argv[5] is the progress window in ms;
+ * the watchdog counts only noteCommittedProgress:
+ * screen-only — report forward progress only (screening) for 4x the deadline.
+ * Must be SIGTERMed at the deadline after printing STALL-NOTICE.
+ * commit-with — report committed progress for 4x the deadline. Must NOT be
+ * stopped; prints COMPLETED.
+ *
* Safety net: the busy loop self-exits after 8s so a failed test kill can't hang CI.
*/
import { installProcessWatchdog, installLoopStallWatchdog } from '../../src/core/process-watchdog.ts';
-import { noteForwardProgress } from '../../src/core/forward-progress.ts';
+import { noteCommittedProgress, noteForwardProgress } from '../../src/core/forward-progress.ts';
const mode = process.argv[2] ?? 'starve-with';
const deadlineMs = Number(process.argv[3] ?? 300);
@@ -97,6 +104,16 @@ if (mode.startsWith('progress-')) {
process.exit(0);
}
+if (mode === 'screen-only' || mode === 'commit-with') {
+ const progressWindowMs = Number(process.argv[5] ?? 400);
+ installProcessWatchdog({ deadlineMs, graceMs, label: 'test-wd', progressWindowMs, stopNotice: 'STOP-NOTICE', progressSignal: 'committed', stallNotice: 'STALL-NOTICE' });
+ const note = mode === 'commit-with' ? noteCommittedProgress : noteForwardProgress;
+ const t0 = Date.now();
+ while (Date.now() - t0 < deadlineMs * 4) { note(); await new Promise((r) => setTimeout(r, 25)); }
+ process.stdout.write('COMPLETED\n');
+ process.exit(0);
+}
+
if (mode === 'starve-with' || mode === 'clean-dispose') {
const handle = installProcessWatchdog({ deadlineMs, graceMs, label: 'test-wd' });
if (mode === 'clean-dispose') {
diff --git a/test/honest-stalls-gbra133.test.ts b/test/honest-stalls-gbra133.test.ts
new file mode 100644
index 0000000000..40f34deee8
--- /dev/null
+++ b/test/honest-stalls-gbra133.test.ts
@@ -0,0 +1,211 @@
+/**
+ * GBRA-133 PR 3a: truthful status and honest stalls. Progress means committed work (a page written, deleted or renamed, a
+ * cursor advanced); screening unchanged files and legacy-sweep slices are not. What it protects:
+ * - a progress-aware deadline never extends a run that committed nothing: the delegated deadline and the watchdog stop it
+ * as a coded stall (`sync_deadline_stalled`, with why and a read-only fix), never "still progressing";
+ * - the drain notes committed progress only for commits; a legacy-sweep slice keeps the governor from calling the pass hung
+ * but extends no deadline; once the governor stops a pass, its late progress events reach no listener;
+ * - a drain stop whose head owner reports restart_required is `owner_restart_required`, with the owner row and a next step
+ * that names the process to restart;
+ * - the commit notifier counts a run that committed pages as progress, and a drain-lease holder that commits nothing is a
+ * failed attempt (`drain_holder_stalled`) that runs the retry tiers to notifier_stalled instead of a silent defer.
+ * Synthetic content only.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+import { DelegatedSyncDeadline } from '../src/commands/sync-persistence-delegate.ts';
+import { noteCommittedProgress, noteForwardProgress, onCommittedProgress, onForwardProgress, registerRunDeadline } from '../src/core/forward-progress.ts';
+import { progressDeadlineDecision } from '../src/core/process-watchdog.ts';
+import { syncDeadlineStallNotice, syncWatchdogPlan } from '../src/core/sync-reconcile.ts';
+import { drainNext, formatDrainSummary, runDrain, type DrainClaim, type DrainOwnerRow, type StallProbe } from '../src/core/persistence/sync-drain.ts';
+import { startServeHeadWatcher, type OnCommitJobStatus, type ServeHeadWatcherOptions } from '../src/core/serve-head-watcher.ts';
+import { RETRY_BACKOFF_MS } from '../src/core/commit-notifier.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { memoryNotifierStore } from './helpers/notifier-memory-store.ts';
+
+afterEach(() => registerRunDeadline(null));
+
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+const base: SyncResult = { status: 'partial', reason: 'writer_yield', fromCommit: null, toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+const screened = (settled: number): SyncResult => ({ ...base,
+ pass: { pass_id: 'pass-example', kind: 'full', round: 1, outcome: 'partial', stop_reason: 'writer_yield', candidates: settled + 5, settled, remaining: 5, not_converged_streak: 0 } as SyncResult['pass'] });
+
+describe('a deadline never extends a run that committed nothing', () => {
+ test('progressDeadlineDecision: past the deadline, a run that committed nothing stops even with a fresh progress note', () => {
+ expect(progressDeadlineDecision(5000, 1000, 0, 500, true)).toBe('extend');
+ expect(progressDeadlineDecision(5000, 1000, 0, 500, false)).toBe('stop');
+ expect(progressDeadlineDecision(999, 1000, 0, 500, false)).toBe('wait');
+ });
+
+ test('the delegated deadline: passes that only screen paths stop the run at the deadline as sync_deadline_stalled', async () => {
+ const lines: string[] = [];
+ const deadline = new DelegatedSyncDeadline(150, 600, line => lines.push(line));
+ try {
+ await sleep(60);
+ deadline.noteSlice(screened(40));
+ await sleep(60);
+ deadline.noteSlice(screened(80));
+ await sleep(200);
+ expect(deadline.stop.signal.aborted).toBe(true);
+ expect(deadline.stalled).toBe(true);
+ expect(lines.join('\n')).toContain('code=sync_deadline_stalled');
+ expect(lines.join('\n')).not.toContain('still committing');
+ } finally { deadline.dispose(); }
+ });
+
+ test('the delegated deadline: a pass that committed a page extends it and is no stall', async () => {
+ const lines: string[] = [];
+ const deadline = new DelegatedSyncDeadline(150, 400, line => lines.push(line));
+ try {
+ await sleep(100);
+ deadline.noteSlice({ ...screened(3), modified: 1 });
+ await sleep(150);
+ expect(deadline.stop.signal.aborted).toBe(false);
+ expect(lines.join('\n')).toContain('still committing');
+ await sleep(450);
+ expect(deadline.stop.signal.aborted).toBe(true);
+ expect(deadline.stalled).toBe(false);
+ } finally { deadline.dispose(); }
+ });
+
+ test('the sync watchdog listens for commits only and carries a coded stall notice (human and --json)', () => {
+ const res = { deadlineMs: 3_600_000, graceMs: 30_000, reason: 'non-TTY default', progressWindowMs: 900_000 };
+ const plan = syncWatchdogPlan(['--source', 'source-a', '--no-pull'], res);
+ expect(plan.watchdog.progressSignal).toBe('committed');
+ expect(plan.watchdog.stallNotice).toContain('code=sync_deadline_stalled');
+ expect(plan.watchdog.stallNotice).toContain('committed nothing');
+ expect(plan.watchdog.stallNotice).toContain('Fix: gbrain sync status --source source-a --json');
+ expect(plan.armedLine).toContain('extends while the sync keeps committing pages');
+ const json = JSON.parse(syncDeadlineStallNotice(['--source', 'source-a', '--no-pull', '--json'], res));
+ expect(json).toMatchObject({ status: 'stalled', code: 'sync_deadline_stalled', committed: 0, deadline_seconds: 3600,
+ fix: { next: 'run', argv: ['gbrain', 'sync', 'status', '--source', 'source-a', '--json'] }, docs: 'docs/guides/error-codes.md#sync_deadline_stalled' });
+ expect(json.why).toContain('legacy-sweep slices');
+ expect(CODES.sync_deadline_stalled.fix.argv).toEqual(['gbrain', 'sync', 'status', '--source', '{source_id}', '--json']);
+ });
+
+ test('forward progress (screening) is not committed progress; a commit is both', () => {
+ let forward = 0, committed = 0;
+ const offForward = onForwardProgress(() => forward++), offCommitted = onCommittedProgress(() => committed++);
+ try {
+ noteForwardProgress();
+ expect([forward, committed]).toEqual([1, 0]);
+ noteCommittedProgress();
+ expect([forward, committed]).toEqual([2, 1]);
+ } finally { offForward(); offCommitted(); }
+ });
+});
+
+describe('drain: only commits are progress, and a stopped pass reports nothing late', () => {
+ const done: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+ const publishing = (ageMs: number): DrainClaim => ({ phase: 'publishing', step: 'group_commit', waiting_on: 'publication', step_age_ms: ageMs, claim_age_ms: ageMs, lapsed: false,
+ owner_pid: 4242, owner_kind: 'serve', owner_nonce: 'n1', last_sql: null, allowance_ms: 150_000, ceiling_ms: 600_000 });
+
+ test('a legacy-sweep slice is not committed progress; a page commit is', async () => {
+ let committed = 0;
+ const off = onCommittedProgress(() => committed++);
+ try {
+ const swept = await runDrain({ pauseMs: 1, pass: async (_signal, onProgress) => { onProgress?.({ phase: 'managed_sync.legacy_swept' } as never); return done; } });
+ expect(swept.drain?.outcome).toBe('synced');
+ expect(committed).toBe(0);
+ await runDrain({ pauseMs: 1, pass: async (_signal, onProgress) => { onProgress?.({ phase: 'managed_sync.page_committed' } as never); return done; } });
+ expect(committed).toBe(1);
+ } finally { off(); }
+ });
+
+ test('after the governor stops a pass, its late progress events reach no deadline listener and no count', async () => {
+ let report!: (event: unknown) => void;
+ const started = Date.now();
+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => null, head: async () => ({ head_state: 'running', request_id: 'req-head', claim: publishing(Date.now() - started) }) };
+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 30, probe,
+ pass: (_signal, onProgress) => { report = event => onProgress?.(event as never); return new Promise<SyncResult>(() => undefined); } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'publication_overdue', in_pass: true } });
+ let forward = 0;
+ const off = onForwardProgress(() => forward++);
+ try {
+ report({ phase: 'managed_sync.page_committed' });
+ report({ phase: 'managed_sync.finish' });
+ await sleep(20);
+ expect(forward).toBe(0);
+ } finally { off(); }
+ });
+
+ test('a stop whose head owner reports restart_required is owner_restart_required, naming the process to restart', async () => {
+ const started = Date.now();
+ const row: DrainOwnerRow = { kind: 'serve', pid: 4242, nonce: 'n1', mode: 'resident', live: true, restart_required: true, root_barrier_age_ms: 700_000 };
+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => null, owner: async () => row,
+ head: async () => ({ head_state: 'running', request_id: 'req-head', claim: publishing(Date.now() - started) }) };
+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 30, probe, pass: () => new Promise<SyncResult>(() => undefined) });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',
+ stall: { cause: 'owner_restart_required', in_pass: true, head_request_id: 'req-head', owner_row: { pid: 4242, restart_required: true } } });
+ const next = drainNext(result, 'gbrain sync --source source-a --no-pull', 'source-a')!;
+ expect(next).toMatchObject({ code: 'drain_stalled', cause: 'owner_restart_required', safe_to_loop: false, command: 'gbrain sources writer status --source source-a --json' });
+ expect(next.why).toContain('the gbrain serve process (pid 4242)');
+ expect(next.why).toContain('reports restart_required');
+ expect(next.fix?.user_message).toContain('Restart the gbrain serve process (pid 4242)');
+ expect(formatDrainSummary(result, 'gbrain sync --source source-a --no-pull', 'source-a').join('\n')).toContain('cause=owner_restart_required');
+ expect(CODES.drain_stalled.reasons as readonly string[]).toContain('owner_restart_required');
+ });
+
+ test('an owner that does not report restart_required keeps the stop as it was', async () => {
+ const started = Date.now();
+ const probe: StallProbe = { blockedHead: async () => null, fingerprint: async () => null,
+ owner: async () => ({ kind: 'serve', pid: 4242, nonce: 'n1', mode: 'resident', live: true, restart_required: false, root_barrier_age_ms: null }),
+ head: async () => ({ head_state: 'running', request_id: 'req-head', claim: publishing(Date.now() - started) }) };
+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 30, probe, pass: () => new Promise<SyncResult>(() => undefined) });
+ expect(result.drain?.stall?.cause).toBe('publication_overdue');
+ });
+});
+
+describe('commit notifier: committed runs are progress, and a stalled lease holder is acted on', () => {
+ const sha = (c: string) => c.repeat(40);
+ const A = sha('a'), B = sha('b'), QUIET = 400;
+ function harness(over: Partial<ServeHeadWatcherOptions> = {}) {
+ const s = { t: 1_000_000, head: A, dbCommit: A as string | null, held: false as boolean | 'stalled', starts: [] as string[], jobs: new Map<string, OnCommitJobStatus>(), lines: [] as string[] };
+ const store = memoryNotifierStore({ lastCommit: () => s.dbCommit });
+ const w = startServeHeadWatcher({} as BrainEngine, {
+ log: line => s.lines.push(line), pollMs: 3000, debounceMs: QUIET, hostId: 'host-example', store, now: () => s.t,
+ setInterval: () => 'interval', clearInterval: () => {}, setTimeout: () => 'timer', clearTimeout: () => {},
+ readFlag: async () => true,
+ listSources: async () => [{ sourceId: 'acme-example', root: '/brains/acme-example', gitDir: null, lastCommit: s.dbCommit }],
+ lastCommit: async () => s.dbCommit, revParse: async () => s.head, syncRunning: () => false, drainHeld: async () => s.held,
+ startSync: async () => { const jobId = 'job-' + (s.starts.length + 1); s.starts.push(jobId); s.jobs.set(jobId, { state: 'running' }); return { jobId }; },
+ jobStatus: jobId => s.jobs.get(jobId) ?? null,
+ ...over,
+ });
+ return { w, s, store, decisions: (kind: string) => w.decisions.filter(d => d.decision === kind), advance: (ms: number) => { s.t += ms; } };
+ }
+
+ test('a resumable run that committed pages resumes even though last_commit has not moved yet', async () => {
+ const h = harness();
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ h.s.jobs.set('job-1', { state: 'done', outcome: 'resumable', reason: 'deadline', committed: true });
+ h.advance(QUIET); await h.w.tick();
+ h.advance(QUIET); await h.w.tick();
+ expect(h.decisions('resume')).toHaveLength(1);
+ expect(h.decisions('retry')).toEqual([]);
+ expect(h.s.starts).toEqual(['job-1', 'job-2']);
+ });
+
+ test('a drain-lease holder that commits nothing is a failed attempt: the retry tiers run to notifier_stalled with the sync-now fix', async () => {
+ const h = harness();
+ h.s.held = 'stalled';
+ await h.w.tick();
+ h.s.head = B; await h.w.tick();
+ for (const wait of [...RETRY_BACKOFF_MS, RETRY_BACKOFF_MS.at(-1)!]) { h.advance(wait); await h.w.tick(); }
+ expect(h.s.starts).toEqual([]);
+ expect(h.decisions('defer_drain_lease')).toEqual([]);
+ expect(h.decisions('retry').map(d => d.detail)[0]).toBe('drain_holder_stalled');
+ expect(h.decisions('stalled').length).toBeGreaterThan(0);
+ expect(h.store.states.get('acme-example')).toMatchObject({ state: 'retry', reason: 'notifier_stalled', last_error_code: 'notifier_stalled' });
+ expect(h.s.lines.filter(l => l.includes('notifier_stalled') && l.includes('drain_holder_stalled'))).toHaveLength(1);
+ expect(h.s.lines.some(l => l.includes('gbrain sync --source acme-example --no-pull'))).toBe(true);
+ expect(CODES.drain_holder_stalled.docs).toBe('docs/guides/on-commit-sync.md#notifier-stalled');
+ // The holder recovers (a live, committing holder): the source is deferred to it again, never started beside it.
+ h.s.held = true;
+ h.advance(RETRY_BACKOFF_MS.at(-1)!); await h.w.tick();
+ expect(h.decisions('defer_drain_lease').length).toBeGreaterThan(0);
+ expect(h.s.starts).toEqual([]);
+ });
+});
diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.ts
index 752a25292c..7af1b257f0 100644
--- a/test/persistence-sync-checkpoint-validation.test.ts
+++ b/test/persistence-sync-checkpoint-validation.test.ts
@@ -241,7 +241,7 @@ test('#5762 a lock timeout in the validation stays transient contention', async
const f = await fixture(engine);
const restore = failValidation(engine, 'lock');
// The checkpoint as the pass left it, read under the pass's drain lease. A later attempt of the same request, after the
- // pass released the lease, is refused revision_conflict (PASS_LEASE_LOST_MESSAGE) by design, so the row is not read afterwards.
+ // pass released the lease, is refused sync_pass_superseded (PASS_LEASE_LOST_MESSAGE) by design, so the row is not read afterwards.
let result: Awaited<ReturnType<typeof performManagedSync>> | undefined;
try { result = await performManagedSync(engine, f.opts); }
finally { await disposePersistenceConsumer(engine); restore(); }
@@ -251,6 +251,33 @@ test('#5762 a lock timeout in the validation stays transient contention', async
expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
}), 180_000);
+test('GBRA-133 PR 3a a pass checkpoint left pending when its pass ends is superseded: no resume advice, no terminal write failure', async () => each(async engine => {
+ const f = await fixture(engine);
+ const restore = failValidation(engine, 'lock');
+ let result: Awaited<ReturnType<typeof performManagedSync>> | undefined;
+ try { result = await performManagedSync(engine, f.opts); }
+ finally { await disposePersistenceConsumer(engine); restore(); }
+ const pending = result!.managedWrite!;
+ expect(pending).toMatchObject({ write_error: 'write_pending', reason: 'database_contention', disposition: 'superseded' });
+ expect(pending.suggestion).not.toContain('Re-run the same sync options to resume this request');
+ expect(pending.suggestion).toContain('the next sync pass re-reads the source and stamps its own checkpoint');
+ const requestId = pending.write_request.request_id;
+ // The next pass runs after the first one released its drain lease: the stale checkpoint is refused as superseded and the source converges.
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ await disposePersistenceConsumer(engine);
+ const [row] = await engine.executeRaw<{ state: string; error_code: string | null }>('SELECT state, error_code FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ expect(row).toEqual({ state: 'conflict', error_code: 'sync_pass_superseded' });
+ const { readTerminalFailures, readTerminalFailureSummary } = await import('../src/core/persistence/terminal-failures.ts');
+ const unresolved = await readTerminalFailures(engine, { sourceId: f.id });
+ expect(unresolved.status === 'ok' ? unresolved.rows!.map(r => r.request_id) : unresolved).toEqual([]);
+ const all = await readTerminalFailures(engine, { sourceId: f.id, state: 'all' });
+ expect(all.status === 'ok' ? all.rows!.filter(r => r.request_id === requestId).map(r => ({ code: r.code, disposition: r.disposition, historical: r.historical })) : all)
+ .toEqual([{ code: 'sync_pass_superseded', disposition: 'superseded', historical: true }]);
+ const summary = await readTerminalFailureSummary(engine, { sourceIds: [f.id] });
+ expect(summary.status === 'ok' ? summary.sources.map(s => ({ source_id: s.source_id, unresolved: s.unresolved.rows, blockers: s.active_blockers.length })) : summary)
+ .toEqual([{ source_id: f.id, unresolved: 0, blockers: 0 }]);
+}), 180_000);
+
test('#5762 the hint names one of three index states and keeps the saved processing flags', async () => {
const syncOptions = { full: false, workingTree: true, srcSubpath: null, exclude: [], includeHidden: [], strategy: null };
const input = { requestId: 'req-1', sourceId: 'notes', processingOptions: { noEmbed: true, noExtract: false, noSchemaPack: true }, syncOptions };
diff --git a/test/process-watchdog-harness.test.ts b/test/process-watchdog-harness.test.ts
index 04ba7eeb6d..3c8fa16fae 100644
--- a/test/process-watchdog-harness.test.ts
+++ b/test/process-watchdog-harness.test.ts
@@ -93,6 +93,30 @@ describe('progress-aware deadline integration (Bun-pinned)', () => {
}, 15000);
});
+// GBRA-133 PR 3a: the sync watchdog counts only committed work. A run that screens for its whole deadline and commits
+// nothing is stopped at the deadline with the stall notice, never extended as "still progressing".
+describe('committed-progress deadline integration (Bun-pinned)', () => {
+ test('a run that only screens (forward progress, no commit) is stopped at the deadline with the stall notice', async () => {
+ const r = await runHarness('screen-only', 300, 150, 6000, 400);
+ expect(r.killedByTest).toBe(false);
+ expect(r.signalled).toBe(true);
+ expect(r.stdout).toContain('STALL-NOTICE');
+ expect(r.stdout).not.toContain('STOP-NOTICE');
+ expect(r.stdout).not.toContain('COMPLETED');
+ expect(r.stderr).toContain('committed nothing');
+ expect(r.stderr).not.toContain('still progressing');
+ }, 15000);
+
+ test('a run that keeps committing past the deadline is never stopped', async () => {
+ const r = await runHarness('commit-with', 300, 150, 6000, 400);
+ expect(r.killedByTest).toBe(false);
+ expect(r.exitCode).toBe(0);
+ expect(r.stdout).toContain('COMPLETED');
+ expect(r.stdout).not.toContain('STALL-NOTICE');
+ expect(r.stderr).toContain('still progressing');
+ }, 15000);
+});
+
describe('loop-stall watchdog integration (Bun-pinned, #4281)', () => {
test('starved loop with a SIGTERM listener is SIGTERMed then SIGKILLed around stall+grace', async () => {
// stall 300 + grace 250 = ~550ms expected death (plus worker boot). The
diff --git a/test/sync-pass-reader-gaps-6712.test.ts b/test/sync-pass-reader-gaps-6712.test.ts
index d36917b005..a3a37afd53 100644
--- a/test/sync-pass-reader-gaps-6712.test.ts
+++ b/test/sync-pass-reader-gaps-6712.test.ts
@@ -6,8 +6,8 @@
* (`passResumeArgs`), so a scheduled re-screen does not drop the `--no-embed --no-extract` the episode carries;
* - a drain that ends on a pass result reports `drain.remaining` from that pass (`result.pass.remaining`), not from a
* cursor the pass never returns;
- * - a delegated sync's progress-aware deadline extends while the owner's passes settle paths (`result.pass.settled`),
- * as it did while a cursor index advanced.
+ * - a delegated sync's progress-aware deadline extends while the owner's passes commit pages, as it did while a cursor
+ * index advanced; GBRA-133 PR 3a: a pass that only settled paths (screened them unchanged) is not progress.
* Synthetic content only.
*/
import { afterEach, describe, expect, test } from 'bun:test';
@@ -56,17 +56,18 @@ describe('#6712 PR 4b lane C: cursor readers on the pass', () => {
expect(result.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'deadline', passes: 1, remaining: 6 });
});
- test('a delegated deadline extends while the owner\'s passes settle paths, and stops once they settle none', async () => {
+ test('a delegated deadline extends while the owner\'s passes commit pages, and stops once they settle paths without committing', async () => {
const lines: string[] = [];
- // A 600 ms deadline with a 400 ms progress window: a slice that settles paths at 450 ms carries the run past 600 ms (to 850 ms).
+ // A 600 ms deadline with a 400 ms progress window: a slice that commits a page at 450 ms carries the run past 600 ms (to 850 ms).
const deadline = new DelegatedSyncDeadline(600, 400, line => lines.push(line));
try {
await new Promise(resolve => setTimeout(resolve, 450));
deadline.noteSlice(passResult(3, 5));
await new Promise(resolve => setTimeout(resolve, 350));
expect(deadline.stop.signal.aborted).toBe(false);
- expect(lines.join('\n')).toContain('still progressing');
- deadline.noteSlice(passResult(0, 5));
+ expect(lines.join('\n')).toContain('still committing');
+ // GBRA-133 PR 3a: this slice settled paths but committed none (screened unchanged): no extension.
+ deadline.noteSlice({ ...passResult(3, 2), added: 0 });
await new Promise(resolve => setTimeout(resolve, 500));
expect(deadline.stop.signal.aborted).toBe(true);
} finally { deadline.dispose(); }