Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): memoize Git tree listings by object id in committed-delete origin checks (GBRA-135, re-port of #7228)

garrytanc805afc942b7
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 288837691b..240fe5c961 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -184,6 +184,32 @@ export function assertConfiguredSyncRoot(root: string, configuredRoot: string |
export function syncGitPath(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): string {
return relative(realpathSync.native(context.gitRoot), resolve(realpathSync.native(context.root), path)).split(sep).join('/');
}
+type SyncTreeItem = { mode: string; kind: string; object: string; name: string };
+const treeName = (name: string): string => process.platform === 'win32' ? name.toLowerCase() : name;
+/**
+ * GBRA-135: one Git tree's entries by name (case-folded on Windows), memoized by object id. A tree object never changes,
+ * so the freeze, the claim and the publish of every committed delete under one directory share one `git ls-tree`
+ * instead of spawning it three times per delete and level (10,000 deletes: about 30,000 spawns). Only a full object id
+ * is memoized (a ref name moves); the cache keeps the most recently used `SYNC_TREE_LISTING_CAP` trees.
+ */
+const SYNC_TREE_LISTING_CAP = 64;
+const syncTreeListings = new Map<string, Map<string, SyncTreeItem[]>>();
+function syncTreeListing(gitRoot: string, tree: string): Map<string, SyncTreeItem[]> {
+ const key = `${gitRoot}\0${tree}`;
+ const cached = syncTreeListings.get(key);
+ if (cached) { syncTreeListings.delete(key); syncTreeListings.set(key, cached); return cached; }
+ const listing = new Map<string, SyncTreeItem[]>();
+ for (const row of syncGit(gitRoot, ['ls-tree', '-z', tree]).split('\0').filter(Boolean)) {
+ const tab = row.indexOf('\t'), [mode, kind, object] = row.slice(0, tab).split(' ');
+ const item = { mode: mode!, kind: kind!, object: object!, name: row.slice(tab + 1) };
+ const name = treeName(item.name);
+ listing.set(name, [...(listing.get(name) ?? []), item]);
+ }
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(tree)) return listing;
+ syncTreeListings.set(key, listing);
+ if (syncTreeListings.size > SYNC_TREE_LISTING_CAP) syncTreeListings.delete(syncTreeListings.keys().next().value!);
+ return listing;
+}
export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target' | 'slugMode'>,
entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'action'> & { working?: boolean }): void {
const gitPath = syncGitPath(context, entry.path);
@@ -202,10 +228,7 @@ export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'git
let tree = context.target;
const parts = syncOriginPath(gitPath).split('/');
for (const [index, part] of parts.entries()) {
- const matches = syncGit(context.gitRoot, ['ls-tree', '-z', tree]).split('\0').filter(Boolean).map(row => {
- const tab = row.indexOf('\t'), [mode, kind, object] = row.slice(0, tab).split(' ');
- return { mode, kind, object, name: row.slice(tab + 1) };
- }).filter(item => item.name === part || process.platform === 'win32' && item.name.toLowerCase() === part.toLowerCase());
+ const matches = syncTreeListing(context.gitRoot, tree).get(treeName(part)) ?? [];
if (!matches.length) return;
// GBRA-133 S-22: a directory where the deleted file was (notes/a.md became notes/a.md/x.md) means the file origin is gone.
if (index === parts.length - 1 && matches.every(item => item.kind === 'tree')) return;
diff --git a/test/sync-origin-tree-listing-gbra135.test.ts b/test/sync-origin-tree-listing-gbra135.test.ts
new file mode 100644
index 0000000000..8a25cd188b
--- /dev/null
+++ b/test/sync-origin-tree-listing-gbra135.test.ts
@@ -0,0 +1,55 @@
+/**
+ * GBRA-135 x GBRA-133: `assertSyncEntryOrigin` proves a committed delete is gone from the pinned target by walking its
+ * path one `git ls-tree` per level. The freeze, the claim and the publish each run it, so 10,000 committed deletes in one
+ * directory spawned about 30,000 listings of the same immutable trees. Tree listings are memoized by object id: a pass
+ * lists each tree once. A `git` shim on PATH counts the listings over a real repository; the verdicts stay the same.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { assertSyncEntryOrigin } from '../src/core/persistence/sync-discovery.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+describe('GBRA-135: committed-delete origin checks list each Git tree once', () => {
+ let dir = '', repo = '', shim = '', log = '', target = '';
+ const git = (...args: string[]) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).trim();
+ beforeAll(() => {
+ dir = mkdtempSync(join(tmpdir(), 'gbra135-ls-tree-'));
+ repo = join(dir, 'repo'); shim = join(dir, 'bin'); log = join(dir, 'git.log');
+ mkdirSync(join(repo, 'notes', 'deep'), { recursive: true }); mkdirSync(shim);
+ git('init', '-q'); git('config', 'user.email', '[email protected]'); git('config', 'user.name', 'a');
+ for (let i = 0; i < 40; i++) writeFileSync(join(repo, 'notes', 'deep', `p${i}.md`), `# p${i}\n`);
+ writeFileSync(join(repo, 'notes', 'deep', 'kept.md'), '# kept\n');
+ git('add', '.'); git('commit', '-qm', 'one');
+ for (let i = 0; i < 40; i++) rmSync(join(repo, 'notes', 'deep', `p${i}.md`));
+ git('add', '-A'); git('commit', '-qm', 'delete');
+ target = git('rev-parse', 'HEAD');
+ const real = execFileSync('sh', ['-c', 'command -v git'], { encoding: 'utf8' }).trim();
+ writeFileSync(join(shim, 'git'), `#!/bin/sh\ncase " $* " in *" ls-tree "*) echo ls-tree >> '${log}';; esac\nexec '${real}' "$@"\n`);
+ chmodSync(join(shim, 'git'), 0o755);
+ });
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+ const listings = () => { try { return readFileSync(log, 'utf8').split('\n').filter(Boolean).length; } catch { return 0; } };
+
+ test('freeze, claim and publish of 40 deletes in one directory list its three trees once', async () => {
+ const context = { root: repo, gitRoot: repo, target, slugMode: 'git-root' as const };
+ await withEnv({ PATH: `${shim}:${process.env.PATH}` }, () => {
+ for (let pass = 0; pass < 3; pass++) for (let i = 0; i < 40; i++) {
+ const path = `notes/deep/p${i}.md`;
+ assertSyncEntryOrigin(context, { path, sourcePath: path, action: 'delete', working: false });
+ }
+ });
+ expect(listings()).toBe(3);
+ });
+
+ test('a path the target still holds is refused as before, from the memoized listing', async () => {
+ const context = { root: repo, gitRoot: repo, target, slugMode: 'git-root' as const };
+ await withEnv({ PATH: `${shim}:${process.env.PATH}` }, () => {
+ expect(() => assertSyncEntryOrigin(context, { path: 'notes/deep/kept.md', sourcePath: 'notes/deep/kept.md', action: 'delete', working: false }))
+ .toThrow('The pinned Git target still contains or aliases the origin selected for deletion.');
+ });
+ expect(listings()).toBe(3);
+ });
+});