Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): the two first-sync stretches that stalled concurrent search
garrytan80952e026698
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.tsindex 96783153ba..33b6df8b3e 100644--- a/src/core/persistence/sync-git-stream.ts+++ b/src/core/persistence/sync-git-stream.ts@@ -322,7 +322,8 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strinconst decided = new Map<string, Dp | null>();const read: ReadFile[] = [];for (const path of paths.slice(start, start + batch)) {- if (step.due()) await step.pause();+ // Each entry reads and hashes a file: the clock, not the entry counter, decides its stretch.+ if (step.over()) 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-narrow.ts b/src/core/persistence/sync-pass-narrow.tsindex 92498400ee..01c43ea173 100644--- a/src/core/persistence/sync-pass-narrow.ts+++ b/src/core/persistence/sync-pass-narrow.ts@@ -104,24 +104,34 @@ async function fullDomain(input: DomainInput): Promise<LevelDomain> {}async function patchedDomain(input: DomainInput, prior: NonNullable<DomainInput['prior']>): Promise<LevelDomain> {- const { pages, tree, inLevel } = input, { cache, changed } = prior, { byOrigin, claimants, domain } = cache;+ const { pages, tree, inLevel, step } = input, { cache, changed } = prior, { byOrigin, claimants, domain } = cache;const slots = new Map<number, string | null>(), touched = new Set<string>();- for (const row of changed.rewritten) if (!isWindowsColonTarget(row.sourcePath)) touched.add(prior.oldKey(row.sourcePath, row.slug));- for (const row of changed.rewritten) slots.set(row.slot, null);+ // A first sync's confirm round patches every page the pass wrote: each loop yields as a full build's does.+ for (const row of changed.rewritten) { if (step.due()) await step.pause(); if (!isWindowsColonTarget(row.sourcePath)) touched.add(prior.oldKey(row.sourcePath, row.slug)); slots.set(row.slot, null); }for (let i = changed.from; i < pages.length; i++) slots.set(i, null);- for (const slot of slots.keys()) if (!isWindowsColonTarget(pages.sourcePath[slot]!)) { const key = input.keyOf(slot); slots.set(slot, key); touched.add(key); }+ // Each origin's re-read slots, gathered once (a scan of every slot per origin was quadratic: 10k slots, 10^8 steps).+ const slotsOf = new Map<string, number[]>();+ for (const slot of slots.keys()) {+ if (step.due()) await step.pause();+ if (isWindowsColonTarget(pages.sourcePath[slot]!)) continue;+ const key = input.keyOf(slot);+ slots.set(slot, key); touched.add(key);+ const same = slotsOf.get(key); if (same) same.push(slot); else slotsOf.set(key, [slot]);+ }for (const key of touched) {+ if (step.due()) await step.pause();const rows = (claimants.get(key) ?? (byOrigin.has(key) ? [byOrigin.get(key)!] : [])).filter(row => !slots.has(row));- for (const [slot, now] of slots) if (now === key) rows.push(slot);+ rows.push(...slotsOf.get(key) ?? []);rows.sort((a, b) => a - b);let win: number | undefined;for (const row of rows) if (claimBeats(pages, row, win)) win = row;if (win === undefined) byOrigin.delete(key); else byOrigin.set(key, win);if (rows.length > 1) claimants.set(key, rows); else claimants.delete(key);}- for (const [slot, key] of slots) if (key !== null) shareBlob(pages, slot, tree, key);+ for (const [slot, key] of slots) { if (step.due()) await step.pause(); if (key !== null) shareBlob(pages, slot, tree, key); }for (const path of cache.markerOnly) { domain.delete(path); touched.add(path); }for (const key of touched) {+ if (step.due()) await step.pause();const at = byOrigin.get(key), claimed = at !== undefined && inLevel(key);if (tree.has(key) || claimed) domain.add(key); else domain.delete(key);if (at === undefined || (claimed && !pages.deleted(at))) cache.unreconciled.delete(key); else cache.unreconciled.add(key);@@ -129,7 +139,7 @@ async function patchedDomain(input: DomainInput, prior: NonNullable<DomainInput[const markerOnly: string[] = [];for (const path of input.markerPaths) if (inLevel(path) && !domain.has(path)) { domain.add(path); markerOnly.push(path); }for (const path of markerOnly) touched.add(path);- for (const path of touched) if (domain.has(path) && fold(path) !== path) cache.unfolded.add(path); else cache.unfolded.delete(path);+ for (const path of touched) { if (step.due()) await step.pause(); if (domain.has(path) && fold(path) !== path) cache.unfolded.add(path); else cache.unfolded.delete(path); }const next = { ...cache, table: pages, markerOnly };return { ...next, ...await spellingTwins(input, next), touched };}diff --git a/test/sync-pass-patched-domain-yield.test.ts b/test/sync-pass-patched-domain-yield.test.tsnew file mode 100644index 0000000000..aaa21f4fa6--- /dev/null+++ b/test/sync-pass-patched-domain-yield.test.ts@@ -0,0 +1,45 @@+/**+ * GBRA-133 PR 2b (search during a sync): a confirm round patches the level's origin domain at the slots the pass wrote+ * (sync-pass-narrow.ts `patchedDomain`). After a first sync that is every page, and the patch ran with no yield at all:+ * at 10k pages it held timers for 0.9-1.4 s at the end of the sync while concurrent searches waited. Its loops now yield+ * as a full build's do.+ *+ * Forced probe (deterministic): every 20th origin key costs 4 ms of thread CPU (`keyOf`, a seam the input supplies), and+ * a confirm round patches all 4,000 pages (about 800 ms of keys). Without yields that is one stretch; with them, none+ * passes the bound, and the patch equals the full build.+ */+import { expect, test } from 'bun:test';+import { domainCache, levelDomain, type DomainInput } from '../src/core/persistence/sync-pass-narrow.ts';+import { PageTable } from '../src/core/persistence/sync-pass.ts';+import type { GitTreeEntry } from '../src/core/persistence/sync-git-stream.ts';+import { loopYield } from '../src/core/persistence/sync-yield.ts';+import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';++const MAX_LAG_MS = 100;+const PAGES = 4_000;+/** Thread CPU clocks tick in about 4 ms steps, so the cost comes in 4 ms pieces. */+const KEY_CPU_MS = 4, KEY_COST_EVERY = 20;++test('a confirm round that patches every page yields; no stretch passes the bound and the patch equals a full build', async () => {+ const tree = new Map<string, GitTreeEntry>(), pages = new PageTable({ name: 'markdown', version: 1 } as never);+ for (let i = 0; i < PAGES; i++) {+ const path = `notes/n${i}.md`;+ tree.set(path, { mode: '100644', oid: i.toString(16).padStart(40, '0') });+ pages.id.push(i + 1); pages.slug.push(`notes/n${i}`); pages.sourcePath.push(path); pages.revision.push('1');+ pages.requestId.push(null); pages.bits.push(0); pages.blobOid.push(undefined); pages.fullEpisode.push(null);+ }+ let costly = false;+ const keyOf = (row: number) => { if (costly && row % KEY_COST_EVERY === 0) spinCpuMs(KEY_CPU_MS); return pages.sourcePath[row]!; };+ const input = (prior?: DomainInput['prior']): DomainInput => ({ pages, tree, keyOf, inLevel: () => true, extra: [], markerPaths: [],+ isFile: () => true, originOf: path => path, step: loopYield(), ...(prior ? { prior } : {}) });+ const full = await levelDomain(input());+ const expected = { domain: [...full.domain].sort(), byOrigin: [...full.byOrigin].sort() };+ costly = true;+ const lag = watchLoopLag();+ let patched: Awaited<ReturnType<typeof levelDomain>>, maxLag = 0;+ try { patched = await levelDomain(input({ cache: domainCache(full, 'tree'), changed: { rewritten: [], from: 0 }, oldKey: sourcePath => sourcePath })); }+ finally { ({ maxLag } = lag.stop()); }+ expect(patched!.touched!.size).toBe(PAGES);+ expect({ domain: [...patched!.domain].sort(), byOrigin: [...patched!.byOrigin].sort() }).toEqual(expected);+ expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);+});diff --git a/test/sync-probe-dirtiness-yield.test.ts b/test/sync-probe-dirtiness-yield.test.tsnew file mode 100644index 0000000000..fad18b3373--- /dev/null+++ b/test/sync-probe-dirtiness-yield.test.ts@@ -0,0 +1,48 @@+/**+ * GBRA-133 PR 2b (search during a sync): a first sync's discovery dirtiness probe (sync-git-stream.ts `probeDirtiness`)+ * read and hashed each candidate file in one stretch of up to 64 files, because it asked the loop budget per entry+ * (`due()` reads the clock every 64 entries). A file read is not an entry's worth of work: at 10k pages the stretch held+ * timers for 1.2-1.3 s and every concurrent search waited. It now asks `over()`, the clock, before each file.+ *+ * Forced probe (deterministic): every file read costs 4 ms of thread CPU (a seam on `readSyncFile`), 64 files. Asked+ * per entry, the probe runs all 64 in one stretch (about 256 ms); asked per file, no stretch passes the bound.+ */+import { afterEach, expect, spyOn, 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 * as discovery from '../src/core/persistence/sync-discovery.ts';+import { probeDirtiness, readIndexLevel, readTreeLevel } from '../src/core/persistence/sync-git-stream.ts';+import { spinCpuMs, watchLoopLag } from './helpers/cpu-time.ts';++const MAX_LAG_MS = 100;+const FILES = 64;+const READ_CPU_MS = 4;++const spies: Array<{ mockRestore(): void }> = [];+afterEach(() => { for (const spy of spies.splice(0)) spy.mockRestore(); });++test('the dirtiness probe yields between file reads; no stretch of reads passes the bound', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-probe-yield-'));+ try {+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+ mkdirSync(join(root, 'notes'), { recursive: true }); git('init', '-q');+ for (let i = 0; i < FILES; i++) writeFileSync(join(root, `notes/n${i}.md`), `---\ntitle: n${i}\n---\n\nNote ${i}.\n`);+ git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+ const head = git('rev-parse', 'HEAD');+ const tree = await readTreeLevel(root, head, '');+ const index = await readIndexLevel(root);+ const read = discovery.readSyncFile;+ let reads = 0;+ spies.push(spyOn(discovery, 'readSyncFile').mockImplementation(((...args: Parameters<typeof read>) => { reads++; spinCpuMs(READ_CPU_MS); return read(...args); }) as typeof read));+ const lag = watchLoopLag();+ let probed: Awaited<ReturnType<typeof probeDirtiness>>, maxLag = 0;+ try { probed = await probeDirtiness(root, root, [...tree.keys()], tree, index); }+ finally { ({ maxLag } = lag.stop()); }+ expect(reads).toBe(FILES);+ expect(probed!.size).toBe(FILES);+ expect([...probed!.values()].every(probe => probe.dp === 'clean')).toBe(true);+ expect(Math.round(maxLag)).toBeLessThan(MAX_LAG_MS);+ } finally { rmSync(root, { recursive: true, force: true }); }+});