Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6643: knock-on recovery tests; never-NULL knock-on predicate; retry-failed wait ordering

garrytan9a1a154d6c0d
diff --git a/src/core/persistence/sync-knock-on.ts b/src/core/persistence/sync-knock-on.ts
index 649ea8403c..3231d05342 100644
--- a/src/core/persistence/sync-knock-on.ts
+++ b/src/core/persistence/sync-knock-on.ts
@@ -93,13 +93,13 @@ export function knockOnRoot(row: Pick<WriteRequest, 'error_detail'>): string | n
const sqlString = (value: string) => `'${value.replaceAll("'", "''")}'`;
/**
* The same predicate as `isSyncKnockOn` over a `persistence_requests` alias, for the checkpoint's clause 3. Literal
- * strings only (no parameters), so every engine plans it the same way.
+ * strings only (no parameters), so every engine plans it the same way; never NULL, so `NOT` of it is safe.
*/
export function syncKnockOnSql(alias: string): string {
const r = alias;
- return `(${r}.state IN ('cancelled','failed','conflict') AND ${r}.recovery IS NULL AND NOT COALESCE(${r}.publication_started,false)
+ return `COALESCE((${r}.state IN ('cancelled','failed','conflict') AND ${r}.recovery IS NULL AND NOT COALESCE(${r}.publication_started,false)
AND (${r}.error_detail->>'origin' = ${sqlString(SYNC_KNOCK_ON_ORIGIN)}
OR (${r}.state='cancelled' AND ${r}.error_code='cancelled' AND (${r}.error_message IN (${LEGACY_KNOCK_ON_CANCEL_MESSAGES.map(sqlString).join(',')})
OR ${LEGACY_KNOCK_ON_CANCEL_PATTERNS.map(pattern => `${r}.error_message LIKE ${sqlString(pattern)}`).join(' OR ')}))
- OR (${r}.state IN ('conflict','failed') AND ${r}.error_code='revision_conflict' AND ${r}.error_message=${sqlString(EARLIER_PAGE_REFUSAL_MESSAGE)})))`;
+ OR (${r}.state IN ('conflict','failed') AND ${r}.error_code='revision_conflict' AND ${r}.error_message=${sqlString(EARLIER_PAGE_REFUSAL_MESSAGE)}))), false)`;
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index bd5b2b6af0..71187aeb54 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -847,7 +847,7 @@ async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor;
...(rootCause ? { root_cause: rootCause } : {}),
request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,
- phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,
+ phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: exhausted ? `${pending.requestId}:${KNOCK_ON_EXHAUSTED}` : pending.requestId,
first_seen: new Date(done.completed_at ?? done.updated_at).toISOString(), ...(done.error_detail ? { write_error_detail: publicFailureDetail(done.error_detail) } : {}) });
// #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.
const hint = done.error_code === CHECKPOINT_VALIDATION_TIMEOUT && !remote ? await checkpointTimeoutHint(engine,
@@ -1310,12 +1310,12 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string
// #6643: a knock-on, and a checkpoint refused only by a receipt that no longer blocks it, recover in place in the drain
// (settleFailedRequest), which waits only on the narrowed gate; neither rediscovers the frozen manifest.
if (failed && cursor.pending && (isSyncKnockOn(failed) || (cursor.pending.intent.kind === 'managed_sync_checkpoint' && failed.error_code === 'recovery_required' && !failed.recovery))) return null;
- const blocker = await oldRunBlocker(engine, cursor, key);
- assertActive();
- if (blocker) return { wait: blocker };
const recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);
assertActive();
if (!((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed)))) return null;
+ const blocker = await oldRunBlocker(engine, cursor, key);
+ assertActive();
+ if (blocker) return { wait: blocker };
// Only the #6340 page faults convert here (a content refusal under --retry-failed keeps its explicit rediscovery; #6513: a checkpoint is never a page fault).
const pageFault = !!failed && !!cursor.pending && cursor.pending.intent.kind !== 'managed_sync_checkpoint' && (pinnedWorktreeConflict(failed) || failed.error_code === 'revision_conflict');
const screen = pageFault ? await loadSyncScreenRun(input.startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote) : null;
diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.ts
index ad28cc5174..edfabdab12 100644
--- a/src/core/persistence/sync-status.ts
+++ b/src/core/persistence/sync-status.ts
@@ -165,7 +165,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
const estimate = unfinished && p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };
const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });
const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);
- // #6643: a knock-on or a superseded run needs no --retry-failed: the plain sync re-freezes the entry.
+ // #6643: a knock-on or a superseded run is not a failure of its page: the resume re-freezes the entry.
const selfHealing = lastError?.detail === 'knock_on' || lastError?.detail === 'run_replaced';
const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');
const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };
@@ -179,8 +179,8 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Pro
+ ' and names the sync to run; it refuses the rest by name and drops nothing.' }
: retired ? { ...repairPreview, verify }
: unfinished || lastError
- ? { argv: ['gbrain', 'sync', ...resume, ...(lastError && !selfHealing ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
- why: lastError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${lastError.detail}); the same sync re-freezes it by itself${lastError.root_cause?.request_id ? `, and request ${lastError.root_cause.request_id} is what it waited on` : ''}.`
+ ? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,
+ why: lastError && selfHealing ? `The last run stopped on a page that only waited on another page of the same sync (${lastError.detail}); --retry-failed (or the same sync) re-freezes it under a fresh request${lastError.root_cause?.request_id ? `, and request ${lastError.root_cause.request_id} is what it waited on` : ''}.`
: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`
: `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }
: null;
diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.ts
new file mode 100644
index 0000000000..5d412efe74
--- /dev/null
+++ b/test/sync-knock-on-recovery-6643.test.ts
@@ -0,0 +1,226 @@
+/**
+ * #6643: managed sync recovers from its own knock-ons.
+ *
+ * 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.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+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 { 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';
+import { laneFaultCancelMessage, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
+import { BULK_GROUP_CANCEL_MESSAGE, EARLIER_PAGE_REFUSAL_MESSAGE, isSyncKnockOn, knockOnDetail, LEGACY_KNOCK_ON_CANCEL_MESSAGES, legacyKnockOnMessage,
+ syncKnockOnSql } from '../src/core/persistence/sync-knock-on.ts';
+import { CODES } from '../src/core/error-registry.ts';
+import { addSettledRange, findIncompleteSyncReceipt } from '../src/core/persistence/checkpoint-validation.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-6643-'));
+let engine: PGLiteEngine;
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;
+const page = (kind: string) => ({ kind });
+
+async function fixture(files: Record<string, string>) {
+ const id = `ko-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);
+ mkdirSync(root); git(root, 'init', '-q');
+ for (const [path, body] of Object.entries(files)) writeFileSync(join(root, path), body);
+ commit(root, 'fixture');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };
+}
+
+/**
+ * A managed run stopped on its second page (a.md committed, b.md refused because it changed after the freeze), with
+ * b.md then restored to its committed bytes. Returns the stopped request and the committed request of a.md.
+ */
+async function stoppedRun() {
+ const f = await fixture({ 'a.md': note('Alpha one.'), 'b.md': note('Beta one.') });
+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');
+ writeFileSync(join(f.root, 'a.md'), note('Alpha two.')); writeFileSync(join(f.root, 'b.md'), note('Beta two.'));
+ commit(f.root, 'version two');
+ writeFileSync(join(f.root, 'b.md'), note('Beta, uncommitted.'));
+ await engine.setConfig('sync.holds', 'fail');
+ expect((await performManagedSync(engine, f.opts)).status).toBe('blocked_by_failures');
+ git(f.root, 'checkout', '--', 'b.md');
+ const [failure] = await readManagedSyncFailures(engine, [f.id]);
+ const stopped = failure!.request_id!;
+ const [root] = await engine.executeRaw<{ request_id: string }>(
+ "SELECT request_id::text AS request_id FROM persistence_requests WHERE source_id=$1 AND slug='a' AND state='committed' ORDER BY sequence DESC LIMIT 1", [f.id]);
+ return { ...f, stopped, rootRequest: root!.request_id };
+}
+/** Rewrites the stopped request into the receipt a knock-on producer writes, as first observed (no ledger row yet). */
+async function asKnockOn(requestId: string, message: string, detail: unknown, state = 'cancelled', code = 'cancelled') {
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'request_id'=$1", [requestId]);
+ await engine.executeRaw(`UPDATE persistence_requests SET state=$2, error_code=$3, error_message=$4, error_detail=$5::jsonb, recovery=NULL, publication_started=false
+ WHERE 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')");
+
+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 }); });
+
+test('the pre-#6643 producer messages are the only untyped knock-ons; an operator cancel never is', () => {
+ expect(LEGACY_KNOCK_ON_CANCEL_MESSAGES).toContain(WINDOW_CANCEL_MESSAGE);
+ expect(LEGACY_KNOCK_ON_CANCEL_MESSAGES).toContain(laneFaultCancelMessage('lock_timeout'));
+ expect(LEGACY_KNOCK_ON_CANCEL_MESSAGES).toContain(laneFaultCancelMessage('statement_timeout'));
+ const base = { recovery: null, publication_started: false, error_detail: null, intent: page('managed_sync_import') } as const;
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE } as never)).toBe(true);
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: BULK_GROUP_CANCEL_MESSAGE } as never)).toBe(true);
+ expect(isSyncKnockOn({ ...base, state: 'conflict', error_code: 'revision_conflict', error_message: EARLIER_PAGE_REFUSAL_MESSAGE } as never)).toBe(true);
+ expect(legacyKnockOnMessage('cancelled', 'cancelled', 'Its predecessor request 1 was never admitted; this page was not published and is re-frozen on the next sync pass.')).toBe(true);
+ // An operator's cancel, a compacted receipt with no message, a published or recovering row, and a non-sync request are not knock-ons.
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: 'Cancelled before publication.' } as never)).toBe(false);
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: null } as never)).toBe(false);
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE, publication_started: true } as never)).toBe(false);
+ expect(isSyncKnockOn({ ...base, state: 'cancelled', error_code: 'cancelled', error_message: WINDOW_CANCEL_MESSAGE, recovery: {} } as never)).toBe(false);
+ expect(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();
+});
+
+test('the SQL predicate agrees with isSyncKnockOn row by row', async () => {
+ const rows: Array<[string, string | null, string | null, unknown, boolean]> = [
+ ['cancelled', 'cancelled', WINDOW_CANCEL_MESSAGE, null, true],
+ ['cancelled', 'cancelled', 'Cancelled before publication.', null, false],
+ ['conflict', 'revision_conflict', EARLIER_PAGE_REFUSAL_MESSAGE, null, true],
+ ['failed', 'revision_conflict', 'The page changed.', null, false],
+ ['cancelled', 'cancelled', null, knockOnDetail('window_dropped', randomUUID()), true],
+ ['committed', null, null, knockOnDetail('window_dropped', null), false],
+ ];
+ for (const [state, code, message, detail, expected] of rows) {
+ const [hit] = await engine.executeRaw<{ hit: boolean }>(`SELECT ${syncKnockOnSql('r')} AS hit FROM (SELECT $1::text AS state, $2::text AS error_code, $3::text AS error_message,
+ $4::jsonb AS error_detail, NULL::jsonb AS recovery, false AS publication_started) r`, [state, code, message, detail == null ? null : JSON.stringify(detail)]);
+ expect(hit!.hit).toBe(expected);
+ expect(isSyncKnockOn({ state, error_code: code, error_message: message, error_detail: detail, recovery: null, publication_started: false, intent: page('managed_sync_import') } as never)).toBe(expected);
+ }
+});
+
+test('a knock-on is re-frozen by the plain sync under sync.holds=fail, and the run finishes', 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));
+ 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.
+ const [old] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [f.stopped]);
+ expect(old!.state).toBe('cancelled');
+ const [b] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug='b' AND state='committed'", [f.id]);
+ expect(b!.n).toBe(2);
+ } finally { await clearConfig(); }
+}), 120_000);
+
+test('a pre-#6643 untyped knock-on is recovered the same way', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ try {
+ const f = await stoppedRun();
+ await 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 });
+ } finally { await clearConfig(); }
+}), 120_000);
+
+test('an operator cancel is never re-frozen', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ try {
+ const f = await stoppedRun();
+ 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 () => {
+ 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');
+ 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' } });
+ 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'");
+ 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 () => {
+ 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);
+ // 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.
+ 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]] });
+ expect(addSettledRange({ from: 0, ranges: [[1, 2]] }, 5, 5)).toEqual({ from: 0, ranges: [[1, 2], [5, 5]] });
+ } finally { await clearConfig(); }
+}), 120_000);
+
+for (const retryFailed of [false, true]) test(`a checkpoint refused by a receipt that turns out to be a knock-on revives under ${retryFailed ? 'the --retry-failed repro command' : 'the plain sync'}, without rediscovery`, async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ try {
+ const f = await stoppedRun();
+ // The pre-#6643 shape: the cursor passed the stopped page (no settled ranges recorded) and froze its checkpoint.
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys #- '{0,pending}' #- '{0,settled}', '{0,index}', completed_keys->0->'total')
+ WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [f.id]);
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$1", [f.id]);
+ const refused = await performManagedSync(engine, f.opts);
+ expect(refused.status).toBe('blocked_by_failures');
+ expect(refused.failures?.[0]).toMatchObject({ code: 'recovery_required', phase: 'checkpoint', root_cause: { request_id: f.stopped } });
+ const runId = (await readSyncStatus(engine, f.id)).run_id;
+ // The receipt that refused it was a knock-on all along (a pre-#6643 producer's message).
+ await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, null);
+ const revived = await performManagedSync(engine, { ...f.opts, retryFailed });
+ expect(revived.status).not.toBe('blocked_by_failures');
+ const status = await readSyncStatus(engine, f.id);
+ expect(status).toMatchObject({ run_id: runId, cursor: { done: true } });
+ const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]);
+ expect(source!.last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));
+ } finally { await clearConfig(); }
+}), 120_000);