Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): committed-mode dirtiness probe reuses a vouched clean probe while the file's lstat and tree entry are unchanged (#7338)

garrytan334e90ced2e9
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.ts
index 33b6df8b3e..0fd2769980 100644
--- a/src/core/persistence/sync-git-stream.ts
+++ b/src/core/persistence/sync-git-stream.ts
@@ -279,7 +279,7 @@ function lfsPointer(blob: Buffer): { oid: string; size: number } | null {
const attributeSet = (value: string | undefined): boolean => value !== undefined && value !== 'unspecified' && value !== 'unset';
-interface ReadFile { path: string; sha256: string; localOid: string; foldedOid: string; size: number; executable: boolean | null }
+interface ReadFile { path: string; sha256: string; localOid: string; foldedOid: string; size: number; executable: boolean | null; statKey: string | null }
/**
* `Dp` for each Git-root-relative path, first match wins: `untracked` (in
@@ -307,6 +307,14 @@ interface ReadFile { path: string; sha256: string; localOid: string; foldedOid:
* through the same `clean_eol`/`clean_lfs` domains. So a staged edit, a staged
* new file, `git rm --cached`, a staged deletion and a staged file removed from
* disk probe exactly as the same disk does with a pristine index.
+ *
+ * Committed mode reuses a `clean` probe (#7338) where the path's lstat key and
+ * its tree entry are the ones the probe was vouched under, and the index entry
+ * is the tree's: a clean verdict depends on the raw bytes alone, so it needs no
+ * read, hash or attribute lookup. A probe is vouched only when the stat taken
+ * before the read is unchanged after the batch's hash and its `mtime` and
+ * `ctime` are older than 2 s before the call began (the working stat cache's
+ * racy window), so an edit made during or after the read always rehashes.
*/
export async function probeDirtiness(root: string, gitRoot: string, paths: string[], tree: Map<string, GitTreeEntry>,
index: Map<string, GitIndexEntry>, opts: { batch?: number; working?: boolean; step?: LoopYield } = {}): Promise<Map<string, DirtinessProbe>> {
@@ -318,6 +326,9 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
let realGitRoot: string | null = null;
try { realRoot = realpathSync.native(root); realGitRoot = realpathSync.native(gitRoot); } catch {}
const step = opts.step ?? loopYield();
+ const cleanKey = !opts.working && realRoot !== null && realGitRoot !== null ? `${realRoot}\0${realGitRoot}` : null;
+ const vouched = cleanKey === null ? null : new Map(cleanProbes.get(cleanKey));
+ const racyFrom = BigInt(Date.now()) * 1_000_000n - WORKING_RACY_WINDOW_NS;
for (let start = 0; start < paths.length; start += batch) {
const decided = new Map<string, Dp | null>();
const read: ReadFile[] = [];
@@ -331,6 +342,11 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
let bytes: Buffer | null = null;
let unreadable = realRoot === null || realGitRoot === null;
const sourcePath = unreadable ? '' : relative(realRoot!, join(realGitRoot!, path)).split(sep).join('/');
+ const statKey = vouched && dp === null && !unreadable ? statAt(realGitRoot!, path) : null;
+ const prior = statKey && statKey !== ABSENT ? vouched!.get(path) : undefined;
+ const signature = `${statKey}|${committed?.oid}|${committed?.mode}|`;
+ if (prior?.startsWith(signature)) { results.set(path, { dp: 'clean', rawOid: committed!.oid, rawSha256: prior.slice(signature.length) }); continue; }
+ vouched?.delete(path);
if (!unreadable) { try { bytes = readSyncFile(root, sourcePath); } catch { unreadable = true; } }
if ((dp === null || opts.working) && !unreadable && bytes === null) dp = 'deleted';
const hashable = bytes !== null && !path.includes('\n') && !path.startsWith('"');
@@ -341,7 +357,7 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
let executable: boolean | null = null;
try { executable = (lstatSync(join(realRoot!, ...sourcePath.split('/'))).mode & 0o111) !== 0; } catch {}
const localOid = gitBlobOid(bytes, format);
- read.push({ path, sha256: sha256(bytes), localOid, size: bytes.length, executable,
+ read.push({ path, sha256: sha256(bytes), localOid, size: bytes.length, executable, statKey: statKey === ABSENT ? null : statKey,
foldedOid: bytes.includes('\r\n') ? gitBlobOid(foldCrlf(bytes), format) : localOid });
}
const undecided = read.filter(file => decided.get(file.path) === null).map(file => file.path);
@@ -357,7 +373,12 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
const attr = attrs?.get(file.path);
if (rawOid === null || attr === undefined || file.executable === null) { settle('unknown'); continue; }
const executableMatches = file.executable === (committed.mode === '100755');
- if (rawOid === committed.oid) { settle(executableMatches ? 'clean' : 'unknown'); continue; }
+ if (rawOid === committed.oid) {
+ settle(executableMatches ? 'clean' : 'unknown');
+ if (executableMatches && file.statKey && vouched!.size < WORKING_STAT_CACHE_MAX_ENTRIES && statAt(realGitRoot!, file.path) === file.statKey
+ && file.statKey.split(':').slice(5).every(ns => BigInt(ns) < racyFrom)) vouched!.set(file.path, `${file.statKey}|${committed.oid}|${committed.mode}|${file.sha256}`);
+ continue;
+ }
if (attributeSet(attr['working-tree-encoding']) || (attributeSet(attr.filter) && attr.filter !== 'lfs')) { settle('unknown'); continue; }
if (attr.filter === 'lfs') { lfs.push({ file, treeOid: committed.oid, executableMatches }); continue; }
const folds = file.foldedOid === committed.oid;
@@ -375,9 +396,17 @@ export async function probeDirtiness(root: string, gitRoot: string, paths: strin
results.set(file.path, { dp, rawOid: file.localOid, rawSha256: file.sha256 });
}
}
+ if (cleanKey !== null) {
+ cleanProbes.delete(cleanKey);
+ cleanProbes.set(cleanKey, vouched!);
+ while (cleanProbes.size > WORKING_STAT_CACHES_REMEMBERED) cleanProbes.delete(cleanProbes.keys().next().value!);
+ }
return results;
}
+/** Committed-mode `clean` probes this process vouched, by root and Git root: path -> `<stat key>|<tree oid>|<tree mode>|<sha256>`. */
+const cleanProbes = new Map<string, Map<string, string>>();
+
/** Raw blob ids (no filters) of present files, in order, or null when Git did not answer every path. */
async function hashRaw(gitRoot: string, paths: string[]): Promise<string[] | null> {
if (paths.length === 0) return [];
diff --git a/test/sync-probe-clean-reuse-7338.test.ts b/test/sync-probe-clean-reuse-7338.test.ts
new file mode 100644
index 0000000000..8981135562
--- /dev/null
+++ b/test/sync-probe-clean-reuse-7338.test.ts
@@ -0,0 +1,97 @@
+/**
+ * #7338: a managed pass probed every unrecorded legacy page on every pass, reading and hashing each one and running
+ * `hash-object` and `check-attr` over all of them, so a commit's latency grew with the pages the bounded legacy sweep had
+ * not recorded yet (the nightly freshness gate's managed cells). Committed mode now reuses a `clean` probe while the
+ * path's lstat key and tree entry are the ones it was vouched under, with the working stat cache's freshness contract:
+ * racy files are rehashed, an edit with a restored mtime is a change, a moved tree entry or a staged index entry is
+ * probed again.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { closeSync, mkdtempSync, openSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, writeSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { probeDirtiness, readIndexLevel, readTreeLevel } from '../src/core/persistence/sync-git-stream.ts';
+
+const dirs: string[] = [];
+afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });
+
+const GIT_ENV = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', env: GIT_ENV, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const blobOid = (content: string) => createHash('sha1').update(`blob ${Buffer.byteLength(content)}\0`).update(content).digest('hex');
+const sha256 = (content: string) => createHash('sha256').update(content).digest('hex');
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+/** Past the 2 s racy window, so a probe made now is vouched. */
+const RACY_WAIT_MS = 2_100;
+
+function repo(files: Record<string, string>): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-clean-reuse-'));
+ dirs.push(root);
+ git(root, 'init', '-q');
+ git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'user.name', 'Writer Example');
+ for (const [path, content] of Object.entries(files)) writeFileSync(join(root, path), content);
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', 'init');
+ return root;
+}
+
+async function probe(root: string, paths: string[]) {
+ return probeDirtiness(root, root, paths, await readTreeLevel(root, 'HEAD', ''), await readIndexLevel(root));
+}
+
+/** Runs `fn` with the repository's Git directory moved away, so any path probed again (attributes, raw OIDs) reads `unknown`. */
+async function withoutGit<T>(root: string, fn: () => Promise<T>): Promise<T> {
+ renameSync(join(root, '.git'), join(root, '.git-away'));
+ try { return await fn(); } finally { renameSync(join(root, '.git-away'), join(root, '.git')); }
+}
+
+describe('#7338: committed mode reuses a vouched clean probe', () => {
+ test('an unchanged clean file past the racy window is not read or hashed again', async () => {
+ const root = repo({ 'a.md': 'alpha\n', 'b.md': 'bravo\n' });
+ const tree = await readTreeLevel(root, 'HEAD', '');
+ const index = await readIndexLevel(root);
+ await sleep(RACY_WAIT_MS);
+ const first = await probeDirtiness(root, root, ['a.md', 'b.md'], tree, index);
+ expect(first.get('a.md')).toEqual({ dp: 'clean', rawOid: blobOid('alpha\n'), rawSha256: sha256('alpha\n') });
+ const again = await withoutGit(root, () => probeDirtiness(root, root, ['a.md', 'b.md'], tree, index));
+ expect(again.get('a.md')).toEqual({ dp: 'clean', rawOid: blobOid('alpha\n'), rawSha256: sha256('alpha\n') });
+ expect(again.get('b.md')).toEqual({ dp: 'clean', rawOid: blobOid('bravo\n'), rawSha256: sha256('bravo\n') });
+ }, 30_000);
+
+ test('a file probed inside the racy window is probed again', async () => {
+ const root = repo({ 'a.md': 'alpha\n' });
+ expect((await probe(root, ['a.md'])).get('a.md')?.dp).toBe('clean');
+ const tree = await readTreeLevel(root, 'HEAD', ''), index = await readIndexLevel(root);
+ expect((await withoutGit(root, () => probeDirtiness(root, root, ['a.md'], tree, index))).get('a.md')?.dp).toBe('unknown');
+ }, 30_000);
+
+ test('a same-inode, same-size edit with a restored mtime is a change', async () => {
+ const root = repo({ 'a.md': 'alpha one\n' });
+ const past = Math.floor(Date.now() / 1000) - 3600;
+ utimesSync(join(root, 'a.md'), past, past);
+ await sleep(RACY_WAIT_MS);
+ expect((await probe(root, ['a.md'])).get('a.md')?.dp).toBe('clean');
+ const before = statSync(join(root, 'a.md'), { bigint: true });
+ const fd = openSync(join(root, 'a.md'), 'r+');
+ try { writeSync(fd, 'alpha two\n', 0); } finally { closeSync(fd); }
+ utimesSync(join(root, 'a.md'), past, past);
+ const after = statSync(join(root, 'a.md'), { bigint: true });
+ expect([after.ino, after.size, after.mtimeNs]).toEqual([before.ino, before.size, before.mtimeNs]);
+ expect((await probe(root, ['a.md'])).get('a.md')).toEqual({ dp: 'modified', rawOid: blobOid('alpha two\n'), rawSha256: sha256('alpha two\n') });
+ }, 30_000);
+
+ test('a moved tree entry or a staged index entry is probed again', async () => {
+ const root = repo({ 'a.md': 'alpha\n' });
+ await sleep(RACY_WAIT_MS);
+ const tree = await readTreeLevel(root, 'HEAD', '');
+ expect((await probe(root, ['a.md'])).get('a.md')?.dp).toBe('clean');
+ const moved = new Map(tree);
+ moved.set('a.md', { ...tree.get('a.md')!, oid: blobOid('alpha moved\n') });
+ const index = new Map([...await readIndexLevel(root)].map(([path, entry]) => [path, { ...entry, oid: blobOid('alpha moved\n') }]));
+ expect((await probeDirtiness(root, root, ['a.md'], moved, index)).get('a.md')?.dp).toBe('modified');
+ const staged = new Map([...await readIndexLevel(root)].map(([path, entry]) => [path, { ...entry, oid: blobOid('alpha staged\n') }]));
+ expect((await probeDirtiness(root, root, ['a.md'], tree, staged)).get('a.md')?.dp).toBe('staged');
+ }, 30_000);
+});