Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: stop the level read when the pass stops; commit fenced writes in slices so the drain lease renews
garrytan0d45567505a3
diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex c970cb22a4..0c93c7186a 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -93,6 +93,30 @@ export async function assertDrainLease(tx: Pick<BrainEngine, 'executeRaw'>, sourif (!rows.length) throw new LockStolenError(lease.lockId, `the drain lease of source ${sourceId} is no longer held by this pass`);}+/** GBRA-133: the longest a transaction holding the fence stays open (plus the item that crosses it); a renewal times out after 30 s. */+export const FENCED_SLICE_MS = 5_000;++/**+ * GBRA-133: `write` for each item in fenced transactions of at most `FENCED_SLICE_MS`. The fence holds the lock row+ * `FOR SHARE`, which blocks this lease's own renewal and release until the transaction ends: one transaction that wrote a+ * round's holds at 65 ms per round trip stayed open for 14 minutes, every renewal timed out and the lease lapsed under the+ * pass. Each slice is fenced again, so a lapsed lease stops the writes at the next slice. `committed` sees each slice once it commits.+ */+export async function inFencedSlices<T>(engine: BrainEngine, sourceId: string, items: readonly T[],+ write: (tx: BrainEngine, item: T) => Promise<void>, committed?: (slice: readonly T[]) => void): Promise<void> {+ for (let start = 0; start < items.length;) {+ const end = await engine.transaction(async tx => {+ await assertDrainLease(tx, sourceId);+ const began = performance.now();+ let next = start;+ do await write(tx, items[next++]!); while (next < items.length && performance.now() - began < FENCED_SLICE_MS);+ return next;+ });+ committed?.(items.slice(start, end));+ start = end;+ }+}+const iso = (value: Date | null | undefined) => value ? value.toISOString() : null;/** The live holder of a source's drain lease (kind and id from the row this module writes beside the lock), or null. */diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex e2703b27db..cb4604a622 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -48,7 +48,7 @@ import { faultPoint } from './fault-points.ts';import { RECOVERY_VERSION } from '../markdown.ts';import { readSyncImportProvenances, recordSyncImportProvenances, syncImportParserFor, writeGitHold,type GitHoldCode, type GitHoldMeta, type SyncImportProvenance } from './sync-holds.ts';-import { assertDrainLease } from './sync-lease.ts';+import { assertDrainLease, inFencedSlices } from './sync-lease.ts';import { clearDeletesWithheld, deleteSetHash, readDeletesWithheld, readOriginDeletedMarker, retireOriginDeletedMarker, writeDeletesWithheld, type DeletesWithheld } from './sync-markers.ts';import { isCompactMatched, type ShadowLevel, type ShadowPath } from './sync-pass.ts';import { SETTLE_MISMATCH_STREAK, type ManagedSyncPassValue, type PassRoundSummary } from './sync-pass-row.ts';@@ -204,17 +204,13 @@ export function summarizeRound(level: ShadowLevel, state: PassApplyState): voidasync function retireMarkers(engine: BrainEngine, level: ShadowLevel, state: PassApplyState): Promise<void> {const retire = await filterYielding(level.paths, entry => !isCompactMatched(entry) && entry.state.marker && !entry.legacyPageless&& ((entry.state.tree === null && !entry.state.present) || entry.state.page?.live === true));- if (!retire.length) return;- await engine.transaction(async tx => {- await assertDrainLease(tx, level.sourceId);- for (const entry of retire) {- const { sourcePath } = passEntryPaths(level, entry.path);- const stored = await readStoredMarker(tx, level, sourcePath);- if (!stored) continue;- const blobOids = Array.isArray(stored.blob_oids) ? stored.blob_oids : [];- if ((stored.kind === 'legacy' ? 'legacy' : 'deleted') !== entry.state.marker!.kind || blobOids.join('\0') !== entry.state.marker!.blobOids.join('\0')) continue;- if (await retireOriginDeletedMarker(tx, { sourceId: level.sourceId, incarnation: level.incarnation, origin: sourcePath, expected: stored })) state.markersRetired++;- }+ await inFencedSlices(engine, level.sourceId, retire, async (tx, entry) => {+ const { sourcePath } = passEntryPaths(level, entry.path);+ const stored = await readStoredMarker(tx, level, sourcePath);+ if (!stored) return;+ const blobOids = Array.isArray(stored.blob_oids) ? stored.blob_oids : [];+ if ((stored.kind === 'legacy' ? 'legacy' : 'deleted') !== entry.state.marker!.kind || blobOids.join('\0') !== entry.state.marker!.blobOids.join('\0')) return;+ if (await retireOriginDeletedMarker(tx, { sourceId: level.sourceId, incarnation: level.incarnation, origin: sourcePath, expected: stored })) state.markersRetired++;});}@@ -348,25 +344,22 @@ function spellingGroups(level: ShadowLevel): Map<string, string[]> {return groups;}-/** Writes the round's holds at level `L` under the drain lease, counts them and settles their paths `held`. */+/** Writes the round's holds at level `L` under the drain lease, counts them and settles their paths `held` as each slice commits. */async function writeHolds(engine: BrainEngine, level: ShadowLevel, input: Pick<PassApplyInput, 'passId' | 'observedAt'>, state: PassApplyState, pending: PendingHold[]): Promise<void> {- if (!pending.length) return;- await engine.transaction(async tx => {- await assertDrainLease(tx, level.sourceId);- for (const hold of pending) {- const { path, sourcePath } = passEntryPaths(level, hold.entry.path);- await writeGitHold(tx, { source_id: level.sourceId, incarnation: level.incarnation, path, source_path: sourcePath, slug: hold.slug,- page_id: hold.pageId !== undefined ? hold.pageId : hold.entry.state.page?.live ? hold.entry.pageId : null,- code: hold.code, message: hold.message, upstream_version: hold.entry.state.levelSha256, observed_at: input.observedAt, run_id: input.passId, mode: 'managed',- meta: { recovery_version: RECOVERY_VERSION, ...levelMeta(level, hold.entry), ...hold.meta } });+ await inFencedSlices(engine, level.sourceId, pending, async (tx, hold) => {+ const { path, sourcePath } = passEntryPaths(level, hold.entry.path);+ await writeGitHold(tx, { source_id: level.sourceId, incarnation: level.incarnation, path, source_path: sourcePath, slug: hold.slug,+ page_id: hold.pageId !== undefined ? hold.pageId : hold.entry.state.page?.live ? hold.entry.pageId : null,+ code: hold.code, message: hold.message, upstream_version: hold.entry.state.levelSha256, observed_at: input.observedAt, run_id: input.passId, mode: 'managed',+ meta: { recovery_version: RECOVERY_VERSION, ...levelMeta(level, hold.entry), ...hold.meta } });+ }, slice => {+ for (const hold of slice) {+ state.holds[hold.kind]++;+ if (hold.code === 'settle_mismatch') state.settleMismatch.push(passEntryPaths(level, hold.entry.path).path);+ if (hold.code === 'origin_conflict' || hold.code === 'page_identity_changed') state.originHeld.add(hold.entry.path);+ settleAs(hold.entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' });}});- for (const hold of pending) {- state.holds[hold.kind]++;- if (hold.code === 'settle_mismatch') state.settleMismatch.push(passEntryPaths(level, hold.entry.path).path);- if (hold.code === 'origin_conflict' || hold.code === 'page_identity_changed') state.originHeld.add(hold.entry.path);- settleAs(hold.entry, { cls: 'held', settled: true, action: 'none', classAction: 'repair' });- }}/**diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex ace2a5972b..691effb27e 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -835,7 +835,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): PrwriteIds: value.obligations.converged?.writeback ?? [] })) return synced(true);const levelInput = { sourceId, context, workingTree: mode === 'working',pass: { noSchemaPack: processingOptions.noSchemaPack, episodeFullId: episode?.full_id ?? null, retryConsumed: round > 1 ? retryConsumed : undefined, exclude: opts.exclude, includeHidden: opts.includeHidden, strategy: opts.strategy, bootstrap: markersOwed(),- slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded, onProgress: beat.report } };+ slugMode: value.obligations.slug_mode, cache: levelCache, passId, recorded: applied.recorded, onProgress: beat.report, assertActive } };const level = await readShadowLevel(engine, levelInput);await faultPoint('sync:level_read', { sourceId, round, level: level ? { statements: level.statements, confirm: level.confirm ?? null, reused: level.reused ?? 0, shadow: level, input: levelInput } : undefined });assertActive();diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex b348c66514..832cae5644 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -43,7 +43,7 @@ import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceRecimport { readManagedMode } from './ownership.ts';import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } from './sync-pass-row.ts';import { faultPoint } from './fault-points.ts';-import { filterYielding, loopYield, progressYield, sortYielding, turnYield, type LoopYield } from './sync-yield.ts';+import { filterYielding, loopYield, progressYield, sortYielding, turnYield, whileActive, type LoopYield } from './sync-yield.ts';import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';import { domainCache, levelDomain, narrowedWalk, walkAttestations, type LevelDomainCache } from './sync-pass-narrow.ts';@@ -76,6 +76,8 @@ export interface PassLevelInput {recorded?: ReadonlySet<number>;/** #7355: called while the read works (its loops' pauses, at most once a second, and the origin history walk), so the drain sees progress before the first commit. */onProgress?: () => void;+ /** Throws once the pass must stop (a job deadline, a lost drain lease): checked at the read's pauses and while its origin history walk runs. */+ assertActive?: () => void;}/** PGLite's keyset page size (design v3.2 §2.1). */const PGLITE_KEYSET_ROWS = 2_000;@@ -576,10 +578,12 @@ async function readUntracked(gitRoot: string, scope: string): Promise<string[]>const timer = () => { const started = performance.now(); return () => Math.round((performance.now() - started) * 10) / 10; };/** #7130: an absent file is deletion evidence only when Git once committed it (sync-origin-evidence.ts); read for those paths alone. */-async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield, onProgress?: () => void): Promise<boolean> {+async function reclassifyByOrigin(gitRoot: string, tips: Array<string | null | undefined>, paths: ShadowPath[], step: LoopYield, pass?: PassLevelInput): Promise<boolean> {const absent = await filterYielding(paths, entry => (entry.result.cls === 'delete' || entry.result.cls === 'delete_drift') && entry.state.originEvidence === undefined, step);if (!absent.length) return false;- const evidence = await readOriginEvidence(gitRoot, tips, absent.map(entry => entry.path), { onCommit: onProgress });+ // A stopped pass leaves the shared walk running: the next pass joins it, or reads the history it cached.+ pass?.assertActive?.();+ const evidence = await whileActive(readOriginEvidence(gitRoot, tips, absent.map(entry => entry.path), { onCommit: pass?.onProgress }), pass?.assertActive);for (const entry of absent) {const state = { ...entry.state, originEvidence: evidence.get(entry.path) ?? 'unknown' as const };Object.assign(entry, { state, result: classifySyncPath(state) });@@ -622,7 +626,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// the one rule discovery and preparation use (sameSyncOrigin; it refuses an origin that could name two files).const originScope = { sourceId, root, scope, slugMode };const pageOrigin = (sourcePath: string, slug: string): string => scopedPageOrigin(originPath(sourcePath), slug, originScope);- const step = progressYield(turnYield(), input.pass?.onProgress);+ const step = progressYield(turnYield(), { onProgress: input.pass?.onProgress, assertActive: input.pass?.assertActive });t = timer();const { head, detached } = await readLevelHead(gitRoot, sourceId);@@ -856,7 +860,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}t = timer();- if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step, input.pass?.onProgress)) timings.origin = t();+ if (await reclassifyByOrigin(gitRoot, [head, baselineCommit], paths, step, input.pass)) timings.origin = t();// Adoption by hash needs the level's bytes: committed mode reads the blobs of the candidates that could adopt.const needBytes = await filterYielding(paths, entry => !['matched', 'held', 'dirty'].includes(entry.result.cls) && entry.state.levelSha256 === null && entry.state.level !== nulldiff --git a/src/core/persistence/sync-yield.ts b/src/core/persistence/sync-yield.tsindex f6211251f6..e6fb8c7b97 100644--- a/src/core/persistence/sync-yield.ts+++ b/src/core/persistence/sync-yield.ts@@ -31,12 +31,26 @@ export function loopYield(): LoopYield {/*** #7355: `step` that also reports from its pauses, at most once per `everyMs`: a level read that screens a large source for- * minutes before its first commit tells the drain's in-pass governor it is working, as a commit does.+ * minutes before its first commit tells the drain's in-pass governor it is working, as a commit does. `assertActive` runs+ * at every pause, so a job deadline or a lost drain lease stops the read at its next pause instead of when it ends.*/-export function progressYield(step: LoopYield, onProgress: (() => void) | undefined, everyMs = 1_000): LoopYield {- if (!onProgress) return step;+export function progressYield(step: LoopYield, hooks: { onProgress?: () => void; assertActive?: () => void }, everyMs = 1_000): LoopYield {+ const { onProgress, assertActive } = hooks;+ if (!onProgress && !assertActive) return step;let last = performance.now();- return { due: step.due, over: step.over, pause: async () => { await step.pause(); if (performance.now() - last >= everyMs) { last = performance.now(); onProgress(); } } };+ return { due: step.due, over: step.over, pause: async () => {+ await step.pause();+ assertActive?.();+ if (onProgress && performance.now() - last >= everyMs) { last = performance.now(); onProgress(); }+ } };+}++/** `work`, or the error `assertActive` throws once it does (checked every `everyMs`); the work itself is not stopped. */+export async function whileActive<T>(work: Promise<T>, assertActive: (() => void) | undefined, everyMs = 1_000): Promise<T> {+ if (!assertActive) return work;+ let timer: ReturnType<typeof setInterval> | undefined;+ const stopped = new Promise<never>((_, reject) => { timer = setInterval(() => { try { assertActive(); } catch (error) { reject(error); } }, everyMs); });+ try { return await Promise.race([work, stopped]); } finally { clearInterval(timer); }}/** How often the shared budget's clock notes that timers ran, and for how many ticks it keeps going once nothing asks. */diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex f6bde76f36..80ffc7b00e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -425,6 +425,7 @@ test/sync-drain-inpass-stall.test.tstest/sync-drain-write-capacity.test.tstest/sync-dry-run-drain-7167.test.tstest/sync-exits-l4-6712.test.ts+test/sync-fenced-slices-gbra133.test.tstest/sync-freshness-6858.test.tstest/sync-frontmatter-recovery.test.tstest/sync-frontmatter-slug-conflict.test.ts@@ -447,6 +448,7 @@ test/sync-page-write-failed-gbra130.test.tstest/sync-pass-abandoned-7355.test.tstest/sync-pass-cost-grouping-gbra130.test.tstest/sync-pass-dirty-after-freeze-gbra130.test.ts+test/sync-pass-stop-in-level-gbra133.test.tstest/sync-prescreen-both-delta-6712.test.tstest/sync-prescreen-drift-6712.test.tstest/sync-slug-root-mode-6694.test.tsdiff --git a/test/sync-fenced-slices-gbra133.test.ts b/test/sync-fenced-slices-gbra133.test.tsnew file mode 100644index 0000000000..435085f21f--- /dev/null+++ b/test/sync-fenced-slices-gbra133.test.ts@@ -0,0 +1,77 @@+/**+ * GBRA-133 (600k soak): a managed pass wrote a round's holds in one transaction that took the drain-lease fence (the lock+ * row `FOR SHARE`) first. At 65 ms per round trip it stayed open for 14 minutes; the lease's own renewal waited on that row,+ * timed out three times, and the lease lapsed under the pass, which then stopped `drain_lease_held` without applying+ * anything; its release waited on the same row until the connection was killed. Fenced per-item writes now commit in+ * slices of at most `FENCED_SLICE_MS`, so a renewal waits for one slice at most.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { SyncResult } from '../src/commands/sync.ts';+import { syncLockId } from '../src/core/db-lock.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { holdPassIdentities, newPassApplyState } from '../src/core/persistence/sync-pass-apply.ts';+import type { ShadowLevel, ShadowPath } from '../src/core/persistence/sync-pass.ts';+import { GIT_HOLD_OP } from '../src/core/persistence/sync-holds.ts';+import { withDrainLease } from '../src/core/persistence/sync-lease.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const HOLDS = 60;+const ROUND_TRIP_MS = 40;+/** A slice (`FENCED_SLICE_MS`, 5 s) plus the hold that crosses it; the whole round takes about twice that. */+const SLICE_BOUND_MS = 6_000;++/** `engine` whose transactions wait `ROUND_TRIP_MS` before each statement (a remote database) and record how long each stayed open. */+function remote(engine: BrainEngine, spans: number[]): BrainEngine {+ const slow = (tx: BrainEngine) => new Proxy(tx, { get: (target, prop) => {+ if (prop === 'executeRaw') return async (...args: Parameters<BrainEngine['executeRaw']>) => { await Bun.sleep(ROUND_TRIP_MS); return target.executeRaw(...args); };+ const value = Reflect.get(target, prop);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+ return new Proxy(engine, { get: (target, prop) => {+ if (prop === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(async tx => {+ const began = performance.now();+ try { return await fn(slow(tx)); } finally { spans.push(performance.now() - began); }+ });+ const value = Reflect.get(target, prop);+ return typeof value === 'function' ? value.bind(target) : value;+ } });+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test(`GBRA-133 [${backend}]: a round's holds commit in fenced slices, so the lease renews while they are written`, () => managedBrain(async ({ engine }) => {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const level = { sourceId: 'default', incarnation, scope: '', slugMode: 'git-root', mode: 'committed' } as unknown as ShadowLevel;+ const items = Array.from({ length: HOLDS }, (_, i) => ({ slug: `notes/held-${i}`, ids: { page: `page-${i}`, file: `file-${i}` },+ entry: { path: `notes/held-${i}.md`, slug: `notes/held-${i}`, pageId: null, revision: null, state: { level: 'a'.repeat(40), levelSha256: null },+ result: { cls: 'import', settled: false, action: 'import' } } as unknown as ShadowPath }));+ const state = newPassApplyState();+ const spans: number[] = [];+ let renewalMs = -1;+ const result = await withDrainLease(engine, 'default', { holder: { kind: 'cli' } }, async () => {+ const holds = holdPassIdentities(remote(engine, spans), level, { passId: 'pass-example', observedAt: new Date().toISOString() }, state, items);+ await Bun.sleep(1_000);+ const asked = performance.now();+ const renewed = await engine.executeRaw('UPDATE gbrain_cycle_locks SET last_refreshed_at=now() WHERE id=$1 RETURNING id', [syncLockId('default')]);+ renewalMs = performance.now() - asked;+ expect(renewed).toHaveLength(1);+ await holds;+ return { status: 'synced' } as unknown as SyncResult;+ });+ expect(result.status).toBe('synced');+ expect(spans.length).toBeGreaterThan(1);+ expect(Math.max(...spans)).toBeLessThan(SLICE_BOUND_MS);+ expect(renewalMs).toBeLessThan(SLICE_BOUND_MS);+ expect(state.holds.page_identity_changed).toBe(HOLDS);+ expect(items.every(item => item.entry.result.cls === 'held' && item.entry.result.settled)).toBe(true);+ const [{ n }] = await engine.executeRaw<{ n: number | string }>('SELECT count(*) AS n FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [GIT_HOLD_OP, `default:${incarnation}:notes/held-%`]);+ expect(Number(n)).toBe(HOLDS);+ }, { databaseUrl, setup: ({ root }) => {+ execFileSync('git', ['-C', root, 'init', '-q']);+ writeFileSync(join(root, 'a.md'), '---\ntype: concept\ntitle: a\n---\n\nA note.\n');+ } }), 120_000);+}diff --git a/test/sync-pass-stop-in-level-gbra133.test.ts b/test/sync-pass-stop-in-level-gbra133.test.tsnew file mode 100644index 0000000000..e9f2f5a1fc--- /dev/null+++ b/test/sync-pass-stop-in-level-gbra133.test.ts@@ -0,0 +1,70 @@+/**+ * GBRA-133 (600k soak): a managed pass whose job deadline passed, or whose drain lease lapsed, kept reading and classifying+ * the whole level (including its Git history walk) before it looked at either: a 30 s first slice stopped at 215 s, and a+ * pass that lost its lease ran on for minutes. The level read now checks the pass is still active at every pause of its+ * loops and while the origin history walk runs, so it stops at the next pause; the walk itself keeps running for the next+ * pass to join or reuse.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { __resetHistoryIndexesForTest } from '../src/core/persistence/sync-origin-evidence.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { loopYield, progressYield, whileActive } from '../src/core/persistence/sync-yield.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args],+ { encoding: 'utf8', input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] }).trim();+const page = (title: string) => `---\ntype: concept\ntitle: ${title}\n---\n\nA note about ${title}.\n`;+const stop = (flag: { stopped: boolean }) => () => { if (flag.stopped) throw new DOMException('stopped', 'AbortError'); };++describe('GBRA-133: a stopped pass stops its level read', () => {+ test('progressYield checks the pass at every pause', async () => {+ const flag = { stopped: false };+ const step = progressYield(loopYield(), { assertActive: stop(flag) });+ await step.pause();+ flag.stopped = true;+ await expect(step.pause()).rejects.toThrow('stopped');+ });++ test('whileActive ends with the stop while the work keeps running, and returns the work when the pass stays active', async () => {+ const flag = { stopped: false };+ let finished = false;+ const work = Bun.sleep(400).then(() => { finished = true; return 'evidence'; });+ const started = performance.now();+ setTimeout(() => { flag.stopped = true; }, 50);+ await expect(whileActive(work, stop(flag), 20)).rejects.toThrow('stopped');+ expect(performance.now() - started).toBeLessThan(300);+ expect(finished).toBe(false);+ expect(await work).toBe('evidence');+ expect(await whileActive(Bun.sleep(30).then(() => 'kept'), stop({ stopped: false }), 10)).toBe('kept');+ });+});++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ test(`GBRA-133 [${backend}]: a pass stopped while its level is read never finishes the read`, () => managedBrain(async ({ engine, root }) => {+ const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+ expect((await performManagedSync(engine, OPTS)).status).toMatch(/^(first_sync|synced)$/);+ // A file the page lost: the next level read walks the history for its origin evidence.+ unlinkSync(join(root, 'b.md')); git(root, ['commit', '-qam', 'remove b']);+ __resetHistoryIndexesForTest();+ const controller = new AbortController();+ const points: string[] = [];+ installFaultHook(async point => {+ points.push(point);+ if (point === 'sync:round_start') controller.abort(new DOMException('deadline', 'AbortError'));+ });+ const result = await performManagedSync(engine, { ...OPTS, signal: controller.signal }).catch(error => error).finally(() => installFaultHook(undefined));+ expect(points).toContain('sync:round_start');+ expect(points).not.toContain('sync:level_read');+ expect(result instanceof Error ? result.name : result.status).toMatch(/^(AbortError|partial)$/);+ }, { databaseUrl, setup: ({ root }) => {+ git(root, ['init', '-q']);+ for (const name of ['a', 'b']) writeFileSync(join(root, `${name}.md`), page(name));+ git(root, ['add', '-A']); git(root, ['commit', '-qm', 'pages']);+ } }), 120_000);+}