Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6643: review round 2 — fence causes from recorded drops, outside_fence in status, failed-cursor binding, checkpoint blockers, per-invocation budgets
garrytan5a49a507a052
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex c2104414cc..40f390debb 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -136,8 +136,13 @@ the root. A cursor refusal is classified by its recorded cause:`window_dropped` (a knock-on), or `outside_fence` (a request was not theentry its cursor held: a person stops the extra drain and reports it).After `sync.knock_on_refreeze_limit` re-freezes at one index (default 3;-0 turns automatic re-freeze off), or 25 in one run, the run stops with-`knock_on_exhausted` and names the root.+0 turns automatic re-freeze off), or after `sync.knock_on_run_limit`+re-freezes in one sync invocation (default 25), the run stops with+`knock_on_exhausted` and names the root. The per-index count resets when+the page commits; the per-invocation count resets on the next sync. A+checkpoint refused by a receipt that turns out to be a knock-on, or at an+index the cursor passed without a commit, is re-assessed on every resume and+commits without rediscovering the manifest.An unknown code is systemic and human: `gbrain errors <code>` explains itoffline, `gbrain doctor --json` says what the brain thinks.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex af6a92d5ff..d0dbd437c2 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -541,6 +541,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6574 (publication round trips). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.209.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },{ since: '0.60.209.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },+ { since: '0.60.213.0', text: 'A managed sync now re-freezes, by itself, a page that was cancelled or refused only because another page of the same sync did not commit (a knock-on), under `sync.holds=fail` too and without `--retry-failed`; an operator cancel is never re-frozen. The re-freeze is bounded by `sync.knock_on_refreeze_limit` (per page, default 3, 0 turns it off) and `sync.knock_on_run_limit` (per sync invocation, default 25); past them the run stops `knock_on_exhausted` naming the root request. A checkpoint refused by such a receipt, or by one at an index the run passed without a commit, is re-assessed on every resume and commits without rediscovering the manifest. A "cursor changed" refusal now records its cause: `run_replaced` (superseded, not failed), `window_dropped` (a knock-on), or `outside_fence` (a coordination fault that needs a person). `--retry-failed` no longer silently does nothing when the old run still has open requests: it returns `partial` with `retryWait` naming the request. `gbrain sync status --json` adds `last_error.root_cause`, `cursors` (every live cursor of the source) and `checkpoint_blockers`, and shows the cursor its recorded failure belongs to. The write owner must run this release for the recovery to apply.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 636acc1918..3f7a44c702 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -78,6 +78,18 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa}}+/**+ * #6643: every receipt (up to 20) that would block the run's checkpoint now, with what `sync status` needs to tell a+ * knock-on from a root; read-only. The checkpoint itself names only the first (`findIncompleteSyncReceipt`).+ */+export async function listIncompleteSyncReceipts(engine: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = [],+ settled: SyncSettledIndexes | null = null, total = 0): Promise<Array<{ request_id: string; slug: string; state: string; code: string | null; index: number | null; recovery: boolean }>> {+ const ranges = settled?.ranges ?? [];+ return engine.executeRaw(`SELECT r.request_id::text AS request_id, r.slug, r.state, r.error_code AS code, (r.intent->>'index')::int AS index, r.recovery IS NOT NULL AS recovery+ FROM persistence_requests r WHERE r.request_id::text IN (SELECT request_id FROM (${INCOMPLETE_SYNC_RECEIPT_SQL.replaceAll('LIMIT 1', 'LIMIT 20')}) blockers) ORDER BY r.sequence LIMIT 20`,+ [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1]), settled ? settled.from : total]);+}+/** #6643: `settled` with `[from, to]` added, merged into the last range when contiguous. */export function addSettledRange(settled: SyncSettledIndexes, from: number, to: number): SyncSettledIndexes {if (to < from) return settled;diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 8102eb7a04..3e0529f254 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -1,5 +1,6 @@import { OperationError } from '../ops/contract.ts';import { writerStamp } from './writer-versions.ts';+import { cursorFenceCause } from './sync-knock-on.ts';import type { FenceFailureDetail } from '../fence-repair/refusal.ts';import type { WithdrawalFailureDetail } from '../facts/withdrawal.ts';import type { Action } from '../agent-output.ts';@@ -193,14 +194,16 @@ export function withAttempt(failure: PublicationFailure, stage: PublicationStage* reason and problem classes; its row numbers stay owner-side (they can* number rows a remote caller never saw).*/-const PUBLIC_DETAIL_KEYS: ReadonlySet<string> = new Set(['origin', 'sqlstate', 'raiser', 'table', 'op', 'branch', 'relationship', 'reason', 'stage', 'fence']);+const PUBLIC_DETAIL_KEYS: ReadonlySet<string> = new Set(['origin', 'sqlstate', 'raiser', 'table', 'op', 'branch', 'relationship', 'reason', 'stage', 'fence', 'cause']);export function publicFailureDetail(detail: unknown): Record<string, unknown> | undefined {if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return undefined;// #5929: an allow-list, so a key added to a stored detail is owner-only unless it is listed here.// #6513: `reason` is public only as a member of the closed enum, whatever a stored detail holds under that key.const rest = Object.fromEntries(Object.entries(detail).filter(([key, value]) => PUBLIC_DETAIL_KEYS.has(key)- && (key !== 'reason' || (PUBLICATION_REASONS as readonly unknown[]).includes(value))));+ && (key !== 'reason' || (PUBLICATION_REASONS as readonly unknown[]).includes(value))+ // #6643: a cursor fence refusal's `cause` is public only as a member of its closed enum.+ && (key !== 'cause' || cursorFenceCause({ cause: value }) !== null)));if ((rest as { origin?: unknown }).origin === 'fence') {const { rows: _rows, issues, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];const publicIssues = Array.isArray(issues) ? issues.map(({ row: _row, ...issue }) => issue) : undefined;diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex a2b189422c..fd355a15bf 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -71,7 +71,7 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [{ code: 'outside_fence', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: a request published outside the cursor that admitted it',human_reason: 'A sync request was not the entry its cursor held (two drains of one cursor, or a writer defect). gbrain sync status --source <source> --json lists the live cursors; stop the extra drain (gbrain autopilot pause --reason <why>) and report the fence snapshot the error carries.' },{ code: 'knock_on_exhausted', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always: re-freezing did not get past the failing page',- human_reason: 'The same page kept being cancelled because an earlier page of the sync never committed. Fix the root request the error names, or raise sync.knock_on_refreeze_limit, then rerun the sync; the count resets when the page commits.' },+ human_reason: 'The same page kept being cancelled because an earlier page of the sync never committed. Fix the root request the error names, or raise sync.knock_on_refreeze_limit (per page) or sync.knock_on_run_limit (per sync), then rerun the sync; the per-page count resets when the page commits.' },{ code: 'sync_incomplete', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: an unfinished cursor resumes with the same command' },// Connection class: transport only; the cursor and manifest stand.{ code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 7081ded3ce..38dba7b70b 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -97,12 +97,15 @@ export interface SyncIntent extends Record<string, unknown> {* admitted ahead (`window`). FOR KEY SHARE keeps the cursor row in place without blocking the drain's* cursor saves, so the next group is admitted while this one publishes.*/-interface SyncCursorFence { run_id: string; request_id: string | null; group: string[] | null; index: string | number | null }+export interface SyncCursorFence { run_id: string; request_id: string | null; group: string[] | null; index: string | number | null;+ /** #6643: the cursor's record of the window members it dropped (sync-run.ts `Cursor.dropped`). */+ dropped?: Array<{ requestId: string; root: string | null }> | null }async function readSyncCursorFence(tx: BrainEngine, cursorKey: string): Promise<SyncCursorFence | undefined> {const [held] = await tx.executeRaw<SyncCursorFence>(`SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id,completed_keys->0->>'index' AS index,(SELECT jsonb_agg(m->>'requestId') FROM (SELECT m FROM jsonb_array_elements(COALESCE(completed_keys->0->'group','[]'::jsonb)) m- UNION ALL SELECT m FROM jsonb_array_elements(COALESCE(completed_keys->0->'window','[]'::jsonb)) g, jsonb_array_elements(g) m) members) AS group+ UNION ALL SELECT m FROM jsonb_array_elements(COALESCE(completed_keys->0->'window','[]'::jsonb)) g, jsonb_array_elements(g) m) members) AS group,+ completed_keys->0->'dropped' AS droppedFROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR KEY SHARE`, [cursorKey]);return held;}@@ -167,9 +170,11 @@ function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteR* #6643: a refusal that is not a failure of its page (a knock-on, or a request whose run another run replaced). Its* next step is the status read, never a `--retry-failed` rerun: the next sync pass re-freezes the entry by itself.*/-function knockOnRefusal(message: string, row: WriteRequest, cause: string): OperationError {+function knockOnRefusal(message: string, row: WriteRequest, cause: string, superseded = false): OperationError {const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];- return opError('revision_conflict', message, `${cause} Request ${row.request_id} in ${row.source_id} published nothing, and the next sync pass re-freezes its page by itself; `+ return opError('revision_conflict', message, superseded+ ? `${cause} Request ${row.request_id} in ${row.source_id} published nothing; the run that replaced its cursor covers its page, and ${status.join(' ')} shows that run. Do not resubmit it.`+ : `${cause} Request ${row.request_id} in ${row.source_id} published nothing, and the next sync pass re-freezes its page by itself; `+ `${status.join(' ')} names the request it waited on (root_cause). Do not resubmit it.`,{ fix: readFix('Shows the sync cursor, the root cause of this refusal and the next step, read-only.', { argv: status }) });}@@ -183,22 +188,24 @@ function withSyncRefusal(error: OperationError, detail: object): OperationError/*** #6643: "The accepted sync cursor changed before publication." has three causes, recorded with a fence snapshot:* - `run_replaced`: another run of the source replaced the cursor; this request's run is superseded, not failed.- * - `window_dropped`: the request was admitted ahead of the cursor (its index is past the cursor's) in a window the- * cursor dropped after an earlier page did not commit, and validated before that drop reached it (a lane row the- * window cancel skipped because it was already claimed). A knock-on of the request the cursor now waits on.- * - `outside_fence`: anything else (a duplicate admission at or behind the cursor): a coordination fault, a root.+ * - `window_dropped`: the cursor recorded this request as a member of a window it dropped after an earlier page did+ * not commit (a lane row the window cancel skipped because it was already claimed). A knock-on of the request whose+ * failure dropped it, as recorded then.+ * - `outside_fence`: anything else (a duplicate admission, a request ahead of the cursor it never dropped): a+ * coordination fault, a root.*/-function cursorFenceRefusal(row: WriteRequest, p: SyncIntent, cursor: SyncCursorFence): OperationError {+export function cursorFenceRefusal(row: WriteRequest, p: SyncIntent, cursor: SyncCursorFence): OperationError {const cursorIndex = cursor.index == null ? null : Number(cursor.index);- const cause = cursor.run_id !== p.runId ? 'run_replaced'- : p.kind !== 'managed_sync_checkpoint' && cursorIndex !== null && Number.isFinite(cursorIndex) && p.index > cursorIndex ? 'window_dropped' : 'outside_fence';+ const drop = cursor.run_id === p.runId && p.kind !== 'managed_sync_checkpoint' && Array.isArray(cursor.dropped)+ ? cursor.dropped.find(member => member?.requestId === row.request_id) : undefined;+ const cause = cursor.run_id !== p.runId ? 'run_replaced' : drop ? 'window_dropped' : 'outside_fence';const fence = { run_id: cursor.run_id, expected_run_id: p.runId, request_id: cursor.request_id, members: cursor.group?.length ?? 0, index: cursorIndex, request_index: p.index };const error = (cause === 'outside_fence' ? (why: string) => syncPublicationRefusal('revision_conflict', CURSOR_CHANGED_REFUSAL_MESSAGE, row, p, why)- : (why: string) => knockOnRefusal(CURSOR_CHANGED_REFUSAL_MESSAGE, row, why))(+ : (why: string) => knockOnRefusal(CURSOR_CHANGED_REFUSAL_MESSAGE, row, why, cause === 'run_replaced'))(cause === 'run_replaced' ? `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`: cause === 'window_dropped' ? `Request ${row.request_id} was admitted ahead of the cursor of ${row.source_id}, which dropped it after an earlier page of the same run did not commit.`: `Request ${row.request_id} is not the entry the cursor of ${row.source_id} holds (cursor at index ${cursorIndex ?? 'unknown'}, request ${cursor.request_id ?? 'none'}), so it must not publish.`);- return withSyncRefusal(error, cause === 'window_dropped' ? { ...knockOnDetail('window_dropped', cursor.request_id), cause, fence }+ return withSyncRefusal(error, cause === 'window_dropped' ? { ...knockOnDetail('window_dropped', drop?.root ?? null), cause, fence }: { origin: SYNC_CURSOR_FENCE_ORIGIN, cause, fence });}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 71187aeb54..f94475e02c 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -103,6 +103,12 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authoritysettled?: SyncSettledIndexes;/** #6643: knock-on re-freezes this run made (the per-run breaker), and checkpoint revivals. */knockOns?: number; checkpointRevivals?: number;+ /**+ * #6643: the window members this run dropped after an earlier page did not commit, each with the request whose+ * failure dropped it (newest last, at most `DROPPED_KEPT`). A member already claimed when its window was cancelled+ * can still validate later; the cursor fence names it a knock-on of `root` only from this record.+ */+ dropped?: Array<{ requestId: string; root: string | null }>;/** #6278 (1.5): the systemic breaker over this run's `preparation_stalled` receipts; recorded with the cursor CAS that consumes each. */breaker?: CursorBreaker;/** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */@@ -173,6 +179,12 @@ function stampProgress(prior: CursorProgress | undefined, fromIndex: number, indconst OP = 'managed-sync';type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });+const DROPPED_KEPT = 512;+/** #6643: `dropped` with every member of `window` recorded as dropped by `root`. */+function withDropped(dropped: Cursor['dropped'], window: Pending[][] | undefined, root: string | null): Cursor['dropped'] {+ const members = (window ?? []).flat().map(member => ({ requestId: member.requestId, root }));+ return members.length ? [...(dropped ?? []), ...members].slice(-DROPPED_KEPT) : dropped;+}/** A managed sync run stopped before admitting the current entry; the recorded failure lets --retry-failed rediscover. */function syncRunRefusal(code: RegistryCode, message: string, retry: Parameters<typeof checkpointRetryCommand>[0], cause: string): OperationError {return opError(code, message, `${cause} Pages committed earlier in this run stay committed. Check the source with the command in fix, then run: ${checkpointRetryCommand(retry)}`,@@ -565,6 +577,8 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:const stale = await tx.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2AND ${SYNC_PAGE_KINDS_SQL} AND intent->>'index'=$3 AND state IN ('failed','cancelled','conflict')`, [cursor.binding.worktree_id, cursor.runId, String(cursor.index)]);const converted = [...new Set([...(cursor.convertedFromFailed ?? []), ...stale.map(row => row.request_id), pending.requestId])];+ const dropped = withDropped(cursor.dropped, cursor.window, pending.requestId);+ if (dropped) base.dropped = dropped;const next: Cursor = input.hold ? advanceHeld(base, converted): input.knockOn ? { ...base, convertedFromFailed: converted, knockOns: (cursor.knockOns ?? 0) + 1,pending: { ...input.refrozen, ...(pending.converted ? { converted: true as const } : {}), knockOn: input.knockOn } }@@ -729,7 +743,7 @@ const CHECKPOINT_REVIVAL_LIMIT = 3;/*** #6643: `sync.knock_on_refreeze_limit`, knock-on re-freezes in a row at one index (default 3; 0 turns automatic* re-freeze off), and `sync.knock_on_run_limit`, the most one run makes before it stops with the root cause (default- * 25, a per-run breaker like `breakerAfter`).+ * 25 per sync invocation, a breaker like `breakerAfter`; the next invocation starts counting again).*/export async function knockOnLimits(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ perIndex: number; perRun: number }> {const read = async (key: string, fallback: number) => {@@ -741,6 +755,8 @@ export async function knockOnLimits(engine: Pick<BrainEngine, 'getConfig'>): Pro}type SettleInput = Parameters<typeof settleFailedRequest>[1];+/** #6643: knock-on re-freezes per sync invocation (keyed by its run options object): `sync.knock_on_run_limit` bounds one invocation, and the next starts again. */+const knockOnsByRun = new WeakMap<object, number>();/*** #6643: the entry of a knock-on (a page cancelled or refused only because another page of its sync did not commit)@@ -756,9 +772,10 @@ async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<if (!entry || entry.path !== pending.intent.path) return null;const limits = await knockOnLimits(engine);if (limits.perIndex === 0) return null;- const attempts = pending.knockOn?.attempts ?? 0, runCount = cursor.knockOns ?? 0;+ const attempts = pending.knockOn?.attempts ?? 0, runCount = knockOnsByRun.get(input.run) ?? 0;if (attempts >= limits.perIndex || runCount >= limits.perRun) return { exhausted: { attempts, limit: limits.perIndex, runCount, runLimit: limits.perRun } };const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;+ knockOnsByRun.set(input.run, runCount + 1);const refrozen = await freezeEntry(engine, base, key, assertActive, input.run);assertActive();const observedAt = input.run.observedAt ?? new Date().toISOString();@@ -769,21 +786,31 @@ async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<return gated === 'pending' ? 'pending' : { cursor: gated };}+/** #6643: checkpoint revivals per sync invocation (keyed by its run options object), so a refusal loop ends the invocation, never the cursor. */+const checkpointRevivalsByRun = new WeakMap<object, number>();+const NOT_FULLY_COMMITTED_MESSAGE = 'The sync cursor is not fully committed.';+const revivableCheckpointRefusal = (done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'recovery'>) => !done.recovery+ && ((done.state === 'failed' && done.error_code === 'recovery_required')+ || (['failed', 'conflict'].includes(done.state) && done.error_code === 'revision_conflict' && done.error_message === NOT_FULLY_COMMITTED_MESSAGE));/**- * #6643: a checkpoint refused `recovery_required` because a receipt blocked it is re-assessed when the run resumes:- * when nothing blocks it any more (a knock-on, a receipt at an index the cursor settled), a fresh checkpoint request- * replaces it by cursor swap. The completed manifest and the old receipt stay as they are. Null when it still blocks.+ * #6643: a checkpoint refused because a receipt blocked it (`recovery_required`) or because the cursor had not reached+ * its end yet ("not fully committed") is re-assessed whenever the run resumes: when nothing blocks it any more (a+ * knock-on, a receipt at an index the cursor settled), a fresh checkpoint request replaces it by cursor swap, and its+ * publication validates everything again. The completed manifest and the old receipt stay as they are. Null when it+ * still blocks, or after `CHECKPOINT_REVIVAL_LIMIT` revivals in this invocation (the next invocation re-assesses).*/async function reviveCheckpoint(engine: BrainEngine, input: SettleInput): Promise<Cursor | null> {const { cursor, key, pending, done } = input;- if (pending.intent.kind !== 'managed_sync_checkpoint' || done.state !== 'failed' || done.error_code !== 'recovery_required' || done.recovery- || cursor.index !== cursor.entries.length || (cursor.checkpointRevivals ?? 0) >= CHECKPOINT_REVIVAL_LIMIT) return null;+ const refused = revivableCheckpointRefusal(done);+ const revivals = checkpointRevivalsByRun.get(input.run) ?? 0;+ if (pending.intent.kind !== 'managed_sync_checkpoint' || !refused || done.recovery || cursor.index !== cursor.entries.length || revivals >= CHECKPOINT_REVIVAL_LIMIT) return null;const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;const fresh = await freezeEntry(engine, base, key, input.assertActive, input.run);if ('hold' in fresh) return null;const blocker = await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, fresh.intent.supersededRequests ?? [], fresh.intent.settled ?? null, cursor.entries.length);input.assertActive();if (blocker) return null;+ checkpointRevivalsByRun.set(input.run, revivals + 1);return saveCursor(engine, key, cursor, { ...base, checkpointRevivals: (cursor.checkpointRevivals ?? 0) + 1, pending: fresh }, false, input.assertActive);}@@ -1226,6 +1253,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:if (!await cancelWindow(engine, next.window, principal, stuck!.requestId, { cursorKey: key, expectedRequestId: cursor.pending!.requestId, principal, worktreeId: cursor.binding.worktree_id })) {return { cursor: await currentCursor(engine, key, cursor) };}+ next.dropped = withDropped(next.dropped, next.window, stuck!.requestId);delete next.window;}const saved = committed || failed || next.group?.length !== members.length ? await saveCursor(engine, key, cursor, next) : cursor;@@ -1309,7 +1337,7 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: stringassertActive();// #6643: a knock-on, and a checkpoint refused only by a receipt that no longer blocks it, recover in place in the drain// (settleFailedRequest), which waits only on the narrowed gate; neither rediscovers the frozen manifest.- if (failed && cursor.pending && (isSyncKnockOn(failed) || (cursor.pending.intent.kind === 'managed_sync_checkpoint' && failed.error_code === 'recovery_required' && !failed.recovery))) return null;+ if (failed && cursor.pending && (isSyncKnockOn(failed) || (cursor.pending.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)))) return null;const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);assertActive();if (!((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed)))) return null;@@ -1415,7 +1443,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst discovery = await discoverManagedSync(engine, opts, context);assertActive();const replaced = await replaceCursor(engine, key, error.cursor, { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);- if ('wait' in replaced) return { ...result(error.cursor, 'partial', 'writer_pending'), retryWait: replaced.wait };+ if ('wait' in replaced) return { ...result(error.cursor, 'partial', 'writer_pending'), ...(authority.writer.remote ? {} : { retryWait: replaced.wait }) };cursor = replaced;}assertActive();@@ -1423,7 +1451,8 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);assertActive();- if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) || !cursor.pending && !cursor.processingOptions)) {+ // #6643: a knock-on recovers in the drain (recoverKnockOn), which keeps its per-index and per-run budgets.+ if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) && !isSyncKnockOn(failed) || !cursor.pending && !cursor.processingOptions)) {if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',{ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },@@ -1437,7 +1466,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config readsif (cursor && opts.retryFailed && !opts.dryRun && !company && !cursor.done) {const retried = await retryFailedStart(engine, cursor, key, { opts, context, authority, processingOptions, syncOptions, startupConfig, frozenRun, runStartedAt, discoveryRun, assertActive });- if (retried && 'wait' in retried) return { ...result(cursor, 'partial', 'writer_pending'), retryWait: retried.wait };+ if (retried && 'wait' in retried) return { ...result(cursor, 'partial', 'writer_pending'), ...(authority.writer.remote ? {} : { retryWait: retried.wait }) };if (retried) { cursor = retried.cursor; if (retried.discoveryTarget) { phase = 'discovery'; discoveryTarget = retried.discoveryTarget; } }}assertActive();diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex edfabdab12..ed10088c00 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -35,6 +35,8 @@ import { resolveRepairScope, type RepairKind, type RepairResult } from '../repaiimport type { RepairKindSpec } from '../repair/registry.ts';import { headCommittedBytes } from './sync-page-fault.ts';import { laneFaultInMessage } from './sync-window.ts';+import { cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';+import { listIncompleteSyncReceipts, type SyncSettledIndexes } from './checkpoint-validation.ts';import { drainEstimate } from './sync-drain.ts';import { resolveManagedSyncContext } from './sync-discovery.ts';@@ -81,6 +83,8 @@ 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: every managed-sync cursor of the source under its current incarnation, newest first (at most 20). */cursors: SyncStatusCursor[];next: Action | null;@@ -88,13 +92,19 @@ export interface SyncStatus {interface CursorHeader { runId: string; index: number; total: number; target: string | null; done?: boolean;progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };- processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] }+ processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'];+ binding?: { worktree_id?: string }; settled?: SyncSettledIndexes;+ pending?: { requestId?: string; intent?: { kind?: string; supersededRequests?: string[]; settled?: SyncSettledIndexes | null } } }-/** The newest cursor a current sync of the source can select: #6518, one recorded under its current incarnation. */-async function cursorHeader(engine: BrainEngine, sourceId: string, incarnation: string): Promise<CursorHeader | null> {- const rows = await engine.executeRaw<{ header: CursorHeader }>(- `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2 ORDER BY updated_at DESC LIMIT 1`, [sourceId, incarnation]);- return rows[0]?.header ?? null;+/**+ * The newest cursor a current sync of the source can select: #6518, one recorded under its current incarnation.+ * #6643: the cursor the recorded failure belongs to comes first, so the shown cursor, its error and `next` agree.+ */+async function cursorHeader(engine: BrainEngine, sourceId: string, incarnation: string, failedKey: string | null): Promise<{ header: CursorHeader; key: string } | null> {+ const rows = await engine.executeRaw<{ header: CursorHeader; key: string }>(+ `SELECT completed_keys->0 AS header, fingerprint AS key FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 AND completed_keys->0->>'incarnation'=$2+ ORDER BY (fingerprint=$3) DESC, updated_at DESC LIMIT 1`, [sourceId, incarnation, failedKey ?? '']);+ return rows[0] ?? null;}/** #6518: whether an unfinished cursor of the source stands under an incarnation it no longer has (nothing current resumes it). */@@ -134,20 +144,23 @@ function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHoexport async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });- const header = await cursorHeader(engine, sourceId, source.incarnation);+ 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);+ const header = selected?.header ?? null;const [committed] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*) AS n FROM persistence_requests WHERE source_id=$1 AND state='committed'AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND completed_at > now() - interval '10 minutes'`, [sourceId]);const records = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);const auto = await fenceAutoRepairFor(engine, records);const holds = records.map(record => holdStatus(record, auto));const repairable = records.filter(record => contentHoldDisposition(record, auto).action === 'repair').length;- const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');+ // #6643: the shown cursor is the one this failure belongs to whenever that cursor stands, so error and `next` agree.const failure = failures[0];const reason = typeof failure?.write_error_detail?.reason === 'string' ? failure.write_error_detail.reason : null;// #6643: a stop the run itself declared, then the root's recorded cause, then a knock-on, then the lane fault or reason.const rootCause = failure?.root_cause;const laneFault = failure?.code === 'knock_on_exhausted' ? null- : (rootCause?.cause === 'outside_fence' || rootCause?.cause === 'run_replaced' ? rootCause.cause : null)+ : (failure && cursorFenceCause(failure.write_error_detail) !== 'window_dropped' ? cursorFenceCause(failure.write_error_detail) : null)+ ?? (rootCause?.cause === 'outside_fence' || rootCause?.cause === 'run_replaced' ? rootCause.cause : null)?? (rootCause && failure && ['cancelled', 'revision_conflict'].includes(failure.code) ? 'knock_on' : null)?? (failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null) ?? reason;const retired = failure || header ? null : await retiredCursorStands(engine, sourceId, source.incarnation);@@ -187,7 +200,20 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proreturn { source_id: sourceId, 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, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),- resume_argv: resume, cursors: await liveCursors(engine, sourceId, source.incarnation, header?.runId ?? null), next };+ resume_argv: resume, ...(await checkpointBlockers(engine, header)), cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures), next };+}++/**+ * #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 }> }> {+ const intent = header?.pending?.intent;+ if (!header || header.done || intent?.kind !== 'managed_sync_checkpoint' || !header.binding?.worktree_id) return {};+ 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) : []);+ return { checkpoint_blockers: rows.map(row => ({ ...row, recovery: row.recovery === true, knock_on: knockOns.has(row.request_id) })) };}/** #6643: one managed-sync cursor of the source (the cursor key digests the writer principal, authority and options, so a source can have several). */@@ -197,12 +223,14 @@ export interface SyncStatusCursor {writer: { kind: string; id: string } | null;pending: { request_id: string; kind: string | null; state: string | null } | null;updated_at: string;- /** The cursor the top-level `cursor`, `run_id` and `next` describe (the newest of the current incarnation). */+ /** The cursor the top-level `cursor`, `run_id`, `last_error` and `next` describe (the one with the recorded failure, else the newest). */shown: boolean;+ /** The code of this cursor's recorded failure, if any. */+ last_error_code: string | null;resume_argv: string[];}-async function liveCursors(engine: BrainEngine, sourceId: string, incarnation: string, shownRun: string | null): Promise<SyncStatusCursor[]> {+async function liveCursors(engine: BrainEngine, sourceId: string, incarnation: string, shownKey: string | null, failures: Array<{ cursor_key: string; code: string }>): Promise<SyncStatusCursor[]> {const rows = await engine.executeRaw<{ fingerprint: string; header: CursorHeader & { authority?: { writer?: { principal?: { kind: string; id: string } } }; pending?: { requestId?: string; intent?: { kind?: string } } };updated_at: string; state: string | null }>(`SELECT c.fingerprint, c.completed_keys->0 AS header, to_char(c.updated_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS updated_at, r.state@@ -211,7 +239,7 @@ async function liveCursors(engine: BrainEngine, sourceId: string, incarnation: sreturn rows.map(row => ({ key_prefix: row.fingerprint.slice(0, 12), run_id: row.header.runId, index: Number(row.header.index), total: Number(row.header.total), done: !!row.header.done,writer: row.header.authority?.writer?.principal ?? null,pending: row.header.pending?.requestId ? { request_id: row.header.pending.requestId, kind: row.header.pending.intent?.kind ?? null, state: row.state } : null,- updated_at: row.updated_at, shown: row.header.runId === shownRun,+ updated_at: row.updated_at, shown: row.fingerprint === shownKey, last_error_code: failures.find(failure => failure.cursor_key === row.fingerprint)?.code ?? null,resume_argv: managedSyncResumeArgs({ sourceId, processingOptions: row.header.processingOptions, syncOptions: row.header.syncOptions }) }));}@@ -285,7 +313,8 @@ export async function unblockSync(engine: BrainEngine, sourceId: string, opts: Uconst [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);- const header = await cursorHeader(engine, sourceId, source.incarnation);+ const [failed] = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');+ const header = (await cursorHeader(engine, sourceId, source.incarnation, failed?.cursor_key ?? null))?.header;const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const context = holds.some(hold => hold.code === 'worktree_dirty') ? await resolveManagedSyncContext(engine, { sourceId, noPull: true }).catch(() => null) : null;const auto = await fenceAutoRepairFor(engine, holds);diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.tsindex 5d412efe74..f0cfa78b29 100644--- a/test/sync-knock-on-recovery-6643.test.ts+++ b/test/sync-knock-on-recovery-6643.test.ts@@ -25,6 +25,8 @@ import { BULK_GROUP_CANCEL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, isSyncKnockOn,syncKnockOnSql } from '../src/core/persistence/sync-knock-on.ts';import { CODES } from '../src/core/error-registry.ts';import { addSettledRange, findIncompleteSyncReceipt } from '../src/core/persistence/checkpoint-validation.ts';+import { publicFailureDetail } from '../src/core/persistence/publication-failure.ts';+import { cursorFenceRefusal } from '../src/core/persistence/sync-prepare.ts';import { withEnv } from './helpers/with-env.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-6643-'));@@ -213,9 +215,12 @@ for (const retryFailed of [false, true]) test(`a checkpoint refused by a receiptconst refused = await performManagedSync(engine, f.opts);expect(refused.status).toBe('blocked_by_failures');expect(refused.failures?.[0]).toMatchObject({ code: 'recovery_required', phase: 'checkpoint', root_cause: { request_id: f.stopped } });- const runId = (await readSyncStatus(engine, f.id)).run_id;- // The receipt that refused it was a knock-on all along (a pre-#6643 producer's message).+ const before = await readSyncStatus(engine, f.id);+ const runId = before.run_id;+ expect(before.checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: false })]);+ // The receipt that refused it was a knock-on all along (a pre-#6643 producer's message): status previews that nothing blocks now.await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, null);+ expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([]);const revived = await performManagedSync(engine, { ...f.opts, retryFailed });expect(revived.status).not.toBe('blocked_by_failures');const status = await readSyncStatus(engine, f.id);@@ -224,3 +229,53 @@ for (const retryFailed of [false, true]) test(`a checkpoint refused by a receiptexpect(source!.last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));} finally { await clearConfig(); }}), 120_000);++test('a stop on an outside_fence refusal is a root that needs a person in sync status, not a retryable revision_conflict', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ expect(publicFailureDetail({ origin: 'sync_cursor_fence', cause: 'outside_fence', fence: { index: 3 } })).toMatchObject({ cause: 'outside_fence' });+ expect(publicFailureDetail({ origin: 'sync_cursor_fence', cause: 'anything else' })).not.toHaveProperty('cause');+ try {+ const f = await stoppedRun();+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,'{0,code}','"revision_conflict"'),'{0,write_error_detail}',$1::jsonb)+ WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$2`, [JSON.stringify({ origin: 'sync_cursor_fence', cause: 'outside_fence' }), f.id]);+ const status = await readSyncStatus(engine, f.id);+ expect(status.last_error).toMatchObject({ code: 'revision_conflict', detail: 'outside_fence', class: 'systemic', needs_human: true });+ expect(status.needs_human).toBe(true);+ expect(status.next?.argv).not.toContain('--retry-failed');+ expect(status.cursors).toHaveLength(1);+ expect(status.cursors[0]).toMatchObject({ run_id: status.run_id, shown: true, done: false, pending: { request_id: f.stopped } });+ } finally { await clearConfig(); }+}), 120_000);++test('the cursor fence names window_dropped only for a member the cursor recorded dropping, with the root recorded then', () => {+ const run = randomUUID(), root = randomUUID(), member = randomUUID(), stray = randomUUID(), now = randomUUID();+ const row = (id: string) => ({ request_id: id, source_id: 'default' }) as never;+ const intent = { kind: 'managed_sync_import', runId: run, index: 7 } as never;+ const fence = { run_id: run, request_id: now, group: null, index: 3, dropped: [{ requestId: member, root }] };+ const detail = (id: string, f: typeof fence) => cursorFenceRefusal(row(id), intent, f).syncRefusal as Record<string, unknown>;+ // A dropped member is a knock-on of the request whose failure dropped it, not of whatever the cursor holds now.+ expect(detail(member, fence)).toMatchObject({ cause: 'window_dropped', origin: 'sync_knock_on', root_request_id: root });+ // A request ahead of the cursor that it never dropped is a coordination fault, not a knock-on.+ expect(detail(stray, fence)).toMatchObject({ cause: 'outside_fence', origin: 'sync_cursor_fence' });+ expect(detail(member, { ...fence, dropped: undefined as never })).toMatchObject({ cause: 'outside_fence' });+ expect(detail(member, { ...fence, run_id: randomUUID() })).toMatchObject({ cause: 'run_replaced' });+});++test('with two cursors, sync status shows the one its recorded failure belongs to and lists both', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ try {+ const f = await stoppedRun();+ const blockedRun = (await readSyncStatus(engine, f.id)).run_id!;+ await clearConfig();+ // A newer cursor of the same source, selected by different options, runs to the end.+ const other = await performManagedSync(engine, { ...f.opts, exclude: ['nothing-matches/**'] });+ expect(other.status).not.toBe('blocked_by_failures');+ const status = await readSyncStatus(engine, f.id);+ expect(status.run_id).toBe(blockedRun);+ expect(status.cursor?.done).toBe(false);+ expect(status.last_error?.code).toBe('source_changed');+ expect(status.next?.argv).not.toContain('--exclude');+ expect(status.cursors).toHaveLength(2);+ expect(status.cursors.filter(cursor => cursor.shown).map(cursor => cursor.run_id)).toEqual([blockedRun]);+ expect(status.cursors.find(cursor => !cursor.shown)).toMatchObject({ done: true, last_error_code: null });+ expect(status.cursors.find(cursor => !cursor.shown)!.resume_argv).toContain('--exclude');+ } finally { await clearConfig(); }+}), 120_000);