Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a killed or crashed pass reads pass_interrupted in sync status and doctor (#7596)

garrytan5afbe04f4841
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index d796841e07..903fb69277 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -14,7 +14,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/managed-sync-orphans.ts` + `src/core/repair/managed-sync-orphans.ts` — `gbrain repair managed-sync-orphans --source <id>` (#5459), explicit-only and preview-bound (approved set, `preview_changed` on drift). `classifyManagedSyncOrphans` (read-only; doctor `sync_failures` names the repair when it finds any) takes the source's managed-sync bookkeeping and classes each row `no_cursor` (a failure row with no cursor to resume), `principal_unadoptable` (an unfinished cursor recorded by a principal that is no longer an active local writer, by join on the recorded principal), `superseded` (a pre-options cursor a later run replaced), `incarnation_retired` (#6518: an unfinished cursor or a failure row recorded under a source incarnation the source no longer has, joined on the source id alone, archived sources excluded, a live pending request still retaining it) or `mirror_only` (#6518: a local ledger row with a `managed_cursor_key` and no durable failure row under that key; `mirrorOnlyManagedFailures`, which throws on a failed durable read rather than naming every mirror), and keeps `pending_request_live` and `resumable` rows untouched. `retireManagedSyncOrphan` retires one row atomically: an `incarnation_retired` cursor needs the source still active under another incarnation at apply time and skips the live-writer veto (no retired key is resumable); a `mirror_row` deletes nothing durable and prunes the ledger row only when the durable read, repeated at apply, still finds none. `pruneMirrorOnlyManagedFailures` is the successful-sync path (`clearSettledManagedSyncFailures`). Doctor `sync_failures` classifies whenever the brain is reachable, so the diagnostic is reachable with no current-incarnation failure visible, and reports a failed classification as unknown. `sources set-strategy` points at it when an unfinished run blocks a strategy change. Pinned by `test/repair-managed-sync-orphans.test.ts` and `test/managed-sync-orphans-incarnation-6518.test.ts` (both engines); `test/repair-explicit-only.test.ts` pins its place last in `REPAIR_KINDS`. #6712 PR 3 (L7): `slug_mode_refused` is an unfinished cursor whose every page committed and whose checkpoint was refused `slug_root_mode_mismatch` while the source still pins the other mode (`slugModeRefusedSql`, bound to the run and request at apply); no sync rediscovers it, so retiring it is how a person keeps the pin, and its slice record is cleared like `checkpoint_moved`'s.
- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/sync-pass-handover-6712.test.ts` (the live pass's handover of an older binary's cursors) and `test/persistence-sync-cursor-strategy-6696.test.ts`.
-- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. Pinned by `test/persistence-sync-lease.test.ts`.
+- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. #7596: `drainHolderLive` is `isLockHolderLive`'s rule at the drain TTL; a killed holder's lock row outlives it until a takeover, so status reads it as not live. Pinned by `test/persistence-sync-lease.test.ts`.
- `src/core/persistence/sync-idle-skips.ts` — GBRA-133 (PR 2b): the managed no-op fast path. An idle tick (`stampIdlePass`) records on the drain lease (`idleClear`) whether its pin read no hold of the incarnation, a zero hold summary, no `managed-sync-failure` row of the source and no owed tail (`readIdleFacts` rides the pin's round trip). `idleSkips` names the settles that then have nothing to do (`IDLE_SKIPS`: the hold report in `performManagedPass`; settled failures, which also needs no ledger row of the source; the needs-human sweep, the sync tail and both heals in `perform.ts`). The tick, its lease, its pass row and its result are unchanged; the upstream observation, the remember replay and the ghost-page report still run. `GBRAIN_SYNC_IDLE_FAST_PATH=0` runs every settle. Pinned by `test/sync-idle-skips-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).
- `src/core/sync-dispatch-read.ts` — GBRA-133 (PR 2b): the routing read of a single-source CLI sync. `withSyncDispatchRead` (`src/commands/sync/run.ts`, never `--all` or `--watch`) answers the source resolver, the company profile, `resolveSyncPersistenceMode`, the content-directory anchor, the managed-flag refusals, the delegation ladder's mode check and `perform.ts`'s connector check from one combined row per source (`syncDispatchRow`: the sources row, the claim, the company receipt and the mode rows). `endSyncDispatchRead` ends the scope for good where the work starts (`performSync` once the route is chosen, `maybeDelegateManagedSyncToServe` before the hand-off), so every read under the drain lease and after a write stays live; outside the scope, or when the combined read fails, each reader runs its own query. Pinned by `test/sync-dispatch-read-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).
- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).
@@ -48,7 +48,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/commands/doctor/checks/managed-sync-movement.ts` + `src/core/persistence/sync-movement.ts` — #6317 (B4, I2): the movement reader and its doctor check. `readManagedSyncMovement` snapshots, per active managed source, the newest `completed_at` of committed `managed_sync_*` receipts in the current source incarnation (the watermark: one probe of the partial index `persistence_requests_sync_watermark`, v223; a count would shrink under compaction), the head claim's `step_since`, the `managed-sync` cursor (`index/total`, `held`) and `sources.last_sync_at`/`last_commit`, and whether a drain or full consumer is live on the owner host. `data_moving` is false when an unfinished cursor has had neither a committed receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` while a consumer is live; with none live the state is `parked` (informational). `sources status --json` and `writer status --json` print `data_moving`, `not_moving_since` and `movement_state` beside `sync_running`, and `sources status` prints the writer-status command beside `data_moving: false`; doctor `managed_sync_not_moving` (warn, scored for `not_moving` only) uses the same rule and command as its fix, and fails on a parked cursor whose admitted queue has no consumer past the ceiling (#6552; fix: the resume sync); `serve` prints one `[gbrain notice]` when a source flips. A failed backlog read is `unknown`, never `nothing_pending` (doctor warns). `/health` stays liveness-only.
- `src/commands/sources-writer-movement.ts` — #6317 (I2): `gbrain sources writer movement [<source>] [--wait <dur>] [--warn-only] [--json]`, the deploy gate `gbrain upgrade` and `post-upgrade` end by printing (bare, so it inherits the default window; neither runs it, because neither restarts the resident processes). The printed step is `MOVEMENT_SUPERVISOR_STEP` from the import-free leaf `src/commands/movement-step.ts` (re-exported here), so upgrade loads it before the swap (#6604). Same source selection as `writer status` (`persistence-admin.ts`). It snapshots through `sync-movement.ts`, waits `max(300 s, preparation budget + 60 s)` (printed as the effective budget; `--wait <dur>` takes sync's duration syntax) and judges each source: `moved` (a new committed publication; a cursor advanced only by holds or a `last_sync_at` touched by an up-to-date check is not movement) and `current` exit 0; `held` exits 0 with a warning and the hold kind's route (`gbrain repair fences --source <id>`; `preparation_stalled` → writer status, then `gbrain sources retry-held <id>`); `within_allowance` (the head's step advanced inside the window) exits 0 with `retry_after_ms`; `not_moving` exits 1 with `managed_sync_not_moving` (`reason: movement_check`, `fix.argv` the writer-status command, `fix.verify` this command); `unknown` (backlog unreadable) exits 1 with `movement_unknown`; other read failures keep their code. `--warn-only` prints the same envelopes and exits 0. Flags are regenerated into `src/core/cli-flag-registry.generated.ts` with `bun run build:flag-registry`.
- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`. #7189: each `SourceFreshness` carries `behind` (`readGitBehind`, injectable `BehindReader`: `rev-list --count <last_commit>..HEAD` and the oldest of those commits' committer age; null without a checkout or a synced commit), printed by `formatSyncFreshness`.
-- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).
+- `src/core/persistence/sync-status.ts` (status coherence) — GBRA-150: `state: blocked` means the source cannot advance (the drain outcome's meaning); a file hold that waits on a person while the source keeps syncing reads `synced` with reason `held_needs_human`, `needs_human` and `next` unchanged (`test/sync-status-blocked-definition.test.ts`); `detail` adds `landing` / `landing_read` (`landing-gaps.ts`). #7189: a `last_error` whose cursor failure row (`op_checkpoints` `managed-sync-failure`) is older than the source's newest committed managed-sync receipt carries `superseded` and sets neither `needs_human`, `state` nor `next` (`liveError`); `needs_human_from` names the hold or the error. #7243 (GBRA-133 PR 3a): every status carries `last_commit` (`sources.last_commit`) and `live` (the drain-lease holder from `readDrainHolder`, read only when the source read's `gbrain_cycle_locks` probe finds a row, with `job_id` for a Minions sync job and `stalled` from `holderStalled`; #7596: a holder that stopped renewing the lease (`drainHolderLive`) is not `live`, and an open pass with no live holder reads `pass_interrupted` (`passStatusState`) with an `interrupted` block (pass, last row write, the dead holder), which `sync-blocked.ts` also lists for doctor `managed_sync_blocked`; test `test/sync-pass-interrupted-7596.test.ts`; `live_job_id` also takes a job holder of a pass); `supersedingAttempt` marks a `last_error` `superseded` (`by`, `age_seconds`) when evidence newer than the failure row passed its phase (`resume` < `discovery` < `freeze`/`admission` < `receipt`/`checkpoint`; evidence: the pass row's `started_at` (pin), a level read (`timings_ms` set or an `up_to_date` idle tick), an uncommitted managed import or delete admitted later, a later commit). The CLI (`sync/operator.ts` `holdsListing`) bounds the holds: `holds_summary` (`topCounts` by code and by state: `needs_human`, `actionable`, `held`) over every hold, then `PLAIN_STATUS_HOLDS` (20) rows needs-human first, or with `--detail` a page of the shared listing contract (`bounded-listing.ts`, kind `sync_status_holds:<source>:<state>`, `--limit`/`--cursor`/`--all`, `--hold-state`), `holds_page` only when a page left rows out or took a cursor, the rows last. Test: `test/sync-status-truthful-7243.test.ts` (both engines).
- `src/core/persistence/resolve-paths.ts` — GBRA-150 `resolveSourcePaths`: what gbrain did with each file path of a source, by its own rules, so a landing check stops copying them. Per path: the sync slug (`resolveSlugForPath`), presence in the last synced commit and at HEAD (Git object reads), the skip reason (`unsyncableReason`, plus `typed_frontmatter` for a skipped metafile), the open hold, the live page by origin (`source_path`) and by slug (`slug_owner` when another file owns it, so a case-folded twin never reads as this file's page), a differing frontmatter `slug:`, chunk and embedding counts (`listEmbeddingStateRows` with its `slugs` filter), and one of `RESOLVE_PATH_STATES` with `searchable` (true / 'keyword' / false), `why` and an existing-command `fix`. Bounded: at most 200 paths, indexed lookups only, nothing written. Tests: `test/sources-resolve-path.test.ts`.
- `src/core/page-searchability.ts` — #7190 `readPageSearchability`: each live page's state, `searchable: true | 'keyword' | false`, chunks, `unembedded` (visible chunks with a NULL active-column vector) and `embedding_hold`, folded from `listEmbeddingStateRows` and the budget-hold read. Shared by resolve-path and `get_write_request`'s `applied`; `gbrain pages status` (#7181) can compose it with its Git view.
- `src/core/persistence/applied-watermark.ts` — #7190 `readAppliedWatermark` (sources status, MCP `sources_status`, `sync --json`) and the cheap `readWriteWatermark` (`get_write_request`): `indexed_through` is `sources.last_commit` (only a finished pass moves it), `embedded_through` reads the oldest page with a NULL vector (held pages count), `committed_through_request` is one below the oldest unsettled request of the incarnation, `pending` adds requests, files behind HEAD, held files and withheld deletes, `writer_heartbeat` is the drain-lease holder and its last progress (redacted for remote callers).
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.md
index 3564a4c43b..acc7235b4f 100644
--- a/docs/guides/sync-unblock-runbook.md
+++ b/docs/guides/sync-unblock-runbook.md
@@ -374,7 +374,8 @@ run converges on the next plain sync with no flag.
| Status `reason` | `state` | What it means | `next` |
|---|---|---|---|
| `pass_unfinished` | resumable | The newest pass is open or stopped at a deadline. | The plain sync (`resume_argv`); safe to loop. |
-| `pass_abandoned` | blocked | Two passes in a row never ended: the drain stopped them for making no progress, or their process was killed. The newest open pass counts once its row has not moved for 5 minutes. | `gbrain doctor --json` and a report with the gbrain version and the newest run's `drain.stall`; another plain sync is likely to stop the same way. |
+| `pass_interrupted` | resumable | The newest pass is open but no process holds the source's drain lease: its process was killed or crashed (an out-of-memory guard, a timeout) before it ended the pass, so nothing recorded a failure. `live` is null and `interrupted` names the pass, its last write and, when the lock row outlived the process, the holder and the pages it committed. Doctor `managed_sync_blocked` lists it as `pass_interrupted` (warn, then fail after an hour). | The plain sync; if that pass stops the same way, the reason becomes `pass_abandoned`. |
+| `pass_abandoned` | blocked | Two passes in a row never ended: the drain stopped them for making no progress, or their process was killed. The newest open pass counts once no process holds the source's drain lease (#7596; a reader without the lease read counts it once its row has not moved for 5 minutes). | `gbrain doctor --json` and a report with the gbrain version and the newest run's `drain.stall`; another plain sync is likely to stop the same way. |
| `not_converged` | resumable | The pass used its four rounds while another writer kept changing the level. Everything it admitted stands. | The plain sync; after three such passes in a row `next` is `gbrain doctor --json` and a report, because another sync will not change it. |
| `settle_mismatch` | resumable | A path keeps settling without reading settled. The next pass re-admits it once; after three passes at one level it is a `settle_mismatch` hold that needs a person. | The plain sync, then report the hold. |
| `deletes_withheld` | blocked | The pass's deletes crossed the mass-delete threshold (#2828) or an absolute cap (#7130: `sync.max_deletes`, default 500; `sync.max_delete_ratio`, default 0.01 above 50 deletes; per source `<key>.source.<id>`). The record's `trip` names which. It wrote one withheld record and synced everything else; no per-page hold is written. | Ask the user: restore the checkout if it is wrong; when the deletion is intended, raise the cap for that source (`gbrain config set sync.max_deletes.source.<id> <n>`) or run `GBRAIN_ALLOW_MASS_RECONCILE=1 gbrain sync --source <id>` on the brain host. `gbrain sync --source <id> --dry-run --json` lists the set and its hash. |
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 91852044ac..8083bdba57 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -167,7 +167,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
-<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
+<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. So does an open pass whose process was killed or crashed with no process left holding its drain lease (code `pass_interrupted`, aged from the pass row's last write), and passes that keep stopping that way (`pass_abandoned`). Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/llms-full.txt b/llms-full.txt
index 049c149726..cb0c372857 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10308,7 +10308,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
-<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
+<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. So does an open pass whose process was killed or crashed with no process left holding its drain lease (code `pass_interrupted`, aged from the pass row's last write), and passes that keep stopping that way (`pass_abandoned`). Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/src/commands/doctor/checks/managed-sync-blocked.ts b/src/commands/doctor/checks/managed-sync-blocked.ts
index 80bebebcbb..32c751eca4 100644
--- a/src/commands/doctor/checks/managed-sync-blocked.ts
+++ b/src/commands/doctor/checks/managed-sync-blocked.ts
@@ -6,7 +6,8 @@
* for less than the threshold warns. Reads the durable cursor and failure rows only; names sources, codes and ages, never
* paths or receipt text.
* #6712 PR 4b: a non-company source's passes that keep stopping (`blocked`, a `not_converged` or `settle_mismatch`
- * streak) count too, aged from when they started stopping (`readBlockedManagedSyncs`).
+ * streak) count too, aged from when they started stopping (`readBlockedManagedSyncs`). #7596: so does an open pass whose process
+ * was killed or crashed (`pass_interrupted`, aged from its last write) and passes that keep stopping that way (`pass_abandoned`).
*/
import type { Check } from '../../doctor.ts';
import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -30,7 +31,7 @@ async function runManagedSyncBlockedCheck(ctx: DoctorContext): Promise<Check[]>
const list = blocked.map(b => `${b.source_id} (${b.code}, blocked ${minutes(b.blocked_since)} min)`).join('; ');
checks.push({ name: 'managed_sync_blocked', status: over.length ? 'fail' : 'warn', readiness_state: 'degraded',
details: { threshold_ms: MANAGED_SYNC_BLOCKED_FAIL_MS, sources: blocked.map(b => ({ ...b, blocked_minutes: minutes(b.blocked_since) })), docs: DOCS },
- message: `${list}: the managed sync run is stopped on a page that did not commit, or its passes keep stopping without converging, so the source indexes nothing new until it is cleared`
+ message: `${list}: the managed sync run is stopped on a page that did not commit, its passes keep stopping without converging, or its pass stopped before it ended with no process left to finish it (killed or crashed), so the source indexes nothing new until it is cleared`
+ `${over.length ? ` (over the ${MANAGED_SYNC_BLOCKED_FAIL_MS / 60_000} min threshold)` : ''}. Freshness sync jobs for the source end dead with the run's next step instead of completed.`,
fix: agentFix(['gbrain', 'sync', 'status', '--source', first.source_id, '--json'],
'Read-only: names the page the run stopped on, its fault class and the next step (a hold to reconcile, a repair to preview, or the resume command).',
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.ts
index d14f5738a9..760cd23080 100644
--- a/src/commands/sync/operator.ts
+++ b/src/commands/sync/operator.ts
@@ -219,6 +219,8 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promis
const live = status.live;
console.log(` live: ${live ? `${live.kind}${live.job_id !== null ? ` job #${live.job_id}` : live.id ? ` ${live.id}` : ''}${live.pid ? ` (PID ${live.pid})` : ''} holds the drain lease since ${live.started_at ?? '?'}`
+ `${live.progress ? `, ${live.progress.committed} page(s) committed since` : ''}${live.stalled ? ', STALLED (no commit or save for the stall window)' : ''}` : 'nothing holds the drain lease'}`);
+ const cut = status.interrupted;
+ if (cut) console.log(` INTERRUPTED: pass ${cut.pass_id.slice(0, 8)} stopped before it ended (last write ${cut.since})${cut.holder ? `; its holder ${cut.holder.kind}${cut.holder.pid ? ` (PID ${cut.holder.pid})` : ''} stopped renewing the lease at ${cut.holder.last_heartbeat_at ?? '?'}${cut.holder.progress ? ` after committing ${cut.holder.progress.committed} page(s)` : ''}` : ''}`);
const pass = status.convergence?.dry_run === false ? status.convergence : null;
if (pass) console.log(` newest pass: ${pass.outcome}${pass.stop_reason ? ` (${pass.stop_reason})` : ''}, round ${pass.round}, pinned ${pass.target.slice(0, 8)}; `
+ `${pass.converged_target ? `last converged at ${pass.converged_target.slice(0, 8)} (${pass.converged_at})` : 'no converged stamp stored'}`);
@@ -279,6 +281,7 @@ export function syncStatusHeadline(status: Pick<SyncStatus, 'source_id' | 'state
case 'head_blocked': return `Source ${status.source_id} is blocked: its oldest write waits on something only an operator clears.`;
case 'recovery_blocked': return `Source ${status.source_id} is blocked: a write's recovery record found changed bytes on disk.`;
case 'pass_unfinished': return `Source ${status.source_id} is resumable: the newest sync pass did not finish; the next sync continues it.`;
+ case 'pass_interrupted': return `Source ${status.source_id} is resumable: the newest sync pass stopped before it ended and no process owns it (killed or crashed); the next sync continues it.`;
case 'pass_abandoned': return `Source ${status.source_id} is blocked: its sync passes keep stopping before they end; another plain sync will not change that (report what doctor shows).`;
case 'not_converged': return `Source ${status.source_id} is resumable: the newest sync pass ran out of rounds before every path settled.`;
case 'settle_mismatch': return `Source ${status.source_id} is resumable: a path keeps settling without reading settled; three passes in a row hold it.`;
diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.ts
index f65c5737f4..e26f09c5c6 100644
--- a/src/core/persistence/sync-blocked.ts
+++ b/src/core/persistence/sync-blocked.ts
@@ -13,6 +13,8 @@
* row stays `open`, so neither rule above saw it: a discovery-phase stop (path `<discovery>`) or an entry's stop read as
* nothing blocked while the source indexed nothing. Such a stop is listed while it is newer than the pass row (no pass has
* started since; a converged or idle pass clears it).
+ * #7596: an open pass whose process stopped without ending it (no live drain-lease holder: killed or crashed) is listed as
+ * `pass_interrupted` from its row's last write, and once passes in a row keep stopping that way, `pass_abandoned` (status's rule).
*/
import type { BrainEngine } from '../engine.ts';
import { readManagedSyncFailures } from './sync-failures.ts';
@@ -49,7 +51,21 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s
.filter(({ fingerprint, updated_at, failure }) => !passSources.has(failure.source_id) && failure.code !== 'sync_incomplete'
&& passFailureKeys(failure.source_id, failure.source_incarnation).includes(fingerprint) && new Date(updated_at).getTime() >= (passRowAt.get(failure.source_id) ?? 0))
.map(({ failure }) => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen }));
- return [...failures
+ const listed = [...failures
.filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key) && !passSources.has(failure.source_id))
.map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes, ...passStops];
+ // #7596: an open pass no recorded stop explains, whose drain lease no process renews: its process was killed or crashed.
+ const open = readings.filter(reading => reading.row.value.telemetry.outcome === 'open' && !listed.some(blocked => blocked.source_id === reading.source_id));
+ if (!open.length) return listed;
+ const [{ inspectLock, isLockHolderLive, syncLockId }, { DRAIN_LEASE_TTL_MINUTES }, { abandonedPasses }, { ABANDONED_REPORT_STREAK }] = await Promise.all([
+ import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts'), import('./sync-pass-row.ts')]);
+ const now = Date.now();
+ for (const { source_id, row } of open) {
+ const lock = await inspectLock(engine, syncLockId(source_id)).catch(() => undefined);
+ if (lock === undefined) continue;
+ const interrupted = !lock || !isLockHolderLive(lock, DRAIN_LEASE_TTL_MINUTES);
+ const abandoned = abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK;
+ if (interrupted || abandoned) listed.push({ source_id, code: abandoned ? 'pass_abandoned' : 'pass_interrupted', run_id: row.value.telemetry.pass_id, blocked_since: abandoned ? passStuckSince(row) : row.updated_at });
+ }
+ return listed;
}
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.ts
index 180f05bd92..3f35dba61b 100644
--- a/src/core/persistence/sync-lease.ts
+++ b/src/core/persistence/sync-lease.ts
@@ -36,7 +36,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type { BrainEngine } from '../engine.ts';
import type { SyncResult } from '../../commands/sync.ts';
import type { Action } from '../agent-output.ts';
-import { fenceLockRow, inspectLock, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';
+import { fenceLockRow, inspectLock, LockStolenError, LockUnavailableError, resolveStealGraceSeconds, syncLockId, withRefreshingLock } from '../db-lock.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';
@@ -160,6 +160,15 @@ export function holderStalled(holder: DrainHolder | null, now = Date.now()): boo
return now - since >= HOLDER_STALL_MS;
}
+/**
+ * #7596: whether a holder still renews the drain lease, by `isLockHolderLive`'s rule at the drain TTL (an unexpired TTL, or a
+ * renewal inside the steal grace). A killed holder's lock row stays until a takeover breaks it, but its renewals stop.
+ */
+export function drainHolderLive(holder: DrainHolder | null, now = Date.now()): boolean {
+ const beat = holder?.last_heartbeat_at ?? holder?.started_at;
+ return !!beat && now - Date.parse(beat) < Math.max(DRAIN_LEASE_TTL_MINUTES * 60_000, resolveStealGraceSeconds(DRAIN_LEASE_TTL_MINUTES) * 1000);
+}
+
/** What a remote caller may see of a holder: its kind and times, never its host, pid or job id. */
export const publicDrainHolder = (holder: DrainHolder | null): DrainHolder | null => holder && { ...holder, id: null, host: null, pid: null };
const redacted = publicDrainHolder;
diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.ts
index 5f05494ee9..185115fd10 100644
--- a/src/core/persistence/sync-pass-status.ts
+++ b/src/core/persistence/sync-pass-status.ts
@@ -56,21 +56,28 @@ export async function passConvergence(engine: Pick<BrainEngine, 'executeRaw'>, i
duration_ms: t.duration_ms, timings_ms: t.timings_ms, last_full_at: o.converged?.last_full_at ?? null };
}
-export type PassStatusReason = 'pass_unfinished' | 'pass_abandoned' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';
+export type PassStatusReason = 'pass_unfinished' | 'pass_interrupted' | 'pass_abandoned' | 'not_converged' | 'settle_mismatch' | 'deletes_withheld' | 'selection_scoped' | 'admission_paused' | 'writeback_failed';
-/** #7355: passes in a row that never ended, the newest open one included once its row has been quiet past the no-progress window. */
-export function abandonedPasses(row: PassRow, now = Date.now()): number {
- const quiet = row.value.telemetry.outcome === 'open' && now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS;
+/**
+ * #7355: passes in a row that never ended, the newest open one included once its row has been quiet past the no-progress
+ * window. #7596: a caller that read the source's drain lease passes `interrupted` instead: the open pass counts when no process
+ * holds the lease (its process was killed or crashed) and never while one does, since a pass writes its row only per batch.
+ */
+export function abandonedPasses(row: PassRow, now = Date.now(), interrupted?: boolean): number {
+ const quiet = row.value.telemetry.outcome === 'open' && (interrupted ?? now - Date.parse(row.updated_at) >= ABANDONED_QUIET_MS);
return row.value.telemetry.outcome === 'open' ? (row.value.obligations.abandoned_streak ?? 0) + (quiet ? 1 : 0) : 0;
}
/**
* The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged, or while a
* writeback its stamp recorded (`converged.writeback`) has a failed or parked Git effect (`writebackFailed`: that request). Null: nothing to add.
+ * #7596 `interrupted`: no process holds the source's drain lease (`drainHolderLive`), so an open pass is one whose process
+ * stopped without ending it (killed or crashed), not one still running: `pass_interrupted`.
*/
-export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now()): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {
+export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now(), interrupted?: boolean): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {
const t = row.value.telemetry;
- if (abandonedPasses(row, now) >= ABANDONED_REPORT_STREAK) return ['blocked', 'pass_abandoned'];
+ if (abandonedPasses(row, now, interrupted) >= ABANDONED_REPORT_STREAK) return ['blocked', 'pass_abandoned'];
+ if (t.outcome === 'open' && interrupted) return ['resumable', 'pass_interrupted'];
if (t.outcome === 'open' || (t.outcome === 'resumable' && t.stop_reason !== 'not_converged' && t.stop_reason !== 'admission_paused')) return ['resumable', 'pass_unfinished'];
if (t.stop_reason === 'admission_paused') return ['resumable', 'admission_paused'];
if (t.stop_reason === 'not_converged' || (row.value.obligations.not_converged_streak ?? 0) > 0) return ['resumable', 'not_converged'];
@@ -82,7 +89,7 @@ export function passStatusState(row: PassRow, withheld: DeletesWithheld | null,
}
/** The next step for a pass reason (`resume`: the plain sync's arguments). */
-export function passStatusNext(sourceId: string, reason: PassStatusReason, row: PassRow, resume: string[], writebackFailed: string | null = null): Action {
+export function passStatusNext(sourceId: string, reason: PassStatusReason, row: PassRow, resume: string[], writebackFailed: string | null = null, interrupted?: boolean): Action {
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
const sync: Action = { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify, why: '' };
switch (reason) {
@@ -106,7 +113,9 @@ export function passStatusNext(sourceId: string, reason: PassStatusReason, row:
why: 'The preview names the parked effect and what a retry runs (read-only); until it commits, the source is never idle.' };
case 'pass_abandoned':
return { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,
- why: `The last ${abandonedPasses(row)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };
+ why: `The last ${abandonedPasses(row, Date.now(), interrupted)} sync passes of ${sourceId} stopped before they ended (the drain abandoned them for making no progress, or their process was killed), so another plain sync is likely to stop the same way. Report what doctor shows, with the gbrain version and the newest sync run's drain.stall (read-only).` };
+ case 'pass_interrupted':
+ return { ...sync, why: `The newest pass of ${sourceId} stopped before it ended and no process holds its drain lease: its process was killed or crashed (an out-of-memory kill or a timeout), so nothing recorded a failure. The plain sync continues it from the current level; if that pass stops the same way, status reads pass_abandoned.` };
case 'selection_scoped':
return { ...sync, why: 'The last pass converged at a narrower selection and did not advance last_commit; the plain sync runs the configured selection.' };
default:
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index 2ac5790239..e29b427bbb 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -49,7 +49,7 @@ import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionEffectParams, syncAdmission
import type { DeletesWithheld } from './sync-markers.ts';
import { listIdentityDowngrades, withIdentityRemedies } from '../sync-identity-downgrades.ts';
import { GIT_PUSH_CODES, readGitPushHolds, type GitPushHold } from './git-push-holds.ts';
-import { holderStalled, readDrainHolder, type DrainHolder } from './sync-lease.ts';
+import { drainHolderLive, holderStalled, readDrainHolder, type DrainHolder } from './sync-lease.ts';
import { syncLockId } from '../db-lock.ts';
export interface SyncStatusHold extends SyncFaultVerdict {
@@ -130,9 +130,15 @@ export interface SyncStatus {
/**
* #7243: the job doing the work now: the holder of the source's drain lease (a serve pass, a sync job, a CLI sync, the
* cycle), its heartbeat and progress, `job_id` when it is a Minions sync job, and `stalled` once it has made no commit
- * or save for the stall window. Null when nothing holds the lease.
+ * or save for the stall window. Null when nothing holds the lease, or (#7596) its holder stopped renewing it.
*/
live: SyncStatusLive | null;
+ /**
+ * #7596: the newest pass is open but no process holds the drain lease: its process was killed or crashed before it ended
+ * the pass. `since` is the pass row's last write; `holder` is the process whose lock row outlived it (a SIGKILL leaves
+ * one until a takeover), with the pages it committed, or null when the lock was released. Null otherwise.
+ */
+ interrupted: { pass_id: string; since: string; holder: DrainHolder | null } | null;
run_id: string | null;
cursor: { index: number; total: number; pinned_target: string | null; last_advance_at: string | null; done: boolean } | null;
/** Managed sync page requests of the source committed in the last ten minutes (waived entries are not requests). */
@@ -223,7 +229,9 @@ export const SYNC_STATUS_REASONS = ['nothing_pending', 'held_by_design', 'held_n
// #6712 PR 4b (design v3.2 §9): the live pass's reasons.
'pass_unfinished', 'not_converged', 'settle_mismatch', 'deletes_withheld', 'selection_scoped', 'admission_paused', 'writeback_failed',
// #7355: passes keep stopping before they end.
- 'pass_abandoned'] as const;
+ 'pass_abandoned',
+ // #7596: the newest pass's process stopped (killed or crashed) without ending it.
+ 'pass_interrupted'] as const;
export type SyncStatusReason = typeof SYNC_STATUS_REASONS[number];
export type SyncStatusRead = { status: 'read' } | { status: 'not_read'; fix: Action };
/** The bound of each default probe (the oldest blocker, the recovery records). */
@@ -390,7 +398,12 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
// #6712 PR 4b (design §9): the pass row (one primary-key read) and the withheld-delete record make the live `convergence` block.
const passRow: PassRow | null = source.pass_value && source.pass_updated_at ? { value: source.pass_value, updated_at: new Date(source.pass_updated_at).toISOString() } : null;
const withheld = passRow ? source.withheld : null;
- const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed) : null;
+ // #7243: whoever holds the drain lease is the job doing the work, a serve-owned pass included (one primary-key probe rode the source read).
+ // #7596: a holder that stopped renewing it was killed; an open pass with no live holder was interrupted, not running.
+ const lockHolder = source.drain_lock ? await readDrainHolder(engine, sourceId).catch(() => null) : null;
+ const holder = drainHolderLive(lockHolder) ? lockHolder : null;
+ const interrupted = passRow?.value.telemetry.outcome === 'open' && !holder;
+ const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed, Date.now(), interrupted) : null;
const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });
const human = holds.find(hold => hold.needs_human) ?? (liveError?.needs_human ? liveError : undefined);
// #6643: a knock-on or a superseded run is not a failure of its page: the resume re-freezes the entry.
@@ -398,8 +411,6 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
// #6706: a live sync job already drains this cursor; the agent watches it instead of starting a second drainer beside it.
- // #7243: whoever holds the drain lease is the job doing the work, a serve-owned pass included (one primary-key probe rode the source read).
- const holder = source.drain_lock ? await readDrainHolder(engine, sourceId).catch(() => null) : null;
const holderJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;
const liveJob = unfinished && !human ? holderJob ?? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId) : null;
const next: Action | null = liveJob !== null
@@ -433,8 +444,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts
const [state, stateReason] = statusState({ human: !!(liveError?.needs_human), heldForHuman: holds.some(hold => hold.needs_human), oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!liveError, actionable: actionable.length > 0, holds: holds.length > 0, pass: passState });
const admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,
{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at, pinned: source.admission_pinned, destructive: source.admission_destructive });
- const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed) : null;
- return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null, run_id: header?.runId ?? null,
+ const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed, interrupted) : null;
+ return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null,
+ interrupted: interrupted && passRow && !liveError ? { pass_id: passRow.value.telemetry.pass_id, since: passRow.updated_at, holder: lockHolder } : null, run_id: header?.runId ?? null,
cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,
committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob ?? holderJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),
needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },
diff --git a/test/managed-sync-blocked-job-6858.test.ts b/test/managed-sync-blocked-job-6858.test.ts
index 0e1346eff3..668e8fbf0c 100644
--- a/test/managed-sync-blocked-job-6858.test.ts
+++ b/test/managed-sync-blocked-job-6858.test.ts
@@ -7,7 +7,7 @@
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -15,6 +15,7 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import type { MinionJobContext } from '../src/core/minions/types.ts';
import { UnrecoverableError } from '../src/core/minions/errors.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
@@ -114,6 +115,9 @@ test('#6858: a freshness sync job whose managed run is blocked ends dead with th
// #6712 PR 4b: a resumed pass records itself open in its pass row while the failure row stays until a pass converges:
// it is draining, not blocked. A pass that stops blocked again is blocked again, with the write's code.
const outcome = (value: string) => engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,telemetry,outcome}',to_jsonb($2::text)) WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [s.id, value]);
+ // The resumed pass holds the source's drain lease while it drains (#7596: an open pass no process holds was killed).
+ await engine.executeRaw(`INSERT INTO gbrain_cycle_locks(id,holder_pid,holder_host,acquired_at,ttl_expires_at,last_refreshed_at)
+ VALUES($1,$2,$3,now(),now()+interval '2 minutes',now())`, [syncLockId(s.id), process.pid, hostname()]);
await outcome('open');
expect(await readBlockedManagedSyncs(engine, [s.id])).toEqual([]);
expect(await check()).toEqual([expect.objectContaining({ name: 'managed_sync_blocked', status: 'ok' })]);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index cb7de6ca77..13a641923f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -482,6 +482,7 @@ test/sync-page-write-failed-gbra130.test.ts
test/sync-pass-abandoned-7355.test.ts
test/sync-pass-cost-grouping-gbra130.test.ts
test/sync-pass-dirty-after-freeze-gbra130.test.ts
+test/sync-pass-interrupted-7596.test.ts
test/sync-pass-phase-lines-7243.serial.test.ts
test/sync-pass-stop-in-level-gbra133.test.ts
test/sync-prescreen-both-delta-6712.test.ts
diff --git a/test/sync-pass-interrupted-7596.test.ts b/test/sync-pass-interrupted-7596.test.ts
new file mode 100644
index 0000000000..a33db74830
--- /dev/null
+++ b/test/sync-pass-interrupted-7596.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #7596: a managed sync killed mid-batch (an external memory guard's SIGTERM, an OOM SIGKILL) leaves its pass row open.
+ * `sync status` read that row as a pass still in progress: `resumable` / `pass_unfinished`, the same as a pass that stopped
+ * cleanly at its deadline, and after a SIGKILL it listed the dead process under `live` because its lock row outlives it.
+ * Doctor `managed_sync_blocked` listed nothing. An open pass with no process renewing the source's drain lease is now
+ * `pass_interrupted` in status (with `interrupted` naming the pass and the dead holder) and in doctor.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { hostname } from 'node:os';
+import { join } from 'node:path';
+import type { Check } from '../src/commands/doctor.ts';
+import { managedSyncBlockedEntry } from '../src/commands/doctor/checks/managed-sync-blocked.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';
+import { drainHolderLive, type DrainHolder } from '../src/core/persistence/sync-lease.ts';
+import { abandonedPasses, passStatusNext, passStatusState } from '../src/core/persistence/sync-pass-status.ts';
+import { MANAGED_SYNC_PASS_OP, type PassRow } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const now = Date.parse('2026-10-25T12:00:00Z');
+const row = (outcome: string, streak: number | undefined, quietMs: number): PassRow => ({ updated_at: new Date(now - quietMs).toISOString(),
+ value: { source_id: 's', incarnation: 'i', lease_token: 't', obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {}, ...(streak ? { abandoned_streak: streak } : {}) },
+ telemetry: { pass_id: 'p', target: 'h', started_at: '', ended_at: null, kind: 'full', round: 0, outcome: outcome as never, stop_reason: null, candidates: 0, settled: 0, remaining: 0, counts: {}, duration_ms: null, timings_ms: {} } } });
+const holder = (beatAgoMs: number): DrainHolder => ({ kind: 'cli', id: null, host: 'host-a', pid: 4242, started_at: new Date(now - 600_000).toISOString(),
+ last_heartbeat_at: new Date(now - beatAgoMs).toISOString(), version: null, progress: null });
+
+describe('#7596: an open pass with no live drain-lease holder reads interrupted', () => {
+ test('a holder that stopped renewing the lease is not live', () => {
+ expect(drainHolderLive(holder(20_000), now)).toBe(true);
+ expect(drainHolderLive(holder(3 * 60_000), now)).toBe(false);
+ expect(drainHolderLive(null, now)).toBe(false);
+ });
+
+ test('the first interrupted pass is resumable pass_interrupted and next is the plain sync', () => {
+ const open = row('open', undefined, 10_000);
+ expect(passStatusState(open, null, null, now, true)).toEqual(['resumable', 'pass_interrupted']);
+ const next = passStatusNext('s', 'pass_interrupted', open, ['--source', 's'], null, true);
+ expect(next.argv).toEqual(['gbrain', 'sync', '--source', 's']);
+ expect(next.why).toContain('killed or crashed');
+ // A pass whose process still renews the lease is running, not interrupted.
+ expect(passStatusState(open, null, null, now, false)).toEqual(['resumable', 'pass_unfinished']);
+ expect(passStatusState(row('synced', undefined, 10_000), null, null, now, true)).toBeNull();
+ });
+
+ test('an interrupted pass after an abandoned one is blocked pass_abandoned without waiting out the quiet window', () => {
+ const second = row('open', 1, 10_000);
+ expect(abandonedPasses(second, now, true)).toBe(2);
+ expect(passStatusState(second, null, null, now, true)).toEqual(['blocked', 'pass_abandoned']);
+ expect(passStatusState(second, null, null, now, false)).toEqual(['resumable', 'pass_unfinished']);
+ // A pass writes its row per batch, so a live holder committing pages for minutes is not quiet, whatever its row's age.
+ expect(passStatusState(row('open', 1, 6 * 60_000), null, null, now, false)).toEqual(['resumable', 'pass_unfinished']);
+ });
+});
+
+const lockRow = (engine: BrainEngine, beat: string, ttl: string) => engine.executeRaw(`INSERT INTO gbrain_cycle_locks(id,holder_pid,holder_host,acquired_at,ttl_expires_at,last_refreshed_at)
+ VALUES($1,$2,$3,now()-interval '10 minutes',now()+$5::interval,now()-$4::interval)
+ ON CONFLICT(id) DO UPDATE SET holder_pid=EXCLUDED.holder_pid,ttl_expires_at=EXCLUDED.ttl_expires_at,last_refreshed_at=EXCLUDED.last_refreshed_at`, [syncLockId('default'), 4242, hostname(), beat, ttl]);
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ test(`#7596 [${backend}]: a killed pass is pass_interrupted in sync status and doctor, and a live one is not`, () => managedBrain(async ({ engine }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toMatch(/^(first_sync|synced)$/);
+ const blocked = async () => (await readBlockedManagedSyncs(engine, ['default'])).filter(entry => entry.source_id === 'default');
+ const doctor = async () => (await managedSyncBlockedEntry.run({ engine } as never) as Check[])[0]!;
+ expect(await blocked()).toEqual([]);
+
+ // The pass's process was killed: its row is left open and its drain lease released (a SIGTERM's cleanup).
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,telemetry,outcome}','"open"') WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);
+ const [{ pass_id }] = await engine.executeRaw<{ pass_id: string }>(`SELECT completed_keys->0->'telemetry'->>'pass_id' AS pass_id FROM op_checkpoints WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);
+ let status = await readSyncStatus(engine, 'default', { detail: false });
+ expect([status.state, status.reason]).toEqual(['resumable', 'pass_interrupted']);
+ expect(status.live).toBeNull();
+ expect(status.interrupted).toMatchObject({ pass_id, holder: null });
+ expect(status.next?.argv?.slice(0, 4)).toEqual(['gbrain', 'sync', '--source', 'default']);
+ expect(status.next?.why).toContain('killed or crashed');
+ expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_interrupted', run_id: pass_id })]);
+ expect(await doctor()).toMatchObject({ name: 'managed_sync_blocked', status: 'warn' });
+
+ // A SIGKILL leaves the lock row behind, its renewals stopped three minutes ago: still no live holder.
+ await lockRow(engine, '3 minutes', '-1 minute');
+ status = await readSyncStatus(engine, 'default', { detail: false });
+ expect([status.state, status.reason]).toEqual(['resumable', 'pass_interrupted']);
+ expect(status.live).toBeNull();
+ expect(status.interrupted?.holder).toMatchObject({ pid: 4242 });
+ expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_interrupted' })]);
+
+ // A holder that renewed the lease just now is a pass still running: not interrupted, not blocked.
+ await lockRow(engine, '1 second', '2 minutes');
+ status = await readSyncStatus(engine, 'default', { detail: false });
+ expect(status.reason).toBe('pass_unfinished');
+ expect(status.live).toMatchObject({ pid: 4242 });
+ expect(status.interrupted).toBeNull();
+ expect(await blocked()).toEqual([]);
+ }, { databaseUrl, setup: ({ root }) => {
+ git(root, ['init', '-q']);
+ writeFileSync(join(root, 'a.md'), '---\ntype: concept\ntitle: a\n---\n\nA note about a.\n');
+ git(root, ['add', '-A']); git(root, ['commit', '-qm', 'a']);
+ } }), 120_000);
+}