Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): admit the next bulk group while the current one publishes (#5984 Phase 1.5)
garrytan3af9460d306a
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex a9e3e56a23..d8de51e343 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -8,6 +8,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';import { publicationConcurrency } from './pool-capacity.ts';+import { cancelOrphanedWindowGroup } from './sync-window.ts';import { runPersistenceEffects } from './effects.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -508,6 +509,9 @@ export class PersistenceConsumer {}/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */private async executeOrGroup(row: WriteRequest): Promise<boolean> {+ // #5984 admit-ahead: a window group whose predecessor did not commit is cancelled, never published after it.+ const orphaned = await cancelOrphanedWindowGroup(this.engine, row);+ if (orphaned) { for (const done of orphaned) this.settled(done); return true; }const group = typeof row.intent?.group === 'string' ? row.intent.group : null;if (!group || this.engine.kind !== 'postgres') return this.execute(row);const followers = await claimGroupFollowers(this.engine, row, group, 63);diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex b70e98956d..0dae00a1e7 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -37,6 +37,7 @@ import { frontmatterSlugConflictMessage } from './verb-errors.ts';import { CHUNKER_VERSION } from '../chunkers/code.ts';import { clearGitHold, recordSyncImportProvenance } from './sync-holds.ts';import { VERSION } from '../../version.ts';+import { windowPredecessor, windowPredecessorCommitted } 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 }@@ -221,15 +222,21 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write}};const validate = async (tx: BrainEngine) => {- const cursor = await sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}`, async () => {+ const after = windowPredecessor(row);+ const cursor = await sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}\0${after ?? ''}`, async () => {await assertManagedSyncActive(tx, true);const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);- // #5984: a bulk group's members are held by the cursor's `group`, its head also by `pending`.+ // #5984: a bulk group's members are held by the cursor's `group`, its head also by `pending`, and+ // admitted-ahead groups by `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.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,- (SELECT jsonb_agg(m->>'requestId') FROM jsonb_array_elements(COALESCE(completed_keys->0->'group','[]'::jsonb)) m) AS group- FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE`, [p.cursorKey]);+ (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+ FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR KEY SHARE`, [p.cursorKey]);+ if (after && !await windowPredecessorCommitted(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.`);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,`The owner epoch of ${row.source_id} changed after this sync was admitted. Do not claim or transfer the source to repair content.`, true);diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex b27ca706ca..28d57128df 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -31,6 +31,7 @@ import type { WriteRequest } from './model.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 { cancelWindow } from './sync-window.ts';import { isContentRefusal } from '../import-screen.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';@@ -70,7 +71,13 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority/** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */progress?: CursorProgress;/** #5984 bulk: the frozen head (also `pending`) and the members admitted with it, in manifest order. */- group?: Pending[]; }+ group?: Pending[];+ /**+ * #5984 admit-ahead: groups frozen and admitted after `group` while it publishes, in manifest order+ * (at most one today). Each member's intent names the previous group's last request (`after`); a+ * window group publishes only after that request committed, and is cancelled when it did not.+ */+ window?: Pending[][]; }export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }/** #5984: the cursor's progress after advancing to `index`, in the drain window that started at `drainStartedAt`. */function stampProgress(prior: CursorProgress | undefined, fromIndex: number, index: number, drainStartedAt: number): CursorProgress {@@ -428,13 +435,64 @@ function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: Wri{ paths: outcome.recovered_frontmatter ? [pending.intent.path] : [], commentValues: outcome.comment_value ? 1 : 0 });}interface BulkPass { settings: BulkSettings; perMemberMs: number | null }+type FreezeAt = (base: Cursor) => (index: number) => Promise<Pending | null>;++/** #5984 bulk: freezes the followers of an eligible head and records them with it as the cursor's group. */+async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,+ assertActive: () => void): Promise<Cursor> {+ const followers = await freezeFollowers(engine, head, config, nextGroupSize(bulk.settings, bulk.perMemberMs) - 1, freezeAt(head));+ if (!followers.length) return head;+ // Members name their group (the head's request ID), so a consumer can claim them together.+ const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId } }));+ return saveCursor(engine, key, head, { ...head, pending: members[0], group: members }, false, assertActive);+}++/**+ * #5984 admit-ahead (one lane, window depth 2): while the cursor's group publishes, freeze and admit the+ * next group so it is queued behind it (per-worktree FIFO) and the consumer claims it as soon as the group+ * commits. Nothing is admitted ahead while a foreground write is queued on the worktree, or when the next+ * entry is not groupable (renames, holds, waivers, the checkpoint and overtaken entries stay on the single path).+ */+async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, freezeAt: FreezeAt,+ assertActive: () => void): Promise<Cursor> {+ if (!bulk.settings.enabled || !cursor.group?.length) return cursor;+ let current = cursor;+ if (!current.window?.length) {+ const start = cursor.index + cursor.group.length;+ if (start >= cursor.entries.length) return cursor;+ const [foreground] = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid+ AND state IN ('queued','running','recovering') AND NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%') LIMIT 1`, [cursor.binding.worktree_id]);+ if (foreground) return cursor;+ const base: Cursor = { ...cursor, index: start - 1 };+ // A freeze refusal here is left for the single path to raise in order, after the publishing group.+ const frozen = await freezeFollowers(engine, base, config, nextGroupSize(bulk.settings, bulk.perMemberMs), freezeAt(base)).catch(() => []);+ if (!frozen.length) return cursor;+ const after = cursor.group.at(-1)!.requestId;+ const members = frozen.map(member => ({ ...member, intent: { ...member.intent, group: frozen[0]!.requestId, after } }));+ current = await saveCursor(engine, key, cursor, { ...cursor, window: [members] }, false, assertActive);+ }+ const members = current.window?.[0];+ if (!members?.length) return current;+ const principal = current.authority.writer.principal;+ const admitted = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',+ [principal.kind, principal.id, members.map(member => member.requestId)]);+ if ((admitted[0]?.n ?? 0) < members.length) {+ // An admission that fails here is retried when the group becomes the cursor's group.+ await admitGroup(engine, members, current, async tx => {+ const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->0->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);+ return held?.request_id === members[0]!.requestId;+ }).catch(() => null);+ }+ assertActive();+ return current;+}/*** #5984 bulk: admits the cursor's group, waits for it and advances over the* committed prefix. A terminal failure leaves that member as the single* pending entry, so the single path records and reports it.*/async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, wait: { waitMs: number; signal?: AbortSignal },- drainStartedAt: number, onProgress: SyncOpts['onProgress']): Promise<{ cursor: Cursor } | { result: SyncResult }> {+ drainStartedAt: number, onProgress: SyncOpts['onProgress'], ahead?: (cursor: Cursor) => Promise<Cursor>): Promise<{ cursor: Cursor } | { result: SyncResult }> {const signal = wait.signal;const members = cursor.group!;const principal = cursor.authority.writer.principal;@@ -452,6 +510,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:onProgress?.({ phase: 'managed_sync.group', bankedFiles: cursor.index, total: cursor.entries.length, group: members.length });await validateSyncAuthority(engine, cursor.authority, members[0]!.slug);assertSyncDispatchActive();+ if (ahead) cursor = await ahead(cursor);const last = rows.find(row => row.request_id === members.at(-1)!.requestId)!;const waited = await awaitWrite(engine, last, config, wait);assertSyncDispatchActive();@@ -469,9 +528,16 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:if (committed) next.progress = stampProgress(cursor.progress, cursor.index, next.index, drainStartedAt);const stuck = members[committed];const stuckRow = stuck ? states.get(stuck.requestId) : undefined;- if (!stuck) { delete next.pending; delete next.group; }- else { next.pending = stuck; if (stuckRow && isTerminalWriteState(stuckRow.state)) delete next.group; else next.group = members.slice(committed); }- const saved = committed || next.group?.length !== members.length ? await saveCursor(engine, key, cursor, next) : cursor;+ const failed = !!stuck && !!stuckRow && isTerminalWriteState(stuckRow.state);+ if (!stuck) {+ // The window's first group becomes the cursor's group; its requests are already admitted and queued.+ const [promoted, ...rest] = next.window ?? [];+ if (promoted) { next.pending = promoted[0]; next.group = promoted; } else { delete next.pending; delete next.group; }+ 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; }+ 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) {return { result: { ...result(saved, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'), ...(cursor.authority.writer.remote ? {} : {@@ -705,16 +771,11 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPif (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');continue;}- if (bulk.settings.enabled && !foregroundQueued && !prior && !cursor.group && !pending.rebound && groupableIntent(pending.intent)) {- const head: Cursor = cursor;- const followers = await freezeFollowers(engine, head, config, nextGroupSize(bulk.settings, bulk.perMemberMs) - 1,- async index => { const frozen = await freezeEntry(engine, { ...head, index }, key, assertActive, frozenRun); return 'hold' in frozen ? null : frozen; });- // Members name their group (the head's request ID), so a consumer can claim them together.- const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId } }));- if (followers.length) cursor = await saveCursor(engine, key, head, { ...head, pending: members[0], group: members }, false, assertActive);- }+ 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 && !foregroundQueued && !prior && !cursor.group && !pending.rebound && 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);+ 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);if ('result' in step) return step.result;cursor = step.cursor;assertActive();diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.tsnew file mode 100644index 0000000000..d036f6e24f--- /dev/null+++ b/src/core/persistence/sync-window.ts@@ -0,0 +1,68 @@+/**+ * #5984 admit-ahead: the groups a draining managed sync admits ahead of the+ * 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.+ */+import type { BrainEngine } from '../engine.ts';+import { completeWrite, lockCounters } from './journal.ts';+import { isTerminal, principalKey, requestPrincipal, type Principal, type WriteRequest } from './model.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.';++/** The request a window group waits for, or null for any other request. */+export function windowPredecessor(row: Pick<WriteRequest, 'intent'>): string | null {+ const after = (row.intent as Record<string, unknown> | null | undefined)?.after;+ return typeof after === 'string' ? after : null;+}++/** 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';+}++/**+ * Cancels a claimed window group whose predecessor did not commit: the claimed+ * head and its still-queued members. Returns the settled rows, or null when the+ * group may publish.+ */+export async function cancelOrphanedWindowGroup(engine: BrainEngine, head: WriteRequest): Promise<WriteRequest[] | null> {+ if (await windowPredecessorCommitted(engine, head)) return null;+ 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]);+ return cancelRows(engine, [head, ...members]);+}++/** 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> {+ const ids = window.flat().map(member => member.requestId);+ if (!ids.length) return;+ 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]);+ await cancelRows(engine, rows);+}++async function cancelRows(engine: BrainEngine, rows: WriteRequest[]): 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: WINDOW_CANCEL_MESSAGE });+ });+ if (done) settled.push(done);+ }+ return settled;+}diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.tsindex 8afdb68437..579788f368 100644--- a/test/managed-sync-bulk.test.ts+++ b/test/managed-sync-bulk.test.ts@@ -11,6 +11,8 @@ import { performSync } from '../src/commands/sync/perform.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { nextGroupSize, resolveBulkSettings } from '../src/core/persistence/sync-group.ts';import { withEnv } from './helpers/with-env.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { WINDOW_CANCEL_MESSAGE, cancelOrphanedWindowGroup, windowPredecessor, windowPredecessorCommitted } from '../src/core/persistence/sync-window.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-bulk-'));let engine: BrainEngine | undefined;@@ -117,6 +119,67 @@ test('a held file ends the group before it: it is held without a request and eveexpect(await engine.getPage('notes/n3', { sourceId: f.id })).toBeNull();}), 300_000);+test('a draining sync admits the next group while the current one publishes; every page commits in manifest order', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ if (!engine) return;+ const f = await fixture(engine, notes(20));+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(result.drain).toMatchObject({ outcome: 'synced' });+ const rows = await engine.executeRaw<{ slug: string; state: string; after: string | null; published: string; sequence: string }>(+ `SELECT slug,state,intent->>'after' AS after,published_at::text AS published,sequence::text FROM persistence_requests+ WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);+ expect(rows).toHaveLength(20);+ expect(rows.every(row => row.state === 'committed')).toBe(true);+ // At least one group was admitted ahead, naming the request it waits for.+ const ahead = rows.filter(row => row.after);+ expect(ahead.length).toBeGreaterThan(0);+ const ids = await engine.executeRaw<{ request_id: string; slug: string }>(`SELECT request_id::text,slug FROM persistence_requests WHERE source_id=$1`, [f.id]);+ const slugOf = new Map(ids.map(row => [row.request_id, row.slug]));+ for (const row of ahead) expect(rows.findIndex(r => r.slug === slugOf.get(row.after!))).toBeLessThan(rows.findIndex(r => r.slug === row.slug));+ // Publication order follows manifest (admission) order.+ const published = rows.map(row => row.published);+ expect([...published].sort()).toEqual(published);+ const [cursor] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync' AND (completed_keys->0 ? 'window' OR completed_keys->0 ? 'group')");+ expect(cursor!.n).toBe(0);+}), 300_000);++test('a failed page cancels the group admitted ahead of it; nothing after the failure publishes', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ if (!engine) return;+ const f = await fixture(engine, notes(40, i => i === 2 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));+ await engine.setConfig('sync.holds', 'fail');+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true })+ .finally(() => engine!.unsetConfig('sync.holds'));+ expect(result.drain).toMatchObject({ outcome: 'blocked' });+ expect(result.managedWrite?.slug).toBe('notes/n2');+ const rows = await engine.executeRaw<{ slug: string; state: string; after: string | null; grp: string | null; error_message: string | null }>(+ `SELECT slug,state,intent->>'after' AS after,intent->>'group' AS grp,error_message FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);+ // Rows are in manifest (admission) order: every page before the failure committed, every page after it was cancelled.+ const failedAt = rows.findIndex(row => row.slug === 'notes/n2');+ expect(rows[failedAt]!.state).toBe('failed');+ expect(rows.slice(0, failedAt).every(row => row.state === 'committed')).toBe(true);+ expect(rows.slice(failedAt + 1).every(row => row.state === 'cancelled')).toBe(true);+ for (const row of rows.slice(failedAt)) expect(await engine.getPage(row.slug, { sourceId: f.id })).toBeNull();+ // The group admitted ahead of the failed one is cancelled with the window reason.+ const ahead = rows.slice(failedAt + 1).filter(row => row.after && row.grp !== rows[failedAt]!.grp);+ expect(ahead.length).toBeGreaterThan(0);+ for (const row of ahead) expect(row).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });+ const [cursor] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0 ? 'window' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ expect(cursor!.n).toBe(0);+}), 300_000);++test('a claimed window group whose predecessor did not commit is cancelled by the consumer, not published', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ if (!engine) return;+ const f = await fixture(engine, notes(1));+ const [worktree] = await engine.executeRaw<{ worktree_id: string }>('SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1', [f.id]);+ const missing = randomUUID();+ const head = { id: randomUUID(), request_id: randomUUID(), worktree_id: worktree!.worktree_id, principal_kind: 'local_cli', principal_id: randomUUID(),+ execution_token: null, state: 'queued', intent: { kind: 'managed_sync_import', after: missing } } as unknown as WriteRequest;+ expect(windowPredecessor(head)).toBe(missing);+ expect(await windowPredecessorCommitted(engine, head)).toBe(false);+ expect(await windowPredecessorCommitted(engine, { ...head, intent: { kind: 'managed_sync_import' } } as unknown as WriteRequest)).toBe(true);+ // A row that does not exist settles nothing and publishes nothing.+ expect(await cancelOrphanedWindowGroup(engine, head)).toEqual([]);+}), 300_000);+test('--no-bulk publishes one page per transaction', async () => withEnv({ GBRAIN_HOME: home }, async () => {if (!engine) return;const f = await fixture(engine, notes(5));