Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b: one loop budget for a level's Git reads and its I⋈P cursor

garrytane95e5d9f492b
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 0bb815706b..bd1a5ee828 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -40,6 +40,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6712 PR 4b: before each round of a pass reads its level (`round`), and after it read it (`level`: its statements and its
// confirm-round verdict), before it applies.
| 'sync:round_start' | 'sync:level_read'
+ // #6712 PR 4b: the level's overlapping reads, which share one loop budget (sync-yield.ts `turnYield`): a Git chunk as its
+ // records are visited (`read`: ls-tree or ls-files; a synchronous hook), an `I⋈P` result in hand before the shared budget
+ // decides whether it waits a turn, and the same result right before its rows are taken.
+ | 'sync:level_chunk' | 'sync:level_result' | 'sync:level_take'
// #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook
// that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.
| 'sync:pass_fold'
@@ -59,7 +63,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
*/
/** `writeId` is the write request row: rows of a caller-bound replay share one `requestId` (crash-robot per-request seams key on the row). */
export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string;
- round?: number; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null; reused?: number } }
+ round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number } | null; reused?: number } }
/** Postgres returns `persistence_effects.id` (bigserial) as a BigInt; `faultPoint` hands hooks its decimal string (#6584). */
export type FaultDetailInput = Omit<FaultDetail, 'effectId'> & { effectId?: string | number | bigint };
type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;
@@ -76,6 +80,10 @@ export const EFFECT_FAULT_POINTS: Record<EffectKind, FaultPoint> = {
let installed: FaultHook | undefined;
/** Gate workers only. */
export function installFaultHook(hook: FaultHook | undefined): void { installed = hook; }
+/** A seam inside synchronous work: the hook runs to its first await, and what it returns is not awaited. */
+export function faultPointNow(point: FaultPoint, detail: FaultDetailInput = {}): void {
+ if (installed) void faultPoint(point, detail).catch(() => undefined);
+}
export async function faultPoint(point: FaultPoint, detail: FaultDetailInput = {}): Promise<void> {
if (!installed) return;
const { effectId, ...rest } = detail;
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index 0f77f6d730..66ac36c7cc 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -12,7 +12,8 @@ import { join, relative, sep } from 'node:path';
import { hardenedGitStream, hardenedStreamComplete, NulRecordSplitter, type HardenedGitStreamResult } from '../hardened-git.ts';
import { gitBlobOid, sha256 } from './digest.ts';
import { readSyncFile } from './sync-discovery.ts';
-import { loopYield } from './sync-yield.ts';
+import { faultPointNow } from './fault-points.ts';
+import { loopYield, type LoopYield } from './sync-yield.ts';
export type Dp = 'clean' | 'clean_eol' | 'clean_lfs' | 'modified' | 'deleted' | 'staged' | 'untracked' | 'unknown';
export interface GitTreeEntry { mode: string; oid: string }
@@ -46,16 +47,27 @@ function outcome(result: HardenedGitStreamResult): string {
const malformed = (read: string, record: string) => new SyncTreeReadIncomplete(read, `malformed record ${JSON.stringify(record.slice(0, 80))}`);
-async function readRecords(gitRoot: string, args: string[], read: string, visit: (record: Buffer) => void): Promise<void> {
+async function readRecords(gitRoot: string, args: string[], read: string, visit: (record: Buffer) => void, shared?: LoopYield): Promise<void> {
const splitter = new NulRecordSplitter();
// A 600k-path read arrives faster than it parses: past the stretch budget, the stream waits one macrotask.
- const step = loopYield();
- const result = await gitStream(gitRoot, args, { timeoutMs: READ_TIMEOUT_MS,
- onChunk: chunk => {
- const records = splitter.push(chunk);
- for (const record of records) visit(record);
- return step.due(records.length) ? step.pause() : undefined;
- } });
+ const step = shared ?? loopYield();
+ const visitChunk = (chunk: Buffer) => {
+ if (shared) faultPointNow('sync:level_chunk', { read });
+ const records = splitter.push(chunk);
+ for (const record of records) visit(record);
+ return step.due(records.length) ? step.pause() : undefined;
+ };
+ // A budget shared with the level's cursor (sync-yield.ts `turnYield`): a chunk waits a turn the cursor already spent.
+ const take = (chunk: Buffer) => shared?.over() ? shared.pause().then(() => visitChunk(chunk)) : visitChunk(chunk);
+ // Bun can close the stream (and hand the next chunk) before a held chunk settles: chunks chain here and the read waits for the last.
+ let tail: Promise<void> | undefined;
+ const result = await gitStream(gitRoot, args, { timeoutMs: READ_TIMEOUT_MS, onChunk: chunk => {
+ const held = tail ? tail.then(() => take(chunk)) : take(chunk);
+ if (!held) return;
+ const settled: Promise<void> = held.finally(() => { if (tail === settled) tail = undefined; });
+ return tail = settled;
+ } });
+ await tail;
if (!hardenedStreamComplete(result) || !splitter.atRecordBoundary) throw new SyncTreeReadIncomplete(read, outcome(result));
}
@@ -106,30 +118,30 @@ function* lines(items: readonly string[], terminator: string): Generator<Buffer>
* Symlinks (120000) and gitlinks (160000) are kept with their mode so a caller
* can mark them unknown.
*/
-export async function readTreeLevel(gitRoot: string, commit: string, scope: string): Promise<Map<string, GitTreeEntry>> {
+export async function readTreeLevel(gitRoot: string, commit: string, scope: string, shared?: LoopYield): Promise<Map<string, GitTreeEntry>> {
const tree = new Map<string, GitTreeEntry>();
- await walkTreeLevel(gitRoot, commit, scope, (path, mode, oid) => tree.set(path, { mode, oid }));
+ await walkTreeLevel(gitRoot, commit, scope, (path, mode, oid) => tree.set(path, { mode, oid }), shared);
return tree;
}
/** `readTreeLevel`'s entries handed to `visit` in `ls-tree` order as they arrive, none kept: a caller that needs only a pass over `T` holds no map of it. */
-export async function walkTreeLevel(gitRoot: string, commit: string, scope: string, visit: (path: string, mode: string, oid: string) => void): Promise<void> {
+export async function walkTreeLevel(gitRoot: string, commit: string, scope: string, visit: (path: string, mode: string, oid: string) => void, shared?: LoopYield): Promise<void> {
await readRecords(gitRoot, ['ls-tree', '-r', '-z', commit, '--', scope === '' ? '.' : scope], 'ls-tree', record => {
const fields = headerFields(record);
if (!fields || !OID.test(fields.b)) throw malformed('ls-tree', record.toString('utf8'));
if (fields.a === 'blob' || fields.a === 'commit') visit(fields.path, fields.mode, fields.b);
- });
+ }, shared);
}
/** `X`: the index (never the worktree), keyed by Git-root-relative path; a conflicted path keeps its highest stage. */
-export async function readIndexLevel(gitRoot: string): Promise<Map<string, GitIndexEntry>> {
+export async function readIndexLevel(gitRoot: string, shared?: LoopYield): Promise<Map<string, GitIndexEntry>> {
const index = new Map<string, GitIndexEntry>();
await readRecords(gitRoot, ['ls-files', '-s', '-z'], 'ls-files', record => {
const fields = headerFields(record);
if (!fields || !OID.test(fields.a) || !/^[0-3]$/.test(fields.b)) throw malformed('ls-files', record.toString('utf8'));
const stage = Number(fields.b);
if ((index.get(fields.path)?.stage ?? -1) < stage) index.set(fields.path, { mode: fields.mode, oid: fields.a, stage });
- });
+ }, shared);
return index;
}
@@ -139,7 +151,7 @@ export async function readIndexLevel(gitRoot: string): Promise<Map<string, GitIn
* map of every path. Paths outside `tree` are not kept; when some tree path never appeared, the index is read whole
* once more to name them.
*/
-export async function readIndexDelta(gitRoot: string, tree: Map<string, GitTreeEntry>): Promise<Map<string, GitIndexEntry | null>> {
+export async function readIndexDelta(gitRoot: string, tree: Map<string, GitTreeEntry>, shared?: LoopYield): Promise<Map<string, GitIndexEntry | null>> {
const delta = new Map<string, GitIndexEntry | null>();
let same = 0;
await readRecords(gitRoot, ['ls-files', '-s', '-z'], 'ls-files', record => {
@@ -153,9 +165,9 @@ export async function readIndexDelta(gitRoot: string, tree: Map<string, GitTreeE
const stage = Number(fields.b);
if (stage === 0 && fields.a === committed.oid && fields.mode === committed.mode) { same++; return; }
if ((delta.get(fields.path)?.stage ?? -1) < stage) delta.set(fields.path, { mode: fields.mode, oid: fields.a, stage });
- });
+ }, shared);
if (same + delta.size === tree.size) return delta;
- const index = await readIndexLevel(gitRoot);
+ const index = await readIndexLevel(gitRoot, shared);
const whole = new Map<string, GitIndexEntry | null>();
for (const [path, committed] of tree) {
const indexed = index.get(path);
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index 1f62e8a829..985cf68018 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -40,7 +40,8 @@ import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlock
import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';
import { readManagedMode } from './ownership.ts';
import { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP, type SyncSelection } from './sync-pass-row.ts';
-import { filterYielding, loopYield, sortYielding, type LoopYield } from './sync-yield.ts';
+import { faultPoint } from './fault-points.ts';
+import { filterYielding, loopYield, sortYielding, turnYield, type LoopYield } from './sync-yield.ts';
import { countsMatch, proveConfirm, readLevelMark, type ConfirmProof, type LevelMark } from './sync-pass-confirm.ts';
export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };
@@ -338,7 +339,7 @@ async function withRoundSnapshot<T>(engine: BrainEngine, fn: (exec: Exec) => Pro
* PGLite reads bounded keyset statements so writers interleave.
*/
async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string, expected: SyncImportParser,
- only?: { table: PageTable; ids: string[]; slots: Map<string, number> }): Promise<{ pages: PageTable; statements: number } | null> {
+ only?: { table: PageTable; ids: string[]; slots: Map<string, number> }, step: LoopYield = loopYield()): Promise<{ pages: PageTable; statements: number } | null> {
// A record's fields usually repeat the page's (origin = source_path, disk = blob, revision = the page's), so those come back
// as a flag instead of a second copy of the string, and so does the parser when it is the Markdown one the level expects
// (`expected`, the same object for every such page; any other comes as text parsed once per distinct value): a 600k-page
@@ -390,6 +391,9 @@ async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: stri
if (parser !== undefined) pages.parser.set(i, parser);
};
const take = (page: Raw[]) => { for (const raw of page) put(raw, pages.length); };
+ // A result in hand waits a turn when the turn already ran the budget (`step` is the level's, shared with its Git reads):
+ // its rows are not taken right after a Git chunk, or after a decode that spent the turn.
+ const turn = async () => { await faultPoint('sync:level_result'); if (step.over()) await step.pause(); await faultPoint('sync:level_take'); };
if (only) {
// A confirm round: the previous round's rows, with the pages the pass wrote re-read into their slots (a new page last,
// as the keyset would read it). A rewritten page that left `I⋈P` cannot be patched: the caller reads it whole.
@@ -412,15 +416,17 @@ async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: stri
const page = await ahead.shift()!;
const more = page.length === POSTGRES_FETCH_ROWS;
if (more) ahead.push(fetch());
+ await turn();
take(page);
if (!more) { for (const queued of ahead) await queued; return { pages, statements }; }
- await new Promise(resolve => setTimeout(resolve, 0));
+ await step.pause();
}
}
let after = 0;
for (;;) {
statements++;
const page = await exec.executeRaw<Raw>(`${select} AND p.id>$5 ORDER BY p.id LIMIT ${PGLITE_KEYSET_ROWS}`, [...params, after]);
+ await turn();
take(page);
if (page.length < PGLITE_KEYSET_ROWS) return { pages, statements };
after = Number(page[page.length - 1]!.id);
@@ -572,7 +578,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const stripped = recorded.slice(scope.length + 1);
return sameSyncOrigin(recorded, stripped, originScope, slug) ? stripped : recorded;
};
- const step = loopYield();
+ const step = turnYield();
t = timer();
const head = revParse(gitRoot, 'HEAD');
@@ -594,7 +600,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
if (cache?.tree?.key === treeKey) return cache.tree;
if (cache) cache.tree = undefined;
const tree = new Map<string, GitTreeEntry>(), colon: string[] = [];
- for (const [path, entry] of await readTreeLevel(gitRoot, head, scope)) {
+ for (const [path, entry] of await readTreeLevel(gitRoot, head, scope, step)) {
if (isWindowsColonTarget(path)) colon.push(path);
else if (eligible(path)) tree.set(path, entry);
if (step.due()) await step.pause();
@@ -609,11 +615,11 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const [gitLevel, snapshot, held] = await Promise.all([
// Working mode reads the whole index (its paths join the domain); committed mode only where it differs from T, read
// after T so the two are never held whole together.
- Promise.all([timed('T', eligibleTree).then(async ({ tree, colon }) => ({ tree, colon, indexDelta: mode === 'committed' ? await timed('X', () => readIndexDelta(gitRoot, tree)) : null })),
- mode === 'working' ? timed('X', () => readIndexLevel(gitRoot)) : Promise.resolve(new Map<string, GitIndexEntry>()),
+ Promise.all([timed('T', eligibleTree).then(async ({ tree, colon }) => ({ tree, colon, indexDelta: mode === 'committed' ? await timed('X', () => readIndexDelta(gitRoot, tree, step)) : null })),
+ mode === 'working' ? timed('X', () => readIndexLevel(gitRoot, step)) : Promise.resolve(new Map<string, GitIndexEntry>()),
timed('U', async () => (mode === 'working' ? (await readUntracked(gitRoot, scope)).filter(eligible) : []))]),
// Issued together, the snapshot's statements pipeline on its one connection (PGLite runs them in turn).
- timed('I⋈P', () => readRoundSnapshot(engine, { kind: engineKind, sourceId, incarnation, worktreeId: context.binding.worktree_id, parser: syncImportParser(pack?.identity ?? null),
+ timed('I⋈P', () => readRoundSnapshot(engine, { kind: engineKind, sourceId, incarnation, worktreeId: context.binding.worktree_id, parser: syncImportParser(pack?.identity ?? null), step,
reuse: cache && input.pass?.passId ? { cache, passId: input.pass.passId, recorded: input.pass.recorded, working: mode === 'working', head } : undefined }, timed)),
timed('H', () => readLevelHolds(engine, sourceId, incarnation, input.pass?.retryConsumed)),
]);
@@ -868,7 +874,7 @@ const confirmGuard = <T>(read: Promise<T>) => read.catch((error: unknown) => { t
* same key reuses the last `I⋈P` when sync-pass-confirm.ts proves it (else reads it whole). The proof never throws: a
* failed mark, proof or delta read reads the round again, whole and unmarked.
*/
-async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; worktreeId: string; parser: SyncImportParser;
+async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; worktreeId: string; parser: SyncImportParser; step: LoopYield;
reuse?: { cache: PassLevelCache; passId: string; recorded?: ReadonlySet<number>; working: boolean; head: string } }, timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {
const { kind, sourceId, incarnation, worktreeId, reuse } = input;
// Reused only at the same commit, worktree and parser, in committed mode: working mode always reads `I⋈P` whole.
@@ -890,7 +896,7 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'
// Read whole, the round holds one `I⋈P`, not the reused one beside it.
if (!confirmed?.read) prior = undefined;
// A failed mark fails what was pipelined after it: the mark's failure is the one to report.
- const read = confirmed?.read ?? await timed('pages', () => readPages(exec, kind, sourceId, incarnation, input.parser)).catch(async (error: unknown) => { await marked; throw error; });
+ const read = confirmed?.read ?? await timed('pages', () => readPages(exec, kind, sourceId, incarnation, input.parser, undefined, input.step)).catch(async (error: unknown) => { await marked; throw error; });
const mark = confirmed?.mark ?? (marked ? await marked : null);
const [work, markers, passRow] = await others;
if (reuse && mark) reuse.cache.pages = { key, mark, table: read!.pages };
diff --git a/src/core/persistence/sync-yield.ts b/src/core/persistence/sync-yield.ts
index 1acf77d568..5f0190c495 100644
--- a/src/core/persistence/sync-yield.ts
+++ b/src/core/persistence/sync-yield.ts
@@ -14,6 +14,8 @@ const CHECK_EVERY = 64;
export interface LoopYield {
/** Whether the current stretch has run its budget; cheap enough to ask per entry (`entries`: how many this call stands for). */
due(entries?: number): boolean;
+ /** Whether the current stretch already ran its budget, asked before work that cannot stop part-way (a chunk, a fetch result). */
+ over(): boolean;
/** One timer turn; the next stretch starts after it. */
pause(): Promise<void>;
}
@@ -22,6 +24,33 @@ export function loopYield(): LoopYield {
let since = performance.now(), n = 0;
return {
due: (entries = 1) => { n += entries; if (n < CHECK_EVERY) return false; n = 0; return performance.now() - since >= LOOP_BUDGET_MS; },
+ over: () => performance.now() - since >= LOOP_BUDGET_MS,
+ pause: async () => { await new Promise<void>(resolve => setTimeout(resolve, 0)); since = performance.now(); },
+ };
+}
+
+/** How often the shared budget's clock notes that timers ran, and for how many ticks it keeps going once nothing asks. */
+const TURN_TICK_MS = 4, TURN_QUIET_TICKS = 25;
+
+/**
+ * One budget for reads that overlap (a level's Git streams and its `I⋈P` cursor): its stretch starts when timers last ran,
+ * not at its own last pause, so the turn one read spent (a Git chunk, a fetch result the driver decoded in one go) counts
+ * against the other, and neither starts its work right after the other's in the same turn. A clock ticks while it is asked.
+ */
+export function turnYield(): LoopYield {
+ let since = performance.now(), n = 0, quiet = 0, clock: ReturnType<typeof setInterval> | undefined;
+ const over = () => {
+ quiet = 0;
+ if (!clock) {
+ since = performance.now();
+ clock = setInterval(() => { since = performance.now(); if (++quiet > TURN_QUIET_TICKS) { clearInterval(clock); clock = undefined; } }, TURN_TICK_MS);
+ (clock as { unref?: () => void }).unref?.();
+ }
+ return performance.now() - since >= LOOP_BUDGET_MS;
+ };
+ return {
+ due: (entries = 1) => { n += entries; if (n < CHECK_EVERY) return false; n = 0; return over(); },
+ over,
pause: async () => { await new Promise<void>(resolve => setTimeout(resolve, 0)); since = performance.now(); },
};
}
diff --git a/test/e2e/sync-pass-shared-budget-6712-postgres.test.ts b/test/e2e/sync-pass-shared-budget-6712-postgres.test.ts
new file mode 100644
index 0000000000..e254ccbebd
--- /dev/null
+++ b/test/e2e/sync-pass-shared-budget-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-shared-budget-6712.test.ts'));
diff --git a/test/sync-pass-shared-budget-6712.test.ts b/test/sync-pass-shared-budget-6712.test.ts
new file mode 100644
index 0000000000..97f7664b1b
--- /dev/null
+++ b/test/sync-pass-shared-budget-6712.test.ts
@@ -0,0 +1,88 @@
+/**
+ * #6712 PR 4b: a level's Git reads and its `I⋈P` read share one loop budget (sync-yield.ts `turnYield`). The two reads
+ * overlap, and each used to yield on its own clock only, so a Git chunk and a fetch result could run back to back in one
+ * turn: at #6858 shape and 5 ms RTT that held timers for 116-138 ms. With one budget, work that finds the turn already
+ * spent waits a turn first.
+ *
+ * Forced probe (deterministic): the first `I⋈P` result waits at `sync:level_result` until the index read's first chunk
+ * is being visited, which the seam makes a 60 ms stretch of Git work (`sync:level_chunk`), so the result resumes in that
+ * chunk's turn; its take then costs 60 ms (`sync:level_take`). One budget: the take waits a turn, so no stretch passes
+ * the bound. Each read on its own budget, the take runs right after the chunk, about 120 ms.
+ *
+ * PGLite here (its keyset read takes the same turn); Postgres through test/e2e/sync-pass-shared-budget-6712-postgres.test.ts.
+ *
+ * Forced probe (deterministic, no database): a Git read whose every chunk waits a turn still returns every record. Bun
+ * closes the stream before a held chunk settles, so a read that did not wait for its last chunk returned the index
+ * without it, and a delta sync froze a deletion of a committed file (page_identity_changed).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { readIndexLevel } from '../src/core/persistence/sync-git-stream.ts';
+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';
+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+/** The ruling's bound on a stretch that keeps timers from running (test/sync-pass-loop-lag-6712.test.ts). */
+const MAX_LAG_MS = 100;
+/** Each side's forced stretch: under the bound alone, over it back to back. */
+const STRETCH_MS = 60;
+const NOTES = 40;
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (let i = 0; i < NOTES; i++) writeFileSync(join(root, `notes/n${i}.md`), `---\ntype: concept\ntitle: notes/n${i}\n---\n\nNote ${i}.\n`);
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+};
+const busy = (ms: number) => { const end = performance.now() + ms; while (performance.now() < end) { /* a stretch the loop cannot break */ } };
+
+afterEach(() => installFaultHook(undefined));
+
+test('a Git read whose chunks each wait a turn returns every record before it resolves', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-shared-budget-'));
+ try {
+ setup({ root });
+ const shared = { due: () => false, over: () => true, pause: () => new Promise<void>(resolve => setTimeout(resolve, 30)) };
+ expect((await readIndexLevel(root, shared)).size).toBe(NOTES);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+
+ describe(`#6712 PR 4b: a level's Git and I⋈P reads share one loop budget (${backend})`, () => {
+ test('a fetch result that lands in a Git chunk\'s turn waits a turn before its take; no stretch passes the bound', () => managedBrain(async ({ engine }) => {
+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+ const context = await resolveManagedSyncContext(engine, { sourceId: 'default', noPull: true, dryRun: true });
+ let open: () => void = () => {};
+ const chunk = new Promise<void>(resolve => { open = resolve; });
+ const seen = { chunk: false, result: false, take: false };
+ installFaultHook(async (point, detail) => {
+ if (point === 'sync:level_chunk' && detail.read === 'ls-files' && !seen.chunk) { seen.chunk = true; open(); busy(STRETCH_MS); }
+ if (point === 'sync:level_result' && !seen.result) { seen.result = true; await Promise.race([chunk, new Promise(resolve => setTimeout(resolve, 10_000))]); }
+ if (point === 'sync:level_take' && !seen.take) { seen.take = true; busy(STRETCH_MS); }
+ });
+ let last = performance.now(), maxLag = 0;
+ const timer = setInterval(() => { const now = performance.now(); maxLag = Math.max(maxLag, now - last - 5); last = now; }, 5);
+ let level: Awaited<ReturnType<typeof readShadowLevel>>;
+ try {
+ last = performance.now();
+ level = await readShadowLevel(engine, { sourceId: 'default', context });
+ } finally {
+ maxLag = Math.max(maxLag, performance.now() - last - 5);
+ clearInterval(timer);
+ installFaultHook(undefined);
+ }
+ expect(seen).toEqual({ chunk: true, result: true, take: true });
+ expect(level!.paths.length).toBe(NOTES);
+ expect(Math.round(maxLag)).toBeGreaterThanOrEqual(STRETCH_MS - 5);
+ expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);
+ }, { ...(databaseUrl ? { databaseUrl } : {}), setup }), 120_000);
+ });
+}