Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712 PR1 lane C: consumer-side one page one fate
garrytan0204fdf98042
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex d552cb0ccf..de7c70c5f9 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,6 +1,6 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';@@ -1030,18 +1030,15 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */private async executeOrGroup(row: WriteRequest, root: RootHold): Promise<boolean> {- // #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.- // A lane group may be claimed while its predecessor still publishes; its commit wait decides instead.- // A bulk-sync group member released mid-group follows the member before it, not only the previous group (#6153 class).+ // #6712: a page publishes whatever its predecessor's fate; a lane group member released mid-group only waits while the+ // member before it is still unfinished (#6153 class).const lane = laneOf(row);- const order = await claimedHeadOrder(this.engine, row, lane !== null);- if (order === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }- if (order) { for (const done of order) this.settled(done); return true; }+ if (await claimedHeadOrder(this.engine, row, lane !== null) === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }const group = publicationGroupKey(row);// A managed import batch also groups on PGLite: its members share one transaction's guards there too.if (!group || this.engine.kind !== 'postgres' && !group.startsWith('import:')) return this.execute(row, root);// #6007: a put_pages or import batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.- const followers = await claimGroupFollowers(this.engine, row, group, independentGroup(group) ? PAGE_BATCH_GROUP_MAX - 1 : 63);+ const followers = await claimGroupFollowers(this.engine, row, group, syncGroup(group) ? 63 : PAGE_BATCH_GROUP_MAX - 1);if (!followers.length && !lane) return this.execute(row, root);const rows = [row, ...followers];for (const member of rows) this.executing.add(member.id);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex de5a9a902f..e1d115cd57 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -22,7 +22,8 @@* already published inside it are restored from their recovery records by* the ordinary recovery path (`recoverPublication`, which also requeues their* claims), and the caller then publishes the members one at a time, so a- * failure is attributed to its own page and no later member overtakes it.+ * failure is attributed to its own page. #6712: every group is independent+ * (one page, one fate): a member that does not commit never cancels another.* A member with a skill bundle or a source-exclusive checkpoint, or whose* file changed since preparation, takes the single path.*@@ -38,10 +39,9 @@ import { localHostId } from './identity.ts';import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease, MANAGED_MODE_SQL } from './ownership.ts';import { 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 { laneFaultBlockedReason, windowPredecessor } from './sync-window.ts';+import { clearResolvedRecoveries, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,+ foregroundPriority, independentGroup, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims, syncGroup } from './journal.ts';import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, holdClaimForPublication, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';import { claimPhaseStamp, enterClaimPhase, startClaimPhase, type ClaimPhaseClock } from './claim-phase.ts';@@ -431,7 +431,7 @@ export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest,}/** Why a group transaction did not commit, for the lane fallback and step-down. */-export type GroupFailure = 'busy' | 'predecessor_failed' | 'predecessor_requeued' | 'wounded' | 'order_timeout' | 'lock_timeout' | 'statement_timeout' | 'failed';+export type GroupFailure = 'busy' | 'predecessor_requeued' | 'wounded' | 'order_timeout' | 'lock_timeout' | 'statement_timeout' | 'failed';function groupFailure(error: unknown): GroupFailure {if (error instanceof LaneAbort) return error.reason;const code = (error as { code?: unknown } | null)?.code;@@ -439,15 +439,14 @@ function groupFailure(error: unknown): GroupFailure {}/**- * #5984 lanes: a lane group that did not commit. A group whose predecessor ended without committing is- * cancelled; one whose predecessor committed takes the single path like any FIFO head (null); one whose- * predecessor still publishes, waits in the queue or is not admitted yet releases its claims so it runs first. Lock and statement timeouts- * cost one lane for the rest of the drain.+ * #5984 lanes: a lane group that did not commit. One whose predecessor ended (committed or not, #6712) takes the single+ * path like any FIFO head (null); one whose predecessor still publishes, waits in the queue or is not admitted yet, or+ * that found the worktree busy, releases its claims so it runs first. Lock and statement timeouts cost one lane for the+ * rest of the drain.*/-async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<boolean | null> {+async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<false | null> {if (run.lane) run.lane.fallbacks++;- // #6402 residual (P4.3): a server fault on the lane group is kept on the rows it releases or cancels (`blocked_reason`- // `lane_<fault>`, the cancel message), so the ledger and `claimedHeadOrder` name it instead of a generic wait.+ // #6402 residual (P4.3): a server fault on the lane group is kept on the rows it releases (`blocked_reason` `lane_<fault>`).const laneFault = reason === 'lock_timeout' || reason === 'statement_timeout' ? reason : null;if (laneFault) stepDownLanes(rows[0]!.worktree_id!, `${reason} on a lane group`);const after = windowPredecessor(rows[0]!);@@ -455,12 +454,7 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G[rows[0]!.principal_kind, rows[0]!.principal_id, after]).then(found => found[0]?.state ?? null) : 'committed';// A group that found the worktree busy (another holder or no publication capacity) releases its claims and is// 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,- knockOnDetail(laneFault ? 'lane_fault' : 'window_predecessor', after))) run.settled(done);- return true;- }+ if (prior !== null && ['committed', 'failed', 'conflict', 'cancelled'].includes(prior) && reason !== 'busy') return null;for (const row of rows) await releaseUnpublishedClaim(engine, row, laneFault ? laneFaultBlockedReason(laneFault) : 'group_member_waiting');return false;}@@ -554,11 +548,13 @@ export interface GroupExecution {type MemberOutcome = { ok: PreparedMutation } | { error: unknown } | { released: 'preparation_deadline' | 'group_member_waiting' | 'claim_lost' };/**- * Prepares a claimed group (four members at a time), publishes it in one- * transaction when every member qualifies, and otherwise publishes the- * members one at a time in order. After a member ends in failure the later- * members are cancelled, and after one is released back to the queue the- * later ones are released too, so nothing overtakes it. Claims are renewed+ * Prepares a claimed group (a sync group four members at a time, a page+ * batch all at once), publishes it in one transaction when every member+ * qualifies, and otherwise publishes the members one at a time in order.+ * #6712: a member that ends in failure is its page's fate alone; the later+ * members still publish. In a sync group, after a member is released back+ * to the queue the later ones are released too, so nothing overtakes it+ * (order, not fate: a released member is claimed again). Claims are renewed* for the whole group while it runs (claim-lease.ts). If the group stops* holding every member's claim while it is still preparing, it lets go: each* member is released unpublished with `claim_lost` (token-fenced, so a member@@ -573,7 +569,7 @@ type MemberOutcome = { ok: PreparedMutation } | { error: unknown } | { released:* aborted, k is released `preparation_deadline` (charged; finished* `preparation_stalled` when that reaches the limit) and the later members* `group_member_waiting` (not charged), and the contiguous prepared prefix- * 0..k-1 publishes. An independent `batch:` group releases only k. An+ * 0..k-1 publishes. A `batch:` or `import:` group releases only k. An* abandoned member's preparation goes to `leftRunning` with its clock.*/export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {@@ -591,8 +587,9 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesreturn (await renewGroupClaims(engine, live.map(([row]) => row), 30_000, signal, live.map(([, i]) => stampOf(i)))).size === live.length;}, run.lease ?? DEFAULT_CLAIM_LEASE_TIMING, () => { for (const prep of inFlight.values()) prep.abort({ code: 'claim_lost' }); });if (run.lane) laneClaimed(run.lane, rows);- // A put_pages batch or a managed import batch is independent page writes: one page's failure never cancels its siblings.- const independent = independentGroup(publicationGroupKey(rows[0]!));+ // #6712: every group's members are independent page writes: one page's failure never cancels its siblings. A sync group+ // keeps its order on release and deadline (a released member goes first when it is claimed again); a batch does not.+ const ordered = syncGroup(publicationGroupKey(rows[0]!));const prepared: MemberOutcome[] = new Array(rows.length);// The first member whose deadline passed in an ordered group: nothing after it is dispatched or published this pass.let cut: number | null = null;@@ -601,10 +598,10 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques// GBRA-75 wave 10: an import group's members read their pages and duplicate candidates through one batch each (import-reads.ts).const reads = preparationReads(engine, publicationGroupKey(rows[0]!)?.startsWith('import:') ? importGroupReads(engine, rows) : undefined);// A put_pages or import group prepares all of its (at most PAGE_BATCH_GROUP_MAX) pages at once.- const width = independent ? PAGE_BATCH_GROUP_MAX : 4;+ const width = ordered ? 4 : PAGE_BATCH_GROUP_MAX;// GBRA-75 wave 10: the members' preparations share one memo of root-level path facts; publication re-checks every path.const preparing = withScreeningPaths(async () => {- for (let start = 0; start < rows.length && (independent || cut === null); start += width) {+ for (let start = 0; start < rows.length && (!ordered || cut === null); start += width) {const wave = rows.slice(start, start + width);const now = Date.now();const cancels = wave.map(() => new AbortController());@@ -620,7 +617,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesawait faultPoint('consumer:preparing', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation, signal });return run.prepare(row, reads, undefined, clocks[i]);}, budget, { onDeadline: () => {- if (independent) return;+ if (!ordered) return;if (cut === null || i < cut) cut = i;for (const [j, other] of inFlight) if (j > i) other.abort({ code: 'group_member_waiting' });} });@@ -654,7 +651,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesfor (let i = 0; i < rows.length; i++) {const row = rows[i]!, outcome = prepared[i];const expired = outcome !== undefined && 'released' in outcome && outcome.released === 'preparation_deadline';- const after = !independent && cut !== null && i > cut;+ const after = ordered && cut !== null && i > cut;if (!expired && !after) continue;held.delete(row.id); released.add(row.id);// A dispatched member the deadline or the suffix abort took off this pass may still run: it blocks the root until it settles or the ceiling passes.@@ -687,40 +684,30 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (run.lane && liveRows.length < rows.length) run.lane.begun.delete(liveRows.at(-1)!.request_id);if (result.done) { for (const row of result.done) run.settled(row); return true; }requeued = new Set(result.requeued);- if (run.lane) { const settled = await laneFallback(engine, liveRows, result.reason, run); if (settled !== null) return settled || progressed; }- } else if (run.lane) {- const settled = await laneFallback(engine, liveRows, 'failed', run);- if (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;+ if (run.lane && await laneFallback(engine, liveRows, result.reason, run) !== null) return progressed;+ } else if (run.lane && await laneFallback(engine, liveRows, 'failed', run) !== null) return progressed;+ let release = false;for (const { row: member, i } of live) {let row = member;let current = await getWriteRequestById(engine, row.id);// A claim the group's file restoration released is taken back, in order, while this pass still owns the worktree.- if (current?.state === 'queued' && requeued.has(row.id) && stop === null) {+ if (current?.state === 'queued' && requeued.has(row.id) && !release) {const reclaimed = await reclaimReleasedWrite(engine, row.id);if (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 === null) { stop = 'cancel'; stopRoot = current.request_id; } }- else if (independent) stop ??= 'release';+ if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; }+ else if (!ordered) release = true;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: BULK_GROUP_CANCEL_MESSAGE, detail: knockOnDetail('bulk_group', stopRoot) }));- run.settled(cancelled); progressed = true; continue;- }+ if (release) { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }const p = prepared[i]!;// #6278: a member aborted by our own cancellation (never a deadline here) is released, not failed.- if ('released' in p) { await releaseUnpublishedClaim(engine, row, p.released === 'claim_lost' ? 'claim_lost' : 'group_member_waiting'); stop ??= independent ? null : 'release'; continue; }+ if ('released' in p) { await releaseUnpublishedClaim(engine, row, p.released === 'claim_lost' ? 'claim_lost' : 'group_member_waiting'); if (ordered) release = true; continue; }const 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'; stopRoot ??= done.request_id; } } else stop = 'release';+ if (['committed', 'conflict', 'failed', 'cancelled'].includes(done.state)) progressed = true;+ else release = true;}return progressed;} finally {diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 5c749e71c3..78ef5f22c1 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -402,9 +402,17 @@ export function publicationGroupKey(row: Pick<WriteRequest, 'operation' | 'intenconst batch = row.intent?.page_batch as { id?: unknown } | undefined;return !row.intent?.kind && typeof batch?.id === 'string' ? `batch:${batch.id}` : null;}-/** Groups whose members are independent page writes: one member's failure never cancels the others. */+/**+ * Groups whose members are independent page writes: one member's failure never cancels the others. #6712 (L2): a bulk+ * managed-sync group (`sync:`) is independent too; one page's failure is that page's fate alone, and the sync side+ * settles each member by its own receipt. Fate only: its claim and preparation widths stay its own (`syncGroup`).+ */export function independentGroup(key: string | null): boolean {- return key !== null && (key.startsWith('batch:') || key.startsWith('import:'));+ return key !== null && (key.startsWith('batch:') || key.startsWith('import:') || key.startsWith('sync:'));+}+/** #6712: a bulk managed-sync group key; such a group claims up to its admitted size (63 followers) and prepares four members at a time. */+export function syncGroup(key: string | null): boolean {+ return key !== null && key.startsWith('sync:');}const GROUP_KEY_SQL = `CASE WHEN intent ? 'group' THEN 'sync:'||(intent->>'group')WHEN operation='put_page' AND intent->>'kind'='managed_file_import' AND jsonb_typeof(intent->'import_batch')='string' THEN 'import:'||(intent->>'import_batch')diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex f83cb1a04e..96f2430eb1 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -808,9 +808,6 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, annoconst left = opts.deadlineAtMs === undefined ? null : Math.max(0, opts.deadlineAtMs - Date.now());const stats = left === null ? await closeLaneRun(laneRun): await Promise.race([closeLaneRun(laneRun), new Promise<undefined>(resolve => { const t: ReturnType<typeof setTimeout> = setTimeout(() => resolve(undefined), left); t.unref?.(); })]);- const { cancelOrphanedLaneRows } = await import('./sync-window.ts');- const settleMs = opts.deadlineAtMs === undefined ? 10_000 : Math.max(0, Math.min(10_000, opts.deadlineAtMs - Date.now()));- await cancelOrphanedLaneRows(engine, laneRun, result?.drain?.outcome === 'blocked' ? settleMs : 0).catch(() => undefined);const lanes = result?.drain?.bulk?.lanes;if (lanes && stats) Object.assign(lanes, { busy: stats.busy, apply_ms_per_page: stats.applyMsPerPage, turn_wait_share: stats.turnWaitShare });}diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.tsindex 1021995ca1..98f209aceb 100644--- a/src/core/persistence/sync-lanes.ts+++ b/src/core/persistence/sync-lanes.ts@@ -147,7 +147,7 @@ export function laneClaimed(state: LaneState, rows: WriteRequest[]): void { statexport function laneFinished(state: LaneState, rows: WriteRequest[]): void { state.claimed.delete(groupKey(rows)); state.begun.delete(groupKey(rows)); }export class LaneAbort extends Error {- constructor(readonly reason: 'predecessor_failed' | 'predecessor_requeued' | 'wounded' | 'order_timeout') { super(`lane ${reason}`); }+ constructor(readonly reason: 'predecessor_requeued' | 'wounded' | 'order_timeout') { super(`lane ${reason}`); }}const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));@@ -170,10 +170,11 @@ export async function awaitLaneBegin(state: LaneState, rows: WriteRequest[], max/*** Inside the group transaction, after its members are applied and before the- * counters are locked: waits until the previous group committed. Each poll is- * a fresh read of the predecessor's receipt. Throws LaneAbort when the- * predecessor ended without committing or went back to the queue, when an- * exclusive writer waits for the worktree's lease, or after `maxMs`.+ * counters are locked: waits until the previous group ended. Each poll is a+ * fresh read of the predecessor's receipt. #6712: a predecessor that ended+ * without committing passes the turn like a committed one (its page's fate is+ * its own). Throws LaneAbort when the predecessor went back to the queue, when+ * an exclusive writer waits for the worktree's lease, or after `maxMs`.*/export async function awaitLaneTurn(tx: BrainEngine, state: LaneState, rows: WriteRequest[], maxMs = 60_000): Promise<void> {const after = predecessorOf(rows);@@ -183,8 +184,7 @@ export async function awaitLaneTurn(tx: BrainEngine, state: LaneState, rows: Wrifor (let poll = 0; ; poll++) {const [prior] = await tx.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',[head.principal_kind, head.principal_id, after]);- if (prior?.state === 'committed') return;- if (prior && ['failed', 'conflict', 'cancelled'].includes(prior.state)) throw new LaneAbort('predecessor_failed');+ if (prior && ['committed', 'failed', 'conflict', 'cancelled'].includes(prior.state)) return;// A released (or not yet admitted) predecessor goes first: this lane gives its slot and claims back, rather than wait on it.if (!prior || prior.state === 'queued') throw new LaneAbort('predecessor_requeued');if (state.coordinationPath && leaseWounded(state.coordinationPath)) throw new LaneAbort('wounded');diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex b6c0b1077e..8921dfbc22 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -40,7 +40,7 @@ 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, 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 { CURSOR_CHANGED_REFUSAL_MESSAGE, 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';@@ -54,7 +54,6 @@ import { describeFixes } from '../fence-repair/report.ts';import { fenceFixesWire } from '../fence-repair/tier1.ts';import type { FenceFix } from '../fence-repair/types.ts';import { VERSION } from '../../version.ts';-import { earlierGroupMemberFailed, windowPredecessor, windowPredecessorAllows } from './sync-window.ts';/** The options that select a managed sync cursor (its key), recorded so a refusal can print the exact retry. */export interface SyncCursorOptions { full: boolean; workingTree: boolean; srcSubpath: string | null; exclude: string[]; includeHidden: string[]; strategy: string | null }@@ -101,15 +100,12 @@ 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.*/-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 }+export 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)) m- 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 dropped+ UNION 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;}@@ -124,9 +120,10 @@ function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<S}/*** #5984: the source-wide part of sync validation as one pipeline: coordinator switch, configured root,- * cursor, window predecessor and owner epoch, each checked in that order. The rows stay locked FOR SHARE.+ * cursor and owner epoch, each checked in that order. The rows stay locked FOR SHARE. #6712: a page no longer+ * waits on its window predecessor's fate (one page, one fate).*/-async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string, after: string | null) {+async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncIntent, root: string) {const [, , held] = await pipelined(tx, [() => assertManagedSyncActive(tx, true),async () => {@@ -134,10 +131,6 @@ async function sourceSyncChecks(tx: BrainEngine, row: WriteRequest, p: SyncIntenassertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);},() => readSyncCursorFence(tx, p.cursorKey),- async () => {- if (after && !await windowPredecessorAllows(tx, row)) throw withSyncRefusal(knockOnRefusal(EARLIER_PAGE_REFUSAL_MESSAGE, row,- `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);if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,@@ -171,15 +164,13 @@ 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.+ * #6643: the refusal of a request whose run another run replaced: not a failure of its page. Its next step is the+ * status read, never a `--retry-failed` rerun: the replacing run covers the page.*/-function knockOnRefusal(message: string, row: WriteRequest, cause: string, superseded = false): OperationError {+function supersededRefusal(message: string, row: WriteRequest, cause: string): OperationError {const status = ['gbrain', 'sync', 'status', '--source', row.source_id, '--json'];- 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.`,+ return opError('revision_conflict', message,+ `${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.`,{ fix: readFix('Shows the sync cursor, the root cause of this refusal and the next step, read-only.', { argv: status }) });}@@ -190,27 +181,20 @@ function withSyncRefusal(error: OperationError, detail: object): OperationError}/**- * #6643: "The accepted sync cursor changed before publication." has three causes, recorded with a fence snapshot:+ * #6643: "The accepted sync cursor changed before publication." has two causes, recorded with a fence snapshot+ * (#6712 retired the third, `window_dropped`, with the window cancel that produced it):* - `run_replaced`: another run of the source replaced the cursor; this request's run is superseded, not failed.- * - `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.+ * - `outside_fence`: anything else (a duplicate admission, a request ahead of the cursor): a coordination fault, a root.*/export function cursorFenceRefusal(row: WriteRequest, p: SyncIntent, cursor: SyncCursorFence): OperationError {const cursorIndex = cursor.index == null ? null : Number(cursor.index);- 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 cause = cursor.run_id !== p.runId ? 'run_replaced' : '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, 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', drop?.root ?? null), cause, fence }- : { origin: SYNC_CURSOR_FENCE_ORIGIN, cause, fence });+ const error = cause === 'run_replaced'+ ? supersededRefusal(CURSOR_CHANGED_REFUSAL_MESSAGE, row, `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`)+ : syncPublicationRefusal('revision_conflict', CURSOR_CHANGED_REFUSAL_MESSAGE, row, p,+ `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, { origin: SYNC_CURSOR_FENCE_ORIGIN, cause, fence });}/**@@ -516,16 +500,10 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr};// #5984: validation's reads are pipelined; each check runs in the order it always did, so the first failing one is reported.const validate = async (tx: BrainEngine) => {- const after = windowPredecessor(row);- const shared = sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}\0${after ?? ''}`, () => sourceSyncChecks(tx, row, p, root, after));+ const shared = sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}`, () => sourceSyncChecks(tx, row, p, root));await pipelined(tx, [() => shared,() => validateSyncAuthority(tx, p.syncAuthority, row.slug),- async () => {- const failed = await earlierGroupMemberFailed(tx, row);- if (failed) throw withSyncRefusal(knockOnRefusal(EARLIER_PAGE_REFUSAL_MESSAGE, row,- `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`.diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.tsindex be92bfb39e..3111382605 100644--- a/src/core/persistence/sync-window.ts+++ b/src/core/persistence/sync-window.ts@@ -3,27 +3,27 @@* group that is publishing (the cursor's `window`).** A window group's members name the previous group's last request in their- * intent (`after`). The per-worktree FIFO claim makes a window group claimable- * only once every earlier request is final, so at claim time that request is- * either committed (the group publishes) or not (an earlier page failed or was- * cancelled). In the second case the group is cancelled here, so no page- * publishes after an earlier page of the same sync failed. Publication- * validation re-checks the same predecessor inside the transaction.+ * intent (`after`), so groups are claimed and committed in manifest order.+ * #6712 (one page, one fate): a page publishes whatever the fate of the page+ * before it; nothing here cancels a page because another one did not commit.+ * The only order a claim keeps is the wait for a predecessor that is still+ * unfinished. The legacy cancel texts stay so receipts older builds wrote+ * still render as superseded knock-ons (sync-knock-on.ts).*/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';+import type { WriteRequest } from './model.ts';+/** The window cancel text older builds wrote (no producer since #6712); the legacy knock-on predicate matches it. */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. */+/** #6402 residual (P4.3): the lane fault a group released under, kept on its rows as `blocked_reason`. */export type LaneFault = 'lock_timeout' | 'statement_timeout';export const laneFaultBlockedReason = (fault: LaneFault) => `lane_${fault}` as const;export const laneFaultOf = (blockedReason: string | null | undefined): LaneFault | null =>blockedReason === 'lane_lock_timeout' ? 'lock_timeout' : blockedReason === 'lane_statement_timeout' ? 'statement_timeout' : null;+/** The lane-fault cancel text older builds wrote (no producer since #6712). */export const laneFaultCancelMessage = (fault: LaneFault) =>`An earlier page of the same sync did not commit after ${fault} on its lane group; this page was not published and is re-frozen on the next sync pass.`;-/** The lane fault a recorded cancel names, so `sync status --json` carries it as the failure's detail (#6402 residual). */+/** The lane fault a recorded legacy cancel names, so `sync status --json` carries it as the failure's detail (#6402 residual). */export const laneFaultInMessage = (message: string | null | undefined): LaneFault | null =>message?.includes(' after lock_timeout on its lane group') ? 'lock_timeout' : message?.includes(' after statement_timeout on its lane group') ? 'statement_timeout' : null;@@ -33,51 +33,8 @@ export function windowPredecessor(row: Pick<WriteRequest, 'intent'>): string | nreturn typeof after === 'string' ? after : null;}-/**- * Whether a window group may still publish: its predecessor committed, or, for a lane group (`intent.lane`),- * is still publishing, since the lane commits only after it (sync-lanes.ts `awaitLaneTurn`). A predecessor- * that ended without committing, or is missing, never lets it publish.- */-export async function windowPredecessorAllows(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>): Promise<boolean> {- const after = windowPredecessor(row);- if (!after) return true;- 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]);- if (prior?.state === 'committed') return true;- return typeof (row.intent as Record<string, unknown> | null | undefined)?.lane === 'string' && ['queued', 'running'].includes(prior?.state ?? '');-}--/** Whether the predecessor of a window group committed (true for requests outside a window). */-export async function windowPredecessorCommitted(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'intent' | 'principal_kind' | 'principal_id'>): Promise<boolean> {- const after = windowPredecessor(row);- if (!after) return true;- 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 === 'committed';-}--/**- * #6252: whether an earlier member of this row's bulk group ended without committing (failed, cancelled or- * 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<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 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`). */-export async function cancelOrphanedWindowGroup(engine: BrainEngine, head: WriteRequest): Promise<WriteRequest[] | null> {- const order = await claimedHeadOrder(engine, head, false);- return order === 'wait' ? null : order;-}-type OrderedRow = Pick<WriteRequest, 'intent' | 'request_id' | 'principal_kind' | 'principal_id' | 'sequence'>;-const ENDED_UNCOMMITTED = ['failed', 'conflict', 'cancelled'];+const UNFINISHED = ['queued', 'running', 'recovering'];/** True for a bulk-sync group member other than its group's head (the head's request ID names the group). */function groupMember(row: Pick<WriteRequest, 'intent' | 'request_id'>): string | null {@@ -86,17 +43,11 @@ function groupMember(row: Pick<WriteRequest, 'intent' | 'request_id'>): string |}/**- * The state of the request a claimed row must follow; null when it follows nothing. A group member follows the+ * The request a claimed row follows, with its state; null when it follows nothing. A group member follows the* member before it in its own group (members are admitted consecutively in one transaction, so it is the* principal's nearest earlier request of that group); a group head or single request follows its window- * predecessor `after` ('missing' when that request is gone). A member's `after` names only the previous group,- * so a member claimed on its own (released mid-group, then claimed again) is ordered by this, never by `after`.+ * predecessor `after` ('missing' when that request is gone).*/-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) {@@ -112,126 +63,13 @@ export async function claimedPredecessor(engine: Pick<BrainEngine, 'executeRaw'>}/**- * What a claimed head may do given the request it follows (`claimedPredecessorState`): publish (null), wait- * (`'wait'`: release the claim so that request goes first), or nothing: its group's claimed head and- * still-queued later members are cancelled and returned. Outside lanes any uncommitted predecessor cancels- * (the per-worktree FIFO claim means it is final). A lane group head may run while the previous group still- * publishes (`awaitLaneTurn` orders the commits and `laneFallback` settles a failed predecessor), but a lane- * group member waits for the member before it and is cancelled when that member ended without committing.+ * What a claimed head may do given the request it follows: publish (null) or wait (`'wait'`: release the claim so that+ * request goes first). #6712: a predecessor that ended, committed or not, or was never admitted, lets it publish; only a+ * lane group member whose predecessor member is still unfinished waits (a lane group head runs beside the previous group,+ * and `awaitLaneTurn` orders the commits).*/-export async function claimedHeadOrder(engine: BrainEngine, head: WriteRequest, lane: boolean): Promise<WriteRequest[] | 'wait' | null> {- 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';- const group = typeof head.intent?.group === 'string' ? head.intent.group : head.request_id;- const members = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2- AND state='queued' AND id<>$3::uuid ORDER BY sequence`, [head.worktree_id, group, head.id]);- const missing = prior === 'missing' ? windowPredecessor(head) : null;- // #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;- 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.`,- 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. `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 true;- const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2- AND request_id=ANY($3::uuid[]) AND state='queued' ORDER BY sequence`, [principal.kind, principal.id, ids]);- 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> {- // One row per transaction, as `cancelRows` does: holding several request rows at once deadlocks against the- // consumer's claim renewals, which lock the same rows in another order. The cursor is re-checked for every row.- for (const row of rows) {- const held = await engine.transaction(async tx => {- await lockCounters(tx, ['brain', principalKey(fence.principal), `worktree:${fence.worktreeId}`]);- const [cursor] = 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 (cursor?.request_id !== fence.expectedRequestId) return false;- 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) {- await completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled', message, detail: knockOn });- }- return true;- });- if (!held) return false;- }- return true;-}--/**- * #5984 lanes: after a drain's lane tasks settled, cancels its lane run's still-queued rows, in manifest order,- * whose predecessor ended without committing (a lane that saw its predecessor go back to the queue releases its- * group, which the window cancellation had skipped while it was claimed). The consumer's FIFO claim cancels the- * same rows later (`claimedHeadOrder`); this settles them before the drain reports. A group member is judged by- * the member before it (`claimedPredecessorState`), so a member released mid-group is cancelled with its group. With- * `settleMs`, it also waits (up to that long) for orphans the consumer already claimed under the FIFO to finish- * cancelling, so a blocked drain never reports one of them still running.- */-export async function cancelOrphanedLaneRows(engine: BrainEngine, run: string, settleMs = 0): Promise<void> {- const started = Date.now();- for (;;) {- const rows = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE state IN ('queued','running') AND intent->>'lane'=$1 ORDER BY sequence`, [run]);- let unsettled = false;- for (const row of rows) {- // In manifest order, so a row cancelled here is the uncommitted predecessor the next row sees.- 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], 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. 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, detail: knockOn });- });- if (done) settled.push(done);- }- return settled;+export async function claimedHeadOrder(engine: Pick<BrainEngine, 'executeRaw'>, head: OrderedRow, lane: boolean): Promise<'wait' | null> {+ if (!lane || !groupMember(head)) return null;+ const prior = (await claimedPredecessor(engine, head))?.state ?? null;+ return prior !== null && UNFINISHED.includes(prior) ? 'wait' : null;}