Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712 lane C: rewrite cascade-pinning tests
garrytancb3946579ddd
diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.tsindex 4c8ee0ed47..169a99d00e 100644--- a/test/managed-sync-bulk.test.ts+++ b/test/managed-sync-bulk.test.ts@@ -12,7 +12,8 @@ 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';+import { claimedHeadOrder, windowPredecessor } from '../src/core/persistence/sync-window.ts';+import { waitFor } from './helpers/wait-for.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-bulk-'));let engine: BrainEngine | undefined;@@ -93,7 +94,11 @@ test('a bulk drain publishes groups in one transaction while every page keeps itexpect(cursor!.n).toBe(0);}), 300_000);-test('a failing member is attributed to its own page, earlier members commit and later members are cancelled, not published', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+/** #6712: every admitted request of the source has settled (the consumer keeps publishing after the run returns). */+const settledAll = (e: BrainEngine, id: string) => waitFor(async () => (await e.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering') LIMIT 1", [id])).length === 0,+ { timeoutMs: 60_000, label: 'admitted requests settle' });++test('#6712: a failing member is attributed to its own page; the members before and after it commit on their own fate', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {if (!engine) return;const f = await fixture(engine, notes(10, i => i === 3 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));// #5988 holds such a file by default; the fail-closed policy keeps it a publication failure inside the group.@@ -103,13 +108,14 @@ test('a failing member is attributed to its own page, earlier members commit andexpect(result).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });expect(result.managedWrite?.slug).toBe('notes/n3');- for (let i = 0; i < 3; i++) expect(await engine.getPage(`notes/n${i}`, { sourceId: f.id })).not.toBeNull();- for (let i = 3; i < 10; i++) expect(await engine.getPage(`notes/n${i}`, { sourceId: f.id })).toBeNull();+ await settledAll(engine, f.id);const states = await engine.executeRaw<{ slug: string; state: string }>(`SELECT slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);expect(states.find(row => row.slug === 'notes/n3')?.state).toBe('failed');- expect(states.filter(row => row.state === 'committed').map(row => row.slug)).toEqual(['notes/n0', 'notes/n1', 'notes/n2']);- expect(states.filter(row => !['committed', 'failed'].includes(row.state)).every(row => row.state === 'cancelled')).toBe(true);+ // Nothing is cancelled for another page's failure: every other admitted page commits.+ expect(states.filter(row => row.slug !== 'notes/n3').every(row => row.state === 'committed')).toBe(true);+ for (const row of states.filter(row => row.state === 'committed')) expect(await engine.getPage(row.slug, { sourceId: f.id })).not.toBeNull();+ expect(await engine.getPage('notes/n3', { sourceId: f.id })).toBeNull();}), 300_000);test('a held file ends the group before it: it is held without a request and every other page commits (#5988)', async () => withEnv({ GBRAIN_HOME: home }, async () => {@@ -149,42 +155,51 @@ test('a draining sync admits the next group while the current one publishes; eveexpect(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 () => {+test('#6712: a failed page leaves the groups admitted ahead of it in the cursor until their own receipts are read; nothing is admitted twice', 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));+ const conflict = '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n';+ const f = await fixture(engine, notes(40, i => i === 2 ? conflict : 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);+ try {+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true });+ expect(result.drain).toMatchObject({ outcome: 'blocked' });+ expect(result.managedWrite?.slug).toBe('notes/n2');+ await settledAll(engine, f.id);+ const rows = await engine.executeRaw<{ request_id: string; slug: string; state: string }>(+ `SELECT request_id::text AS request_id,slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);+ const failedAt = rows.findIndex(row => row.slug === 'notes/n2');+ expect(rows[failedAt]!.state).toBe('failed');+ expect(rows.filter((_, i) => i !== failedAt).every(row => row.state === 'committed')).toBe(true);+ // Every request admitted after the failure is still named by the blocked cursor (its pending entry or window), so a resume reads its receipt instead of freezing it again.+ const [cursor] = await engine.executeRaw<{ keys: { pending?: { requestId: string }; window?: Array<Array<{ requestId: string }>>; done?: boolean } }>(+ "SELECT completed_keys->0 AS keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ expect(cursor!.keys.done).not.toBe(true);+ const held = new Set([cursor!.keys.pending?.requestId, ...(cursor!.keys.window ?? []).flat().map(member => member.requestId)]);+ for (const row of rows.slice(failedAt)) expect(held.has(row.request_id)).toBe(true);+ // The file is fixed; the same plain sync finishes, every page committed exactly once.+ writeFileSync(join(f.root, 'notes/n2.md'), '---\ntitle: Note 2\n---\nA durable observation number 2.\n');+ execFileSync('git', ['-C', f.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'fix']);+ const resumed = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, retryFailed: true });+ expect(resumed.drain).toMatchObject({ outcome: 'synced' });+ const committed = await engine.executeRaw<{ slug: string; n: number }>(+ `SELECT slug,count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' AND state='committed' GROUP BY slug`, [f.id]);+ expect(committed).toHaveLength(40);+ expect(committed.every(row => row.n === 1)).toBe(true);+ const conflicts = await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND error_code='revision_conflict'", [f.id]);+ expect(conflicts).toHaveLength(0);+ } finally { await engine.unsetConfig('sync.holds'); }}), 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 () => {+test('#6712: a claimed window head publishes whatever its predecessor became; it is never cancelled for it', 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(),+ const head = { id: randomUUID(), request_id: randomUUID(), worktree_id: worktree!.worktree_id, principal_kind: 'local_cli', principal_id: randomUUID(), sequence: 1,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([]);+ expect(await claimedHeadOrder(engine, head, false)).toBeNull();+ expect(await claimedHeadOrder(engine, head, true)).toBeNull();}), 300_000);test('--no-bulk publishes one page per transaction', async () => withEnv({ GBRAIN_HOME: home }, async () => {diff --git a/test/sync-cancelled-knock-on.test.ts b/test/sync-cancelled-knock-on.test.tsindex 7a49cc4ee4..45067d4eeb 100644--- a/test/sync-cancelled-knock-on.test.ts+++ b/test/sync-cancelled-knock-on.test.ts@@ -2,8 +2,8 @@* #6402: a knock-on `cancelled` receipt is a retryable page fault, the same verdict sync's own `Next:` gives.** Protects: `cancelled` is in the fault table (page / retry / not needs_human), so `sync status` hands the- * loop the retry instead of paging a person; a group head whose window predecessor was never admitted is- * cancelled with a message naming that request, not "an earlier page did not commit"; the failure ledger+ * loop the retry instead of paging a person (an older build's knock-on cancel still renders that way); since+ * #6712 a group head whose window predecessor was never admitted or failed publishes on its own fate; the failure ledger* restarts `first_seen`/`attempts` when a run targets a new commit (a `--retry-failed` of the same target keeps* counting, as `persistence-sync-failures.serial.test.ts` pins) and moves `updated_at`; a resume refused for conflicting* cursor options (`invalid_params`, a caller error) leaves the recorded diagnosis untouched.@@ -24,7 +24,7 @@ import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';import { managedSyncRetryCommand, readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';import { claimedHeadOrder, laneFaultBlockedReason, laneFaultCancelMessage, laneFaultInMessage, laneFaultOf, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';-import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';import { withEnv } from './helpers/with-env.ts';@@ -105,7 +105,7 @@ test('the ledger restarts first_seen and attempts when the run targets a new comexpect((await updatedAt()) > t2).toBe(true);}));-test('a head whose window predecessor was never admitted is cancelled naming that request', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('#6712: a head whose window predecessor was never admitted publishes on its own fate, never cancelled for it', async () => withEnv({ GBRAIN_HOME: home }, async () => {await registerLocalWriter(engine, 'cli');const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");const ctx: OperationContext = { engine, config: { engine: 'pglite' }, dryRun: false, remote: false, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } } as OperationContext;@@ -115,16 +115,12 @@ test('a head whose window predecessor was never admitted is cancelled naming thaawait admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default', sourceIncarnation: source!.incarnation,slug: 'notes/knock-on', pageId: null, requestId: randomUUID(), callerIntent: intent, intent });const head = (await claimNextWrite(engine, localHostId()))!;- const settled = await claimedHeadOrder(engine, head, false);- expect(Array.isArray(settled)).toBe(true);- const [row] = settled as Awaited<ReturnType<typeof claimNextWrite>>[];- expect(row!.state).toBe('cancelled');- expect(row!.error_code).toBe('cancelled');- expect(row!.error_message).toContain(missing);- expect(row!.error_message).not.toBe(WINDOW_CANCEL_MESSAGE);+ expect(await claimedHeadOrder(engine, head, false)).toBeNull();+ expect(await claimedHeadOrder(engine, head, true)).toBeNull();+ expect((await getWriteRequestById(engine, head.id))!.state).toBe('running');}));-test('#6402 residual (P4.3): a lane group released after a lock timeout keeps the fault on its rows, and its cancel names it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('#6402 residual (P4.3) / #6712: a lane group released after a lock timeout keeps the fault on its rows and publishes after a failed predecessor', async () => withEnv({ GBRAIN_HOME: home }, async () => {expect(laneFaultBlockedReason('lock_timeout')).toBe('lane_lock_timeout');expect(laneFaultOf('lane_statement_timeout')).toBe('statement_timeout');expect(laneFaultOf('group_member_waiting')).toBeNull();@@ -152,16 +148,11 @@ test('#6402 residual (P4.3): a lane group released after a lock timeout keeps thconst head = (await claimNextWrite(engine, localHostId()))!;expect(head.request_id).toBe(headId);expect(head.blocked_reason).toBeNull();- // Claimed as a window head (a lane head re-runs through laneFallback, which names the fault itself).- const settled = await claimedHeadOrder(engine, head, false);- expect(Array.isArray(settled)).toBe(true);- const rows = settled as Awaited<ReturnType<typeof claimNextWrite>>[];- expect(rows.map(row => row!.state)).toEqual(['cancelled', 'cancelled']);- for (const row of rows) {- expect(row!.error_code).toBe('cancelled');- expect(row!.error_message).toBe(laneFaultCancelMessage('lock_timeout'));- expect(row!.error_message).toContain('after lock_timeout on its lane group');- }+ // #6712: claimed as a window head behind a predecessor that failed, it publishes on its own fate instead of being cancelled.+ expect(await claimedHeadOrder(engine, head, false)).toBeNull();+ expect((await getWriteRequestById(engine, head.id))!.state).toBe('running');+ // An older build's cancel text still names the fault, and still classifies as a retryable page fault.+ expect(laneFaultCancelMessage('lock_timeout')).toContain('after lock_timeout on its lane group');expect(classifySyncFault({ code: 'cancelled' })).toMatchObject({ class: 'page', safe_actions: ['retry'], needs_human: false });}));diff --git a/test/sync-group-member-order.test.ts b/test/sync-group-member-order.test.tsindex 4209b76488..a29414c1f1 100644--- a/test/sync-group-member-order.test.ts+++ b/test/sync-group-member-order.test.ts@@ -1,11 +1,9 @@/**- * #6153 class (wave 11, PR #6263 CI): a bulk-sync group member released back to the queue mid-group (its group- * fell back to the single path and an earlier member went back to the queue with `writer_busy`) was later- * claimed on its own and published, although the member before it in its group then failed. Its `after` names- * only the previous group, so the window checks (`cancelOrphanedWindowGroup`, the lane claim, the drain's- * `cancelOrphanedLaneRows`) let it through and a page after a failed page published. A group member's- * predecessor is the member before it: a member whose predecessor ended without committing is cancelled, and- * under lanes a member whose predecessor is still unfinished waits. Postgres only (bulk groups and lanes).+ * #6153 class (wave 11, PR #6263 CI) and #6712 (one page, one fate): a bulk-sync group member's predecessor is the+ * member before it in its group (its `after` names only the previous group). Under lanes a member whose predecessor+ * is still unfinished releases its claim and waits, so lane commits stay in manifest order. Since #6712 a member whose+ * predecessor ended without committing publishes on its own: the members of a sync group share a transaction budget,+ * never a fate (dependency edges keep two changes of one page out of the same group). Postgres only (bulk groups and lanes).*/import { describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -16,7 +14,6 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';-import { cancelOrphanedLaneRows, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { closeLaneRun, openLanes } from '../src/core/persistence/sync-lanes.ts';import type { WriteRequest } from '../src/core/persistence/model.ts';import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../scripts/persistence/harness.ts';@@ -58,8 +55,8 @@ function consumer(engine: BrainEngine, config: HarnessConfig, sources: FixtureSoconst state = async (engine: BrainEngine, row: WriteRequest) => (await getWriteRequestById(engine, row.id))!;const pageOf = async (engine: BrainEngine, source: FixtureSource, slug: string) => engine.getPage(slug, { sourceId: source.id });-describe.skipIf(!process.env.DATABASE_URL)('a bulk group member never publishes after the member before it ended without committing', () => {- test('FIFO claim: the member is cancelled, not published', () => withBrain(async ({ engine, config, sources }) => {+describe.skipIf(!process.env.DATABASE_URL)('a bulk group member has its own fate: it publishes after the member before it ended, committed or not', () => {+ test('FIFO claim: a member whose predecessor was cancelled publishes on its own', () => withBrain(async ({ engine, config, sources }) => {const { b, c } = await group(engine, config, sources[0]!, null);await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);const { instance } = consumer(engine, config, sources);@@ -67,11 +64,12 @@ describe.skipIf(!process.env.DATABASE_URL)('a bulk group member never publishesinstance.start();await waitFor(async () => !['queued', 'running'].includes((await state(engine, c)).state), { timeoutMs: 15_000, label: 'the member settles' });} finally { await instance.stop(); }- expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });- expect(await pageOf(engine, sources[0]!, 'order/c')).toBeNull();+ expect(await state(engine, c)).toMatchObject({ state: 'committed' });+ expect(await pageOf(engine, sources[0]!, 'order/c')).not.toBeNull();+ expect(await pageOf(engine, sources[0]!, 'order/b')).toBeNull();}), 120_000);- test('lane claim: the member is cancelled, not published', () => withBrain(async ({ engine, config, sources }) => {+ test('lane claim: a member whose predecessor was cancelled publishes on its own', () => withBrain(async ({ engine, config, sources }) => {const run = randomUUID();const { b, c } = await group(engine, config, sources[0]!, run);await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);@@ -81,19 +79,11 @@ describe.skipIf(!process.env.DATABASE_URL)('a bulk group member never publishesinstance.start();await waitFor(async () => !['queued', 'running'].includes((await state(engine, c)).state), { timeoutMs: 15_000, label: 'the member settles' });} finally { await instance.stop(); await closeLaneRun(run, 5_000); }- expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });- expect(await pageOf(engine, sources[0]!, 'order/c')).toBeNull();+ expect(await state(engine, c)).toMatchObject({ state: 'committed' });+ expect(await pageOf(engine, sources[0]!, 'order/c')).not.toBeNull();}), 120_000);- test('the drain-end sweep cancels a queued member whose predecessor failed', () => withBrain(async ({ engine, config, sources }) => {- const run = randomUUID();- const { b, c } = await group(engine, config, sources[0]!, run);- await cancelWriteRequest(engine, { kind: 'local_cli', id: b.principal_id }, b.request_id);- await cancelOrphanedLaneRows(engine, run);- expect(await state(engine, c)).toMatchObject({ state: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE });- }), 120_000);-- test('a member whose predecessor committed still publishes', () => withBrain(async ({ engine, config, sources }) => {+ test('a member whose predecessor committed still publishes, after it', () => withBrain(async ({ engine, config, sources }) => {const run = randomUUID();const { c } = await group(engine, config, sources[0]!, run);openLanes(sources[0]!.binding.worktree_id, run, 4, null);@@ -102,8 +92,7 @@ describe.skipIf(!process.env.DATABASE_URL)('a bulk group member never publishesinstance.start();await waitFor(async () => (await state(engine, c)).state === 'committed', { timeoutMs: 15_000, label: 'both pages commit' });} finally { await instance.stop(); await closeLaneRun(run, 5_000); }- const rows = await engine.executeRaw<{ slug: string; state: string }>(`SELECT slug,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [sources[0]!.id]);+ const rows = await engine.executeRaw<{ slug: string; state: string }>(`SELECT slug,state FROM persistence_requests WHERE source_id=$1 ORDER BY completed_at, sequence`, [sources[0]!.id]);expect(rows).toEqual([{ slug: 'order/b', state: 'committed' }, { slug: 'order/c', state: 'committed' }]);}), 120_000);});-diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.tsindex 869733a7ec..6e3aaaf90a 100644--- a/test/sync-knock-on-recovery-6643.test.ts+++ b/test/sync-knock-on-recovery-6643.test.ts@@ -1,11 +1,12 @@/**- * #6643: managed sync recovers from its own knock-ons.+ * #6643: managed sync recovers from its own knock-ons; #6712 (one page, one fate) retired every producer.*- * Protects: a page cancelled or refused only because another page of the same sync did not commit is re-frozen under a- * fresh request by the run itself, even under `sync.holds=fail` and without `--retry-failed`; an operator's cancel is- * never re-frozen; the re-freeze is bounded (`sync.knock_on_refreeze_limit`, `sync.knock_on_run_limit`) and an- * exhausted run names its root request in its result and in a fresh `sync status`; the pre-#6643 producer messages are- * recognised, nothing else is; and the checkpoint does not wait on a knock-on receipt.+ * Protects: a legacy knock-on receipt an older build wrote (a page cancelled or refused only because another page of+ * the same sync did not commit) is re-frozen in place under a fresh request by the run itself, even under+ * `sync.holds=fail` and without `--retry-failed`; an operator's cancel is never re-frozen; the re-freeze is bounded per+ * entry (`STOPS_PER_ENTRY`, no config key) and past it the failure is recorded as a retryable page fault; the retired+ * `knock_on_exhausted` code renders superseded; the pre-#6643 producer messages are recognised, nothing else is; and+ * the checkpoint waits on every receipt the cursor did not settle (no knock-on exemption).*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -16,7 +17,7 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { performManagedSync, STOPS_PER_ENTRY } from '../src/core/persistence/sync-run.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';@@ -73,7 +74,7 @@ async function asKnockOn(requestId: string, message: string, detail: unknown, stawait engine.executeRaw(`UPDATE persistence_requests SET state=$2, error_code=$3, error_message=$4, error_detail=$5::jsonb, recovery=NULL, publication_started=falseWHERE request_id=$1::uuid`, [requestId, state, code, message, detail == null ? null : JSON.stringify(detail)]);}-const clearConfig = () => engine.executeRaw("DELETE FROM config WHERE key IN ('sync.holds','sync.knock_on_refreeze_limit','sync.knock_on_run_limit')");+const clearConfig = () => engine.executeRaw("DELETE FROM config WHERE key='sync.holds'");beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });@@ -95,8 +96,9 @@ test('the pre-#6643 producer messages are the only untyped knock-ons; an operatoexpect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE, intent: page('put_page') } as never)).toBe(false);// The typed marker survives compaction (no intent, no message).expect(isSyncKnockOn({ ...base, intent: null, state: 'cancelled', error_code: 'cancelled', error_message: null, error_detail: knockOnDetail('bulk_group', null) } as never)).toBe(true);- expect(classifySyncFault({ code: 'knock_on_exhausted' })).toMatchObject({ class: 'systemic', needs_human: true });- expect(CODES.knock_on_exhausted).toBeDefined();+ // #6712: the retired stop renders superseded: a retryable page fault a plain sync resumes, never a human page.+ expect(classifySyncFault({ code: 'knock_on_exhausted' })).toEqual({ class: 'page', safe_actions: ['retry'], needs_human: false });+ expect(CODES.knock_on_exhausted).toMatchObject({ retired_in: '0.60.249.0' });});test('the SQL predicate agrees with isSyncKnockOn row by row', async () => {@@ -122,7 +124,6 @@ test('a knock-on is re-frozen by the plain sync under sync.holds=fail, and the rawait asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));const resumed = await performManagedSync(engine, f.opts);expect(resumed.status).not.toBe('blocked_by_failures');- expect(resumed.knockOns).toEqual({ refrozen: 1 });const status = await readSyncStatus(engine, f.id);expect(status.cursor?.done).toBe(true);// The stopped receipt is immutable; the page committed under a fresh request.@@ -139,7 +140,7 @@ test('a pre-#6643 untyped knock-on is recovered the same way', async () => withEawait asKnockOn(f.stopped, EARLIER_PAGE_REFUSAL_MESSAGE, null, 'conflict', 'revision_conflict');const resumed = await performManagedSync(engine, f.opts);expect(resumed.status).not.toBe('blocked_by_failures');- expect(resumed.knockOns).toEqual({ refrozen: 1 });+ expect((await readSyncStatus(engine, f.id)).cursor?.done).toBe(true);} finally { await clearConfig(); }}), 120_000);@@ -149,55 +150,43 @@ test('an operator cancel is never re-frozen', async () => withEnv({ GBRAIN_HOME:await asKnockOn(f.stopped, 'Cancelled before publication.', null);const resumed = await performManagedSync(engine, f.opts);expect(resumed.status).toBe('blocked_by_failures');- expect(resumed.knockOns).toBeUndefined();expect(resumed.failureCodes).toEqual([{ code: 'cancelled', count: 1 }]);} finally { await clearConfig(); }}), 120_000);-test('sync.knock_on_refreeze_limit=0 turns the re-freeze off', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {- try {- const f = await stoppedRun();- await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- await engine.setConfig('sync.knock_on_refreeze_limit', '0');- const resumed = await performManagedSync(engine, f.opts);- expect(resumed.status).toBe('blocked_by_failures');- expect(resumed.knockOns).toBeUndefined();- } finally { await clearConfig(); }-}), 120_000);--test('an exhausted re-freeze stops with knock_on_exhausted naming the root, in the result and in a fresh sync status', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('a legacy knock-on is re-frozen at most STOPS_PER_ENTRY times in a row; past that the failure is recorded as a retryable page fault', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {try {const f = await stoppedRun();await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- await engine.setConfig('sync.knock_on_run_limit', '0');+ // The entry was already re-frozen STOPS_PER_ENTRY times in a row.+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,pending,stops}',to_jsonb($2::int))+ WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [f.id, STOPS_PER_ENTRY]);const resumed = await performManagedSync(engine, f.opts);expect(resumed.status).toBe('blocked_by_failures');- expect(resumed.failureCodes).toEqual([{ code: 'knock_on_exhausted', count: 1 }]);- expect(resumed.failures?.[0]).toMatchObject({ code: 'knock_on_exhausted', root_cause: { request_id: f.rootRequest, slug: 'a', state: 'committed' } });+ expect(resumed.failureCodes).toEqual([{ code: 'cancelled', count: 1 }]);const status = await readSyncStatus(engine, f.id);- expect(status.last_error).toMatchObject({ code: 'knock_on_exhausted', class: 'systemic', needs_human: true, root_cause: { request_id: f.rootRequest } });- expect(status.needs_human).toBe(true);- // Raising the limit again lets the same sync re-freeze and finish.- await engine.executeRaw("DELETE FROM config WHERE key='sync.knock_on_run_limit'");+ expect(status.last_error).toMatchObject({ code: 'cancelled', class: 'page', safe_actions: ['retry'], needs_human: false });+ expect(status.needs_human).toBe(false);+ // The printed retry finishes the sync.const again = await performManagedSync(engine, { ...f.opts, retryFailed: true });expect(again.status).not.toBe('blocked_by_failures');expect((await readSyncStatus(engine, f.id)).cursor?.done).toBe(true);} finally { await clearConfig(); }}), 180_000);-test('the checkpoint waits on a real failed receipt, never on a knock-on of a pre-#6643 cursor, and skips the indexes a cursor settled', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('the checkpoint waits on every receipt the cursor did not settle, a legacy knock-on included (#6712), and skips the indexes a cursor settled', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {try {const f = await stoppedRun();const [row] = await engine.executeRaw<{ worktree_id: string; run_id: string; idx: number }>("SELECT worktree_id::text AS worktree_id, intent->>'runId' AS run_id, (intent->>'index')::int AS idx FROM persistence_requests WHERE request_id=$1::uuid", [f.stopped]);- const check = (settled: Parameters<typeof findIncompleteSyncReceipt>[4]) => findIncompleteSyncReceipt(engine, row!.worktree_id, row!.run_id, [], settled, 2);+ const check = (settled: Parameters<typeof findIncompleteSyncReceipt>[4]) => findIncompleteSyncReceipt(engine, row!.worktree_id, row!.run_id, [], settled);// A real failure (no knock-on marker, no matching message) blocks under every cursor shape.expect(await check(null)).toBe(f.stopped);expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, knockOnDetail('window_predecessor', f.rootRequest));- // A cursor from before #6643 recorded no settled ranges: a knock-on below its end does not block.- expect(await check(null)).toBeNull();- // A #6643 cursor names what it settled: an unsettled knock-on index still blocks, a settled one does not.+ // #6712: no knock-on exemption: a legacy knock-on blocks unless the cursor settled its index or converted it.+ expect(await check(null)).toBe(f.stopped);+ expect(await findIncompleteSyncReceipt(engine, row!.worktree_id, row!.run_id, [f.stopped], null)).toBeNull();expect(await check({ from: 0, ranges: [] })).toBe(f.stopped);expect(await check({ from: 0, ranges: [[row!.idx, row!.idx]] })).toBeNull();expect(addSettledRange(addSettledRange({ from: 0, ranges: [] }, 1, 2), 3, 4)).toEqual({ from: 0, ranges: [[1, 4]] });@@ -246,17 +235,14 @@ test('a stop on an outside_fence refusal is a root that needs a person in sync s} finally { await clearConfig(); }}), 120_000);-test('the cursor fence names window_dropped only for a member the cursor recorded dropping, with the root recorded then', () => {- const run = randomUUID(), root = randomUUID(), member = randomUUID(), stray = randomUUID(), now = randomUUID();+test('#6712: the cursor fence has two causes; a request the cursor does not hold is outside_fence, even one an older cursor recorded dropping', () => {+ const run = randomUUID(), root = randomUUID(), member = randomUUID(), now = randomUUID();const row = (id: string) => ({ request_id: id, source_id: 'default' }) as never;const intent = { kind: 'managed_sync_import', runId: run, index: 7 } as never;const fence = { run_id: run, request_id: now, group: null, index: 3, dropped: [{ requestId: member, root }] };const detail = (id: string, f: typeof fence) => cursorFenceRefusal(row(id), intent, f).syncRefusal as Record<string, unknown>;- // A dropped member is a knock-on of the request whose failure dropped it, not of whatever the cursor holds now.- expect(detail(member, fence)).toMatchObject({ cause: 'window_dropped', origin: 'sync_knock_on', root_request_id: root });- // A request ahead of the cursor that it never dropped is a coordination fault, not a knock-on.- expect(detail(stray, fence)).toMatchObject({ cause: 'outside_fence', origin: 'sync_cursor_fence' });- expect(detail(member, { ...fence, dropped: undefined as never })).toMatchObject({ cause: 'outside_fence' });+ expect(detail(member, fence)).toMatchObject({ cause: 'outside_fence', origin: 'sync_cursor_fence' });+ expect(detail(member, fence)).not.toHaveProperty('root_request_id');expect(detail(member, { ...fence, run_id: randomUUID() })).toMatchObject({ cause: 'run_replaced' });});