Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: race waiver and origin-equivalence preparations against the sync budget (#6278 B3)
garrytandc8f821365ac
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 0af1acc953..519973b7eb 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -17,7 +17,7 @@ import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-orimport { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';import { screeningRequest } from './noop-kernel.ts';-import { noopWaiversEnabled, screenWaiver, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';+import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';import { resolve } from 'node:path';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';@@ -313,7 +313,7 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): Mreturn diagnostic;}async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assertActive: () => void,- run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string }): Promise<Pending | Held> {+ run: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal }): Promise<Pending | Held> {assertActive();const entry = cursor.entries[cursor.index];const retry = { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath };@@ -358,7 +358,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, assslug = entry.slug!; pageId = occupant?.page.id ?? entry.pageId ?? null; revision = occupant ? occupant.revision : entry.revision ?? null;const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });assertActive();- if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly))) {+ if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,`Page ${slug} was imported from ${entry.path} by another run of source ${cursor.sourceId} with different content after this run enumerated it, so the run stopped before admitting it.`);}@@ -683,18 +683,22 @@ async function alreadyImportedAtOrigin(engine: BrainEngine, cursor: Cursor, entr}}-/** #5522: the page now at the origin already holds exactly the content this entry would import (the preparer's own no-op verdict). */+/**+ * #5522: the page now at the origin already holds exactly the content this entry would import (the preparer's own no-op verdict).+ * #6278: the preparation races the sync budget; past it the origin refusal stands, and a cancelled run propagates.+ */async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: Cursor['entries'][number], key: string,- snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, content: string, rawHash: string | null, lineEndingOnly: boolean): Promise<boolean> {+ snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, content: string, rawHash: string | null, lineEndingOnly: boolean, signal?: AbortSignal): Promise<boolean> {if (!snapshot || snapshot.page.deleted_at != null) return false;const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath: entry.sourcePath, path: entry.path, rawHash, content, lineEndingOnly,processingOptions: cursor.processingOptions, ownerEpoch: String(cursor.binding.owner_epoch), syncAuthority: cursor.authority,cursorKey: key, runId: cursor.runId, slugMode: cursor.slugMode, index: cursor.index, total: cursor.entries.length, from: cursor.from, target: cursor.target, working: entry.working ?? false };try {- const prepared = await prepareManagedSyncMutation(engine, screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: snapshot.page.slug,- page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind });+ const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: snapshot.page.slug,+ page_id: snapshot.page.id, worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent }), { engine: engine.kind }), await syncPreparationBudgetMs(engine), signal);return (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file && prepared.observedRevision === snapshot.revision;- } catch {+ } catch (error) {+ if (signal?.aborted) throw error;return false;}}@@ -737,7 +741,7 @@ const WAIVER_RUN_MAX = 64;*/async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | null> {- const first = await screenWaiver(engine, cursor, head, config);+ const first = await screenWaiver(engine, cursor, head, config, frozenRun.signal);if (!first) return null;assertActive();const run: WaiverRunEntry[] = [{ pending: head, waived: first }];@@ -746,7 +750,7 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:const batch = Array.from({ length: Math.min(4, max - run.length, cursor.entries.length - next) }, (_, i) => next + i);const frozen = await Promise.all(batch.map(index => freezeEntry(engine, { ...cursor, index }, key, assertActive, frozenRun).catch(() => null)));const screened = await Promise.all(frozen.map((entry, i) => entry && !('hold' in entry) && !entry.rebound- ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config).catch(() => null) : null));+ ? screenWaiver(engine, { ...cursor, index: batch[i]! }, entry, config, frozenRun.signal).catch(() => null) : null));for (const [i, waived] of screened.entries()) {if (!waived) break extend;run.push({ pending: frozen[i] as Pending, waived });@@ -1091,7 +1095,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst company = currentCompanyBrainSync(context.sourceId);const processingOptions = syncProcessingOptions(opts);const syncOptions = cursorSyncOptions(opts);- const frozenRun: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string } = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}) };+ const frozenRun: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string; signal?: AbortSignal } = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}) };const runStartedAt = new Date().toISOString();const key = managedCursorKey(context.incarnation, authority, company, syncOptions);let cursor: Cursor | null = null;@@ -1103,6 +1107,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst discoveryRun = randomUUID();const inheritedSignal = currentSourceFilesystemSignal();const signal = opts.signal && inheritedSignal ? AbortSignal.any([opts.signal, inheritedSignal]) : opts.signal ?? inheritedSignal;+ if (signal) frozenRun.signal = signal;const assertActive = () => {assertSyncDispatchActive();throwIfAborted(signal);@@ -1267,7 +1272,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst screened: Cursor = cursor;const waived: Cursor | null = prior ? null : await waiveNoopEntry(engine, screened, pending, config, key,(tx, noop) => writeCursor(tx, key, screened, { ...waivedCursor(screened, noop), progress: stampProgress(screened.progress, screened.index, screened.index + 1, drainStartedAt) },- holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened));+ holdClear(screened, pending.intent.path, observedAt)), tx => currentCursor(tx, key, screened), signal);if (waived) {cursor = waived;opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length, waived: true });diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex e8696976be..edd9a66362 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -22,6 +22,52 @@ export interface WaiverCursor { sourceId: string; incarnation: string; root: strexport interface WaiverEntry { requestId: string; slug: string; pageId: number | null; intent: SyncIntent }export interface NoopWaiver { kind: 'import' | 'delete'; kernel: NoopKernelWaiver[] }+/** `persistence.sync_preparation_ms` (Lane A defines and validates it): the budget a managed sync member's preparation gets; default 120 s. */+export const SYNC_PREPARATION_MS_KEY = 'persistence.sync_preparation_ms';+export const SYNC_PREPARATION_DEFAULT_MS = 120_000;+const BUDGET_TTL_MS = 5000;+let budgets = new WeakMap<object, { at: number; read: Promise<number> }>();+/** The sync preparation budget of `engine`'s brain, read at most every BUDGET_TTL_MS; a failed or malformed read is the default. */+export function syncPreparationBudgetMs(engine: Pick<BrainEngine, 'getConfig'>, now = Date.now()): Promise<number> {+ const held = budgets.get(engine);+ if (held && now - held.at < BUDGET_TTL_MS) return held.read;+ const read = engine.getConfig(SYNC_PREPARATION_MS_KEY).then(value => {+ const n = Number(value?.trim());+ return Number.isInteger(n) && n > 0 ? n : SYNC_PREPARATION_DEFAULT_MS;+ }, () => SYNC_PREPARATION_DEFAULT_MS);+ budgets.set(engine, { at: now, read });+ return read;+}+/** Test seam: the next read sees the current config. */+export function resetSyncPreparationBudget(): void { budgets = new WeakMap(); }++/** The error `raceSyncBudget` rejects with when the budget passes; callers treat it as "cannot decide" and fail open. */+export class SyncPreparationBudgetExceeded extends Error {+ constructor(readonly budgetMs: number) { super(`The sync preparation did not finish within ${budgetMs} ms.`); this.name = 'SyncPreparationBudgetExceeded'; }+}+/**+ * #6278 (1.10): a sync preparation run outside the consumer (a waiver screen or+ * the #5522 origin-equivalence check) runs on the feeder's event loop, where the+ * consumer's deadline cannot see a hang. This races `work` against the sync+ * budget and the run's signal: past the budget it rejects with+ * `SyncPreparationBudgetExceeded` (the caller fails open: nothing is waived,+ * the origin refusal stands, nothing is counted or held); an aborted signal+ * rejects with its reason, so run cancellation propagates. The late result is+ * dropped, never read.+ */+export function raceSyncBudget<T>(work: Promise<T>, budgetMs: number, signal?: AbortSignal): Promise<T> {+ if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException('The sync was cancelled.', 'AbortError'));+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => { cleanup(); reject(new SyncPreparationBudgetExceeded(budgetMs)); }, budgetMs);+ timer.unref?.();+ const onAbort = () => { cleanup(); reject(signal!.reason ?? new DOMException('The sync was cancelled.', 'AbortError')); };+ const cleanup = () => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); };+ signal?.addEventListener('abort', onAbort, { once: true });+ work.then(value => { cleanup(); resolve(value); }, error => { cleanup(); reject(error); });+ });+}+const rethrowAbort = (error: unknown, signal?: AbortSignal) => { if (signal?.aborted) throw error; };+/** DX-A15: `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry, for triage. */export function noopWaiversEnabled(env: NodeJS.ProcessEnv = process.env): boolean { return env.GBRAIN_SYNC_WAIVE_NOOP !== '0'; }@@ -53,8 +99,8 @@ export function unfinishedPageRequestParams(cursor: Pick<WaiverCursor, 'sourceId* waiver decision.*/export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine, cursor: C, pending: WaiverEntry, config: GBrainConfig, key: string,- advance: (tx: BrainEngine, waived: NoopWaiver) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>): Promise<C | null> {- const waived = await screenWaiver(engine, cursor, pending, config);+ advance: (tx: BrainEngine, waived: NoopWaiver) => Promise<C>, reread: (tx: BrainEngine) => Promise<C>, signal?: AbortSignal): Promise<C | null> {+ const waived = await screenWaiver(engine, cursor, pending, config, signal);if (!waived) return null;const intent = pending.intent;return engine.transaction(async tx => {@@ -80,7 +126,7 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine* already soft-deleted at its frozen revision, or an unchanged import). A* revoked sync authority throws.*/-export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<NoopWaiver | null> {+export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<NoopWaiver | null> {if (!noopWaiversEnabled() || pending.pageId === null) return null;const intent = pending.intent;if (intent.kind === 'managed_sync_delete') {@@ -90,7 +136,7 @@ export async function screenWaiver(engine: BrainEngine, cursor: WaiverCursor, peawait validateSyncAuthority(engine, cursor.authority, pending.slug);return { kind: 'delete', kernel: [] };}- const kernel = await unchangedSyncImport(engine, cursor, pending, config);+ const kernel = await unchangedSyncImport(engine, cursor, pending, config, signal);if (!kernel) return null;await validateSyncAuthority(engine, cursor.authority, pending.slug);return { kind: 'import', kernel };@@ -156,14 +202,14 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,}/** #5984: whether `waiveNoopEntry` would waive this frozen entry now (read-only; the bulk group stops before such an entry). */-export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<boolean> {+export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<boolean> {if (!noopWaiversEnabled() || pending.pageId === null) return false;const intent = pending.intent;if (intent.kind === 'managed_sync_delete') {if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return false;return softDeletedAt(await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true }), pending);}- return (await unchangedSyncImport(engine, cursor, pending, config)) !== null;+ return (await unchangedSyncImport(engine, cursor, pending, config, signal)) !== null;}function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, pending: WaiverEntry): boolean {@@ -178,15 +224,17 @@ function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapsho* publication can never resolve (a pending contextual-mode stamp, and file* bytes that differ from the prepared content yet parse to the same page), so* an unchanged legacy file stops taking a request ID on every run.+ * #6278: the preparation races the sync budget (`raceSyncBudget`); past it+ * nothing is waived, and a cancelled run propagates.*/-export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<NoopKernelWaiver[] | null> {+export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig, signal?: AbortSignal): Promise<NoopKernelWaiver[] | null> {const intent = pending.intent;if (intent.kind !== 'managed_sync_import' || intent.renameFrom || pending.pageId === null || typeof intent.path !== 'string' || typeof intent.content !== 'string') return null;try {const snapshot = await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true });const row = screeningRequest({ source_id: cursor.sourceId, source_incarnation: cursor.incarnation, slug: pending.slug, page_id: pending.pageId,worktree_id: cursor.binding.worktree_id, authority: cursor.authority.writer, intent, request_id: pending.requestId });- const prepared = await prepareManagedSyncMutation(engine, row, config);+ const prepared = await raceSyncBudget(prepareManagedSyncMutation(engine, row, config), await syncPreparationBudgetMs(engine), 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,@@ -195,7 +243,8 @@ export async function unchangedSyncImport(engine: BrainEngine, cursor: WaiverCurif (inspected.admitReason) return null;await prepared.validate?.(engine);return inspected.waived ?? [];- } catch {+ } catch (error) {+ rethrowAbort(error, signal);return null;}}diff --git a/test/sync-waiver-budget.test.ts b/test/sync-waiver-budget.test.tsnew file mode 100644index 0000000000..1749da1106--- /dev/null+++ b/test/sync-waiver-budget.test.ts@@ -0,0 +1,108 @@+/**+ * #6278 (B3, plan 1.10): a sync preparation that runs outside the consumer (a+ * no-op waiver screen, the #5522 origin-equivalence check) races the sync+ * budget (`persistence.sync_preparation_ms`) and the run's signal. Past the+ * budget nothing is waived and the origin refusal stands (fail open: the entry+ * is admitted and the consumer's own deadline covers it); a cancelled run+ * propagates. The forced probe sets a 1 ms budget: a full re-sync that waives+ * every unchanged file under the default budget admits every file instead. It+ * runs on Postgres: PGLite's WASM queries block the event loop, so a timer+ * cannot interrupt them (the plan's ceiling covers that case), and the probe+ * would see the preparation win every race there.+ */+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 { raceSyncBudget, resetSyncPreparationBudget, SYNC_PREPARATION_DEFAULT_MS, SYNC_PREPARATION_MS_KEY, SyncPreparationBudgetExceeded, syncPreparationBudgetMs } from '../src/core/persistence/sync-waivers.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-budget-'));+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();++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 }); });++test('raceSyncBudget: a fast preparation wins, a hung one rejects at the budget, an aborted run rejects with its reason', async () => {+ expect(await raceSyncBudget(Promise.resolve('prepared'), 1000)).toBe('prepared');+ const hung = new Promise<never>(() => {});+ await expect(raceSyncBudget(hung, 20)).rejects.toBeInstanceOf(SyncPreparationBudgetExceeded);+ const controller = new AbortController();+ const raced = raceSyncBudget(hung, 60_000, controller.signal);+ controller.abort(new Error('run cancelled'));+ await expect(raced).rejects.toThrow('run cancelled');+ const aborted = new AbortController(); aborted.abort(new Error('already cancelled'));+ await expect(raceSyncBudget(Promise.resolve('late'), 60_000, aborted.signal)).rejects.toThrow('already cancelled');+ await expect(raceSyncBudget(Promise.reject(new Error('refused')), 60_000)).rejects.toThrow('refused');+});++test('syncPreparationBudgetMs: the documented default, a configured value, a malformed value, and a memo within its TTL', async () => {+ const fake = (value: string | null) => ({ getConfig: async () => value }) as unknown as Pick<BrainEngine, 'getConfig'>;+ expect(await syncPreparationBudgetMs(fake(null))).toBe(SYNC_PREPARATION_DEFAULT_MS);+ expect(SYNC_PREPARATION_DEFAULT_MS).toBe(120_000);+ expect(await syncPreparationBudgetMs(fake('45000'))).toBe(45_000);+ expect(await syncPreparationBudgetMs(fake('soon'))).toBe(SYNC_PREPARATION_DEFAULT_MS);+ expect(await syncPreparationBudgetMs(fake('-5'))).toBe(SYNC_PREPARATION_DEFAULT_MS);+ let reads = 0;+ const counted = { getConfig: async () => { reads++; return '30000'; } } as unknown as Pick<BrainEngine, 'getConfig'>;+ expect(await syncPreparationBudgetMs(counted, 1000)).toBe(30_000);+ expect(await syncPreparationBudgetMs(counted, 2000)).toBe(30_000);+ expect(reads).toBe(1);+ expect(await syncPreparationBudgetMs(counted, 10_000)).toBe(30_000);+ expect(reads).toBe(2);+ const failing = { getConfig: async () => { throw new Error('database away'); } } as unknown as Pick<BrainEngine, 'getConfig'>;+ expect(await syncPreparationBudgetMs(failing)).toBe(SYNC_PREPARATION_DEFAULT_MS);+});++test('forced probe: under a 1 ms budget the waiver screen cannot decide, so a full re-sync admits every unchanged file instead of waiving it', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) await probe(engine);+}), 240_000);++async function probe(engine: BrainEngine) {+ const id = `budget-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (let i = 0; i < 3; i++) { mkdirSync(join(root, 'notes'), { recursive: true }); writeFileSync(join(root, `notes/n${i}.md`), `---\ntitle: N${i}\n---\nA synthetic observation ${i}.\n`); }+ 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');+ const sync = (full = false) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, full });+ const requests = () => engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [id]).then(rows => rows[0]!.n);+ expect((await sync()).status).toBe('first_sync');+ expect(await requests()).toBe(3);+ try {+ // Default budget: the full re-sync waives every unchanged import without a request.+ expect(await sync(true)).toMatchObject({ status: 'synced', waived: { imports: 3, deletes: 0 } });+ expect(await requests()).toBe(3);+ // 1 ms budget: the screen fails open and each entry is admitted (a no-op publication), nothing is held or failed.+ await engine.setConfig(SYNC_PREPARATION_MS_KEY, '1');+ resetSyncPreparationBudget();+ const admitted = await sync(true);+ expect(admitted).toMatchObject({ status: 'synced', added: 0, modified: 0 });+ expect(admitted.held_count ?? 0).toBe(0);+ if (engine.kind === 'postgres') {+ expect(admitted.waived).toEqual({ imports: 0, deletes: 0 });+ expect(await requests()).toBe(6);+ }+ expect(await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state<>'committed' AND intent->>'kind'='managed_sync_import'", [id])).toEqual([]);+ } finally {+ await engine.unsetConfig(SYNC_PREPARATION_MS_KEY);+ resetSyncPreparationBudget();+ await disposePersistenceConsumer(engine);+ }+}