Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): a failed backlog read is unknown movement, never nothing_pending (#6781)

garrytan9041394aa73a
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 582f19201b..6393ebaed1 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -29,8 +29,8 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.
- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.
- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.
-- `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. `/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` carries the read failure's own code with `fix.next: report`. `--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/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/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths. Writer status's blockers also carry each request's `operation`, `intent_kind` and `preparation_attempts`; a running blocker's `claim` adds the preparation `step`, `step_age_ms`, `waiting_on`, the owner process (kind, pid, gbrain build, from the live claim's stamp), `budget_ms` and, past the budget, `stall: { reason: 'preparation_overdue', step, step_age_ms, waiting_on, budget_ms }` (`claimStall`; `WRITE_HEALTH_REASONS`, the wire enum, is unchanged). `WRITER_NEXT_ACTIONS` has entries for `preparation_deadline` (keep the request id: the owner will claim it again) and `preparation_stalled` (do not resubmit under the same id; retry-held after the fix), and the result carries `preparation_policy` (the budgets, ceiling, attempt limit and switch in effect). Doctor `persistence_write_stall` prints the same fields. Tests: `test/persistence-writer-status-stall.test.ts`.
- `src/core/schema-migrations/v220-persistence-request-preparation-attempts.ts` — #6278: `persistence_requests.preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0)`, the count of cut-offs of a request's preparation. Existing rows start at 0; a commit resets it. It is a migration-created column (also in the `persistence_requests` CREATE TABLE of `src/schema.sql`, with no index) so a fresh install and an upgraded brain keep the same column order. Tests: `test/persistence-preparation-attempts-migration.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index e52dec1db3..1d29782f32 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -142,7 +142,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-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. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
+<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:
1. `gbrain sources status <id> --json`: `data_moving`, `not_moving_since`, `movement_state` and, beside `data_moving: false`, the exact `gbrain sources writer status --source <id> --json` to run next. Doctor's `managed_sync_not_moving` fix is that same command.
2. `gbrain sources writer status --source <id> --json`: every running claim ends in one `claim.next` envelope (`code` `claim_running`, `claim_overdue` or `claim_lapsed`). `claim_running` carries `retry_after_ms` and a `run` of the same status command while the owner is inside its allowance (the owner's own budget will cut the write; nothing to do but rerun after the delay), `tell_user_to_run` naming the owner `kind` and pid past the ceiling or when the owner reads `restart_required` (restart that process), `run` the printed resume command for a lapsed claim. `host.consumers` lists the processes on this host holding a consumer (pid, kind, mode `full|waiter_only`, started_at, the pool gauge), so a second consumer is visible in the same call.
diff --git a/src/commands/doctor/checks/managed-sync-movement.ts b/src/commands/doctor/checks/managed-sync-movement.ts
index be081f8ce3..7b36f67533 100644
--- a/src/commands/doctor/checks/managed-sync-movement.ts
+++ b/src/commands/doctor/checks/managed-sync-movement.ts
@@ -9,7 +9,9 @@
* warned, unless (#6552 §2, #6712 PR 2) admitted requests wait in its queue
* with no consumer and no progress for longer than that ceiling: nothing will
* ever drain them, so the check fails and names the resume sync (which runs
- * its own consumer) as the safe action. Reads the database only.
+ * its own consumer) as the safe action. A source whose backlog read failed
+ * (#6781, `movement_state: unknown`) warns with `details.health: unknown`,
+ * never `ok`. Reads the database only.
*/
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -26,9 +28,10 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>
const stuck = pending.filter(m => m.movement_state === 'not_moving');
const parked = pending.filter(m => m.movement_state === 'parked');
const stranded = parked.filter(strandedQueue);
- const details = { count: stuck.length, parked: parked.length, stranded: stranded.length, sources: pending.map(m => ({ source_id: m.source_id, movement_state: m.movement_state, data_moving: m.data_moving,
+ const unknown = pending.filter(m => m.movement_state === 'unknown');
+ const details = { count: stuck.length, parked: parked.length, stranded: stranded.length, ...(unknown.length ? { unknown: unknown.length, health: 'unknown' } : {}), sources: pending.map(m => ({ source_id: m.source_id, movement_state: m.movement_state, data_moving: m.data_moving,
not_moving_since: m.not_moving_since, last_commit_at: m.last_commit_at, last_progress_at: m.last_progress_at, cursor: m.cursor, head: m.head, live: m.live, admitted: m.admitted,
- ceiling_ms: m.ceiling_ms, writer_status_command: m.writer_status_command })), docs: DOCS };
+ ceiling_ms: m.ceiling_ms, writer_status_command: m.writer_status_command, ...(m.unknown ? { unknown: m.unknown } : {}) })), docs: DOCS };
if (stranded.length) {
const first = stranded[0]!;
checks.push({ name: 'managed_sync_not_moving', status: 'fail', readiness_state: 'degraded', details,
@@ -44,6 +47,11 @@ async function runManagedSyncMovementCheck(ctx: DoctorContext): Promise<Check[]>
+ `managed sync data has not moved for longer than the ${Math.round(first.ceiling_ms / 1000)}s ceiling while a sync or consumer is live. The health signals are green; the data is not.`,
fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', first.source_id, '--json'],
'Read-only: names the request at the head, its step, what it waits on, the owner process and the next step (`claim.next`) on the running claim.', 'managed_sync_not_moving', { docs: DOCS }) });
+ } else if (unknown.length) {
+ checks.push({ name: 'managed_sync_not_moving', status: 'warn', readiness_state: 'degraded', details,
+ message: `${unknown.map(m => m.source_id).join(', ')}: the managed sync backlog could not be read (${unknown[0]!.unknown?.error ?? 'no detail'}), so whether sync data moves is unknown; this is not an all-clear.`,
+ fix: agentFix(['gbrain', 'sources', 'writer', 'movement', unknown[0]!.source_id, '--json'],
+ 'Read-only: reads the backlog again and judges movement over one window; if the read keeps failing, gbrain doctor --json checks the database.', 'managed_sync_not_moving', { docs: DOCS }) });
} else if (pending.length) {
checks.push({ name: 'managed_sync_not_moving', status: 'ok', severity: 'info', details,
message: `Managed sync data is moving${parked.length ? `; ${parked.map(m => `${m.source_id} is parked at ${m.cursor!.index}/${m.cursor!.total} (no sync or consumer live; resume: ${m.cursor!.resume_command})`).join('; ')}` : ''}.` });
diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.ts
index 84cf4c690f..af65261b4f 100644
--- a/src/commands/sources-writer-movement.ts
+++ b/src/commands/sources-writer-movement.ts
@@ -17,9 +17,11 @@
* Exit: `not_moving` → 1 with code `managed_sync_not_moving` (`reason:
* movement_check`) and the writer summary; `parked` → 1 with the same code
* and `state: parked` (after a restart nothing picked the catch-up up);
- * `held`/`within_allowance`/`moved`/`nothing_pending` → 0; `--warn-only`
- * prints the same envelopes and exits 0. A read failure keeps its own code
- * (`fix.next: report`), never `managed_sync_not_moving`. `gbrain upgrade`
+ * `held`/`within_allowance`/`moved`/`nothing_pending` → 0; `unknown` (#6781:
+ * the backlog read failed) → 1 with its own code `movement_unknown` (`reason:
+ * backlog_read_failed`); `--warn-only` prints the same envelopes and exits 0.
+ * A read failure keeps its own code (`fix.next: report`), never
+ * `managed_sync_not_moving`. `gbrain upgrade`
* never runs this (it owns no relaunch); it prints the bare command for the
* supervisor's step.
*/
@@ -51,8 +53,10 @@ waits the window, and judges each one from committed pages and the head's step
--warn-only Print the same verdicts and envelopes but exit 0 (pipelines that cannot fail).
States: moved, within_allowance (a step or cursor advanced; a multi-wave group preparing
normally), held (advanced only by holds; the hold kind's repair route is printed), parked
-(pending work and nothing live to move it), not_moving, nothing_pending.
-Exit 1 with code managed_sync_not_moving for not_moving and parked; 0 otherwise.
+(pending work and nothing live to move it), not_moving, nothing_pending, unknown (the
+sync backlog could not be read, so pending work is not known; never nothing_pending).
+Exit 1 with code managed_sync_not_moving for not_moving and parked, 1 with code
+movement_unknown for unknown; 0 otherwise.
Run it after restarting serve and the workers: gbrain sources writer movement`;
export { MOVEMENT_SUPERVISOR_STEP } from './movement-step.ts';
@@ -96,8 +100,8 @@ export interface MovementReport {
source_id: string;
state: MovementVerdict;
exit: 0 | 1;
- code: 'managed_sync_not_moving' | null;
- reason?: 'movement_check';
+ code: 'managed_sync_not_moving' | 'movement_unknown' | null;
+ reason?: 'movement_check' | 'backlog_read_failed';
why: string;
fix: RenderedAction | null;
retry_after_ms?: number;
@@ -115,6 +119,11 @@ export function movementReport(before: SourceMovement | undefined, after: Source
const verify = { argv: ['gbrain', 'sources', 'writer', 'movement', id, '--json'] };
const head = after.head?.step ? ` The head is at step ${after.head.step}${after.head.waiting_on && after.head.waiting_on !== 'unknown' ? ` (waiting on ${after.head.waiting_on})` : ''}${after.head.owner ? `, held by ${after.head.owner.kind} pid ${after.head.owner.pid}` : ''}.` : '';
switch (state) {
+ case 'unknown':
+ return { source_id: id, state, exit: 1, code: 'movement_unknown', reason: 'backlog_read_failed',
+ why: `${id}: the managed sync backlog could not be read (${after.unknown?.error ?? 'no detail'}), so whether sync work is pending is not known; this is not a nothing-pending verdict.`,
+ fix: renderAction({ argv: ['gbrain', 'sources', 'writer', 'movement', id, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Read-only: reads the backlog again. If it keeps failing, gbrain doctor --json checks the database connection.', verify }, ctx), before, after };
case 'nothing_pending':
return { source_id: id, state, exit: 0, code: null, why: `${id}: no managed sync is pending${after.holds.count ? ` (${after.holds.count} held file(s) await their repair)` : ''}.`, fix: null, before, after };
case 'moved':
@@ -146,7 +155,7 @@ export function movementReport(before: SourceMovement | undefined, after: Source
}
export function formatMovementReport(r: MovementReport): string[] {
- const lines = [`${r.state === 'not_moving' || r.state === 'parked' ? '✗' : '✓'} ${r.source_id}: ${r.state}${r.code ? ` [${r.code}${r.reason ? `/${r.reason}` : ''}]` : ''}`, ` ${r.why}`];
+ const lines = [`${r.exit !== 0 ? '✗' : '✓'} ${r.source_id}: ${r.state}${r.code ? ` [${r.code}${r.reason ? `/${r.reason}` : ''}]` : ''}`, ` ${r.why}`];
if (r.fix?.command) lines.push(` Next: ${r.fix.command}${r.retry_after_ms ? ` (after ${Math.round(r.retry_after_ms / 1000)}s)` : ''}${r.fix.next === 'tell_user_to_run' ? ' (the host operator runs it)' : ''}`);
return lines;
}
@@ -219,8 +228,11 @@ export async function runMovementCheck(engine: BrainEngine, opts: { sourceId?: s
}
const sources = after.map(m => movementReport(byId.get(m.source_id), m, window.window_ms));
const failing = sources.find(r => r.exit !== 0);
- const error = failing ? toAgentError(opError('managed_sync_not_moving', failing.why, `Run ${writerStatusCommand(failing.source_id)} and follow the running claim's next step; verify with gbrain sources writer movement ${failing.source_id}.`,
- { reason: failing.reason, fix: readFix('Read-only: the request at the head, its step, wait cause, owner and next action.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', failing.source_id, '--json'] }) }),
- { transport: 'cli', command: 'sources writer movement', render: cliRenderContext() }) : undefined;
+ const error = !failing ? undefined : toAgentError(failing.code === 'movement_unknown'
+ ? opError('movement_unknown', failing.why, `Rerun gbrain sources writer movement ${failing.source_id}; if the backlog read keeps failing, run gbrain doctor --json.`,
+ { reason: failing.reason, fix: readFix('Read-only: reads the managed sync backlog again.', { argv: ['gbrain', 'sources', 'writer', 'movement', failing.source_id, '--json'] }) })
+ : opError('managed_sync_not_moving', failing.why, `Run ${writerStatusCommand(failing.source_id)} and follow the running claim's next step; verify with gbrain sources writer movement ${failing.source_id}.`,
+ { reason: failing.reason, fix: readFix('Read-only: the request at the head, its step, wait cause, owner and next action.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', failing.source_id, '--json'] }) }),
+ { transport: 'cli', command: 'sources writer movement', render: cliRenderContext() });
return { schema_version: 1, window_ms: window.window_ms, budget_ms: window.budget_ms, window_source: window.source, waited_ms: waited, sources, exit_code: failing ? 1 : 0, ...(error ? { error } : {}) };
}
diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.ts
index 05ca49a08b..0655bdfd66 100644
--- a/src/core/persistence/sync-movement.ts
+++ b/src/core/persistence/sync-movement.ts
@@ -23,11 +23,14 @@
* between cron runs; informational, never scored), `held` (the newest activity
* is a hold: #6298's containment, not a stall), `moving` (a commit or a step
* advance within `persistence.preparation_ceiling_ms`), `not_moving` (none for
- * longer than the ceiling while something live should have produced one).
+ * longer than the ceiling while something live should have produced one),
+ * `unknown` (#6781: the backlog read failed, so whether work is pending is not
+ * known; `unknown.reason` is `backlog_read_failed`; never `nothing_pending`).
* `data_moving` is true/false for the live states and null otherwise;
* `not_moving_since` is the last watermark. `judgeMovement` compares two
* snapshots over a window for the standalone command (`moved`,
- * `within_allowance`, `held`, `parked`, `not_moving`, `nothing_pending`).
+ * `within_allowance`, `held`, `parked`, `not_moving`, `nothing_pending`,
+ * `unknown`).
* `startMovementWatch` is the serve's unref'd ticker that prints one
* `[gbrain notice managed_sync_not_moving]` when a source flips to not moving
* and one line when it moves again.
@@ -38,7 +41,9 @@ import { claimStateOf, type ClaimState } from './claim-phase.ts';
import { readPreparationPolicy } from './switches.ts';
import { listHostConsumers } from './consumer-heartbeat.ts';
-export type MovementState = 'moving' | 'held' | 'parked' | 'not_moving' | 'nothing_pending';
+export type MovementState = 'moving' | 'held' | 'parked' | 'not_moving' | 'nothing_pending' | 'unknown';
+/** #6781: why a source's movement is `unknown`; `error` is the failed read's message, bounded. */
+export interface MovementUnknown { reason: 'backlog_read_failed'; error: string }
export interface MovementHead {
request_id: string;
state: string;
@@ -74,6 +79,8 @@ export interface SourceMovement {
ceiling_ms: number;
owner_is_this_host: boolean | null;
writer_status_command: string;
+ /** Set only when `movement_state` is `unknown`. */
+ unknown?: MovementUnknown;
}
export const MOVEMENT_WATCH_MS = 60_000;
@@ -121,7 +128,12 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
FROM persistence_source_bindings b JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation
JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE ($1::text[] IS NULL OR b.source_id=ANY($1::text[])) ORDER BY b.source_id`, [opts.sourceIds ?? null]);
if (!bindings.length) return [];
- const backlog = new Map((await readManagedSyncBacklog(engine, bindings.map(b => b.source_id)).catch(() => [])).map(b => [b.source_id, b]));
+ let unknown: MovementUnknown | null = null;
+ let backlogRows: ManagedSyncBacklog[] = [];
+ try { backlogRows = await readManagedSyncBacklog(engine, bindings.map(b => b.source_id)); } catch (error) {
+ unknown = { reason: 'backlog_read_failed', error: (error instanceof Error ? error.message : String(error)).slice(0, 300) };
+ }
+ const backlog = new Map(backlogRows.map(b => [b.source_id, b]));
const policy = await readPreparationPolicy(engine);
const { localHostId } = await import('./identity.ts');
const { persistenceConsumerStatus } = await import('./service.ts');
@@ -162,7 +174,7 @@ export async function readSourceMovement(engine: BrainEngine, opts: { sourceIds?
cursor: cursor ? { index: cursor.index, total: cursor.total, remaining: cursor.remaining, held: cursor.held, last_progress_at: cursor.last_progress_at, resume_command: cursor.resume_command, resume_args: cursor.resume_args } : null,
head, holds, admitted, admitted_since: iso(mark?.admitted_since), live: { drain: !!drain || !!jobDrain, drain_pid: drain?.holder_pid ?? null, drain_job_id: jobDrain, consumer }, ceiling_ms: policy.ceilingMs, owner_is_this_host: ownerHere,
writer_status_command: writerStatusCommand(binding.source_id) };
- out.push({ ...base, ...verdict(base, now) });
+ out.push(unknown ? { ...base, movement_state: 'unknown', data_moving: null, not_moving_since: null, unknown } : { ...base, ...verdict(base, now) });
}
return out;
}
@@ -183,6 +195,9 @@ function safeJson(text: string): unknown { try { return JSON.parse(text); } catc
/** One human line per source for `gbrain sources status`; null for a source with nothing pending. */
export function formatSourceMovement(m: SourceMovement): string | null {
if (m.movement_state === 'nothing_pending') return null;
+ if (m.movement_state === 'unknown') {
+ return `${m.source_id}: managed sync movement UNKNOWN: the sync backlog could not be read (${m.unknown?.reason ?? 'backlog_read_failed'}: ${m.unknown?.error ?? 'no detail'}); this is not a report that nothing is pending. Recheck: gbrain sources writer movement ${m.source_id}`;
+ }
const where = m.head?.step ? ` head at step ${m.head.step}${m.head.waiting_on && m.head.waiting_on !== 'unknown' ? ` (waiting on ${m.head.waiting_on})` : ''}${m.head.owner ? `, ${m.head.owner.kind} pid ${m.head.owner.pid}` : ''};` : '';
switch (m.movement_state) {
case 'not_moving': return `${m.source_id}: managed sync NOT MOVING since ${m.not_moving_since} (no committed page or step advance for longer than ${Math.round(m.ceiling_ms / 1000)}s while a ${m.live.drain ? 'sync' : 'consumer'} is live);${where} inspect: ${m.writer_status_command}`;
@@ -193,9 +208,9 @@ export function formatSourceMovement(m: SourceMovement): string | null {
}
/** The command's verdict over a window: what changed between two snapshots of one source. */
-export type MovementVerdict = 'moved' | 'within_allowance' | 'held' | 'parked' | 'not_moving' | 'nothing_pending';
+export type MovementVerdict = 'moved' | 'within_allowance' | 'held' | 'parked' | 'not_moving' | 'nothing_pending' | 'unknown';
export function judgeMovement(before: SourceMovement | undefined, after: SourceMovement): MovementVerdict {
- if (after.movement_state === 'nothing_pending') return 'nothing_pending';
+ if (after.movement_state === 'nothing_pending' || after.movement_state === 'unknown') return after.movement_state;
if (!before) return after.movement_state === 'moving' ? 'moved' : after.movement_state;
if (after.last_commit_at && (!before.last_commit_at || after.last_commit_at > before.last_commit_at)) return 'moved';
if (after.holds.last_hold_at && (!before.holds.last_hold_at || after.holds.last_hold_at > before.holds.last_hold_at)) return 'held';
diff --git a/test/sync-movement.test.ts b/test/sync-movement.test.ts
index 9ec927483a..149e3c26a0 100644
--- a/test/sync-movement.test.ts
+++ b/test/sync-movement.test.ts
@@ -22,9 +22,9 @@
* the not-moving fixture; the default window never drops below one sync
* preparation budget; every state's envelope follows the v1 contract.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -33,10 +33,13 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { syncLockId, tryAcquireDbLock, type DbLockHandle } from '../src/core/db-lock.ts';
import { withEnv } from './helpers/with-env.ts';
import { judgeMovement, readSourceMovement, startMovementWatch, formatSourceMovement, MOVEMENT_WATERMARK_SQL } from '../src/core/persistence/sync-movement.ts';
-import { movementReport, movementWindowMs, parseMovementArgs, runMovementCheck, MOVEMENT_SUPERVISOR_STEP } from '../src/commands/sources-writer-movement.ts';
+import { movementReport, movementWindowMs, parseMovementArgs, runMovementCheck, runWriterMovementCli, MOVEMENT_HELP, MOVEMENT_SUPERVISOR_STEP } from '../src/commands/sources-writer-movement.ts';
import { managedSyncMovementEntry } from '../src/commands/doctor/checks/managed-sync-movement.ts';
import { deriveNext, cliRenderContext } from '../src/core/agent-output.ts';
import { CODES } from '../src/core/error-registry.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-movement-'));
let engine: BrainEngine;
@@ -381,3 +384,95 @@ describe('doctor managed_sync_not_moving and the serve notice', () => {
}
}), 60_000);
});
+
+describe('#6781: a failed backlog read is unknown, never nothing_pending', () => {
+ /** The reporter's two arms: the same engine, except that the backlog SELECT alone rejects in the second. */
+ const BACKLOG_SQL = /FROM op_checkpoints WHERE op='managed-sync' AND COALESCE\(completed_keys->0->>'done','false'\)<>'true'/;
+ const failingBacklog = (target: BrainEngine): BrainEngine => new Proxy(target, {
+ get(t, prop) {
+ if (prop === 'executeRaw') {
+ return (sql: string, params?: unknown[]) => BACKLOG_SQL.test(sql) ? Promise.reject(new Error('OFFLINE_SENTINEL backlog read failed')) : t.executeRaw(sql, params);
+ }
+ const value = Reflect.get(t, prop, t);
+ return typeof value === 'function' ? value.bind(t) : value;
+ },
+ });
+ beforeEach(() => _resetCliExitVerdictForTests());
+
+ test('reader, window verdict and human line: control arm not_moving, injected arm unknown', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await managedSource();
+ await cursor(f, 2, 7, { progress: { startedAt: Date.now() - 400_000, startIndex: 0, lastAt: Date.now() - 300_000, lastIndex: 2 } });
+ await request(f, 'committed', { completedAt: ago(300_000) });
+ const lock = await tryAcquireDbLock(engine, syncLockId(f.id));
+ try {
+ const control = (await readSourceMovement(engine, { sourceIds: [f.id] }))[0]!;
+ expect(control).toMatchObject({ movement_state: 'not_moving', data_moving: false, cursor: { remaining: 5 } });
+ const injected = (await readSourceMovement(failingBacklog(engine), { sourceIds: [f.id] }))[0]!;
+ expect(injected).toMatchObject({ source_id: f.id, movement_state: 'unknown', data_moving: null, not_moving_since: null, cursor: null,
+ unknown: { reason: 'backlog_read_failed' }, live: { drain: true } });
+ expect(injected.unknown!.error).toContain('OFFLINE_SENTINEL');
+ expect(judgeMovement(undefined, injected)).toBe('unknown');
+ expect(judgeMovement(control, injected)).toBe('unknown');
+ const line = formatSourceMovement(injected);
+ expect(line).toContain('UNKNOWN');
+ expect(line).toContain('backlog_read_failed');
+ } finally { await lock!.release(); await finish(f); }
+ }), 60_000);
+
+ test('writer movement exits 1 with movement_unknown (never managed_sync_not_moving); --warn-only exits 0', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await managedSource();
+ await cursor(f, 2, 7);
+ try {
+ const result = await runMovementCheck(failingBacklog(engine), { sourceId: f.id, waitMs: 1_000, pollMs: 1, sleep: async () => {} });
+ expect(result.exit_code).toBe(1);
+ expect(result.sources[0]).toMatchObject({ source_id: f.id, state: 'unknown', exit: 1, code: 'movement_unknown', reason: 'backlog_read_failed' });
+ expect(result.error).toMatchObject({ code: 'movement_unknown', reason: 'backlog_read_failed' });
+ expect(JSON.stringify(result)).not.toContain('managed_sync_not_moving');
+ expect(result.sources[0]!.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'movement', f.id, '--json'], actor: 'agent', consent: [] });
+
+ // The command resolves the brain host config before it uses the connected engine.
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') }));
+ const out: string[] = [];
+ const logSpy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { out.push(args.map(String).join(' ')); });
+ const errSpy = spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ await runWriterMovementCli([f.id, '--wait', '1s'], failingBacklog(engine));
+ expect(currentExitCode()).toBe(1);
+ expect(out.join('\n')).toContain(`✗ ${f.id}: unknown [movement_unknown/backlog_read_failed]`);
+ _resetCliExitVerdictForTests();
+ out.length = 0;
+ await runWriterMovementCli([f.id, '--wait', '1s', '--warn-only'], failingBacklog(engine));
+ expect(currentExitCode()).toBe(0);
+ expect(out.join('\n')).toContain('--warn-only: exiting 0 despite the verdict above.');
+ } finally { logSpy.mockRestore(); errSpy.mockRestore(); }
+ expect(MOVEMENT_HELP).toContain('unknown');
+ expect(MOVEMENT_HELP).toContain('movement_unknown');
+ } finally { await finish(f); }
+ }), 60_000);
+
+ test('doctor warns with health unknown; sources status and the writer_status admin op show unknown instead of blanking', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const f = await managedSource();
+ await cursor(f, 2, 7);
+ try {
+ const broken = failingBacklog(engine);
+ const [check] = await managedSyncMovementEntry.run({ engine: broken } as unknown as Parameters<typeof managedSyncMovementEntry.run>[0]) as unknown as Array<Record<string, unknown>>;
+ expect(check).toMatchObject({ name: 'managed_sync_not_moving', status: 'warn', details: { health: 'unknown' } });
+ const details = check!.details as { unknown: number; sources: Array<{ source_id: string; movement_state: string }> };
+ expect(details.unknown).toBeGreaterThanOrEqual(1);
+ expect(details.sources).toContainEqual(expect.objectContaining({ source_id: f.id, movement_state: 'unknown' }));
+ expect(String(check!.message)).toContain(f.id);
+ expect(String(check!.message)).toContain('could not be read');
+
+ const logs: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(' ')); });
+ try { await runSources(broken, ['status', f.id, '--json']); } finally { spy.mockRestore(); }
+ const status = JSON.parse(logs.join('\n')) as { sources: Array<{ source_id: string; movement_state?: string; data_moving?: unknown }> };
+ expect(status.sources.find(s => s.source_id === f.id)).toMatchObject({ movement_state: 'unknown', data_moving: null });
+
+ const admin = await runPersistenceAdministration(broken, 'writer_status', { source_id: f.id }) as { movement: Array<{ source_id: string; movement_state: string }> };
+ expect(admin.movement).toEqual([expect.objectContaining({ source_id: f.id, movement_state: 'unknown' })]);
+ } finally { await finish(f); }
+ }), 60_000);
+});
+