Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a first sync's batch build counts same-blob twins once per blob, not once per winner
garrytana2a2b1181198
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 1fc21a96ff..4f4e103c69 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -153,6 +153,11 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shslug: entry.slug!, pageId: entry.pageId, revision: entry.revision, level: null }]));const leaving = new Map(deletes.map(entry => [entry.path, entry]));const fresh = imports.filter(entry => !entry.state.page);+ // Same-blob twins per level, and the leaving pages per recorded blob, counted once: a scan per winner was quadratic.+ const twinsAt = new Map<string | null | undefined, number>();+ for (const entry of fresh) twinsAt.set(entry.state.level, (twinsAt.get(entry.state.level) ?? 0) + 1);+ const leavingAt = new Map<string, ShadowPath[]>();+ for (const gone of leaving.values()) for (const oid of new Set(gone.state.record?.blobOids ?? [])) { const at = leavingAt.get(oid); if (at) at.push(gone); else leavingAt.set(oid, [gone]); }const slugOf = new Map(fresh.map(entry => [entry.path, resolveSlugForPath(entryPaths(level, entry.path).sourcePath)]));// #6727, as discovery does: a new origin with no live page at its slug takes the one legacy page (no recorded origin)// that folds to it; several, or one the importer cannot write, keep the slug and the freeze holds legacy_slug_conflict.@@ -249,12 +254,12 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Shentries.push({ ...base, pageId: null, revision: null, ...(origin.revision === held.revision ? { renameFrom: held } : { renameHeld: held }) });continue;}- const moved = [...leaving.values()].filter(gone => deleteEntries.has(gone.path) && !renamed.has(gone.path) && gone.state.record?.blobOids.includes(winner.state.level ?? ''));- const twins = fresh.filter(other => other.state.level === winner.state.level);+ const moved = (leavingAt.get(winner.state.level ?? '') ?? []).filter(gone => deleteEntries.has(gone.path) && !renamed.has(gone.path));+ const twins = twinsAt.get(winner.state.level) ?? 0;// #6729: a Git rename with an edit keeps its page when Git pairs it and the identity is confirmed, as discovery's delta does.- const inexact = moved.length === 1 && twins.length === 1 ? null : (await gitRenames())?.get(winner.path);+ const inexact = moved.length === 1 && twins === 1 ? null : (await gitRenames())?.get(winner.path);const gitMoved = inexact && deleteEntries.has(inexact.from) && !renamed.has(inexact.from) ? leaving.get(inexact.from) : undefined;- if (gitMoved?.pageId != null || (moved.length === 1 && twins.length === 1)) {+ if (gitMoved?.pageId != null || (moved.length === 1 && twins === 1)) {const gone = gitMoved ?? moved[0]!;const origin = entryPaths(level, gone.path).sourcePath;entries.push({ ...base, pageId: null, revision: null, renameFrom: { sourcePath: origin, slug: gone.slug!, pageId: gone.pageId!, revision: gone.revision! },diff --git a/test/sync-pass-batch-entries-6712.test.ts b/test/sync-pass-batch-entries-6712.test.tsnew file mode 100644index 0000000000..2593ee6b05--- /dev/null+++ b/test/sync-pass-batch-entries-6712.test.ts@@ -0,0 +1,46 @@+/**+ * GBRA-133 PR 2b (search during a sync): a pass's batch build (sync-pass-run.ts `batchEntries`) counted each import+ * winner's same-blob twins by filtering every new origin, once per winner: quadratic in a first sync's new files (at 10k,+ * about 10^8 compares and a 1.1-1.4 s stretch that held every concurrent search). Twins are counted once per blob now,+ * and a moved page is looked up by blob instead of by a scan of the leaving pages.+ *+ * Forced probe: a first sync of ${PATHS} new files sharing one blob (each has every other as a twin). The stretch from the+ * batch build's start to the first freeze is timed on the thread's CPU; the run is aborted there, so nothing is imported.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { watchLoopLag } from './helpers/cpu-time.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const PATHS = 8_000;+const MAX_LAG_MS = 100;++const git = (root: string, args: string[], input?: string) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', input, maxBuffer: 1 << 26 }).trim();+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 % 100}/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']);+};++afterEach(() => installFaultHook(undefined));++describe('GBRA-133 PR 2b: a first sync builds its batch in linear time', () => {+ test(`the batch build of ${PATHS} new same-blob files never blocks a timer for ${MAX_LAG_MS} ms`, () => managedBrain(async ({ engine }) => {+ let lag: ReturnType<typeof watchLoopLag> | undefined, maxLag: number | undefined;+ const stop = new AbortController();+ installFaultHook(async point => {+ if (point === 'sync:batch_entries' && !lag) lag = watchLoopLag();+ if (point === 'sync:after_freeze' && lag && maxLag === undefined) { maxLag = lag.stop().maxLag; stop.abort(); }+ });+ await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true, signal: stop.signal }).catch(() => undefined);+ installFaultHook(undefined);+ if (lag && maxLag === undefined) lag.stop();+ expect(maxLag).toBeDefined();+ expect(Math.round(maxLag!)).toBeLessThan(MAX_LAG_MS);+ }, { setup }), 300_000);+});