Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): #6712 PR 4b a large pass holds one compact level and yields to the event loop

garrytande9e3c0d60c1
diff --git a/scripts/bench/sync-convergence-lib.ts b/scripts/bench/sync-convergence-lib.ts
index f242d653a4..4ee5386c74 100644
--- a/scripts/bench/sync-convergence-lib.ts
+++ b/scripts/bench/sync-convergence-lib.ts
@@ -352,13 +352,24 @@ export function breakdown(rounds: ReadonlyArray<Record<string, number>>): Record
}
/** Samples process.memoryUsage().rss every everyMs: phasePeak() is the maximum since the last mark(), stop() the overall maximum. */
-export function startRssSampler(everyMs: number): { phasePeak: () => number; mark: () => void; stop: () => { peak: number; samples: number } } {
- let peak = process.memoryUsage().rss, phase = peak, samples = 1;
- const timer = setInterval(() => { const rss = process.memoryUsage().rss; samples++; if (rss > peak) peak = rss; if (rss > phase) phase = rss; }, everyMs);
+/**
+ * RSS every `everyMs` (overall and per phase peaks), and the event loop's lag: how late each tick fired past `everyMs`,
+ * the longest stretch a pass kept timers from running (#6712 PR 4b, ruling 4).
+ */
+export function startRssSampler(everyMs: number): { phasePeak: () => number; phaseLag: () => number; mark: () => void; stop: () => { peak: number; samples: number; maxLagMs: number } } {
+ let peak = process.memoryUsage().rss, phase = peak, samples = 1, last = performance.now(), maxLag = 0, phaseLag = 0;
+ const timer = setInterval(() => {
+ const now = performance.now(), lag = Math.max(0, now - last - everyMs);
+ last = now;
+ if (lag > maxLag) maxLag = lag;
+ if (lag > phaseLag) phaseLag = lag;
+ const rss = process.memoryUsage().rss; samples++; if (rss > peak) peak = rss; if (rss > phase) phase = rss;
+ }, everyMs);
return {
phasePeak: () => Math.max(phase, process.memoryUsage().rss),
- mark: () => { phase = process.memoryUsage().rss; },
- stop: () => { clearInterval(timer); return { peak: Math.max(peak, process.memoryUsage().rss), samples }; },
+ phaseLag: () => Math.round(phaseLag),
+ mark: () => { phase = process.memoryUsage().rss; phaseLag = 0; },
+ stop: () => { clearInterval(timer); return { peak: Math.max(peak, process.memoryUsage().rss), samples, maxLagMs: Math.round(maxLag) }; },
};
}
diff --git a/scripts/bench/sync-convergence.ts b/scripts/bench/sync-convergence.ts
index fe9a8e0f84..3ca7ca2cf4 100644
--- a/scripts/bench/sync-convergence.ts
+++ b/scripts/bench/sync-convergence.ts
@@ -132,7 +132,7 @@ async function runChild(config: ChildConfig): Promise<number> {
const r = await pass.idleTickProbe(engine, tick);
idle.push({ wall: performance.now() - t, idle: r.idle, reasons: r.reasons.map(String), rows: r.rows, timings_ms: r.timings_ms });
}
- const idlePeak = sampler.phasePeak();
+ const idlePeak = sampler.phasePeak(), idleLag = sampler.phaseLag();
const full: Array<{ wall: number; timings_ms: Record<string, number>; counts: unknown }> = [];
sampler.mark();
for (let i = 0; i < config.full_rounds; i++) {
@@ -140,10 +140,11 @@ async function runChild(config: ChildConfig): Promise<number> {
const r = await round();
full.push({ wall: performance.now() - t, timings_ms: r.timings_ms, counts: r.counts });
}
- const fullPeak = sampler.phasePeak();
+ const fullPeak = sampler.phasePeak(), fullLag = sampler.phaseLag();
const overall = sampler.stop();
out({ available: true, connect_ms: Math.round(connectMs), seeded_pages: seeded?.pages ?? 0, idle, full,
- rss: { after_connect: rssAfterConnect, idle_peak_sampled: idlePeak, full_peak_sampled: fullPeak, peak_sampled: overall.peak, samples: overall.samples, vm_hwm: readVmHwm() } });
+ rss: { after_connect: rssAfterConnect, idle_peak_sampled: idlePeak, full_peak_sampled: fullPeak, peak_sampled: overall.peak, samples: overall.samples, vm_hwm: readVmHwm() },
+ loop_lag_ms: { idle_max: idleLag, full_max: fullLag, max: overall.maxLagMs } });
return 0;
} catch (error) {
sampler.stop();
@@ -166,12 +167,18 @@ async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, c
return { at: performance.timeOrigin + t, wall: performance.now() - t, status: r.status, reason: r.reason ?? null, pass: r.pass ?? null };
};
let edits = 0;
- const commitOne = () => {
+ // The bench's own commit runs Git asynchronously, so its wait is not counted as the pass's event-loop lag.
+ const gitAsync = (args: string[]) => new Promise<void>((done, fail) => {
+ const child = spawn('git', ['-C', live.repo, ...args], { stdio: 'ignore' });
+ child.on('error', fail);
+ child.on('exit', code => (code === 0 ? done() : fail(new Error(`git ${args.join(' ')} exited ${code}`))));
+ });
+ const commitOne = async () => {
const path = fixturePath((edits * 7919) % live.files);
writeFileSync(join(live.repo, path), fixtureContent((edits * 7919) % live.files, 1000 + edits, live.large));
edits++;
- git(live.repo, ['add', '--', path]);
- git(live.repo, ['-c', 'user.name=Bench', '-c', '[email protected]', 'commit', '-q', '-m', 'bench edit ' + edits]);
+ await gitAsync(['add', '--', path]);
+ await gitAsync(['-c', 'user.name=Bench', '-c', '[email protected]', 'commit', '-q', '-m', 'bench edit ' + edits]);
};
try {
const warmup: Array<Awaited<ReturnType<typeof sync>>> = [];
@@ -179,19 +186,20 @@ async function runLive(engine: import('../../src/core/engine.ts').BrainEngine, c
ctx.sampler.mark();
const idle: Array<Awaited<ReturnType<typeof sync>> & { idle: boolean; reasons: string[]; rows: number; timings_ms: Record<string, number> }> = [];
for (let i = 0; i < config.idle_rounds; i++) { const r = await sync(); idle.push({ ...r, idle: r.status === 'up_to_date' && !r.pass, reasons: r.pass ? [r.pass.kind] : [], rows: 0, timings_ms: {} }); }
- const idlePeak = ctx.sampler.phasePeak();
+ const idlePeak = ctx.sampler.phasePeak(), idleLag = ctx.sampler.phaseLag();
ctx.sampler.mark();
const full: Array<Awaited<ReturnType<typeof sync>> & { timings_ms: Record<string, number>; counts: unknown }> = [];
for (let i = 0; i < config.full_rounds; i++) {
- commitOne();
+ await commitOne();
const r = await sync();
const [row] = await engine.executeRaw<{ timings: Record<string, number> | null }>("SELECT completed_keys->0->'telemetry'->'timings_ms' AS timings FROM op_checkpoints WHERE op='managed-sync-pass' AND completed_keys->0->>'source_id'=$1", [config.source_id]);
full.push({ ...r, timings_ms: row?.timings ?? {}, counts: r.pass });
}
- const fullPeak = ctx.sampler.phasePeak();
+ const fullPeak = ctx.sampler.phasePeak(), fullLag = ctx.sampler.phaseLag();
const overall = ctx.sampler.stop();
ctx.out({ available: true, connect_ms: Math.round(ctx.connectMs), seeded_pages: ctx.seededPages, warmup, idle, full,
- rss: { after_connect: ctx.rssAfterConnect, idle_peak_sampled: idlePeak, full_peak_sampled: fullPeak, peak_sampled: overall.peak, samples: overall.samples, vm_hwm: readVmHwm() } });
+ rss: { after_connect: ctx.rssAfterConnect, idle_peak_sampled: idlePeak, full_peak_sampled: fullPeak, peak_sampled: overall.peak, samples: overall.samples, vm_hwm: readVmHwm() },
+ loop_lag_ms: { idle_max: idleLag, full_max: fullLag, max: overall.maxLagMs } });
return 0;
} finally { await disposePersistenceConsumer(engine); }
}
@@ -361,6 +369,7 @@ function report(r: ReportInput): Record<string, unknown> {
rss_mib: rss ? { after_connect: mib(rss.after_connect ?? null), idle_peak_sampled: mib(rss.idle_peak_sampled ?? null), full_peak_sampled: mib(rss.full_peak_sampled ?? null),
peak_sampled: mib(rss.peak_sampled ?? null), vm_hwm: mib(rss.vm_hwm ?? null), samples: rss.samples ?? null,
process: r.engineKind === 'pglite' ? 'measuring child; includes the in-process PGLite database' : 'measuring child; database server and proxy are other processes' } : null,
+ loop_lag_ms: (m as { loop_lag_ms?: unknown } | null)?.loop_lag_ms ?? null,
breakdown_ms: { idle: breakdown(idle.map(t => t.timings_ms)), full: breakdown(full.map(t => t.timings_ms)) },
connect_ms: m?.connect_ms ?? null,
seeded_pages_seen_by_child: m?.seeded_pages ?? null,
@@ -381,6 +390,7 @@ function printSummary(doc: Record<string, unknown>): void {
`idle tick: ${s(doc.idle_tick_ms)}, idle fraction ${doc.idle_tick_idle_fraction ?? 'n/a'}, DB rows max ${doc.idle_tick_db_rows_max ?? 'n/a'}`,
`full round: ${s(doc.full_round_ms)}`,
`peak RSS: sampled ${rss?.peak_sampled ?? 'n/a'} MiB, VmHWM ${rss?.vm_hwm ?? 'n/a'} MiB`,
+ `event-loop lag: ${JSON.stringify(doc.loop_lag_ms ?? null)} ms`,
`phases: ${JSON.stringify(doc.phases)}`,
];
for (const [kind, table] of Object.entries(doc.breakdown_ms as Record<string, Record<string, unknown>>))
diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.ts
index e0ba16a9db..72646748a3 100644
--- a/src/core/hardened-git.ts
+++ b/src/core/hardened-git.ts
@@ -96,10 +96,12 @@ export type HardenedGitInput = string | Buffer | Iterable<Buffer | string> | Asy
* buffered here) and feeding `stdin` with backpressure. The process is killed
* with SIGKILL past `timeoutMs` or `maxBytes` of stdout. A throw from
* `onChunk` or from a `stdin` iterable kills the process and rejects, so a
- * caller never mistakes a run cut short for a finished one.
+ * caller never mistakes a run cut short for a finished one. An `onChunk` that
+ * returns a promise holds stdout until it settles (a large read yields to the
+ * event loop between chunks); a rejection fails the run like a throw.
*/
export async function hardenedGitStream(root: string, args: string[],
- opts: { stdin?: HardenedGitInput; timeoutMs: number; maxBytes?: number; onChunk?: (chunk: Buffer) => void }): Promise<HardenedGitStreamResult> {
+ opts: { stdin?: HardenedGitInput; timeoutMs: number; maxBytes?: number; onChunk?: (chunk: Buffer) => void | Promise<void> }): Promise<HardenedGitStreamResult> {
assertHardenedGitArgs(args);
return await new Promise<HardenedGitStreamResult>((accept, reject) => {
const child = spawn('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],
@@ -117,7 +119,9 @@ export async function hardenedGitStream(root: string, args: string[],
bytes += chunk.length;
if (opts.maxBytes !== undefined && bytes > opts.maxBytes) { stopped = 'too_large'; child.kill('SIGKILL'); return; }
last = chunk[chunk.length - 1] ?? last;
- try { opts.onChunk?.(chunk); } catch (error) { fail(error); }
+ let held: void | Promise<void>;
+ try { held = opts.onChunk?.(chunk); } catch (error) { fail(error); return; }
+ if (held) { child.stdout?.pause(); held.then(() => child.stdout?.resume(), fail); }
});
child.on('error', () => { if (child.pid === undefined) settle(() => accept({ ok: false, reason: 'unavailable' })); });
child.on('close', (code: number | null, signal: NodeJS.Signals | null) => settle(() => {
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index 84cd9558f5..aaf383528a 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -12,6 +12,7 @@ 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';
export type Dp = 'clean' | 'clean_eol' | 'clean_lfs' | 'modified' | 'deleted' | 'staged' | 'untracked' | 'unknown';
export interface GitTreeEntry { mode: string; oid: string }
@@ -45,13 +46,38 @@ 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: string) => void): Promise<void> {
+async function readRecords(gitRoot: string, args: string[], read: string, visit: (record: Buffer) => void): 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 => { for (const record of splitter.push(chunk)) visit(record.toString('utf8')); } });
+ onChunk: chunk => {
+ const records = splitter.push(chunk);
+ for (const record of records) visit(record);
+ return step.due(records.length) ? step.pause() : undefined;
+ } });
if (!hardenedStreamComplete(result) || !splitter.atRecordBoundary) throw new SyncTreeReadIncomplete(read, outcome(result));
}
+/** The common modes as one string each, so a 600k-entry map holds no per-entry copy. */
+const MODE_NAMES = new Map(['100644', '100755', '120000', '160000', '040000'].map(mode => [mode, mode]));
+
+/**
+ * One `<mode> <a> <b>\t<path>` record (`ls-tree`: type and OID; `ls-files -s`: OID and stage), its fields decoded straight
+ * from the record's bytes as strings of their own (no substring keeps the record alive), or null when the header before the
+ * tab has fewer than three fields (a fourth is ignored, as `split(' ')` did).
+ */
+function headerFields(record: Buffer): { mode: string; a: string; b: string; path: string } | null {
+ const tab = record.indexOf(9);
+ const first = tab < 0 ? -1 : record.indexOf(32);
+ const second = first < 0 || first > tab ? -1 : record.indexOf(32, first + 1);
+ if (second < 0 || second > tab) return null;
+ const third = record.indexOf(32, second + 1);
+ const raw = record.toString('latin1', 0, first);
+ return { mode: MODE_NAMES.get(raw) ?? raw, a: record.toString('latin1', first + 1, second), b: record.toString('latin1', second + 1, third < 0 || third > tab ? tab : third),
+ path: record.toString('utf8', tab + 1) };
+}
+
function* lines(items: readonly string[], terminator: string): Generator<Buffer> {
for (let i = 0; i < items.length; i += 1000) yield Buffer.from(items.slice(i, i + 1000).map(item => item + terminator).join(''));
}
@@ -63,31 +89,23 @@ function* lines(items: readonly string[], terminator: string): Generator<Buffer>
* can mark them unknown.
*/
export async function readTreeLevel(gitRoot: string, commit: string, scope: string): Promise<Map<string, GitTreeEntry>> {
- // #6712 PR 4b: a commit's tree never changes, so the last one read by commit id is reused (a pass's second round); callers
- // only read the map.
- const key = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit) ? `${gitRoot}\0${commit}\0${scope}` : null;
- if (key !== null && lastTree?.key === key) return lastTree.tree;
const tree = new Map<string, GitTreeEntry>();
await readRecords(gitRoot, ['ls-tree', '-r', '-z', commit, '--', scope === '' ? '.' : scope], 'ls-tree', record => {
- const tab = record.indexOf('\t');
- const [mode = '', type = '', oid = ''] = tab < 0 ? [] : record.slice(0, tab).split(' ');
- if (!OID.test(oid)) throw malformed('ls-tree', record);
- if (type === 'blob' || type === 'commit') tree.set(record.slice(tab + 1), { mode, oid });
+ const fields = headerFields(record);
+ if (!fields || !OID.test(fields.b)) throw malformed('ls-tree', record.toString('utf8'));
+ if (fields.a === 'blob' || fields.a === 'commit') tree.set(fields.path, { mode: fields.mode, oid: fields.b });
});
- if (key !== null) lastTree = { key, tree };
return tree;
}
-let lastTree: { key: string; tree: Map<string, GitTreeEntry> } | null = null;
/** `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>> {
const index = new Map<string, GitIndexEntry>();
await readRecords(gitRoot, ['ls-files', '-s', '-z'], 'ls-files', record => {
- const tab = record.indexOf('\t');
- const [mode = '', oid = '', stage = ''] = tab < 0 ? [] : record.slice(0, tab).split(' ');
- if (!OID.test(oid) || !/^[0-3]$/.test(stage)) throw malformed('ls-files', record);
- const path = record.slice(tab + 1);
- if ((index.get(path)?.stage ?? -1) < Number(stage)) index.set(path, { mode, oid, stage: Number(stage) });
+ 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 });
});
return index;
}
@@ -100,7 +118,8 @@ export async function readIndexLevel(gitRoot: string): Promise<Map<string, GitIn
export async function readRenameHints(gitRoot: string, from: string, to: string): Promise<GitRenameHint[]> {
const byOid = new Map<string, { deleted: string[]; added: string[] }>();
let meta: string | null = null;
- await readRecords(gitRoot, ['diff-tree', '-r', '-z', '--no-renames', from, to], 'diff-tree', record => {
+ await readRecords(gitRoot, ['diff-tree', '-r', '-z', '--no-renames', from, to], 'diff-tree', bytes => {
+ const record = bytes.toString('utf8');
if (meta === null) {
if (!record.startsWith(':')) throw malformed('diff-tree', record);
meta = record;
@@ -231,10 +250,12 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
let realRoot: string | null = null;
let realGitRoot: string | null = null;
try { realRoot = realpathSync.native(root); realGitRoot = realpathSync.native(gitRoot); } catch {}
+ const step = loopYield();
for (let start = 0; start < paths.length; start += batch) {
const decided = new Map<string, Dp | null>();
const read: ReadFile[] = [];
for (const path of paths.slice(start, start + batch)) {
+ if (step.due()) await step.pause();
const committed = tree.get(path);
const indexed = index.get(path);
let dp: Dp | null = opts.working ? (committed ? null : 'untracked') : !committed && !indexed ? 'untracked'
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index ed14672f13..43bad2eeed 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -32,6 +32,7 @@ import { VERSION } from '../../version.ts';
import type { BrainEngine } from '../engine.ts';
import { resolveSlugForPath } from '../sync.ts';
import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';
+import { loopYield } from './sync-yield.ts';
import { admitKeepDbReconcile, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';
import type { SyncProcessingOptions } from './sync-authority.ts';
import type { SyncClassified } from './sync-classify.ts';
@@ -130,7 +131,11 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, in
await adoptRecords(engine, level, state);
await sweepLegacy(engine, level, input, state);
await admitKeepDb(engine, level, input, state);
- for (const entry of level.paths) if (entry.result.cls === 'matched' && entry.slug) state.matchedSlugs.push(entry.slug);
+ const step = loopYield();
+ for (const entry of level.paths) {
+ if (step.due()) await step.pause();
+ if (entry.result.cls === 'matched' && entry.slug) state.matchedSlugs.push(entry.slug);
+ }
summarizeRound(level, state);
}
@@ -184,10 +189,13 @@ async function readStoredMarker(exec: Pick<BrainEngine, 'executeRaw'>, level: Sh
/** Design §2.6: the round's deletes through #2828's valve; a trip withholds them all under one source-level record. */
async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
const deletes = level.paths.filter(entry => entry.result.action === 'delete' && !entry.result.settled && !entry.result.inFlight);
- const deleting = new Set(deletes.map(entry => entry.path));
- const live = level.paths.filter(entry => entry.state.page?.live === true && entry.slug);
- const plan = planReconcileDeletes(live.map(entry => ({ slug: entry.slug!, source_path: entry.path })), live.filter(entry => !deleting.has(entry.path)).map(entry => entry.path), () => true);
- const tripped = deletes.length > 0 && plan.massDelete && (input.remote || !massReconcileAllowed());
+ // The valve plans over every live page only when the round deletes something (no delete never trips it).
+ const plan = deletes.length ? (() => {
+ const deleting = new Set(deletes.map(entry => entry.path));
+ const live = level.paths.filter(entry => entry.state.page?.live === true && entry.slug);
+ return planReconcileDeletes(live.map(entry => ({ slug: entry.slug!, source_path: entry.path })), live.filter(entry => !deleting.has(entry.path)).map(entry => entry.path), () => true);
+ })() : null;
+ const tripped = !!plan?.massDelete && (input.remote || !massReconcileAllowed());
state.withheldCount = tripped ? deletes.length : 0;
if (tripped) {
for (const entry of deletes) settleAs(entry, { settled: true, action: 'none', withheld: true });
@@ -196,7 +204,7 @@ async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input:
await engine.transaction(async tx => {
await assertDrainLease(tx, level.sourceId);
state.withheld = await writeDeletesWithheld(tx, { sourceId: level.sourceId, incarnation: level.incarnation, target: level.head, count: deletes.length,
- reconcilable: plan.reconcilableCount, ratio: plan.reconcilableCount ? deletes.length / plan.reconcilableCount : 1, set_hash: deleteSetHash(paths), samples: paths });
+ reconcilable: plan!.reconcilableCount, ratio: plan!.reconcilableCount ? deletes.length / plan!.reconcilableCount : 1, set_hash: deleteSetHash(paths), samples: paths });
});
return;
}
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.ts
index c57843366f..1293f295d1 100644
--- a/src/core/persistence/sync-pass-episode.ts
+++ b/src/core/persistence/sync-pass-episode.ts
@@ -23,6 +23,7 @@ import { isSyncable, matchesAnyGlob } from '../sync.ts';
import { parseUsdLimit } from '../spend-posture.ts';
import { digest } from './digest.ts';
import { readTreeLevel } from './sync-git-stream.ts';
+import { loopYield } from './sync-yield.ts';
import { SYNC_PASS_COST_OP, type PassEpisode, type SyncSelection } from './sync-pass-row.ts';
type Exec = Pick<BrainEngine, 'executeRaw'>;
@@ -48,30 +49,48 @@ export interface EpisodeClosure {
released: number;
}
-/** Design §6's closure test over the paths of `T` (the module header). */
-export function episodeClosure(input: { treePaths: Iterable<string>; episode: SyncSelection; pass: SyncSelection; configuredSelection: SyncSelection; configured: boolean;
- scope: string; slugMode: 'git-root' | 'source-root' }): EpisodeClosure {
+type ClosureInput = { episode: SyncSelection; pass: SyncSelection; configuredSelection: SyncSelection; configured: boolean; scope: string; slugMode: 'git-root' | 'source-root' };
+interface ClosureTally { included: boolean; covers: boolean; released: number }
+
+/** One stretch of design §6's closure test: `paths` folded into `tally`. */
+function tallyClosure(input: ClosureInput, paths: Iterable<string>, tally: ClosureTally): ClosureTally {
const inE = selectionEligible(input.episode, input.scope, input.slugMode);
const inPass = selectionEligible(input.pass, input.scope, input.slugMode);
const inConfig = selectionEligible(input.configuredSelection, input.scope, input.slugMode);
- let included = true, covers = true, released = 0;
- for (const path of input.treePaths) {
+ for (const path of paths) {
const e = inE(path), c = inConfig(path);
- if (e && !inPass(path)) included = false;
- if (c && !e) covers = false;
- if (e && !c) released++;
+ if (e && !inPass(path)) tally.included = false;
+ if (c && !e) tally.covers = false;
+ if (e && !c) tally.released++;
}
- if (input.configured) return { closes: true, by: 'configured', stampChunker: covers, released };
+ return tally;
+}
+
+function closureOf(configured: boolean, { included, covers, released }: ClosureTally): EpisodeClosure {
+ if (configured) return { closes: true, by: 'configured', stampChunker: covers, released };
return included ? { closes: true, by: 'inclusion', stampChunker: false, released: 0 } : { closes: false, by: null, stampChunker: false, released: 0 };
}
-/** The closure of an open episode at the pinned target `head` (one `ls-tree` of the whole commit). */
+/** Design §6's closure test over the paths of `T` (the module header). */
+export function episodeClosure(input: ClosureInput & { treePaths: Iterable<string> }): EpisodeClosure {
+ return closureOf(input.configured, tallyClosure(input, input.treePaths, { included: true, covers: true, released: 0 }));
+}
+
+/** The closure of an open episode at the pinned target `head` (one `ls-tree` of the whole commit), yielding between stretches. */
export async function passEpisodeClosure(input: { gitRoot: string; root: string; head: string; slugMode: 'git-root' | 'source-root'; episode: PassEpisode; pass: SyncSelection;
configuredSelection: SyncSelection; configured: boolean }): Promise<EpisodeClosure> {
const scope = relative(realpathSync.native(input.gitRoot), realpathSync.native(input.root)).split(sep).join('/');
- const tree = await readTreeLevel(input.gitRoot, input.head, '');
- return episodeClosure({ treePaths: tree.keys(), episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode });
+ const paths = [...(await readTreeLevel(input.gitRoot, input.head, '')).keys()];
+ const closure: ClosureInput = { episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode };
+ const tally: ClosureTally = { included: true, covers: true, released: 0 };
+ const step = loopYield();
+ for (let i = 0; i < paths.length; i += CLOSURE_STRETCH) {
+ tallyClosure(closure, paths.slice(i, i + CLOSURE_STRETCH), tally);
+ if (step.due(CLOSURE_STRETCH)) await step.pause();
+ }
+ return closureOf(input.configured, tally);
}
+const CLOSURE_STRETCH = 2_048;
/** What a pass's admissions reserve under (registered at pin, dropped at the pass's end). */
interface PassCostScope { sourceId: string; incarnation: string; scope: string; pricePerMTok: number }
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 07d88469dc..87732e2149 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -30,7 +30,8 @@ import type { PassStamp, SyncCursorOptions, SyncIntent } from './sync-prepare.ts
import { OPEN_AT_STAMP_CAP, passFingerprint, readPassRow, SYNC_ORIGIN_DELETED_OP, writePassRow, type ManagedSyncPassValue, type PassEpisode,
type PassKind, type PassOutcome, type SyncSelection } from './sync-pass-row.ts';
import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
-import { passIdleProbe, readShadowLevel, workingIdleChange, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
+import { passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
+import { loopYield } from './sync-yield.ts';
import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';
import { syncPassKind } from './sync-classify.ts';
import { PASS_BATCH_KEY_PREFIX, readConvergedWatermark, SyncAdmissionPaused, type PassEntry } from './sync-pass-batch.ts';
@@ -501,12 +502,17 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (!('entries' in drained)) return await stop(drained);
}
}
+ // The pass's level cache: its next round at the same commit reuses the tree; it dies with the pass.
+ const levelCache: PassLevelCache = {};
for (let round = 1; round <= PASS_MAX_ROUNDS; round++) {
assertActive();
value.telemetry.round = round;
input.onLevelRead(head);
+ // The previous round's level is done with: dropped before the next one is read, so a large source holds one level, not two.
+ lastLevel = null;
const level = await readShadowLevel(engine, { 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() } });
+ 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(),
+ cache: levelCache } });
assertActive();
if (!level) throw new Error(`Source ${sourceId} became a company-brain source during its sync pass.`);
// Each round reads the level at the current HEAD, and its batches freeze that commit (a commit landing mid-pass is
@@ -528,7 +534,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const deletes: ShadowPath[] = [], imports: ShadowPath[] = [], inFlight: ShadowPath[] = [], mismatch: ShadowPath[] = [], owed: ShadowPath[] = [];
lastMismatch = mismatch;
const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));
+ const step = loopYield();
for (const entry of level.paths) {
+ if (step.due()) await step.pause();
const r = entry.result;
if (r.settled) continue;
if (r.inFlight) { inFlight.push(entry); continue; }
diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.ts
index c6d5f5cf29..3def1e3fd0 100644
--- a/src/core/persistence/sync-pass.ts
+++ b/src/core/persistence/sync-pass.ts
@@ -38,6 +38,7 @@ 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 { loopYield, sortYielding } from './sync-yield.ts';
export { MANAGED_SYNC_PASS_OP, SYNC_ORIGIN_DELETED_OP };
@@ -58,6 +59,8 @@ export interface PassLevelInput {
bootstrap?: boolean;
/** The pass imports without the schema pack (`no-schema-pack` or an episode carrying it): its parser expects no pack. */
noSchemaPack?: boolean;
+ /** The pass's own cache (it dies with the pass): the eligible tree of the commit and selection its last round read. */
+ cache?: PassLevelCache;
}
/** PGLite's keyset page size (design v3.2 §2.1); Postgres reads `I⋈P` in one statement of its snapshot. */
const PGLITE_KEYSET_ROWS = 2_000;
@@ -65,6 +68,22 @@ const PGLITE_KEYSET_ROWS = 2_000;
const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;
const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];
+/** What one pass reuses between its rounds: a commit's tree never changes, so the next round at the same commit and selection reads it from here. */
+export interface PassLevelCache { tree?: { key: string; tree: Map<string, GitTreeEntry> } }
+
+/**
+ * Classifier results never change once made (a settle replaces the object), so equal ones are one object: a 600k-path
+ * level holds a handful instead of one per path. Bounded; a result past the bound stays its own.
+ */
+const SHARED_RESULTS = new Map<string, SyncClassified>();
+function sharedResult(result: SyncClassified): SyncClassified {
+ const key = JSON.stringify(result);
+ const shared = SHARED_RESULTS.get(key);
+ if (shared) return shared;
+ if (SHARED_RESULTS.size < 256) SHARED_RESULTS.set(key, Object.freeze(result) as SyncClassified);
+ return result;
+}
+
/** One classified path of the shadow level. */
export interface ShadowPath { path: string; slug: string | null; pageId: number | null; revision: string | null; state: SyncPathState; result: SyncClassified;
/** A page-less path unchanged since the baseline whose page a committed request deleted: the bootstrap writes it a `legacy` marker (`legacy_pageless`). */
@@ -120,20 +139,37 @@ async function withRoundSnapshot<T>(engine: BrainEngine, fn: (exec: Exec) => Pro
* keyset statements so writers interleave.
*/
async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string): Promise<{ rows: PageRow[]; statements: number }> {
+ // 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 the parser as text parsed once per distinct value: a 600k-page
+ // read then holds about one string per field per page.
const select = `SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted,
- p.revision_write_request_id::text AS request_id,
- c.completed_keys IS NOT NULL AS has_record, c.completed_keys->0->>'origin' AS rec_origin, c.completed_keys->0->>'blob_oid' AS rec_blob_oid,
- c.completed_keys->0->>'disk_blob_oid' AS rec_disk_blob_oid, c.completed_keys->0->>'revision' AS rec_revision, c.completed_keys->0->'parser' AS rec_parser,
- c.completed_keys->0->>'full_episode' AS rec_full_episode
+ p.revision_write_request_id::text AS request_id, c.completed_keys IS NOT NULL AS has_record,
+ c.completed_keys->0->>'origin' IS NOT DISTINCT FROM p.source_path AS rec_origin_same,
+ CASE WHEN c.completed_keys->0->>'origin' IS DISTINCT FROM p.source_path THEN c.completed_keys->0->>'origin' END AS rec_origin,
+ c.completed_keys->0->>'blob_oid' AS rec_blob_oid,
+ c.completed_keys->0->>'disk_blob_oid' IS NOT DISTINCT FROM c.completed_keys->0->>'blob_oid' AS rec_disk_same,
+ CASE WHEN c.completed_keys->0->>'disk_blob_oid' IS DISTINCT FROM c.completed_keys->0->>'blob_oid' THEN c.completed_keys->0->>'disk_blob_oid' END AS rec_disk_blob_oid,
+ c.completed_keys->0->>'revision' IS NULL AS rec_revision_null,
+ NULLIF(c.completed_keys->0->>'revision', p.knowledge_revision::text) AS rec_revision,
+ (c.completed_keys->0->'parser')::text AS rec_parser, c.completed_keys->0->>'full_episode' AS rec_full_episode
FROM pages p LEFT JOIN op_checkpoints c ON c.op=$2 AND c.fingerprint=$3||p.id::text
WHERE p.source_id=$1 AND p.source_path IS NOT NULL`;
const params = [sourceId, SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:`];
- type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin: string | null; rec_blob_oid: string | null;
- rec_disk_blob_oid: string | null; rec_revision: string | null; rec_parser: SyncImportProvenance['parser'] | null; rec_full_episode: string | null };
+ type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin_same: boolean; rec_origin: string | null; rec_blob_oid: string | null;
+ rec_disk_same: boolean; rec_disk_blob_oid: string | null; rec_revision_null: boolean; rec_revision: string | null; rec_parser: string | null; rec_full_episode: string | null };
const rows: PageRow[] = [];
- const take = (page: Raw[]) => { for (const { has_record, rec_origin, rec_blob_oid, rec_disk_blob_oid, rec_revision, rec_parser, rec_full_episode, ...row } of page) rows.push({ ...row, arm1: null, attested_hash: null,
- record: has_record ? { origin: rec_origin ?? '', blob_oid: rec_blob_oid ?? undefined, disk_blob_oid: rec_disk_blob_oid, revision: rec_revision ?? undefined, parser: rec_parser ?? undefined,
- full_episode: rec_full_episode } : null }); };
+ const parsers = new Map<string, SyncImportProvenance['parser'] | undefined>();
+ const parserOf = (text: string | null) => {
+ if (text === null) return undefined;
+ if (!parsers.has(text)) parsers.set(text, JSON.parse(text) ?? undefined);
+ return parsers.get(text);
+ };
+ const take = (page: Raw[]) => {
+ for (const raw of page) rows.push({ id: raw.id, slug: raw.slug, source_path: raw.source_path, revision: raw.revision, deleted: raw.deleted, request_id: raw.request_id,
+ arm1: null, attested_hash: null, record: raw.has_record ? { origin: raw.rec_origin_same ? raw.source_path : raw.rec_origin ?? '', blob_oid: raw.rec_blob_oid ?? undefined,
+ disk_blob_oid: raw.rec_disk_same ? raw.rec_blob_oid : raw.rec_disk_blob_oid, revision: raw.rec_revision_null ? undefined : raw.rec_revision ?? raw.revision,
+ parser: parserOf(raw.rec_parser), full_episode: raw.rec_full_episode } : null });
+ };
if (kind === 'postgres') { take(await exec.executeRaw<Raw>(select, params)); return { rows, statements: 1 }; }
let after = 0, statements = 0;
for (;;) {
@@ -282,13 +318,14 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const includeHidden = [...new Set([...input.pass?.includeHidden ?? [], ...(settled(includeHiddenRead) ?? '').split(/[\n,]/).map(v => v.trim()).filter(Boolean)].map(v => v.endsWith('/') ? `${v}**` : v))];
const keepDbPrefixes = (() => { try { return loadStorageConfig(root)?.keep_db ?? []; } catch { return []; } })();
const sourceRelative = (gitPath: string) => (scope ? gitPath.slice(scope.length + 1) : gitPath);
- // Pure per path and asked several times per path in a round, so each is computed once.
- const memo = <T>(fn: (path: string) => T) => { const seen = new Map<string, T>(); return (path: string): T => { let value = seen.get(path); if (value === undefined && !seen.has(path)) seen.set(path, value = fn(path)); return value as T; }; };
- const eligible = memo((gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
- && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden }));
- const originPath = memo((path: string) => syncOriginPath(path));
- const originOf = memo((gitPath: string) => originPath(slugMode === 'source-root' && scope ? sourceRelative(gitPath) : gitPath));
- const gitPathOf = memo((origin: string) => { const o = originPath(origin); return slugMode === 'source-root' && scope ? `${scope}/${o}` : o; });
+ // Eligibility of a path outside the cached tree (every path of the tree is eligible); origins validate per call: a
+ // 600k-path level keeps no per-path memo of either.
+ const eligible = (gitPath: string) => (!scope || gitPath.startsWith(`${scope}/`)) && !matchesAnyGlob(sourceRelative(gitPath), exclude)
+ && !isReservedSkillBundlePath(slugMode === 'source-root' ? sourceRelative(gitPath) : gitPath) && isSyncable(gitPath, { strategy: strategy as 'markdown', includeHidden });
+ const originPath = (path: string) => syncOriginPath(path);
+ const originOf = (gitPath: string) => originPath(slugMode === 'source-root' && scope ? sourceRelative(gitPath) : gitPath);
+ const gitPathOf = (origin: string) => { const o = originPath(origin); return slugMode === 'source-root' && scope ? `${scope}/${o}` : o; };
+ const step = loopYield();
t = timer();
const head = revParse(gitRoot, 'HEAD');
@@ -299,12 +336,26 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const mode: 'committed' | 'working' = working ? 'working' : 'committed';
timings.rev_parse = t();
+ // A commit's tree never changes: the pass's next round at the same commit and selection reuses the eligible tree.
+ const treeKey = JSON.stringify([gitRoot, head, scope, slugMode, strategy, exclude, includeHidden]);
+ const cache = input.pass?.cache;
+ const eligibleTree = async (): Promise<Map<string, GitTreeEntry>> => {
+ if (cache?.tree?.key === treeKey) return cache.tree.tree;
+ if (cache) cache.tree = undefined;
+ const tree = new Map<string, GitTreeEntry>();
+ for (const [path, entry] of await readTreeLevel(gitRoot, head, scope)) {
+ if (eligible(path)) tree.set(path, entry);
+ if (step.due()) await step.pause();
+ }
+ if (cache) cache.tree = { key: treeKey, tree };
+ return tree;
+ };
// The Git level, the database snapshot and the holds are independent reads: they overlap, so each key times its own
// read and `reads` is the wall time of the three together.
const timed = async <T>(key: string, read: () => Promise<T>): Promise<T> => { const st = timer(); try { return await read(); } finally { timings[key] = st(); } };
t = timer();
const [gitLevel, snapshot, held] = await Promise.all([
- Promise.all([timed('T', () => readTreeLevel(gitRoot, head, scope)), timed('X', () => readIndexLevel(gitRoot)),
+ Promise.all([timed('T', eligibleTree), timed('X', () => readIndexLevel(gitRoot)),
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', () => withRoundSnapshot(engine, async exec => {
@@ -322,45 +373,61 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
}),
]);
timings.reads = t();
- const [treeAll, index, untrackedPaths] = gitLevel;
- const tree = new Map<string, GitTreeEntry>([...treeAll].filter(([path]) => eligible(path)));
+ const [tree, index, untrackedPaths] = gitLevel;
+ const inLevel = (path: string) => tree.has(path) || eligible(path);
const untracked = new Set(untrackedPaths);
- const { pages, open, markers, passRow, statements } = snapshot;
+ const { open, markers, passRow, statements } = snapshot;
const { holds, retry } = held;
const toGit = (holdPath: string) => (scope ? `${scope}/${holdPath}` : holdPath);
const holdByGitPath = new Map<string, GitHoldRecord>(holds.map(hold => [toGit(hold.path), hold]));
const moved = new Set(held.moved.map(toGit));
- // The page claiming each origin: the live one first, else the newest tombstone.
+ // The page claiming each origin: the live one first, else the newest tombstone. The rows leave the snapshot's result
+ // here (the driver's transaction keeps that object until its connection's next one), so only `byOrigin` holds them.
t = timer();
const byOrigin = new Map<string, PageRow>();
- for (const row of pages) {
+ for (const row of snapshot.pages) {
const key = gitPathOf(row.source_path);
const prior = byOrigin.get(key);
if (!prior || (prior.deleted && !row.deleted) || (prior.deleted === row.deleted && Number(row.id) > Number(prior.id))) byOrigin.set(key, row);
+ if (step.due()) await step.pause();
}
- const domain = new Set<string>([...tree.keys(), ...untracked, ...(mode === 'working' ? [...index.keys()].filter(eligible) : []), ...[...byOrigin.keys()].filter(eligible), ...[...markers.keys()].map(gitPathOf).filter(eligible)]);
+ snapshot.pages = [];
+ const domain = new Set<string>();
+ for (const path of tree.keys()) { domain.add(path); if (step.due()) await step.pause(); }
+ for (const path of untracked) domain.add(path);
+ if (mode === 'working') for (const path of index.keys()) if (inLevel(path)) domain.add(path);
+ let reconcilable = 0;
+ for (const [path, row] of byOrigin) {
+ if (!inLevel(path)) continue;
+ domain.add(path);
+ if (!row.deleted) reconcilable++;
+ if (step.due()) await step.pause();
+ }
+ for (const origin of markers.keys()) { const path = gitPathOf(origin); if (inLevel(path)) domain.add(path); }
// Spellings of one origin that differ only by case or separator (the domain holds each path once).
const fold = (path: string) => path.replaceAll('\\', '/').toLowerCase();
- const spellings = new Map<string, string[]>();
+ const spellings = new Map<string, string | string[]>();
// Files at L count, and so does a live page's separator-spelled origin; a case-only respelling whose old file this sync
// removes is no refusal (discovery's one exception).
for (const path of domain) {
+ if (step.due()) await step.pause();
const live = byOrigin.get(path);
if (!tree.has(path) && !(mode === 'working' && (untracked.has(path) || index.has(path))) && !(live && !live.deleted && live.source_path.includes('\\'))) continue;
const folded = fold(path);
- spellings.set(folded, [...spellings.get(folded) ?? [], path]);
+ const prior = spellings.get(folded);
+ spellings.set(folded, prior === undefined ? path : typeof prior === 'string' ? [prior, path] : [...prior, path]);
}
// As discovery does, only spellings that name one page are twins: a live origin's page slug, else the slug its path names.
const twins = new Set<string>();
for (const paths of spellings.values()) {
- if (paths.length < 2) continue;
+ if (typeof paths === 'string') continue;
const slugOf = (path: string) => { const live = byOrigin.get(path); return live && !live.deleted ? live.slug : resolveSlugForPath(originOf(path)); };
const bySlug = new Map<string, string[]>();
for (const path of paths) bySlug.set(slugOf(path), [...bySlug.get(slugOf(path)) ?? [], path]);
for (const group of bySlug.values()) if (group.length > 1) for (const path of group) twins.add(path);
}
- const reconcilable = [...byOrigin.entries()].filter(([path, row]) => !row.deleted && eligible(path)).length;
+ spellings.clear();
timings.domain = t();
// Working mode rehashes every path (the full round's unconditional rehash); committed mode probes candidates only.
@@ -378,54 +445,64 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
: probe.rawOid ?? (probe.rawSha256 === null && !readPresent(root, path, scope) ? null : `unreadable:${path}`);
};
// `A` only matters where the file or the database moved (no row settles on `fileSame ∧ dbSame` with a proof): read it
- // for those pages alone, so a converged source reads none.
+ // for those pages alone, so a converged source reads none. The same walk finds whether any path needs the baseline tree.
t = timer();
- const unproven = [...byOrigin].filter(([path, row]) => {
- if (row.request_id === null) return false;
+ const unproven: PageRow[] = [];
+ let wantBaseline = false;
+ for (const [path, row] of byOrigin) {
+ if (step.due()) await step.pause();
const level = levelOf(path, probes.get(path));
- return row.deleted || level === null || !recordOids(row.record).includes(level) || row.record?.revision == null || String(row.record.revision) !== row.revision;
- }).map(([, row]) => row);
+ if (!row.deleted && row.record?.revision == null && level !== null && !recordOids(row.record).includes(level) && inLevel(path)) wantBaseline = true;
+ if (row.request_id === null) continue;
+ if (row.deleted || level === null || !recordOids(row.record).includes(level) || row.record?.revision == null || String(row.record.revision) !== row.revision) unproven.push(row);
+ }
const attestationStatements = unproven.length ? await readAttestations(engine, engineKind, sourceId, incarnation, unproven) : 0;
timings.A = t();
const baselineCommit = (context.source.last_commit && revParse(gitRoot, context.source.last_commit)) || null;
+ // The baseline tree, read once when a page needs it (no record revision; design §2.3) or the bootstrap's legacy walk does,
+ // so the classification itself never waits.
let baselineTree: Map<string, GitTreeEntry> | null | undefined;
- const baselineOf = async (path: string): Promise<string | null> => {
- if (!baselineCommit) return null;
- if (baselineTree === undefined) { const bt = timer(); baselineTree = await readTreeLevel(gitRoot, baselineCommit, scope).catch(() => null); timings.baseline = bt(); }
- return baselineTree?.get(path)?.oid ?? null;
+ const loadBaseline = async () => {
+ if (baselineTree !== undefined || !baselineCommit) return;
+ const bt = timer();
+ baselineTree = await readTreeLevel(gitRoot, baselineCommit, scope).catch(() => null);
+ timings.baseline = bt();
};
+ if (wantBaseline) await loadBaseline();
+ const baselineOf = (path: string): string | null => baselineTree?.get(path)?.oid ?? null;
const fp = (path: string) => syncImportParserFor(sourceRelative(path), pack?.identity ?? null);
- const stateOf = async (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): Promise<{ state: SyncPathState; row?: PageRow; legacyPageless?: true }> => {
+ const stateOf = (path: string, dirty: SyncPathState['dirty'], probe: { dp: string; rawOid: string | null; rawSha256: string | null } | undefined): { state: SyncPathState; row?: PageRow; legacyPageless?: true } => {
const committed = tree.get(path) ?? null;
const row = byOrigin.get(path);
const level = levelOf(path, probe);
+ const origin = originOf(path);
// Presence decides only rows 4-6 (a level of absent); a committed path in T is not read here (Dp covers it).
const presentNow = mode === 'working' ? level !== null : level === null ? readPresent(root, path, scope) : true;
const record = row?.record ?? null;
const recordBlobOids = recordOids(record);
const attested = row && (row.arm1 || row.attested_hash) ? { hash: row.attested_hash ?? null, arm1: row.arm1 === true } : null;
const hold = holdByGitPath.get(path);
- const marker = markers.get(originOf(path)) ?? null;
+ const marker = markers.get(origin) ?? null;
const deletion = !row && !marker && level !== null ? legacyDeletions.get(path) : undefined;
const virtualMarker: SyncPathState['marker'] = deletion ? { kind: 'legacy', blobOids: [level!], deletion } : null;
const legacyPageless = deletion ? true as const : undefined;
const needsBaseline = row && !row.deleted && (record?.revision == null) && level !== null && !recordBlobOids.includes(level);
const state: SyncPathState = {
mode, tree: committed?.oid ?? null, level, present: presentNow, dirty, diskOid: probe?.rawOid ?? null,
- page: row ? { live: !row.deleted, revision: row.revision, originMatches: !!record && originPath(record.origin) === originPath(row.source_path) } : null,
+ page: row ? { live: !row.deleted, revision: row.revision, originMatches: !!record && (record.origin === row.source_path || originPath(record.origin) === originPath(row.source_path)) } : null,
record: record ? { blobOids: recordBlobOids, revision: record.revision != null ? String(record.revision) : null, parserSame: sameParser(record.parser, fp(path)) } : null,
attested, levelSha256: probe?.rawSha256 ?? null,
published: !!attested?.hash && probe?.rawSha256 === attested.hash,
hold: hold ? { atLevel: holdAtLevel(hold, level, probe?.rawSha256 ?? null) && !moved.has(path), rescreenDue: holdRescreenDue(hold, retry.has(hold.path)), retried: retry.has(hold.path) } : null,
- marker: marker ?? virtualMarker, baseline: needsBaseline ? await baselineOf(path) : null,
+ marker: marker ?? virtualMarker, baseline: needsBaseline ? baselineOf(path) : null,
spelling: twins.has(path),
episodeUnsatisfied: input.pass ? !!input.pass.episodeFullId && !!row && !row.deleted && record?.full_episode !== input.pass.episodeFullId
: input.full === true && !!row && !row.deleted,
fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true,
keepDb: !mirror && keepDbPrefixes.length > 0 && !!row && isKeepDbSlug(row.slug, keepDbPrefixes),
- openWork: !!row && open.pageIds.has(Number(row.id)) || open.origins.has(originOf(path)),
+ openWork: !!row && open.pageIds.has(Number(row.id)) || open.origins.has(origin),
};
return { state, ...(row ? { row } : {}), ...(legacyPageless ? { legacyPageless } : {}) };
};
@@ -437,9 +514,12 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
if (baselineCommit && (input.pass ? input.pass.bootstrap === true : !passRow)) {
const pageless: Array<{ path: string; slug: string }> = [];
for (const path of domain) {
+ if (step.due()) await step.pause();
if (byOrigin.has(path) || markers.has(originOf(path))) continue;
const level = levelOf(path, probes.get(path));
- if (level === null || level !== await baselineOf(path)) continue;
+ if (level === null) continue;
+ await loadBaseline();
+ if (level !== baselineOf(path)) continue;
const slug = resolveSlugForPath(originOf(path));
if (slug) pageless.push({ path, slug });
}
@@ -450,15 +530,16 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
t = timer();
const paths: ShadowPath[] = [];
- const candidates: string[] = [];
+ const candidates: string[] = [], candidateAt: number[] = [];
const settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);
- for (const path of [...domain].sort()) {
+ for (const path of await sortYielding([...domain], step)) {
+ if (step.due()) await step.pause();
const probe = probes.get(path);
- const { state, row, legacyPageless } = await stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);
- const result = classifySyncPath(state);
+ const { state, row, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);
+ const result = sharedResult(classifySyncPath(state));
// Rows 1-10 precede row 11 and `matched` settles either way, so only the rest are Dp candidates (design v3.2 §2.1).
const staged = mode === 'committed' && tree.has(path) && (index.get(path)?.oid !== tree.get(path)!.oid || (index.get(path)?.stage ?? 0) !== 0);
- if (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) candidates.push(path);
+ if (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) { candidates.push(path); candidateAt.push(paths.length); }
paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}) });
}
timings.classify = t();
@@ -467,12 +548,12 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st
const probed = await probeDirtiness(root, gitRoot, candidates, tree, index);
timings.Dp = (timings.Dp ?? 0) + t();
t = timer();
- const at = new Map(paths.map((entry, i) => [entry.path, i]));
- for (const path of candidates) {
+ for (const [k, path] of candidates.entries()) {
+ if (step.due()) await step.pause();
const probe = probed.get(path);
- const i = at.get(path)!;
- const { state } = await stateOf(path, (probe?.dp ?? 'unknown') as SyncPathState['dirty'], probe);
- paths[i] = { ...paths[i]!, state, result: classifySyncPath(state) };
+ const i = candidateAt[k]!;
+ const { state } = stateOf(path, (probe?.dp ?? 'unknown') as SyncPathState['dirty'], probe);
+ paths[i] = { ...paths[i]!, state, result: sharedResult(classifySyncPath(state)) };
}
timings.classify += t();
}
diff --git a/src/core/persistence/sync-yield.ts b/src/core/persistence/sync-yield.ts
new file mode 100644
index 0000000000..5413a8e0d3
--- /dev/null
+++ b/src/core/persistence/sync-yield.ts
@@ -0,0 +1,54 @@
+/**
+ * #6712 PR 4b (design v3 "Bounded memory": CPU loops yield): the cooperative yield of a large level's synchronous loops.
+ * A 600k-path round classifies, maps and sorts for seconds; without a turn of the event loop between stretches the
+ * persistence consumer's idle probe, lease renewals and every timer starve for that long. A loop asks `due()` once per
+ * entry (a counter, then the clock every 64 entries: a probe's entry reads a file) and awaits `pause()` when its stretch has run
+ * `LOOP_BUDGET_MS`: one macrotask (`setImmediate`), so expired timers and I/O run before it continues.
+ */
+
+/** A stretch of synchronous work longer than this yields (the ruling bounds a stretch at about 100 ms; the rest is room for the entry that crosses it and for work outside these loops). */
+export const LOOP_BUDGET_MS = 30;
+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;
+ /** One macrotask turn; the next stretch starts after it. */
+ pause(): Promise<void>;
+}
+
+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; },
+ pause: async () => { await new Promise<void>(resolve => setImmediate(resolve)); since = performance.now(); },
+ };
+}
+
+/** `items.sort()` (code-unit order, as the default comparator) in runs merged with yields between stretches. */
+export async function sortYielding(items: string[], step: LoopYield): Promise<string[]> {
+ const RUN = 16_384;
+ let runs: string[][] = [];
+ for (let i = 0; i < items.length; i += RUN) {
+ runs.push(items.slice(i, i + RUN).sort());
+ if (step.due(RUN)) await step.pause();
+ }
+ while (runs.length > 1) {
+ const next: string[][] = [];
+ for (let r = 0; r < runs.length; r += 2) {
+ const a = runs[r]!, b = runs[r + 1];
+ if (!b) { next.push(a); continue; }
+ const out = new Array<string>(a.length + b.length);
+ let i = 0, j = 0, k = 0;
+ while (i < a.length && j < b.length) {
+ out[k++] = b[j]! < a[i]! ? b[j++]! : a[i++]!;
+ if (step.due()) await step.pause();
+ }
+ while (i < a.length) out[k++] = a[i++]!;
+ while (j < b.length) out[k++] = b[j++]!;
+ next.push(out);
+ }
+ runs = next;
+ }
+ return runs[0] ?? [];
+}
diff --git a/test/sync-pass-loop-lag-6712.test.ts b/test/sync-pass-loop-lag-6712.test.ts
new file mode 100644
index 0000000000..9cbd989b53
--- /dev/null
+++ b/test/sync-pass-loop-lag-6712.test.ts
@@ -0,0 +1,52 @@
+/**
+ * #6712 PR 4b ruling 4: a pass must not starve the event loop. A 600k-path round classified, mapped and sorted in one
+ * synchronous stretch of seconds (6-8 s at 600k), so the persistence consumer's idle probe missed its deadline and every
+ * timer waited. The level read now yields between stretches (sync-yield.ts).
+ *
+ * Authoring gate: (1) protects the bound on the longest stretch a level read keeps timers from running; (2) a loop over
+ * the level's paths (the tree copy, the page map, the domain, the classification, the sort, the dirtiness probe) that runs
+ * to the end without yielding fails here; (3) the timing benches report the lag but gate nothing; (4) no seam: a real
+ * managed brain and a real Git level of ${PATHS} paths, read as a pass's round reads it.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';
+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+
+const PATHS = 60_000;
+/** The ruling's bound: no stretch of a level read blocks timers for more than about this long. */
+const MAX_LAG_MS = 100;
+
+const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', input, maxBuffer: 1 << 28 }).trim();
+
+/** A commit of `PATHS` Markdown paths sharing one blob, written to the index and the object store only (no files on disk). */
+const setup = ({ root }: { root: string }) => {
+ git(root, ['init', '-q']);
+ const blob = git(root, ['hash-object', '-w', '--stdin'], '---\ntitle: Note\n---\n\nSynthetic note.\n');
+ const lines: string[] = [];
+ for (let i = 0; i < PATHS; i++) lines.push(`100644 ${blob}\tnotes/d${i % 300}/note-${i}.md`);
+ git(root, ['update-index', '--add', '--index-info'], lines.join('\n') + '\n');
+ git(root, ['-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'many notes']);
+};
+
+describe('#6712 PR 4b ruling 4: a level read yields to the event loop', () => {
+ test(`reading and classifying a ${PATHS}-path level never blocks a timer for ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {
+ // A pass resolves its context once, before its rounds; each round's level read is what this times.
+ const context = await resolveManagedSyncContext(engine, { sourceId: 'default', noPull: true, dryRun: true });
+ let last = performance.now(), maxLag = 0, ticks = 0;
+ const timer = setInterval(() => { const now = performance.now(); maxLag = Math.max(maxLag, now - last - 5); last = now; ticks++; }, 5);
+ let level: Awaited<ReturnType<typeof readShadowLevel>>;
+ try {
+ last = performance.now();
+ level = await readShadowLevel(engine, { sourceId: 'default', context });
+ } finally {
+ // The stretch that ends the read counts too: the timer never got to fire after it.
+ maxLag = Math.max(maxLag, performance.now() - last - 5);
+ clearInterval(timer);
+ }
+ expect(level!.paths.length).toBe(PATHS);
+ expect(ticks).toBeGreaterThan(0);
+ expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);
+ }, { setup }), 300_000);
+});