Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(sync): knock-on recovery, checkpoint settled ranges and revival, cursor fence causes (#6643)
garrytan934732d43210
diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex acf2392535..dbe861706d 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -19,6 +19,10 @@ export interface SyncResult {failures?: ManagedSyncFailure[];runId?: string;managedWrite?: import('../core/persistence/sync-run.ts').ManagedSyncWriteDiagnostic;+ /** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */+ retryWait?: import('../core/persistence/sync-run.ts').RetryWait;+ /** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */+ knockOns?: { refrozen: number; perIndexLimit: number; runLimit: number };status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';fromCommit: string | null;toCommit: string;diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 1808c3c0bb..88c38e2341 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -94,6 +94,8 @@ export class OperationError extends Error {public fenceIssues?: Array<Record<string, unknown>>;/** A `fact_withdrawn` refusal's withdrawal: when and for which subject the exact claim was forgotten. Absence carries no meaning. */public withdrawn?: WithdrawnDetail;+ /** #6643: a managed-sync refusal's owner-side classification (knock-on root, cursor fence snapshot); stored as the receipt's error_detail, never in the envelope. */+ public syncRefusal?: Record<string, unknown>;/** Set to 1 by opError(); toJSON() emits `contract_version` only when set. */public contractVersion?: 1;/**diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 88c45fe4ee..636acc1918 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -23,13 +23,20 @@ import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } fromimport { docsAnchor } from './connector-errors.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import type { SyncCursorOptions } from './sync-prepare.ts';+import { syncKnockOnSql } from './sync-knock-on.ts';export const CHECKPOINT_VALIDATION_TIMEOUT = 'checkpoint_validation_timeout';export const CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE = 'The sync checkpoint validation timed out on a large request table; the checkpoint did not commit.';export const REQUEST_INDEXES_REPAIR_COMMAND = 'gbrain repair request-indexes --apply';const SYNC_PAGE_KINDS = "r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete')";-const incompleteSyncReceiptSql = (superseded: boolean) => `(SELECT r.request_id::text AS request_id FROM persistence_requests r+/**+ * #6643: clause 3 skips a terminal, recovery-free receipt the cursor settled another way: one the run converted in place+ * ($3, #5988), one at an index the cursor passed without a commit (waived or held: the settled ranges $4..$5), and, only+ * below $6 (the index from which the cursor recorded its settled ranges, i.e. a cursor that began before #6643), a+ * knock-on (sync-knock-on.ts), which never published and whose entry the cursor re-froze when it reached it.+ */+export const INCOMPLETE_SYNC_RECEIPT_SQL = `(SELECT r.request_id::text AS request_id FROM persistence_requests rWHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)UNION ALL (SELECT r.request_id::text FROM persistence_requests rWHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}@@ -38,19 +45,29 @@ const incompleteSyncReceiptSql = (superseded: boolean) => `(SELECT r.request_id:WHERE r.worktree_id=$1::uuid AND r.intent->>'runId'=$2 AND r.state<>'committed' AND ${SYNC_PAGE_KINDS}AND NOT EXISTS (SELECT 1 FROM persistence_requests committed WHERE committed.source_id=r.source_idAND committed.intent->>'runId'=$2 AND committed.intent->>'index'=r.intent->>'index'- AND committed.state='committed' AND committed.intent ? 'runId')${superseded ? ' AND NOT (r.request_id::text=ANY($3::text[]))' : ''} LIMIT 1)+ AND committed.state='committed' AND committed.intent ? 'runId')+ AND NOT (r.request_id::text=ANY($3::text[]))+ AND NOT (r.state IN ('failed','cancelled','conflict') AND r.recovery IS NULL+ AND EXISTS (SELECT 1 FROM unnest($4::int[], $5::int[]) AS settled(lo, hi) WHERE (r.intent->>'index')::int BETWEEN settled.lo AND settled.hi))+ AND NOT ((r.intent->>'index')::int < $6::int AND ${syncKnockOnSql('r')}) LIMIT 1)LIMIT 1`;-export const INCOMPLETE_SYNC_RECEIPT_SQL = incompleteSyncReceiptSql(false);++/** #6643: the index ranges a cursor passed without a commit, and the index it began recording them at. */+export interface SyncSettledIndexes { from: number; ranges: Array<[number, number]> }/*** The request id of a receipt that blocks the run's checkpoint, or null.* `superseded` names failed content-refusal requests the run converted in* place (#5988): their entry was held, so they no longer block the checkpoint.+ * `settled` (#6643) is the cursor's record of the indexes it passed without a+ * commit; null for a checkpoint frozen before #6643, whose whole run predates it.*/-export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = []): Promise<string | null> {+export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, runId: string, superseded: string[] = [],+ settled: SyncSettledIndexes | null = null, total = 0): Promise<string | null> {try {- const [row] = await tx.executeRaw<{ request_id: string }>(superseded.length ? incompleteSyncReceiptSql(true) : INCOMPLETE_SYNC_RECEIPT_SQL,- superseded.length ? [worktreeId, runId, superseded] : [worktreeId, runId]);+ const ranges = settled?.ranges ?? [];+ const [row] = await tx.executeRaw<{ request_id: string }>(INCOMPLETE_SYNC_RECEIPT_SQL,+ [worktreeId, runId, superseded, ranges.map(range => range[0]), ranges.map(range => range[1]), settled ? settled.from : total]);return row?.request_id ?? null;} catch (error) {const failure = error as { code?: string; message?: string };@@ -61,6 +78,14 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa}}+/** #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;+ const last = settled.ranges.at(-1);+ if (last && from <= last[1] + 1) return { ...settled, ranges: [...settled.ranges.slice(0, -1), [last[0], Math.max(last[1], to)]] };+ return { ...settled, ranges: [...settled.ranges, [from, to]] };+}+export interface RequestIndexState {name: string;state: 'valid' | 'missing' | 'invalid' | 'building';diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex c3bd21662e..9cccd5c9e8 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -130,7 +130,7 @@ export { fileHash as persistenceFileHash, publishFile as publishPersistenceFilefunction requestError(error: unknown): PublicationFailure {if (error instanceof OperationError) {// #6188: a typed fence refusal keeps its location in the bounded detail, which outlives receipt compaction.- const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error);+ const detail = fenceFailureDetail(error) ?? withdrawalFailureDetail(error) ?? (error.syncRefusal as PublicationFailure['detail'] | undefined);return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };}const refusal = databaseRefusal(error);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 888ea3b5bd..55aad87689 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -39,6 +39,7 @@ import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnersimport { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, stepDownLanes, type LaneState } from './sync-lanes.ts';import { cancelRows, laneFaultBlockedReason, laneFaultCancelMessage, windowPredecessor } from './sync-window.ts';+import { BULK_GROUP_CANCEL_MESSAGE, knockOnDetail } from './sync-knock-on.ts';import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,foregroundPriority, independentGroup, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';@@ -455,7 +456,8 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G// claimed again as a lane head; publishing its members one at a time would hold the lanes back.if (prior === 'committed' && reason !== 'busy') return null;if (prior !== null && ['failed', 'conflict', 'cancelled'].includes(prior)) {- for (const done of await cancelRows(engine, rows, laneFault ? laneFaultCancelMessage(laneFault) : undefined)) run.settled(done);+ for (const done of await cancelRows(engine, rows, laneFault ? laneFaultCancelMessage(laneFault) : undefined,+ knockOnDetail(laneFault ? 'lane_fault' : 'window_predecessor', after))) run.settled(done);return true;}for (const row of rows) await releaseUnpublishedClaim(engine, row, laneFault ? laneFaultBlockedReason(laneFault) : 'group_member_waiting');@@ -680,6 +682,8 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (settled !== null) return settled || progressed;}let stop: 'cancel' | 'release' | null = null;+ /** #6643: the member whose non-commit cancels the rest of the group (the cancel's knock-on root). */+ let stopRoot: string | null = null;for (const { row: member, i } of live) {let row = member;let current = await getWriteRequestById(engine, row.id);@@ -689,14 +693,14 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (reclaimed) { row = reclaimed; current = reclaimed; }}if (!current || current.execution_token !== row.execution_token || current.state !== 'running') {- if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; if (current.state !== 'committed' && !independent) stop ??= 'cancel'; }+ if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; if (current.state !== 'committed' && !independent && stop === null) { stop = 'cancel'; stopRoot = current.request_id; } }else if (independent) stop ??= 'release';continue;}if (stop === 'release') { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }if (stop === 'cancel') {const cancelled = await engine.transaction(tx => completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled',- message: 'An earlier page of the same bulk sync group failed; this page was not published and is re-frozen after that failure is resolved.' }));+ message: BULK_GROUP_CANCEL_MESSAGE, detail: knockOnDetail('bulk_group', stopRoot) }));run.settled(cancelled); progressed = true; continue;}const p = prepared[i]!;@@ -705,7 +709,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesconst done = 'ok' in p ? await bounded(() => publishMutation(engine, row, p.ok, run.hostId)) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');run.settled(done);if (done.state === 'committed') { progressed = true; continue; }- if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; if (!independent) stop = 'cancel'; } else stop = 'release';+ if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; if (!independent) { stop = 'cancel'; stopRoot ??= done.request_id; } } else stop = 'release';}return progressed;} finally {diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.tsindex 58ed033acd..5d8a3153d6 100644--- a/src/core/persistence/sync-failures.ts+++ b/src/core/persistence/sync-failures.ts@@ -29,7 +29,16 @@ export interface ManagedSyncFailure {processingOptions?: Partial<SyncProcessingOptions>;/** #6513: the receipt's public failure detail (`publicFailureDetail`: fixed identifiers and the closed `reason`), when the receipt stored one. */write_error_detail?: Record<string, unknown>;+ /**+ * #6643: the request whose failure this one is a knock-on of (or, for a checkpoint, the receipt that blocks it),+ * followed through recorded knock-on roots. `request_id` null with `unknown` true: the canceller recorded no root+ * (a receipt from before #6643); the victim is then the only request named.+ */+ root_cause?: ManagedSyncRootCause;}+export interface ManagedSyncRootCause { request_id: string | null; slug: string | null; state: string | null; code: string | null; message: string | null;+ /** The cursor fence cause when the root is a cursor refusal (`outside_fence`, `run_replaced`, `window_dropped`). */+ cause?: string; unknown?: true }export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {const failure = { ...value, first_seen: value.first_seen ?? new Date().toISOString(), attempts: 1 };@@ -184,7 +193,13 @@ export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: sexport function formatManagedSyncFailure(failure: ManagedSyncFailure): string {const clean = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ').slice(0, 1000);- return `source=${clean(failure.source_id)} path=${clean(failure.path)} code=${clean(failure.code)}: ${clean(failure.message)} request=${failure.request_id ?? '<not-admitted>'} run=${failure.run_id} target=${failure.target ?? '<undiscovered>'}${publicationDetailText(failure.write_error_detail)}`;+ return `source=${clean(failure.source_id)} path=${clean(failure.path)} code=${clean(failure.code)}: ${clean(failure.message)} request=${failure.request_id ?? '<not-admitted>'} run=${failure.run_id} target=${failure.target ?? '<undiscovered>'}${publicationDetailText(failure.write_error_detail)}${rootCauseText(failure.root_cause, clean)}`;+}+/** #6643: the root-cause clause of a failure line: the request, page and error that caused it, or that none was recorded. */+export function rootCauseText(root: ManagedSyncRootCause | undefined, clean: (value: string) => string = value => value): string {+ if (!root) return '';+ if (!root.request_id) return ' root_cause=<not recorded: this receipt predates root tracking>';+ return ` root_cause=request ${root.request_id}${root.slug ? ` (${clean(root.slug)})` : ''}: ${root.state ?? 'missing'}${root.code ? ` ${clean(root.code)}` : ''}${root.cause ? ` cause=${root.cause}` : ''}${root.message ? ` ${clean(root.message)}` : ''}`;}const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;/** #6513: the fixed identifiers of a public failure detail (`raiser`, `table`) and its closed `reason`, as ` key=value` text; nothing else of it. */diff --git a/src/core/persistence/sync-knock-on.ts b/src/core/persistence/sync-knock-on.tsnew file mode 100644index 0000000000..649ea8403c--- /dev/null+++ b/src/core/persistence/sync-knock-on.ts@@ -0,0 +1,105 @@+/**+ * #6643: a managed-sync page request that ended without committing only because another request of the same sync did+ * not commit (a knock-on), told apart from a page that really failed.+ *+ * A knock-on never published anything: it was cancelled before its claim published (`cancelRows`, the bulk group's+ * member cancel) or refused by a dependency validation before any write ("An earlier page of this sync did not+ * commit."). It is therefore never a reason to block a sync: the run re-freezes its entry under a fresh request+ * (sync-run.ts `recoverKnockOn`), and the checkpoint does not wait for it (`checkpoint-validation.ts`).+ *+ * The canceller records why and which request it depended on in the receipt's `error_detail` (`origin:+ * 'sync_knock_on'`), which outlives receipt compaction. Receipts written before #6643 carry no marker; they are matched+ * by the exact messages their producers wrote, and nothing else: an operator's cancel ("Cancelled before+ * publication."), an authority or restore cancel, and a compacted receipt with no message are never knock-ons.+ */+import type { WriteRequest } from './model.ts';++export const SYNC_KNOCK_ON_ORIGIN = 'sync_knock_on';+export type KnockOnReason = 'group_member' | 'window_predecessor' | 'predecessor_never_admitted' | 'lane_fault' | 'window_cancelled'+ | 'suffix_cancelled' | 'bulk_group' | 'window_dropped';+export interface KnockOnDetail { origin: typeof SYNC_KNOCK_ON_ORIGIN; reason: KnockOnReason; root_request_id: string | null }++export const knockOnDetail = (reason: KnockOnReason, rootRequestId: string | null | undefined): KnockOnDetail =>+ ({ origin: SYNC_KNOCK_ON_ORIGIN, reason, root_request_id: rootRequestId ?? null });++/** The dependency validation refusal (`revision_conflict`) a page gets when an earlier page of its run did not commit. */+export const EARLIER_PAGE_REFUSAL_MESSAGE = 'An earlier page of this sync did not commit.';+/** The cursor fence refusal; its `error_detail` says which of #6643's three causes it was (sync-prepare.ts `cursorFenceRefusal`). */+export const CURSOR_CHANGED_REFUSAL_MESSAGE = 'The accepted sync cursor changed before publication.';+/** `error_detail.origin` of a cursor fence refusal that is not a knock-on (`run_replaced`, `outside_fence`). */+export const SYNC_CURSOR_FENCE_ORIGIN = 'sync_cursor_fence';+export type CursorFenceCause = 'run_replaced' | 'window_dropped' | 'outside_fence';+/** The cause a cursor fence refusal recorded, or null (a receipt from before #6643, or another refusal). */+export function cursorFenceCause(detail: unknown): CursorFenceCause | null {+ const cause = (detail as { cause?: unknown } | null)?.cause;+ return cause === 'run_replaced' || cause === 'window_dropped' || cause === 'outside_fence' ? cause : null;+}+/** The bulk group publisher's cancel of the members after one that did not commit (group-publish.ts). */+export const BULK_GROUP_CANCEL_MESSAGE = 'An earlier page of the same bulk sync group failed; this page was not published and is re-frozen after that failure is resolved.';++/**+ * The exact messages pre-#6643 knock-on producers stored, for receipts without the typed marker. The window, lane-fault+ * and never-admitted texts are sync-window.ts's own (`WINDOW_CANCEL_MESSAGE`, `laneFaultCancelMessage`, both+ * never-admitted cancels); the parity test pins this list to those producers.+ */+export const LEGACY_KNOCK_ON_CANCEL_MESSAGES: readonly string[] = [+ 'An earlier page of the same sync did not commit; this page was not published and is re-frozen after that failure is resolved.',+ 'An earlier page of the same sync did not commit after lock_timeout on its lane group; this page was not published and is re-frozen on the next sync pass.',+ 'An earlier page of the same sync did not commit after statement_timeout on its lane group; this page was not published and is re-frozen on the next sync pass.',+ BULK_GROUP_CANCEL_MESSAGE,+];+/** SQL LIKE patterns of the never-admitted cancels, whose text names request ids. */+export const LEGACY_KNOCK_ON_CANCEL_PATTERNS: readonly string[] = [+ 'Its predecessor request % was never admitted; this page was not published and is re-frozen on the next sync pass.',+ 'The first page of its group (request %) was cancelled because its predecessor request % was never admitted; this page was not published and is re-frozen on the next sync pass.',+];+const LEGACY_PATTERN_RES = LEGACY_KNOCK_ON_CANCEL_PATTERNS.map(pattern =>+ new RegExp(`^${pattern.split('%').map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.+')}$`));++const SYNC_PAGE_KINDS = new Set(['managed_sync_import', 'managed_sync_delete']);++/** The typed marker a receipt carries, or null. */+export function knockOnOf(detail: unknown): KnockOnDetail | null {+ const d = detail as Partial<KnockOnDetail> | null;+ if (!d || typeof d !== 'object' || d.origin !== SYNC_KNOCK_ON_ORIGIN || typeof d.reason !== 'string') return null;+ return { origin: SYNC_KNOCK_ON_ORIGIN, reason: d.reason as KnockOnReason, root_request_id: typeof d.root_request_id === 'string' ? d.root_request_id : null };+}++/** Whether a terminal message is one a pre-#6643 knock-on producer wrote. */+export function legacyKnockOnMessage(state: string, code: string | null | undefined, message: string | null | undefined): boolean {+ if (!message) return false;+ if (state === 'cancelled') return code === 'cancelled' && (LEGACY_KNOCK_ON_CANCEL_MESSAGES.includes(message) || LEGACY_PATTERN_RES.some(re => re.test(message)));+ return (state === 'conflict' || state === 'failed') && code === 'revision_conflict' && message === EARLIER_PAGE_REFUSAL_MESSAGE;+}++/**+ * Whether a sync page request ended without committing only because another request of its sync did not commit. It+ * must be terminal, uncommitted, recovery-free and never have started publication; a compacted receipt counts only by+ * its typed marker (its intent and message are gone, so the page kind is taken from the marker's producer).+ */+export function isSyncKnockOn(row: Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'error_detail' | 'recovery' | 'publication_started' | 'intent'>): boolean {+ if (!['cancelled', 'failed', 'conflict'].includes(row.state) || row.recovery || row.publication_started) return false;+ const kind = (row.intent as Record<string, unknown> | null | undefined)?.kind;+ if (kind != null && !SYNC_PAGE_KINDS.has(String(kind))) return false;+ if (knockOnOf(row.error_detail)) return true;+ return kind != null && legacyKnockOnMessage(row.state, row.error_code, row.error_message);+}++/** The request a knock-on depended on, when its canceller recorded it. */+export function knockOnRoot(row: Pick<WriteRequest, 'error_detail'>): string | null {+ return knockOnOf(row.error_detail)?.root_request_id ?? null;+}++const sqlString = (value: string) => `'${value.replaceAll("'", "''")}'`;+/**+ * The same predicate as `isSyncKnockOn` over a `persistence_requests` alias, for the checkpoint's clause 3. Literal+ * strings only (no parameters), so every engine plans it the same way.+ */+export function syncKnockOnSql(alias: string): string {+ const r = alias;+ return `(${r}.state IN ('cancelled','failed','conflict') AND ${r}.recovery IS NULL AND NOT COALESCE(${r}.publication_started,false)+ AND (${r}.error_detail->>'origin' = ${sqlString(SYNC_KNOCK_ON_ORIGIN)}+ OR (${r}.state='cancelled' AND ${r}.error_code='cancelled' AND (${r}.error_message IN (${LEGACY_KNOCK_ON_CANCEL_MESSAGES.map(sqlString).join(',')})+ OR ${LEGACY_KNOCK_ON_CANCEL_PATTERNS.map(pattern => `${r}.error_message LIKE ${sqlString(pattern)}`).join(' OR ')}))+ OR (${r}.state IN ('conflict','failed') AND ${r}.error_code='revision_conflict' AND ${r}.error_message=${sqlString(EARLIER_PAGE_REFUSAL_MESSAGE)})))`;+}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 443d84eddc..d53d368dc4 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -37,7 +37,8 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';import { companyBrainProfile } from '../company-brain/profile.ts';import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';-import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';+import { checkpointRetryCommand, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';+import { CURSOR_CHANGED_REFUSAL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, knockOnDetail, SYNC_CURSOR_FENCE_ORIGIN } from './sync-knock-on.ts';import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';import { frontmatterSlugConflictMessage } from './verb-errors.ts';import { chunkerStamp } from '../chunkers/code.ts';@@ -80,6 +81,8 @@ export interface SyncIntent extends Record<string, unknown> {blobOid?: string;/** #5988 checkpoint only: failed content-refusal requests of this run converted in place; they no longer block the checkpoint. */supersededRequests?: string[];+ /** #6643 checkpoint only: the indexes the cursor passed without a commit (waived or held), from the index it began recording them. */+ settled?: SyncSettledIndexes;syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';}@@ -93,16 +96,17 @@ 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.*/-async function readSyncCursorFence(tx: BrainEngine, cursorKey: string): Promise<{ run_id: string; request_id: string | null; group: string[] | null } | undefined> {- const [held] = await tx.executeRaw<{ run_id: string; request_id: string | null; group: string[] | null }>(- `SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id,+interface SyncCursorFence { run_id: string; request_id: string | null; group: string[] | null; index: string | number | 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)) mUNION ALL SELECT m FROM jsonb_array_elements(COALESCE(completed_keys->0->'window','[]'::jsonb)) g, jsonb_array_elements(g) m) members) AS groupFROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR KEY SHARE`, [cursorKey]);return held;}-const sharedValidations = new WeakMap<object, Map<string, Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>>>();-function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>) {+const sharedValidations = new WeakMap<object, Map<string, Promise<SyncCursorFence | null>>>();+function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<SyncCursorFence | null>) {if ((tx as { _pageTransaction?: boolean })._pageTransaction !== true) return run();let byKey = sharedValidations.get(tx);if (!byKey) { byKey = new Map(); sharedValidations.set(tx, byKey); }@@ -123,8 +127,8 @@ async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncInten},() => readSyncCursorFence(tx, p.cursorKey),async () => {- if (after && !await windowPredecessorAllows(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p,- `Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`);+ if (after && !await windowPredecessorAllows(tx, row)) throw withSyncRefusal(syncPublicationRefusal('revision_conflict', EARLIER_PAGE_REFUSAL_MESSAGE, row, p,+ `Request ${row.request_id} was admitted ahead of request ${after} of the same sync run, which did not commit, so this page must not publish after it.`), knockOnDetail('window_predecessor', after));},async () => {const current = await getWorktreeBinding(tx, row.source_id);@@ -158,6 +162,33 @@ function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteR+ `Once it is final and the cause is fixed, run: ${rerun}`, { fix, ...extra });}+/** #6643: attaches the owner-side classification the coordinator stores as the receipt's `error_detail`. */+function withSyncRefusal(error: OperationError, detail: object): OperationError {+ error.syncRefusal = { ...detail };+ return error;+}++/**+ * #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.+ */+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 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 = syncPublicationRefusal('revision_conflict', CURSOR_CHANGED_REFUSAL_MESSAGE, row, p,+ 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 }+ : { origin: SYNC_CURSOR_FENCE_ORIGIN, cause, fence });+}+/*** #5988: a deterministic content refusal at publication. The wire `error`* stays `invalid_params` (what older receipts stored), so the stored code and@@ -417,14 +448,19 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrawait pipelined(tx, [() => shared,() => validateSyncAuthority(tx, p.syncAuthority, row.slug),- async () => { if (await earlierGroupMemberFailed(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p, `Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`); },+ async () => {+ const failed = await earlierGroupMemberFailed(tx, row);+ if (failed) throw withSyncRefusal(syncPublicationRefusal('revision_conflict', EARLIER_PAGE_REFUSAL_MESSAGE, row, p,+ `Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`), knockOnDetail('group_member', failed));+ },async () => {const cursor = await shared;// #6513: a checkpoint whose cursor another run replaced is superseded, not conflicted; a page keeps `revision_conflict`.const replaced = checkpointCursorReplaced(p, cursor?.run_id, row.source_id);if (replaced) throw syncPublicationRefusal(replaced.code, replaced.message, row, p, replaced.cause);- if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id) && !(screening?.unsaved && cursor.request_id == null)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,- `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);+ if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id) && !(screening?.unsaved && cursor.request_id == null)))) {+ throw cursorFenceRefusal(row, p, cursor);+ }},async () => { if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row, p.path === null ? undefined : { root, path: join(root, p.path) }); },async () => {@@ -464,7 +500,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,`The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);- const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? []);+ const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId, p.supersededRequests ?? [], p.settled ?? null, p.total);if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,`Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `+ `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex b46363813e..b94ed2bbfd 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -27,17 +27,18 @@ import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan }import { readCommittedBlob } from '../company-brain/revision.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-stats.ts';-import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure } from './sync-failures.ts';+import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure, type ManagedSyncRootCause } from './sync-failures.ts';import { writeFailureDiagnostic } from './verb-errors.ts';import { extractManagedStaleLinks } from './links-maintenance.ts';-import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint } from './checkpoint-validation.ts';+import { addSettledRange, CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';import { principalKey, type WriteRequest } from './model.ts';import { readJournalLimits } from './limits.ts';import { assertManagedSyncAllowed } from './worktree-refresh.ts';import type { GBrainConfig } from '../config.ts';import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';-import { cancelRows, cancelWindow } from './sync-window.ts';+import { cancelRowsUnderCursor, cancelWindow } from './sync-window.ts';+import { cursorFenceCause, isSyncKnockOn, knockOnDetail, knockOnRoot } from './sync-knock-on.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { isContentRefusal } from '../import-screen.ts';@@ -76,7 +77,13 @@ export interface ManagedSyncWriteDiagnostic {interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; rebound?: true;/** #5988: re-frozen in place from a failed content refusal; a second refusal of the same bytes stays blocked. */- converted?: true; }+ converted?: true;+ /**+ * #6643: re-frozen in place because the request before it at this index was a knock-on (`attempts` such re-freezes in+ * a row at this index, `root` the request the last knock-on depended on). Kept apart from `converted`, so a knock-on+ * never uses up the content/file-change allowance. The entry then publishes on its own (no group, no window).+ */+ knockOn?: { attempts: number; root: string | null }; }/** #5988: the frozen entry is held instead of admitted. #6340 `overtaken`: another cursor of the source imported the entry's page meanwhile (#5522), so the checkpoint accepts a source already at this target. */interface Held { hold: HeldEntry; overtaken?: true }interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean; companyReceiptId?: string;@@ -92,6 +99,10 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authorityfences?: FencesTally };/** #5988: failed content-refusal requests this run converted in place. */convertedFromFailed?: string[];+ /** #6643: the indexes this cursor passed without a commit (waived or held), recorded from `settled.from` on; the checkpoint carries them. */+ settled?: SyncSettledIndexes;+ /** #6643: knock-on re-freezes this run made (the per-run breaker), and checkpoint revivals. */+ knockOns?: number; checkpointRevivals?: number;/** #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. */@@ -212,6 +223,9 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul}/** Compare-and-swap inside the caller's transaction; a lost swap returns the cursor that won. */async function writeCursor(tx: BrainEngine, key: string, before: Cursor | null, next: Cursor, inTx?: (tx: BrainEngine) => Promise<unknown>, synchronous = false): Promise<Cursor> {+ // #6643: a cursor records the indexes it settles without a commit from its first save by this build on; a cursor saved+ // before (a run that began on an older build) starts recording at the index it had then.+ if (!next.settled) next.settled = before && before.runId === next.runId ? { from: before.settled?.from ?? before.index, ranges: before.settled?.ranges ?? [] } : { from: 0, ranges: [] };if (before === null) {if (synchronous) await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT DO NOTHING`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);@@ -245,26 +259,28 @@ async function currentCursor(engine: BrainEngine, key: string, cached: Cursor):/** The cursor after a waived entry: counted under `waived`, plus the #5751 kernel breakdown kept for `legacySkips`. */function waivedCursor(cursor: Cursor, waived: NoopWaiver): Cursor {const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };- const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts,+ const next: Cursor = { ...cursor, index: cursor.index + 1, settled: settleIndex(cursor), counts: { ...cursor.counts,waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };delete next.pending; delete next.group;if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;return next;}+/** #6643: the cursor's settled indexes with its current entry added (it passes that entry without a commit). */+function settleIndex(cursor: Cursor): SyncSettledIndexes {+ return addSettledRange(cursor.settled ?? { from: cursor.index, ranges: [] }, cursor.index, cursor.index);+}/** The rollback signal of an admission whose cursor no longer holds the frozen entry (ENG-A7). */class CursorMoved extends Error {}-async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor> {+async function replaceCursor(engine: BrainEngine, key: string, before: CursorHeader, next: Cursor, assertActive: () => void): Promise<Cursor | { wait: RetryWait }> {+ next.settled ??= { from: 0, ranges: [] };return engine.transaction(async tx => {assertActive();await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [next.binding.worktree_id]);- const active = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [next.sourceId]);- if (active.length) {- const current = (await readCursor(tx, key))!;- assertActive();- return current;- }+ // #6643: only the old cursor's own open requests and recovery-bearing ones veto the swap, and the caller is told which.+ const blocker = await oldRunBlocker(tx, next, key);+ if (blocker) { assertActive(); return { wait: blocker }; }await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`, [`${OP}-manifest`, next.runId, JSON.stringify(next.entries)]);const swapped = await tx.executeRaw('UPDATE op_checkpoints SET completed_keys=$4::text::jsonb,updated_at=now() WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb RETURNING fingerprint',[OP, key, JSON.stringify([before]), JSON.stringify([header(next)])]);@@ -421,6 +437,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass...(run.observedAt ? { holdObservedAt: run.observedAt } : {}), ...(blob ? { blobOid: blob.oid } : {}),...(!entry && cursor.releasedHolds?.length ? { releasedHolds: cursor.releasedHolds } : {}),...(!entry && cursor.convertedFromFailed?.length ? { supersededRequests: cursor.convertedFromFailed } : {}),+ ...(!entry && cursor.settled ? { settled: cursor.settled } : {}),processingOptions: cursor.processingOptions,// A cursor created before its options were recorded has the same key, so this run's options are its options....(!entry ? { syncOptions: cursor.syncOptions ?? run.syncOptions, ...(run.repoPath ? { repoPath: run.repoPath } : {}) } : {}),@@ -467,7 +484,7 @@ const heldWrite = (held: Cursor, hold: HeldEntry, observedAt: string) => (tx: Br/** #5988: the cursor one entry on, past a held entry (no request admitted for it). */function advanceHeld(held: Cursor, converted?: string[]): Cursor {- const next: Cursor = { ...held, index: held.index + 1, counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 },+ const next: Cursor = { ...held, index: held.index + 1, settled: settleIndex(held), counts: { ...held.counts, held: (held.counts.held ?? 0) + 1 },...(converted ? { convertedFromFailed: converted } : {}) };delete next.pending;return next;@@ -514,7 +531,9 @@ const resumeArgsOf = (cursor: Cursor, run: { syncOptions: SyncCursorOptions; repasync function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; assertActive: () => void;observedAt: string; waitMs: number; failedId: string; base?: Cursor } & ({ hold: HeldEntry; refrozen?: undefined } | { hold?: undefined;/** #6340: instead of a hold, the entry re-frozen under a fresh request (its file changed after admission); same gate, same conversion record. */- refrozen: Pending })): Promise<Cursor | 'pending'> {+ refrozen: Pending;+ /** #6643: the re-freeze replaces a knock-on: the new pending carries this instead of `converted`, and the run counts it. */+ knockOn?: { attempts: number; root: string | null } })): Promise<Cursor | 'pending'> {const { cursor, key, pending, assertActive } = input;const principal = cursor.authority.writer.principal;const base: Cursor = input.base ?? { ...cursor }; delete base.group; delete base.window; delete base.pending;@@ -522,13 +541,16 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:const after = failedRow?.sequence == null ? null : String(failedRow.sequence);const keys = [{ sourceId: cursor.sourceId, slug: pending.slug }, ...(pending.intent.renameFrom && pending.intent.renameFrom.slug !== pending.slug ? [{ sourceId: cursor.sourceId, slug: pending.intent.renameFrom.slug }] : [])];const deadline = performance.now() + input.waitMs;+ // #6643: the window and the run's queued suffix are cancelled only while the cursor still holds this entry, so a+ // converter that lost the cursor swap to another drainer never cancels the replacement the winner admitted.+ const fence = { cursorKey: key, expectedRequestId: cursor.pending?.requestId ?? pending.requestId, principal, worktreeId: cursor.binding.worktree_id };for (;;) {assertActive();- if (cursor.window?.length) await cancelWindow(engine, cursor.window, principal);+ if (cursor.window?.length && !await cancelWindow(engine, cursor.window, principal, pending.requestId, fence)) return currentCursor(engine, key, cursor);if (after !== null) {const queued = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND state='queued'AND ${SYNC_PAGE_KINDS_SQL} AND sequence>$3::bigint ORDER BY sequence`, [cursor.binding.worktree_id, cursor.runId, after]);- if (queued.length) await cancelRows(engine, queued);+ if (queued.length && !await cancelRowsUnderCursor(engine, fence, queued, knockOnDetail('suffix_cancelled', pending.requestId))) return currentCursor(engine, key, cursor);}const saved = await engine.transaction(async tx => {assertActive();@@ -542,7 +564,10 @@ 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 next: Cursor = input.hold ? advanceHeld(base, converted) : { ...base, convertedFromFailed: converted, pending: { ...input.refrozen, converted: true } };+ 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 } }+ : { ...base, convertedFromFailed: converted, pending: { ...input.refrozen, converted: true } };return writeCursor(tx, key, cursor, next, async inner => {if (input.hold) await heldWrite(cursor, input.hold, input.observedAt)(inner);await recordSyncConversion(inner, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: input.hold ? 'held' : 'refrozen' });@@ -576,6 +601,8 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: sconst previous = blocked.pending!;const failed = await getWriteRequest(engine, blocked.authority.writer.principal, previous.requestId);if (!failed || !['failed', 'conflict', 'cancelled'].includes(failed.state)) return blocked;+ // #6643: a knock-on is re-frozen by the drain itself (settleFailedRequest → recoverKnockOn), with or without a screen.+ if (isSyncKnockOn(failed)) return blocked;const entry = blocked.entries[blocked.index];if (preparationStalled(failed)) {if (blocked.companyPlan || previous.intent.kind === 'managed_sync_checkpoint' || !entry || entry.path !== previous.intent.path) return blocked;@@ -695,6 +722,91 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });}+/** #6643: the terminal code of a run that stopped re-freezing knock-ons (per-index limit or per-run breaker). */+export const KNOCK_ON_EXHAUSTED = 'knock_on_exhausted';+/** #6643: the most knock-on re-freezes one run makes before it stops with the root cause (a per-run breaker, like `breakerAfter`). */+export const KNOCK_ON_RUN_LIMIT = 25;+const CHECKPOINT_REVIVAL_LIMIT = 3;+/** `sync.knock_on_refreeze_limit`: knock-on re-freezes in a row at one index (default 3; 0 turns automatic re-freeze off). */+export async function knockOnRefreezeLimit(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {+ const raw = (await engine.getConfig('sync.knock_on_refreeze_limit').catch(() => null))?.trim();+ const parsed = raw ? Number(raw) : NaN;+ return Number.isInteger(parsed) && parsed >= 0 ? parsed : 3;+}++type SettleInput = Parameters<typeof settleFailedRequest>[1];++/**+ * #6643: the entry of a knock-on (a page cancelled or refused only because another page of its sync did not commit)+ * is re-frozen under a fresh request, whatever the hold policy, the source kind or `--retry-failed`: a knock-on never+ * published anything, so it is not a failure of its page. The re-freeze goes through the narrowed gate+ * (`holdUnderGate`), which settles the run's suffix under the cursor fence and records every stale receipt at the+ * index as superseded. Bounded per index (`sync.knock_on_refreeze_limit`) and per run (`KNOCK_ON_RUN_LIMIT`).+ */+async function recoverKnockOn(engine: BrainEngine, input: SettleInput): Promise<null | 'pending' | { cursor: Cursor } | { exhausted: { attempts: number; limit: number; runCount: number } }> {+ const { cursor, key, pending, done, assertActive } = input;+ if (pending.intent.kind === 'managed_sync_checkpoint' || !isSyncKnockOn(done)) return null;+ const entry = cursor.entries[cursor.index];+ if (!entry || entry.path !== pending.intent.path) return null;+ const limit = await knockOnRefreezeLimit(engine);+ if (limit === 0) return null;+ const attempts = pending.knockOn?.attempts ?? 0, runCount = cursor.knockOns ?? 0;+ if (attempts >= limit || runCount >= KNOCK_ON_RUN_LIMIT) return { exhausted: { attempts, limit, runCount } };+ const base: Cursor = { ...cursor }; delete base.pending; delete base.group; delete base.window;+ const refrozen = await freezeEntry(engine, base, key, assertActive, input.run);+ assertActive();+ const observedAt = input.run.observedAt ?? new Date().toISOString();+ const gated = 'hold' in refrozen+ ? await holdUnderGate(engine, { cursor, key, pending, hold: refrozen.hold, assertActive, observedAt, waitMs: input.waitMs, failedId: done.id, base })+ : await holdUnderGate(engine, { cursor, key, pending, refrozen, knockOn: { attempts: attempts + 1, root: knockOnRoot(done) ?? pending.knockOn?.root ?? null },+ assertActive, observedAt, waitMs: input.waitMs, failedId: done.id, base });+ return gated === 'pending' ? 'pending' : { cursor: gated };+}++/**+ * #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.+ */+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 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;+ return saveCursor(engine, key, cursor, { ...base, checkpointRevivals: (cursor.checkpointRevivals ?? 0) + 1, pending: fresh }, false, input.assertActive);+}++/**+ * #6643: what caused a blocked entry. A knock-on names the request its canceller recorded, followed while that+ * request is itself a knock-on; a checkpoint refused `recovery_required` names the receipt that blocks it. Null for a+ * page that failed on its own (it is the root); `unknown` when the knock-on recorded no root.+ */+async function syncRootCause(engine: BrainEngine, cursor: Cursor, pending: Pending, done: WriteRequest): Promise<ManagedSyncRootCause | null> {+ let rootId: string | null;+ if (pending.intent.kind === 'managed_sync_checkpoint') {+ if (done.error_code !== 'recovery_required') return null;+ rootId = /request ([0-9a-f-]{36})/i.exec(done.error_message ?? '')?.[1] ?? null;+ if (!rootId) return null;+ } else if (isSyncKnockOn(done)) rootId = knockOnRoot(done) ?? pending.knockOn?.root ?? null;+ else return null;+ if (!rootId) return { request_id: null, slug: null, state: null, code: null, message: null, unknown: true };+ const seen = new Set<string>();+ for (;;) {+ seen.add(rootId);+ const row = await getWriteRequest(engine, cursor.authority.writer.principal, rootId);+ if (!row) return { request_id: rootId, slug: null, state: 'missing', code: null, message: null };+ const next = isSyncKnockOn(row) ? knockOnRoot(row) : null;+ if (next && !seen.has(next) && seen.size < 8) { rootId = next; continue; }+ const cause = cursorFenceCause(row.error_detail);+ return { request_id: row.request_id, slug: row.slug, state: row.state, code: row.error_code ?? null, message: row.error_message ?? null, ...(cause ? { cause } : {}) };+ }+}+/*** A page request of the run ended without committing. #6188: a fence refusal is held in the same* run (or the run returns `partial` while the source's other requests settle); anything else is@@ -704,14 +816,29 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;run: { screen?: SyncScreenRun | null; observedAt?: string; repoPath?: string; syncOptions: SyncCursorOptions }; syncOptions: SyncCursorOptions; processingOptions: SyncProcessingOptions;remote: boolean; waitMs: number; signal?: AbortSignal }): Promise<{ cursor: Cursor } | { result: SyncResult }> {const { cursor, key, pending, done, syncOptions, processingOptions, remote } = input;- const converted = await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs);+ // #6643: a page whose run another run replaced is superseded, not failed: go on with the winning cursor.+ if (cursorFenceCause(done.error_detail) === 'run_replaced') {+ const current = await currentCursor(engine, key, cursor);+ if (current.runId !== cursor.runId) return { cursor: current };+ }+ const knockOn = await recoverKnockOn(engine, input);+ if (knockOn === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };+ if (knockOn && 'cursor' in knockOn) { input.assertActive(); return { cursor: knockOn.cursor }; }+ const revived = await reviveCheckpoint(engine, input);+ if (revived) { input.assertActive(); return { cursor: revived }; }+ const converted = knockOn ? null : await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs);if (converted === 'pending') return { result: result(cursor, 'partial', input.signal?.aborted ? 'timeout' : 'writer_pending') };if (converted && 'tripped' in converted) return { result: breakerResult(converted.tripped, pending, done, remote) };if (converted) { input.assertActive(); return { cursor: converted }; }// #6513: a checkpoint another run superseded records nothing; this run goes on with the winning cursor as it stands.if (checkpointSuperseded(pending, done)) return { cursor: await currentCursor(engine, key, cursor) };+ const rootCause = await syncRootCause(engine, cursor, pending, done);+ const exhausted = knockOn && 'exhausted' in knockOn ? knockOn.exhausted : null;const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',- code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',+ code: exhausted ? KNOCK_ON_EXHAUSTED : done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'),+ message: exhausted ? `This page was re-frozen ${exhausted.attempts} time(s) at the same index (limit ${exhausted.limit}), or this run re-froze ${exhausted.runCount} knock-on page(s) (limit ${KNOCK_ON_RUN_LIMIT}), and an earlier page of the same sync still did not commit; the run stopped instead of re-freezing again.`+ : done.error_message ?? 'The accepted sync request did not commit.',+ ...(rootCause ? { root_cause: rootCause } : {}),request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,@@ -1088,7 +1215,13 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:if (rest.length) next.window = rest; else delete next.window;} else { next.pending = stuck; if (failed) delete next.group; else next.group = members.slice(committed); }// A failed page stops the run: groups admitted ahead of it are cancelled, never published after it.- if (failed && next.window) { await cancelWindow(engine, next.window, principal); delete next.window; }+ // #6643: fenced on the cursor this pass read, and naming the stuck request as the cancelled groups' knock-on root.+ if (failed && next.window) {+ 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) };+ }+ delete next.window;+ }const saved = committed || failed || next.group?.length !== members.length ? await saveCursor(engine, key, cursor, next) : cursor;for (let index = cursor.index + 1; index <= saved.index && index <= next.index; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length });if (stuck && stuckRow && !isTerminalWriteState(stuckRow.state) && saved.index === next.index) {@@ -1164,13 +1297,16 @@ export async function managedSyncCursorKey(engine: BrainEngine, opts: SyncOpts):*/async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string, input: { opts: SyncOpts; context: ManagedSyncContext; authority: SyncAuthority;processingOptions: SyncProcessingOptions; syncOptions: SyncCursorOptions; startupConfig: BrainEngine; frozenRun: Parameters<typeof freezeEntry>[4]; runStartedAt: string;- discoveryRun: string; assertActive: () => void }): Promise<{ cursor: Cursor; discoveryTarget?: string } | null> {+ discoveryRun: string; assertActive: () => void }): Promise<{ cursor: Cursor; discoveryTarget?: string } | { wait: RetryWait } | null> {const { opts, context, authority, processingOptions, syncOptions, assertActive } = input;- 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) return null;const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;+ assertActive();+ // #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;+ const blocker = await oldRunBlocker(engine, cursor, key);+ assertActive();+ if (blocker) return { wait: blocker };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;@@ -1183,7 +1319,24 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: stringconst discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();const discovery = await discoverManagedSync(engine, opts, context);assertActive();- return { cursor: await replaceCursor(engine, key, header(cursor), { ...discovery, authority, processingOptions, syncOptions, runId: input.discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive), discoveryTarget };+ const replaced = await replaceCursor(engine, key, header(cursor), { ...discovery, authority, processingOptions, syncOptions, runId: input.discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);+ if ('wait' in replaced) return replaced;+ return { cursor: replaced, discoveryTarget };+}++/** #6643: a request the whole-manifest retirement must wait for, named with its producer, instead of a silent no-op. */+export interface RetryWait { request_id: string; kind: string | null; slug: string; state: string; recovery: boolean; retry_after_ms: number }+/**+ * #6643: what retiring the cursor's frozen manifest must wait for: a request of this cursor (any of its runs) that is+ * still open or carries recovery, or any recovery-bearing request on the worktree (its replay may touch a file the+ * new manifest reads). Foreground and maintenance writes that are merely queued on other pages no longer veto it.+ */+async function oldRunBlocker(engine: Pick<BrainEngine, 'executeRaw'>, cursor: Pick<Cursor, 'sourceId' | 'binding'>, key: string): Promise<RetryWait | null> {+ const [row] = await engine.executeRaw<{ request_id: string; kind: string | null; slug: string; state: string; recovery: boolean }>(+ `SELECT request_id::text AS request_id, intent->>'kind' AS kind, slug, state, recovery IS NOT NULL AS recovery FROM persistence_requests+ WHERE source_id=$1 AND ((intent->>'cursorKey'=$2 AND state IN ('queued','running','recovering')) OR (worktree_id=$3::uuid AND recovery IS NOT NULL))+ ORDER BY sequence LIMIT 1`, [cursor.sourceId, key, cursor.binding.worktree_id]);+ return row ? { ...row, recovery: row.recovery === true, retry_after_ms: 5000 } : null;}export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {@@ -1255,7 +1408,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPdiscoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();const discovery = await discoverManagedSync(engine, opts, context);assertActive();- cursor = await replaceCursor(engine, key, error.cursor, { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, 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 };+ cursor = replaced;}assertActive();if (company && opts.retryFailed && cursor && !cursor.done && !opts.dryRun) {@@ -1276,6 +1431,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) { cursor = retried.cursor; if (retried.discoveryTarget) { phase = 'discovery'; discoveryTarget = retried.discoveryTarget; } }}assertActive();@@ -1390,7 +1546,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPcontinue;}const freezeAt: FreezeAt = base => async index => { const frozen = await freezeEntry(engine, { ...base, index }, key, assertActive, frozenRun); return 'hold' in frozen ? null : frozen; };- if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);+ if (bulk.settings.enabled && (bulk.foregroundFirst || !foregroundQueued) && !prior && !cursor.group && !pending.rebound && !pending.knockOn && groupableIntent(pending.intent)) cursor = await formGroup(engine, cursor, pending, key, bulk, config, freezeAt, assertActive);if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress,opts.drainStartedAt ? next => admitAhead(engine, next, key, bulk, config, freezeAt, assertActive) : undefined);diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.tsindex ef0865c54e..84e8bafd5f 100644--- a/src/core/persistence/sync-window.ts+++ b/src/core/persistence/sync-window.ts@@ -13,6 +13,7 @@import type { BrainEngine } from '../engine.ts';import { completeWrite, lockCounters } from './journal.ts';import { isTerminal, principalKey, requestPrincipal, type Principal, type WriteRequest } from './model.ts';+import { knockOnDetail, type KnockOnDetail } from './sync-knock-on.ts';export const WINDOW_CANCEL_MESSAGE = 'An earlier page of the same sync did not commit; this page was not published and is re-frozen after that failure is resolved.';/** #6402 residual (P4.3): the lane fault a group released or cancelled under, kept on its rows as `blocked_reason` / the cancel message. */@@ -60,12 +61,13 @@ export async function windowPredecessorCommitted(engine: Pick<BrainEngine, 'exec* conflicted). Such a row must not publish: a group commits in manifest order, so its pages after a member that* did not commit are cancelled and re-frozen once that member is resolved, never written ahead of it.*/-export async function earlierGroupMemberFailed(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'request_id' | 'worktree_id' | 'sequence'>): Promise<boolean> {+export async function earlierGroupMemberFailed(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'request_id' | 'worktree_id' | 'sequence'>): Promise<string | null> {const group = (row.intent as Record<string, unknown> | null | undefined)?.group;- if (typeof group !== 'string' || group === row.request_id || !row.worktree_id) return false;- const failed = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2- AND sequence<$3 AND state IN ('failed','cancelled','conflict') LIMIT 1`, [row.worktree_id, group, row.sequence]);- return failed.length > 0;+ if (typeof group !== 'string' || group === row.request_id || !row.worktree_id) return null;+ // #6643: the earliest member that did not commit is the one this row depends on (its knock-on root).+ const [failed] = await engine.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2+ AND sequence<$3 AND state IN ('failed','cancelled','conflict') ORDER BY sequence LIMIT 1`, [row.worktree_id, group, row.sequence]);+ return failed?.request_id ?? null;}/** Cancels a claimed window group (outside lanes) that may not publish; null when it may (`claimedHeadOrder`). */@@ -91,17 +93,22 @@ function groupMember(row: Pick<WriteRequest, 'intent' | 'request_id'>): string |* so a member claimed on its own (released mid-group, then claimed again) is ordered by this, never by `after`.*/export async function claimedPredecessorState(engine: Pick<BrainEngine, 'executeRaw'>, row: OrderedRow): Promise<string | null> {+ return (await claimedPredecessor(engine, row))?.state ?? null;+}++/** `claimedPredecessorState` with the request it names (#6643: the root a knock-on cancel records). */+export async function claimedPredecessor(engine: Pick<BrainEngine, 'executeRaw'>, row: OrderedRow): Promise<{ state: string; requestId: string | null } | null> {const group = groupMember(row);if (group) {- const [previous] = await engine.executeRaw<{ state: string }>(`SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2+ const [previous] = await engine.executeRaw<{ state: string; request_id: string }>(`SELECT state, request_id::text AS request_id FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2AND sequence<$3 AND intent->>'group'=$4 ORDER BY sequence DESC LIMIT 1`, [row.principal_kind, row.principal_id, row.sequence, group]);- if (previous) return previous.state;+ if (previous) return { state: previous.state, requestId: previous.request_id };}const after = windowPredecessor(row);if (!after) return null;const [prior] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',[row.principal_kind, row.principal_id, after]);- return prior?.state ?? 'missing';+ return { state: prior?.state ?? 'missing', requestId: after };}/**@@ -113,7 +120,8 @@ export async function claimedPredecessorState(engine: Pick<BrainEngine, 'execute* group member waits for the member before it and is cancelled when that member ended without committing.*/export async function claimedHeadOrder(engine: BrainEngine, head: WriteRequest, lane: boolean): Promise<WriteRequest[] | 'wait' | null> {- const prior = await claimedPredecessorState(engine, head);+ const predecessor = await claimedPredecessor(engine, head);+ const prior = predecessor?.state ?? null;if (prior === null || prior === 'committed') return null;if (lane && !groupMember(head)) return null;if (lane && !ENDED_UNCOMMITTED.includes(prior)) return 'wait';@@ -124,19 +132,56 @@ export async function claimedHeadOrder(engine: BrainEngine, head: WriteRequest,// #6402 (P4.3): a group released after a lane fault names that fault when its predecessor then ended uncommitted. The// claim cleared the head's own `blocked_reason`; its still-queued members keep the one the release stamped.const fault = laneFaultOf(head.blocked_reason) ?? members.map(member => laneFaultOf(member.blocked_reason)).find(Boolean) ?? null;- if (!missing) return fault ? cancelRows(engine, [head, ...members], laneFaultCancelMessage(fault)) : cancelRows(engine, [head, ...members]);+ const root = predecessor?.requestId ?? null;+ if (!missing) return fault ? cancelRows(engine, [head, ...members], laneFaultCancelMessage(fault), knockOnDetail('lane_fault', root))+ : cancelRows(engine, [head, ...members], WINDOW_CANCEL_MESSAGE, knockOnDetail(groupMember(head) ? 'group_member' : 'window_predecessor', root));// #6402: a predecessor that was never admitted is named, never reported as "an earlier page did not commit".- return [...await cancelRows(engine, [head], `Its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`),- ...await cancelRows(engine, members, `The first page of its group (request ${head.request_id}) was cancelled because its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`)];+ return [...await cancelRows(engine, [head], `Its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`,+ knockOnDetail('predecessor_never_admitted', missing)),+ ...await cancelRows(engine, members, `The first page of its group (request ${head.request_id}) was cancelled because its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`,+ knockOnDetail('predecessor_never_admitted', missing))];}-/** The sync side's cancellation of the window after a failed page: every member nobody claimed yet. */-export async function cancelWindow(engine: BrainEngine, window: Array<Array<{ requestId: string }>>, principal: Principal): Promise<void> {+/**+ * The sync side's cancellation of the window after a failed page: every member nobody claimed yet. `root` is the+ * request whose failure dropped the window (#6643). `maxSequence` fences a converter that lost its cursor swap: only+ * rows admitted before it read the cursor are cancelled, never a replacement the winning converter just admitted.+ */+export async function cancelWindow(engine: BrainEngine, window: Array<Array<{ requestId: string }>>, principal: Principal, root: string | null = null,+ fence?: CursorFence): Promise<boolean> {const ids = window.flat().map(member => member.requestId);- if (!ids.length) return;+ if (!ids.length) return true;const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2AND request_id=ANY($3::uuid[]) AND state='queued' ORDER BY sequence`, [principal.kind, principal.id, ids]);- await cancelRows(engine, rows);+ if (fence) return cancelRowsUnderCursor(engine, fence, rows, knockOnDetail('window_cancelled', root));+ await cancelRows(engine, rows, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_cancelled', root));+ return true;+}++/** The cursor a fenced cancellation belongs to: its key and the request its `pending` held when the canceller read it. */+export interface CursorFence { cursorKey: string; expectedRequestId: string; principal: Principal; worktreeId: string }++/**+ * #6643: cancels unpublished rows only while the cursor still holds the entry the canceller read. The counter locks+ * come first (the order every admission takes, `admitWriteInTransaction` then the cursor FOR SHARE), so a converter+ * that lost its cursor swap can never cancel the replacement request the winner admitted: either the winner's swap is+ * already visible (the cursor no longer names `expectedRequestId`, nothing is cancelled, false) or it waits behind+ * this transaction and admits its replacement afterwards.+ */+export async function cancelRowsUnderCursor(engine: BrainEngine, fence: CursorFence, rows: WriteRequest[], knockOn: KnockOnDetail,+ message = WINDOW_CANCEL_MESSAGE): Promise<boolean> {+ return engine.transaction(async tx => {+ await lockCounters(tx, ['brain', principalKey(fence.principal), `worktree:${fence.worktreeId}`]);+ const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints+ WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE`, [fence.cursorKey]);+ if (held?.request_id !== fence.expectedRequestId) return false;+ for (const row of rows) {+ const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);+ if (!current || isTerminal(current) || current.execution_token !== row.execution_token || current.publication_started || current.recovery) continue;+ await completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled', message, detail: knockOn });+ }+ return true;+ });}/**@@ -155,25 +200,31 @@ export async function cancelOrphanedLaneRows(engine: BrainEngine, run: string, slet unsettled = false;for (const row of rows) {// In manifest order, so a row cancelled here is the uncommitted predecessor the next row sees.- if (!ENDED_UNCOMMITTED.includes(await claimedPredecessorState(engine, row) ?? '')) continue;+ const predecessor = await claimedPredecessor(engine, row);+ if (!ENDED_UNCOMMITTED.includes(predecessor?.state ?? '')) continue;// A running orphan is one the consumer claimed under the FIFO after the lanes closed; it cancels it itself.if (row.state === 'running') unsettled = true;- else await cancelRows(engine, [row]);+ else await cancelRows(engine, [row], WINDOW_CANCEL_MESSAGE, knockOnDetail(groupMember(row) ? 'group_member' : 'window_predecessor', predecessor?.requestId));}if (!unsettled || Date.now() - started >= settleMs) return;await new Promise(resolve => setTimeout(resolve, 50));}}-/** Cancels unpublished rows (queued, or claimed with the given token) with the window reason. */-export async function cancelRows(engine: BrainEngine, rows: WriteRequest[], message = WINDOW_CANCEL_MESSAGE): Promise<WriteRequest[]> {+/**+ * Cancels unpublished rows (queued, or claimed with the given token) with the window reason. Every caller is a sync+ * knock-on producer; `knockOn` records why and the request it depended on (#6643), so recovery and the checkpoint+ * recognise the cancel without matching its message.+ */+export async function cancelRows(engine: BrainEngine, rows: WriteRequest[], message = WINDOW_CANCEL_MESSAGE,+ knockOn: KnockOnDetail = knockOnDetail('window_cancelled', null)): Promise<WriteRequest[]> {const settled: WriteRequest[] = [];for (const row of rows) {const done = await engine.transaction(async tx => {await lockCounters(tx, ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])]);const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);if (!current || isTerminal(current) || current.execution_token !== row.execution_token || current.publication_started || current.recovery) return current ?? null;- return completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled', message });+ return completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled', message, detail: knockOn });});if (done) settled.push(done);}