Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP #6712 lane C: retired-surface test, claim/width probe, runbook, retry-failed for blocked checkpoints
garrytan9c4e80ab7f7b
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 75c50c8062..05e2937538 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -27,7 +27,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-slug-mode.ts` — #6694: the checkpoint's slug-root mode against the source's pinned `slug_root_mode`. `emptySyncScope` (source root is the repository root, both realpathed) lets `sync-prepare.ts`'s checkpoint `UPDATE` accept either pin and keep the pinned one; at a subdirectory a differing pin is diagnosed by `pinnedSlugModeMismatch` after the guarded `UPDATE` matched nothing and refused `slug_root_mode_mismatch` (cause and the person's two choices from `slugModeMismatchCause`); anything else stays `revision_conflict` (`CHECKPOINT_MOVED_MESSAGE`). `slugModeCheckpointRevivable` is the second revival predicate of `sync-run.ts` `reviveCheckpoint`: a checkpoint refused `slug_root_mode_mismatch`, or an older release's moved-checkpoint `revision_conflict`, is revived when `last_commit` still equals the run's `from` and the pin is unset, equal to the run's mode or the scope is empty; `retryFailedStart` does not consult it, so `--retry-failed` keeps its rediscovery. Test: `test/sync-slug-root-mode-6694.test.ts` (both engines).-- `src/core/persistence/sync-knock-on.ts` — #6643: a sync page request that ended without committing only because another request of its sync did not commit (a knock-on). Cancellers stamp `error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }` (survives compaction); pre-#6643 receipts match only their producers' exact messages (`LEGACY_KNOCK_ON_CANCEL_MESSAGES`, the never-admitted patterns, `EARLIER_PAGE_REFUSAL_MESSAGE`), never an operator cancel. `isSyncKnockOn` and `syncKnockOnSql` are one predicate (the SQL is never NULL, so `NOT` of it is safe in clause 3). `cursorFenceCause` reads the three causes of "cursor changed" (`run_replaced`, `window_dropped` only for a request the cursor recorded in `Cursor.dropped`, else `outside_fence`). `sync-run.ts` `recoverKnockOn` re-freezes the entry through `holdUnderGate` (budgets `sync.knock_on_refreeze_limit` per index, `sync.knock_on_run_limit` per invocation; past them `knock_on_exhausted` with `root_cause`), `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end, and `checkpoint-validation.ts` skips knock-ons of pre-#6643 cursors and the cursor's settled index ranges. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`).+- `src/core/persistence/sync-knock-on.ts` — #6643, shrunk by #6712 (one page, one fate): no producer is left. It keeps the legacy predicate over receipts older builds wrote (`error_detail` `{ origin: 'sync_knock_on', reason, root_request_id }`, or the pre-#6643 producers' exact messages, never an operator cancel): `isSyncKnockOn`/`syncKnockOnSql` (one predicate, never NULL) feed the terminal classifier, which renders such a receipt superseded, and `sync-run.ts` `refreezeInPlace`, which re-freezes the entry when a resumed cursor meets one (bounded by `STOPS_PER_ENTRY`, no config key). `cursorFenceCause` reads the two live causes of "cursor changed" (`run_replaced`, `outside_fence`; an older `window_dropped` still parses). `checkpoint-validation.ts` clause 3 skips converted receipts and the cursor's settled index ranges only; #6712 removed the knock-on exemption. `reviveCheckpoint` re-assesses a refused checkpoint at the cursor's end. `sync status` shows the cursor the recorded failure belongs to, `cursors`, and `checkpoint_blockers` (`listIncompleteSyncReceipts`, each with `knock_on`).- `src/core/persistence/terminal-classify.ts` — #6650: `classifyTerminal` turns one terminal receipt (`failed` / `conflict` / `cancelled`, or any row still holding `recovery`) into a `TerminalVerdict` (category, code, origin, class, `safe_actions`, `needs_human`, `defect`, `historical`, `root_request_id`, one structured `action`) at read time; nothing is persisted. A recovery record outranks the code (`recovery_pending` / `recovery_blocked`); a knock-on is read through `isSyncKnockOn` (typed marker survives compaction) or the SQL twin `terminalKnockOnSql`; `storage_error` and `source_changed` route by their recorded origin or cause, and a row whose code and origin do not say what happened is `diagnosis_required` (read-only writer status, never a guessed fix). A `source_changed` whose canonical file is missing is `canonical_file_missing` (a ghost page; its exit is the `gbrain repair ghost-pages` preview, never a sync retry), and an origin-less `fence_unrenderable` adoption refusal is its own defect category. `TERMINAL_FIXED_IN` names the release that fixed a category; a row whose build (`error_detail.attempt.consumer_version`, else `admitter_version`) is older is historical. It also owns the supersession rule `repair/failed-writes.ts` reuses (`supersessionSql`, `supersessionOrderSql`, `dispositionOf`, `PAGE_REMOVAL_OPERATIONS`). Tests: `test/terminal-failures-6650.test.ts` (TS↔SQL twin parity included), `test/terminal-classify-6696.test.ts`.- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex d200900d9e..ac6421f791 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1794,7 +1794,7 @@ More: [docs/guides/multi-language-fts.md#cjk-keyword-budget](../../docs/guides/m| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| A managed sync kept re-freezing a page that only waited on another page of the same sync, and stopped at its limit because that earlier page still did not commit. | A page cancelled or refused only because an earlier page of its sync did not commit published nothing, so the sync re-freezes it under a fresh request by itself; the limit stops a loop when the earlier page keeps failing. | Read gbrain sync status --source <id> --json: last_error.root_cause names the request that keeps failing. Fix that request, or raise sync.knock_on_refreeze_limit / sync.knock_on_run_limit, then rerun the same sync. Run: gbrain sync status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |+| Retired: an older gbrain stopped a managed sync that kept re-freezing a page cancelled only because another page of the same sync did not commit. This build never cancels a page for another page's failure, so the stop is superseded. | Since #6712 each page of a sync has its own fate: a page that does not commit is held or stops the run on its own, and the pages after it still publish. A ledger row or receipt with this code was written by an older build. | Rerun the same plain gbrain sync --source <id> --no-pull; it resumes the stopped entry under a fresh request. gbrain sync status --source <id> --json shows what remains. Run: gbrain sync status --source '{source_id}' --json | agent | `gbrain doctor --json` | 1 | no |More: [docs/guides/sync-unblock-runbook.md#decision-table](../../docs/guides/sync-unblock-runbook.md#decision-table)diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex c25fab1957..78f577d0a3 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -103,10 +103,10 @@ Every hold and error has three fields, from one table| `pinned_git_worktree_conflict` | page | retry | no | the same path fails again after a rerun || `source_changed` | page | retry | no | the same path fails again after a rerun || `cancelled` | page | retry | no | the same group is cancelled again after a rerun |-| `knock_on` | page | retry | no | the same root request is named again after a rerun |+| `knock_on` | page | retry | no | never: superseded; an older gbrain cancelled this page for another page's failure and a plain sync re-freezes it || `run_replaced` | page | retry | no | never: another run of the source superseded this one and covers its pages || `outside_fence` | systemic | none | yes | always: a request published outside the cursor that admitted it |-| `knock_on_exhausted` | systemic | none | yes | always: re-freezing did not get past the failing page |+| `knock_on_exhausted` | page | retry | no | never: superseded; a plain sync resumes the entry an older gbrain stopped on || `sync_incomplete` | page | retry | no | never: an unfinished cursor resumes with the same command || `connection_lost` | connection | retry | no | three reruns in a row end connection_lost (the database is unreachable from this host) || `database_contention` | connection | retry | no | three reruns in a row stop on it |@@ -136,23 +136,30 @@ or `statement_timeout` on a parallel publish lane) also carries that fault asThe verdict is the same retry; the detail says the database, not the page,ended the group.-A page that only waited on another page of the same sync (a knock-on: its-group, window or lane predecessor did not commit) is re-frozen by the sync-itself under a fresh request on the next pass; `--retry-failed` is not-needed for it. Its error carries `last_error.detail: knock_on` and-`last_error.root_cause` (the request, page and error it waited on); act on-the root. A cursor refusal is classified by its recorded cause:-`run_replaced` (another run of the source took over; nothing to do),-`window_dropped` (a knock-on), or `outside_fence` (a request was not the-entry its cursor held: a person stops the extra drain and reports it).-After `sync.knock_on_refreeze_limit` re-freezes at one index (default 3;-0 turns automatic re-freeze off), or after `sync.knock_on_run_limit`-re-freezes in one sync invocation (default 25), the run stops with-`knock_on_exhausted` and names the root. The per-index count resets when-the page commits; the per-invocation count resets on the next sync. A-checkpoint refused by a receipt that turns out to be a knock-on, or at an-index the cursor passed without a commit, is re-assessed on every resume and-commits without rediscovering the manifest.+Each page of a sync has its own fate (#6712): a page that does not commit is+held, retried or stops the run on its own, and the pages admitted after it+still publish and are counted from their own receipts. No page is cancelled+for another page's failure, and two changes of one page (a delete and an+import of one slug, say) are never published in the same group: the later+one waits for the earlier one, and is held behind it (`blocked_on`) when the+earlier one is held. A file that changed after its request was admitted+(`source_changed`) is retried after the manifest's last entry, at most three+times, then held `worktree_dirty`. A transport fault re-freezes the entry in+place; a systemic stop is re-frozen in place by the next plain sync, at most+three times in a row before the failure stays recorded for `--retry-failed`.++A `knock_on` or `knock_on_exhausted` error was written by an older gbrain+(a page cancelled only because another page of its sync did not commit, or+the stop that bounded re-freezing them). Both are superseded: the next plain+sync re-freezes the entry under a fresh request; act on `root_cause` if it+fails again. A cursor refusal is classified by its recorded cause:+`run_replaced` (another run of the source took over; nothing to do) or+`outside_fence` (a request was not the entry its cursor held: a person stops+the extra drain and reports it); an older build's `window_dropped` reads as+a knock-on. A checkpoint refused by a receipt at an index the cursor passed+without a commit is re-assessed on every resume and commits without+rediscovering the manifest; one a receipt still blocks is rediscovered by+`--retry-failed`.An unknown code is systemic and human: `gbrain errors <code>` explains itoffline, `gbrain doctor --json` says what the brain thinks.diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 78ef5f22c1..09de6397e9 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -402,13 +402,9 @@ 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. #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`).- */+/** Groups whose members are independent page writes: one member's failure never cancels the others. */export function independentGroup(key: string | null): boolean {- return key !== null && (key.startsWith('batch:') || key.startsWith('import:') || key.startsWith('sync:'));+ return key !== null && (key.startsWith('batch:') || key.startsWith('import:'));}/** #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 {diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 8487d9209d..bd4868a642 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1352,9 +1352,17 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: stringconst { opts, context, authority, processingOptions, syncOptions, assertActive } = input;const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;assertActive();+ // #6712: --retry-failed resets the in-place re-freeze bound of an entry the run stopped on for a fault not its page's; the drain re-freezes it again.+ if (failed && cursor.pending && (cursor.pending.stops ?? 0) >= STOPS_PER_ENTRY && ['failed', 'conflict', 'cancelled'].includes(failed.state) && (isSyncKnockOn(failed) || receiptClass(failed) !== 'page')) {+ const { stops: _stops, ...pending } = cursor.pending;+ return { cursor: await saveCursor(engine, key, cursor, { ...cursor, pending }, false, assertActive) };+ }// #6643/#6712: a legacy knock-on (re-frozen in place, `refreezeInPlace`) and a checkpoint refused only by a receipt that no- // longer blocks it recover in the drain (settleFailedRequest); neither rediscovers the frozen manifest.- if (failed && cursor.pending && (isSyncKnockOn(failed) || (cursor.pending.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)))) return null;+ // longer blocks it recover in the drain (settleFailedRequest); neither rediscovers the frozen manifest. A checkpoint a+ // receipt still blocks (since #6712 a legacy knock-on the cursor never settled is one) rediscovers, as --retry-failed says.+ if (failed && cursor.pending && isSyncKnockOn(failed)) return null;+ if (failed && cursor.pending?.intent.kind === 'managed_sync_checkpoint' && cursor.index === cursor.entries.length && revivableCheckpointRefusal(failed)+ && !await findIncompleteSyncReceipt(engine, cursor.binding.worktree_id, cursor.runId, cursor.convertedFromFailed ?? [], cursor.settled ?? null)) return null;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;diff --git a/test/error-registry-retired.test.ts b/test/error-registry-retired.test.tsnew file mode 100644index 0000000000..bd789edbb4--- /dev/null+++ b/test/error-registry-retired.test.ts@@ -0,0 +1,65 @@+/**+ * #6712 (DX): a retired surface never stays in a printed fix. `knock_on_exhausted` used to tell agents to raise+ * `sync.knock_on_refreeze_limit` / `sync.knock_on_run_limit`; #6712 deleted both keys with the knock-on re-freeze budget,+ * so the code is a tombstone (`retired_in`) whose fix points at a plain sync.+ *+ * Protects: no registered fix, suggestion, `why`, fault-table reason or terminal-classifier action names a retired+ * config key; every `--flag` a registered fix argv passes to `gbrain` is a flag that command still accepts; a retired+ * code's fix is read-only and needs no consent; the retired keys are no longer accepted by `config set`.+ */+import { expect, test } from 'bun:test';+import { CODES, NOTICE_CODES, type CodeEntry } from '../src/core/error-registry.ts';+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';+import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';+import { knockOnDetail } from '../src/core/persistence/sync-knock-on.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';++/** Config keys and CLI flags a release deleted; a printed fix must never name them. Add to this list when retiring one. */+const RETIRED_KEYS = ['sync.knock_on_refreeze_limit', 'sync.knock_on_run_limit'];++const entries = (registry: Record<string, unknown>) => Object.entries(registry) as Array<[string, CodeEntry]>;+const fixText = (entry: CodeEntry) => [entry.suggestion, entry.why, ...(entry.fix ? [entry.fix.argv.join(' '), entry.fix.why] : [])].filter(Boolean).join('\n');++test('no registered fix, suggestion or reason names a retired config key', () => {+ const texts: Array<[string, string]> = [+ ...entries(CODES).map(([code, entry]) => [`CODES.${code}`, fixText(entry)] as [string, string]),+ ...entries(NOTICE_CODES).map(([code, entry]) => [`NOTICE_CODES.${code}`, fixText(entry)] as [string, string]),+ ...SYNC_FAULT_TABLE.map(rule => [`SYNC_FAULT_TABLE.${rule.code}`, `${rule.human_reason ?? ''}\n${rule.escalate}`] as [string, string]),+ ];+ // The terminal classifier's verdict for a legacy knock-on receipt (the only producer of the retired budget's text).+ const verdict = classifyTerminal({ request_id: 'r', source_id: 'default', slug: 's', operation: 'submit_job', state: 'cancelled', error_code: 'cancelled',+ error_detail: knockOnDetail('window_predecessor', null), recovery: null, blocked_reason: null, compacted: false, publication_started: false,+ intent_kind: 'managed_sync_import', error_message: null });+ expect(verdict).toBeTruthy();+ texts.push(['classifyTerminal(knock_on)', JSON.stringify(verdict)]);+ const named = texts.flatMap(([where, text]) => RETIRED_KEYS.filter(key => text.includes(key)).map(key => `${where} names ${key}`));+ expect(named).toEqual([]);+});++test('the retired config keys are no longer accepted', () => {+ for (const key of RETIRED_KEYS) expect(KNOWN_CONFIG_KEYS).not.toContain(key);+});++test('every flag a registered fix passes to gbrain is one that command still accepts', () => {+ const unknown: string[] = [];+ for (const [code, entry] of [...entries(CODES), ...entries(NOTICE_CODES)]) {+ const argv = entry.fix?.argv;+ if (!argv || argv[0] !== 'gbrain' || !argv[1] || !CLI_FLAG_REGISTRY[argv[1]]) continue;+ for (const flag of argv.slice(2).filter(arg => arg.startsWith('--')).map(arg => arg.split('=')[0]!)) {+ if (!CLI_FLAG_REGISTRY[argv[1]]!.includes(flag)) unknown.push(`${code}: gbrain ${argv[1]} ${flag}`);+ }+ }+ expect(unknown).toEqual([]);+});++test('a retired code renders superseded: its fix is read-only, needs no consent, and its suggestion is a plain rerun', () => {+ const retired = entries(CODES).filter(([, entry]) => entry.retired_in);+ expect(retired.map(([code]) => code)).toContain('knock_on_exhausted');+ for (const [, entry] of retired) {+ expect(entry.summary).toMatch(/^Retired:/);+ expect(entry.fix).toMatchObject({ consent: [], requires_exclusive: false });+ expect(entry.fix!.argv.join(' ')).not.toMatch(/config set|--retry-failed|--reset-checkpoint/);+ }+ expect(CODES.knock_on_exhausted.suggestion).toContain('gbrain sync --source <id> --no-pull');+});diff --git a/test/sync-group-member-order.test.ts b/test/sync-group-member-order.test.tsindex a29414c1f1..48228b7084 100644--- a/test/sync-group-member-order.test.ts+++ b/test/sync-group-member-order.test.ts@@ -95,4 +95,27 @@ describe.skipIf(!process.env.DATABASE_URL)('a bulk group member has its own fateconst 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);++ test('#6712 (Eng 2): a sync group keeps its claim size and its preparation width of four; only its fate changed', () => withBrain(async ({ engine, config, sources }) => {+ const headId = randomUUID();+ const slugs = Array.from({ length: 12 }, (_, i) => `order/m${i}`);+ for (const [i, slug] of slugs.entries()) {+ const intent = { content: `${slug} body`, group: headId };+ await admitWrite(engine, admission(config, sources[0]!, slug, '', 0, { requestId: i === 0 ? headId : randomUUID(), callerIntent: intent, intent }));+ }+ let inFlight = 0, widest = 0;+ const groups = new Set<unknown>();+ const instance = new PersistenceConsumer(engine, { engine: 'postgres' }, async (reads, row) => {+ groups.add(reads); widest = Math.max(widest, ++inFlight);+ try { await new Promise(resolve => setTimeout(resolve, 50)); return prepared(row, sources); } finally { inFlight--; }+ }, { hostId: config.hostId, concurrency: 1, pollMs: 20 });+ try {+ instance.start();+ await waitFor(async () => (await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state<>'committed'", [sources[0]!.id])).length === 0,+ { timeoutMs: 30_000, label: 'every member commits' });+ } finally { await instance.stop(); }+ // One claim took all twelve members (a batch group would stop at PAGE_BATCH_GROUP_MAX), prepared four at a time.+ expect(groups.size).toBe(1);+ expect(widest).toBe(4);+ }), 120_000);});diff --git a/test/sync-knock-on-recovery-6643.test.ts b/test/sync-knock-on-recovery-6643.test.tsindex 6e3aaaf90a..565608bb37 100644--- a/test/sync-knock-on-recovery-6643.test.ts+++ b/test/sync-knock-on-recovery-6643.test.ts@@ -194,7 +194,7 @@ test('the checkpoint waits on every receipt the cursor did not settle, a legacy} 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 () => {+for (const retryFailed of [false, true]) test(`#6712: a checkpoint a legacy knock-on still blocks ${retryFailed ? 'is rediscovered by the --retry-failed repro command and finishes' : 'stays blocked under the plain sync, naming the knock-on'}`, 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.@@ -204,16 +204,18 @@ for (const retryFailed of [false, true]) test(`a checkpoint refused by a receiptconst 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 before = await readSyncStatus(engine, f.id);- const runId = before.run_id;- expect(before.checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: false })]);- // The receipt that refused it was a knock-on all along (a pre-#6643 producer's message): status previews that nothing blocks now.+ expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: false })]);+ // The receipt that refused it was a knock-on (a pre-#6643 producer's message): it still blocks, and status says what it is.await asKnockOn(f.stopped, WINDOW_CANCEL_MESSAGE, null);- expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([]);- 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 } });+ expect((await readSyncStatus(engine, f.id)).checkpoint_blockers).toEqual([expect.objectContaining({ request_id: f.stopped, slug: 'b', knock_on: true })]);+ const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });+ if (!retryFailed) {+ expect(resumed.status).toBe('blocked_by_failures');+ expect((await readSyncStatus(engine, f.id)).cursor?.done).not.toBe(true);+ return;+ }+ expect(resumed.status).not.toBe('blocked_by_failures');+ expect((await readSyncStatus(engine, f.id)).cursor).toMatchObject({ 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(); }