Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): waive runs of unchanged imports in batched waiver transactions (GBRA-75 wave 8)
time-attackd816ff630619
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex c664ea88fa..69a91f739d 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -37,7 +37,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an- `src/core/persistence/checkpoint-validation.ts` — the managed sync checkpoint's incomplete-receipt validation (#5762): `INCOMPLETE_SYNC_RECEIPT_SQL` is three `LIMIT 1` probes (recovery; an open page receipt of the run; a non-committed page receipt with no committed sibling at its index) served by `persistence_requests_recovery`, `persistence_requests_sync_run_open` and `persistence_requests_sync_run_committed`, with the same result as the former single predicate. `findIncompleteSyncReceipt` returns the blocking receipt's request id and maps only this statement's 57014 statement timeout to the terminal, non-transient `checkpoint_validation_timeout`. `readRequestIndexStates` reads each index as valid, missing, INVALID or building (Postgres `pg_stat_progress_create_index`); `formatCheckpointTimeoutHint` / `checkpointTimeoutHint` is the one formatter for the three-state hint and the filled retry (`gbrain sync --source <id> --no-pull --retry-failed` plus the cursor-selecting options the checkpoint intent records in `syncOptions` and the saved processing flags), used by the sync summary and `get_write_request`. Tests: `test/persistence-sync-checkpoint-validation.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. The page's current `knowledge_revision`, read with the projection flags, must still equal the snapshot's revision (a write after the screen's snapshot admits as `revision_moved`). Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries pass it. Used by connector sync, `import-mutations.ts`, and `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.-- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. Tests: `test/sync-waiver-budget.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.+- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. GBRA-75 wave 8: `unchangedSyncImport` prepares with `{ unsaved: true }`, so its validation also accepts this run's cursor with nothing pending; before that every import waiver-run screen failed the cursor check and each unchanged file took a pending save, a second screen and its own waiver transaction. `waiveNoopRun` (up to 64 entries, one cursor write) re-reads the owner epoch under its lock (a change passes nothing; the per-entry path then refuses it) and each import's file bytes (an edit ends the prefix). Tests: `test/sync-waiver-budget.test.ts`, `test/sync-waiver-run-imports.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.- `src/core/persistence/fault-points.ts` — named crash seams for the persistence gate. `faultPoint(point, detail)` is a no-op unless a gate worker installed a hook with `installFaultHook`; production never does. Seams: `publication:<boundary>` (the five `PublicationHooks.boundary` names, routed through `withFaultPoints` in `publishMutation`), `effect:<kind>:mid` for every `EffectKind` in `completeEffect` (after the side effect, before its completion is recorded; `EFFECT_FAULT_POINTS` is a `Record<EffectKind, FaultPoint>`), `effect_recovery:before_clear` (`effect-recovery.ts`), `publication_recovery:before_clear` (`recoverPublication`), `sync:mid_checkpoint` (after each committed cursor step in `sync-run.ts` `saveCursor`) and `consumer:prepared` (between preparing a claimed request and publishing it). Used by `scripts/persistence/crash-robot.ts`.diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex e1fb882f05..a27368c0d4 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -298,7 +298,13 @@ async function resolveSyncOrigin(engine: BrainEngine, row: WriteRequest, p: Sync* `boundedReads`: a relation lock held elsewhere ends the statement on the server at the budget (plan 1.4),* so the member is released without a zombie statement pinning a connection until the ceiling.*/-export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock): Promise<PreparedMutation> {+/**+ * `screening.unsaved`: a waiver screen of a frozen entry the cursor does not yet name (a waiver run's head and followers).+ * Its validation also accepts this run's cursor with nothing pending; the waiver transaction then requires exactly that+ * cursor (run, index, nothing pending) under its lock.+ */+export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock?: ClaimPhaseClock,+ screening?: { unsaved: true }): Promise<PreparedMutation> {const engine = boundedReads(unbounded, clock);const p = row.intent as SyncIntent | null;if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,@@ -353,7 +359,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrasync () => { if (await earlierGroupMemberFailed(tx, row)) throw syncPublicationRefusal('revision_conflict', 'An earlier page of this sync did not commit.', row, p, `Request ${row.request_id} follows a page of the same bulk group that did not commit, so this page must not publish after it.`); },async () => {const cursor = await shared;- if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,+ if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id) && !(screening?.unsaved && cursor.request_id == null)))) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,`Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);},async () => { if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row, p.path === null ? undefined : { root, path: join(root, p.path) }); },diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 838f76d18b..30d9ff95d5 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -12,7 +12,8 @@ import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';import { startClaimPhase } from './claim-phase.ts';import { inspectUnchanged, screeningRequest, type NoopKernelWaiver } from './noop-kernel.ts';import { validateSyncAuthority, type SyncAuthority } from './sync-authority.ts';-import { readSyncFile } from './sync-discovery.ts';+import { readSyncFile, syncRawHash } from './sync-discovery.ts';+import { getWorktreeBinding } from './ownership.ts';import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';@@ -183,6 +184,9 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,completed_keys->0->'index' AS index,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE`, [key]);if (held?.run_id !== cursor.runId || Number(held.index) !== cursor.index || held.request_id != null) return { cursor: await reread(tx), waived: 0 };await faultPoint('sync:mid_waiver_run', { sourceId: cursor.sourceId });+ // The run's screens may span many entries: an owner change since the first one sends the run back to the per-entry path.+ const binding = await getWorktreeBinding(tx, cursor.sourceId);+ if (!binding || String(binding.owner_epoch) !== run[0]!.pending.intent.ownerEpoch) return null;const pages = await tx.executeRaw<{ id: number | string; slug: string; deleted: boolean; knowledge_revision: string | number | null }>('SELECT id,slug,deleted_at IS NOT NULL AS deleted,knowledge_revision FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])', [cursor.sourceId, run.map(entry => entry.pending.slug)]);const bySlug = new Map(pages.map(page => [page.slug, page]));@@ -200,6 +204,7 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break;if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break;if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break;+ if (waived.kind === 'import' && syncRawHash(cursor.root, pending.intent.path!) !== pending.intent.rawHash) break;valid++;}if (!valid) return null;@@ -248,7 +253,7 @@ export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCurworktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });// #6278 (1.4): the clock carries the budget, so the preparation's lock-prone reads end on the server at it (boundedReads).const budgetMs = await syncPreparationBudgetMs(engine);- const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, row, config, startClaimPhase(Date.now(), undefined, budgetMs)), budgetMs, signal);+ const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, row, config, startClaimPhase(Date.now(), undefined, budgetMs), { unsaved: true }), budgetMs, signal);if (prepared.file || prepared.target === 'skill_bundle') return null;const file = { root: cursor.root, path: join(cursor.root, intent.path), content: intent.content };const inspected = await inspectUnchanged(engine, { prepared: { ...prepared, target: 'page', file }, snapshot, sourcePath: intent.sourcePath, databaseOnly: false,diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 0f06ed112f..712950d286 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -118,6 +118,7 @@ test/sync-frontmatter-slug-conflict.test.tstest/sync-group-member-order.test.tstest/sync-legacy-holds.test.tstest/sync-waiver-budget.test.ts+test/sync-waiver-run-imports.test.tstest/takes-vector-lifecycle-5885.serial.test.tstest/trust-channel-writes.test.tstest/trust-guarded-supersession.test.tsdiff --git a/test/sync-waiver-run-imports.test.ts b/test/sync-waiver-run-imports.test.tsnew file mode 100644index 0000000000..cb28b74464--- /dev/null+++ b/test/sync-waiver-run-imports.test.ts@@ -0,0 +1,146 @@+/**+ * GBRA-75 wave 8: a run of unchanged imports (a full re-sync, or the first sync of an+ * already-imported source) is waived in waiver-run transactions of up to 64 entries,+ * with one cursor write each, instead of a pending save and a waiver per file. The+ * screen of an entry the cursor does not yet name validates against this run's cursor+ * with nothing pending; the run's transaction re-checks each file's bytes and the+ * owner epoch, so an edit or an owner change after the screens still ends the run.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+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 { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { withEnv } from './helpers/with-env.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-waiver-run-imports-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const OPTS = { noPull: true, noEmbed: true, noExtract: true };+const note = (i: number) => `---\ntitle: N${i}\n---\nA synthetic observation ${i}.\n`;++beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });++/** A synced source of `n` notes; the next `full` sync screens every file as an unchanged import. */+async function syncedSource(engine: BrainEngine, n: number) {+ const id = `wri-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (let i = 0; i < n; i++) writeFileSync(join(root, `n${String(i).padStart(2, '0')}.md`), note(i));+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', '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');+ expect((await performManagedSync(engine, { sourceId: id, ...OPTS })).status).toBe('first_sync');+ await disposePersistenceConsumer(engine);+ return { id, root };+}+const importRequests = (engine: BrainEngine, id: string) => 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", [id]);+function countTransactions(engine: BrainEngine): { engine: BrainEngine; count: () => number } {+ let count = 0;+ return { count: () => count, engine: new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<unknown>) => { count++; return target.transaction(fn); };+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ } }) };+}++test('a full re-sync of unchanged files waives them in one waiver-run transaction, not a pending save and a waiver per file', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await syncedSource(engine, 12);+ const before = (await importRequests(engine, f.id)).length;+ const counted = countTransactions(engine);+ const waived: number[] = [];+ try {+ const result = await performManagedSync(counted.engine, { sourceId: f.id, ...OPTS, full: true,+ onProgress: event => { if (event.phase === 'managed_sync.page_committed' && event.waived) waived.push(event.bankedFiles!); } });+ expect(result).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 12, deletes: 0 } });+ expect(waived).toEqual(Array.from({ length: 12 }, (_, i) => i + 1));+ expect((await importRequests(engine, f.id)).length).toBe(before);+ // The per-entry path takes two transactions per file (24 here); the run takes one for all twelve.+ expect(counted.count()).toBeLessThan(8);+ } finally { await disposePersistenceConsumer(counted.engine); }+ }+}), 120_000);++test('a file edited after its screen ends the waiver run before it: earlier files are waived, the edited one is not', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await syncedSource(engine, 8);+ const before = (await importRequests(engine, f.id)).length;+ let fired = 0;+ installFaultHook(point => {+ if (point !== 'sync:mid_waiver_run' || fired++) return;+ writeFileSync(join(f.root, 'n03.md'), note(3) + 'An uncommitted edit made during the run.\n');+ });+ try {+ const result = await performManagedSync(engine, { sourceId: f.id, ...OPTS, full: true });+ expect(fired).toBeGreaterThan(0);+ expect(result).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 7, deletes: 0 } });+ // The edited file is not waived: only it is admitted, and its publication refuses the changed bytes (a conflict).+ const admitted = (await importRequests(engine, f.id)).slice(before);+ expect(new Set(admitted.map(row => row.slug))).toEqual(new Set(['n03']));+ expect(admitted[0]!.state).toBe('conflict');+ const [cursor] = await engine.executeRaw<{ index: number; done: boolean }>("SELECT (completed_keys->0->>'index')::int AS index,(completed_keys->0->>'done')::boolean AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ expect(cursor).toMatchObject({ index: 8, done: true });+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }+ }+}), 120_000);++test('an owner change during a waiver run\'s screens waives nothing: the run falls back and the sync refuses the old owner', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await syncedSource(engine, 8);+ let bumped = false;+ // n04 is first read by its freeze, after n00..n03 were screened and before the run's transaction.+ const proxy = new Proxy(engine, { get(target, key) {+ if (key === 'readPageSnapshot') return async (slug: string, opts: Parameters<BrainEngine['readPageSnapshot']>[1]) => {+ if (slug === 'n04' && !bumped) {+ bumped = true;+ await target.executeRaw('UPDATE persistence_worktrees SET owner_epoch=owner_epoch+1 WHERE id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1)', [f.id]);+ }+ return target.readPageSnapshot(slug, opts);+ };+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ try {+ const outcome = await performManagedSync(proxy, { sourceId: f.id, ...OPTS, full: true }).then(result => ({ result }), (error: unknown) => ({ error }));+ expect(bumped).toBe(true);+ // The run re-reads the owner epoch under its lock and passes nothing; the head's per-entry screen then admits it,+ // and its publication refuses the stale owner, so the cursor stays at the head.+ expect('result' in outcome).toBe(true);+ const result = (outcome as { result: Awaited<ReturnType<typeof performManagedSync>> }).result;+ expect(result).toMatchObject({ status: 'blocked_by_failures', waived: { imports: 0, deletes: 0 }, managedCursor: { index: 0 }, failureCodes: [{ code: 'owner_unavailable' }] });+ } finally { await disposePersistenceConsumer(proxy); }+ }+}), 120_000);++test('a crash inside a waiver run of imports skips nothing and waives nothing twice', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await syncedSource(engine, 10);+ const before = (await importRequests(engine, f.id)).length;+ let fired = 0;+ installFaultHook(point => { if (point === 'sync:mid_waiver_run' && fired++ === 0) throw new Error('injected crash inside the waiver run'); });+ try {+ await expect(performManagedSync(engine, { sourceId: f.id, ...OPTS, full: true })).rejects.toThrow('injected crash');+ await disposePersistenceConsumer(engine);+ const result = await performManagedSync(engine, { sourceId: f.id, ...OPTS, full: true });+ expect(result).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 10, deletes: 0 } });+ expect((await importRequests(engine, f.id)).length).toBe(before);+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }+ }+}), 120_000);