Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync status): checkpoint_blockers is always an array (#6712 PR 0)

garrytana1b85c41ca16
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 64dec8af2b..450cd37f5e 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -25,7 +25,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/sync-checkpoint-replaced.ts` — wave 16 (GBRA-79, #6513 comments): a managed-sync checkpoint whose cursor another run of the source replaced is superseded, not failed. `checkpointCursorReplaced` is the classification the shared validator (`sync-prepare.ts` `sourceSyncChecks` consumer) and the checkpoint's final locked compare-and-swap both apply before their own checks: a checkpoint intent whose durable cursor names another `runId` refuses `sync_cursor_replaced` (receipt state `conflict`, through `coordinator.ts` `conflictCode`); a page request whose cursor moved keeps `revision_conflict` (its run re-admits from the current cursor), a same-run index lag keeps `revision_conflict`, a missing manifest keeps `storage_error`. `checkpointSuperseded` recognizes that receipt in `sync-run.ts`: `settleFailedRequest` records no managed-sync failure for it and continues with the winning cursor as it stands (`currentCursor`, the same move the ENG-A7 admission guard makes when the cursor moves under it; the winner's run id, index and manifest are kept, nothing of it is cleared or advanced), and `retryFailedStart` never treats a checkpoint receipt as a page fault. Before, the loser's run recorded the conflict as a `managed-sync-failure` row, doctor reported it, and `--retry-failed` rediscovered from HEAD. Test: `test/managed-sync-checkpoint-replaced.test.ts` (replacement before validation on both engines; replacement from a second Postgres session between validation and the CAS; `--retry-failed` afterwards converts nothing; controls: index lag, missing manifest).
-- `src/core/persistence/sync-knock-on.ts` — #6643: a sync page request that ended without committing only because another request of its sync did not commit (a knock-on). Cancellers stamp `error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }` (survives compaction); pre-#6643 receipts match only their producers' exact messages (`LEGACY_KNOCK_ON_CANCEL_MESSAGES`, the never-admitted patterns, `EARLIER_PAGE_REFUSAL_MESSAGE`), never an operator cancel. `isSyncKnockOn` and `syncKnockOnSql` are one predicate (the SQL is never NULL, so `NOT` of it is safe in clause 3). `cursorFenceCause` reads the three causes of "cursor changed" (`run_replaced`, `window_dropped` only for a request the cursor recorded in `Cursor.dropped`, else `outside_fence`). `sync-run.ts` `recoverKnockOn` re-freezes the entry through `holdUnderGate` (budgets `sync.knock_on_refreeze_limit` per index, `sync.knock_on_run_limit` per invocation; past them `knock_on_exhausted` with `root_cause`), `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end, and `checkpoint-validation.ts` skips knock-ons of pre-#6643 cursors and the cursor's settled index ranges. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`).
+- `src/core/persistence/sync-knock-on.ts` — #6643: a sync page request that ended without committing only because another request of its sync did not commit (a knock-on). Cancellers stamp `error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }` (survives compaction); pre-#6643 receipts match only their producers' exact messages (`LEGACY_KNOCK_ON_CANCEL_MESSAGES`, the never-admitted patterns, `EARLIER_PAGE_REFUSAL_MESSAGE`), never an operator cancel. `isSyncKnockOn` and `syncKnockOnSql` are one predicate (the SQL is never NULL, so `NOT` of it is safe in clause 3). `cursorFenceCause` reads the three causes of "cursor changed" (`run_replaced`, `window_dropped` only for a request the cursor recorded in `Cursor.dropped`, else `outside_fence`). `sync-run.ts` `recoverKnockOn` re-freezes the entry through `holdUnderGate` (budgets `sync.knock_on_refreeze_limit` per index, `sync.knock_on_run_limit` per invocation; past them `knock_on_exhausted` with `root_cause`), `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end, and `checkpoint-validation.ts` skips knock-ons of pre-#6643 cursors and the cursor's settled index ranges. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`; #6712 PR 0: always an array, empty unless a checkpoint is pending; `test/sync-status-checkpoint-blockers-shape.test.ts`).
- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index a7b2c381a8..7f91f4b73a 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -85,8 +85,12 @@ export interface SyncStatus {
human_reason?: string;
/** The resume arguments after `gbrain sync` for this source's cursor (its stored options when one exists). */
resume_argv: string[];
- /** #6643: for a cursor whose checkpoint has not committed, every receipt that would block it now (empty: the next sync commits it). */
- checkpoint_blockers?: Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean; knock_on: boolean }>;
+ /**
+ * #6643: for a cursor whose checkpoint has not committed, every receipt that would block it now (empty: the next sync
+ * commits it). #6712 PR 0: always present; empty when no checkpoint is pending (no cursor, a finished one, or one
+ * still before its checkpoint step).
+ */
+ checkpoint_blockers: Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean; knock_on: boolean }>;
/** #6643: every managed-sync cursor of the source under its current incarnation, newest first (at most 20). */
cursors: SyncStatusCursor[];
/** #6650: the source's terminal write receipts that did not commit, summarized (`terminal-failures.ts`); `unknown` when the bounded read timed out. */
@@ -247,16 +251,16 @@ export async function readCheckpointBlockers(engine: BrainEngine, sourceId: stri
if (!source) return [];
const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');
const selected = await cursorHeader(engine, sourceId, source.incarnation, failures[0]?.cursor_key ?? null);
- return (await checkpointBlockers(engine, selected?.header ?? null)).checkpoint_blockers ?? [];
+ return (await checkpointBlockers(engine, selected?.header ?? null)).checkpoint_blockers;
}
/**
* #6643: a cursor at its end whose checkpoint has not committed lists every receipt that would block that checkpoint now
* (the checkpoint's own refusal names only the first), each marked when it is a knock-on; empty means the next sync commits it.
*/
-async function checkpointBlockers(engine: BrainEngine, header: CursorHeader | null): Promise<{ checkpoint_blockers?: Array<Awaited<ReturnType<typeof listIncompleteSyncReceipts>>[number] & { knock_on: boolean }> }> {
+async function checkpointBlockers(engine: BrainEngine, header: CursorHeader | null): Promise<{ checkpoint_blockers: Array<Awaited<ReturnType<typeof listIncompleteSyncReceipts>>[number] & { knock_on: boolean }> }> {
const intent = header?.pending?.intent;
- if (!header || header.done || intent?.kind !== 'managed_sync_checkpoint' || !header.binding?.worktree_id) return {};
+ if (!header || header.done || intent?.kind !== 'managed_sync_checkpoint' || !header.binding?.worktree_id) return { checkpoint_blockers: [] };
const rows = await listIncompleteSyncReceipts(engine, header.binding.worktree_id, header.runId, intent.supersededRequests ?? [], intent.settled ?? null, Number(header.total));
const knockOns = new Set(rows.length ? (await engine.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests r
WHERE r.request_id::text = ANY($1::text[]) AND ${syncKnockOnSql('r')}`, [rows.map(row => row.request_id)])).map(row => row.request_id) : []);
diff --git a/test/sync-status-checkpoint-blockers-shape.test.ts b/test/sync-status-checkpoint-blockers-shape.test.ts
new file mode 100644
index 0000000000..28c4f1e8c5
--- /dev/null
+++ b/test/sync-status-checkpoint-blockers-shape.test.ts
@@ -0,0 +1,118 @@
+/**
+ * #6712 PR 0: `gbrain sync status --json` always carries `checkpoint_blockers` as an array, so the convergence
+ * gate's status oracle (and an operator agent) can read it without guessing whether its absence means "nothing
+ * blocks" or "not computed".
+ *
+ * Protects: the rendered JSON of `sync status --source <id> --json` (the command's own renderer,
+ * `runSyncStatus`) has `checkpoint_blockers` as an array in all four states of a managed source: no cursor
+ * (empty), an unfinished cursor before its checkpoint step (empty: no checkpoint is pending yet), a finished
+ * cursor (empty), and a cursor at its checkpoint behind a receipt that still holds a publication recovery record
+ * (that receipt, marked `recovery`). `cursors` stays an array in each.
+ * Fails when: the field is left out for an absent, unfinished or finished cursor (master before this change
+ * omitted it in all three).
+ * PGLite in-memory; no production seam.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runSyncStatus } from '../src/commands/sync/operator.ts';
+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SOURCE = 'shape-src';
+let engine: PGLiteEngine;
+let home: string;
+let worktreeId: string;
+let incarnation: string;
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-status-shape-'));
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ const root = join(home, 'repo');
+ mkdirSync(root);
+ execFileSync('git', ['-C', root, 'init', '-q']);
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, root]);
+ await claimWorktree(engine, SOURCE, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ worktreeId = (await getWorktreeBinding(engine, SOURCE))!.worktree_id;
+ incarnation = (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [SOURCE]))[0]!.incarnation;
+}, 60_000);
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+beforeEach(async () => {
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync'");
+ await engine.executeRaw('DELETE FROM persistence_requests');
+});
+
+/** The JSON document `gbrain sync status --source <id> --json` prints. */
+async function statusJson(): Promise<Record<string, unknown>> {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { await withEnv({ GBRAIN_SOURCE: undefined, GBRAIN_HOME: home }, () => runSyncStatus(engine, ['--source', SOURCE, '--json'])); } finally { console.log = log; }
+ return JSON.parse(lines.join('\n')) as Record<string, unknown>;
+}
+async function cursor(header: Record<string, unknown>): Promise<string> {
+ const runId = randomUUID();
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`, [`fp-${runId}`, JSON.stringify([{
+ runId, sourceId: SOURCE, incarnation, target: 'a'.repeat(40), binding: { worktree_id: worktreeId }, ...header }])]);
+ return runId;
+}
+
+describe('sync status --json checkpoint_blockers is always an array', () => {
+ test('no cursor: an empty array', async () => {
+ const status = await statusJson();
+ expect(status.cursor).toBeNull();
+ expect(status.checkpoint_blockers).toEqual([]);
+ expect(status.cursors).toEqual([]);
+ });
+
+ test('an unfinished cursor before its checkpoint step: an empty array (no checkpoint is pending yet)', async () => {
+ await cursor({ index: 1, total: 3, pending: { requestId: randomUUID(), intent: { kind: 'managed_sync_import', path: 'notes/two.md' } } });
+ const status = await statusJson();
+ expect(status.cursor).toMatchObject({ index: 1, total: 3, done: false });
+ expect(status.checkpoint_blockers).toEqual([]);
+ expect(Array.isArray(status.cursors)).toBe(true);
+ });
+
+ test('a finished cursor: an empty array', async () => {
+ await cursor({ index: 3, total: 3, done: true });
+ const status = await statusJson();
+ expect(status.cursor).toMatchObject({ done: true });
+ expect(status.checkpoint_blockers).toEqual([]);
+ expect(Array.isArray(status.cursors)).toBe(true);
+ });
+
+ test('a cursor at its checkpoint behind a receipt that holds a recovery record: that receipt', async () => {
+ const runId = randomUUID(), blocker = randomUUID();
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,
+ terminal_reservation,state,error_code,error_message,recovery,intent,completed_at,updated_at,admitter_version,worktree_id)
+ VALUES('local_cli','fixture',$1::uuid,'submit_job',$2,$3::uuid,'notes/two',$4,'{}'::jsonb,0,0,'failed','storage_error','x',$5::text::jsonb,$6::text::jsonb,
+ now()-interval '1 hour',now()-interval '1 hour','0.60.243.0',$7::uuid)`,
+ [blocker, SOURCE, incarnation, randomUUID(), JSON.stringify({ version: 1, path: '/nonexistent/x.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' }),
+ JSON.stringify({ kind: 'managed_sync_import', runId, index: 2 }), worktreeId]);
+ });
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-sync',$1,$2::text::jsonb)`, [`fp-${runId}`, JSON.stringify([{
+ runId, sourceId: SOURCE, incarnation, index: 3, total: 3, target: 'a'.repeat(40), binding: { worktree_id: worktreeId },
+ pending: { requestId: randomUUID(), intent: { kind: 'managed_sync_checkpoint' } } }])]);
+ const status = await statusJson();
+ expect(status.cursor).toMatchObject({ index: 3, total: 3, done: false });
+ expect(status.checkpoint_blockers).toEqual([expect.objectContaining({ request_id: blocker, slug: 'notes/two', recovery: true, knock_on: false })]);
+ expect(Array.isArray(status.cursors)).toBe(true);
+ });
+});