Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: a kept tree listing's drop timer closes over only its entry, so a resident serve no longer keeps every pass it ran (#7358)
garrytan35ae85bdd5a9
diff --git a/src/core/persistence/sync-tree-reuse.ts b/src/core/persistence/sync-tree-reuse.tsindex 4dbbbfe701..b323ee658e 100644--- a/src/core/persistence/sync-tree-reuse.ts+++ b/src/core/persistence/sync-tree-reuse.ts@@ -25,6 +25,18 @@ const TREE_REUSE_MIN_DIFF_BOUND = 2_000;interface TreeReuseEntry { head: string; tree: Map<string, GitTreeEntry>; at: number; expiry: ReturnType<typeof setTimeout> }const entries = new Map<string, TreeReuseEntry>();+/**+ * #7358: the drop timer of a kept value, created here so its callback closes over only `map`, `key` and `value`. A timer made+ * inside the reading function closed over that function's scope (the previous entry and the pass's options, its loop yield+ * and through it the whole pass), and a cleared timer still holds its callback: every pass of a resident process stayed+ * reachable from the newest timer.+ */+function dropWhenIdle<V>(map: Map<string, { value?: unknown; tree?: unknown }>, key: string, field: 'value' | 'tree', value: V): ReturnType<typeof setTimeout> {+ const expiry = setTimeout(() => { if (map.get(key)?.[field] === value) map.delete(key); }, TREE_REUSE_MAX_AGE_MS);+ expiry.unref?.();+ return expiry;+}+export class LevelReuseMismatch extends Error {readonly code = 'level_reuse_mismatch';constructor(read: string, detail: string) { super(`sync level reuse: the reused ${read} differs from a whole read (${detail})`); this.name = 'LevelReuseMismatch'; }@@ -44,11 +56,7 @@ export async function readTreeLevelReusing(gitRoot: string, head: string, scope:const key = JSON.stringify([...opts.key, gitRoot, scope]);const prior = opts.allowed ? entries.get(key) : undefined;if (prior) { clearTimeout(prior.expiry); entries.delete(key); }- const keep = (tree: Map<string, GitTreeEntry>) => () => {- const expiry = setTimeout(() => { if (entries.get(key)?.tree === tree) entries.delete(key); }, TREE_REUSE_MAX_AGE_MS);- expiry.unref?.();- entries.set(key, { head, tree, at: Date.now(), expiry });- };+ const keep = (tree: Map<string, GitTreeEntry>) => () => { entries.set(key, { head, tree, at: Date.now(), expiry: dropWhenIdle(entries, key, 'tree', tree) }); };const whole = async () => { const tree = await readTreeLevel(gitRoot, head, scope, opts.shared); return { tree, reuse: 'read' as const, keep: opts.allowed ? keep(tree) : () => {} }; };if (!opts.allowed || !prior || Date.now() - prior.at > TREE_REUSE_MAX_AGE_MS || /[\\[*?]|^:/.test(scope)) return whole();let reuse: TreeReuse = 'same';@@ -86,9 +94,7 @@ export function keepPassPages<T extends object>(key: readonly string[], value: Tconst k = JSON.stringify(key);const prior = passPages.get(k);if (prior) clearTimeout(prior.expiry);- const expiry = setTimeout(() => { if (passPages.get(k)?.value === value) passPages.delete(k); }, TREE_REUSE_MAX_AGE_MS);- expiry.unref?.();- passPages.set(k, { value, at: Date.now(), expiry });+ passPages.set(k, { value, at: Date.now(), expiry: dropWhenIdle(passPages, k, 'value', value) });}export function takePassPages<T>(key: readonly string[]): T | undefined {const k = JSON.stringify(key), entry = passPages.get(k);diff --git a/test/sync-tree-reuse-gbra133.test.ts b/test/sync-tree-reuse-gbra133.test.tsindex 9fe8a6ade7..c04df62f22 100644--- a/test/sync-tree-reuse-gbra133.test.ts+++ b/test/sync-tree-reuse-gbra133.test.ts@@ -10,6 +10,9 @@* larger than the bound, a scope with pathspec magic and a missing commit all read whole.* - A managed pass on PGLite (and Postgres when DATABASE_URL is set) patches the listing on its next commit, imports* the same pages, and reads whole under `sync.level_reuse false`.+ * - #7358: a kept listing holds only its commit and tree. Its drop timer once closed over the reading function's scope+ * (the previous entry and the pass's options), and a cleared timer keeps its callback, so a resident serve kept every+ * pass it ran. Each read's loop yield and each managed pass's progress callback is collectable after the next pass.* Before: every pass listed the whole tree.*/import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from 'bun:test';@@ -21,6 +24,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { installFaultHook } from '../src/core/persistence/fault-points.ts';import { readTreeLevel, type GitTreeEntry } from '../src/core/persistence/sync-git-stream.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { loopYield } from '../src/core/persistence/sync-yield.ts';import { __resetTreeReuseForTests, LevelReuseMismatch, readTreeLevelReusing, TREE_REUSE_MAX_AGE_MS } from '../src/core/persistence/sync-tree-reuse.ts';import { managedBrain } from './helpers/managed-brain.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';@@ -121,6 +125,26 @@ describe('readTreeLevelReusing: T across passes', () => {expect((await pass('brain/bulk/b1*')).reuse).toBe('read');}, 120_000);+ test('#7358: a kept listing holds only its commit and tree; the options and loop yield of every earlier read are collectable', async () => {+ const refs: Array<WeakRef<object>> = [];+ const read = async () => {+ const shared = loopYield();+ refs.push(new WeakRef(shared));+ const got = await readTreeLevelReusing(root, git(root, 'rev-parse', 'HEAD'), 'brain', { key: KEY, allowed: true, shared });+ got.keep();+ return got.reuse;+ };+ expect(await read()).toBe('read');+ for (let i = 0; i < 3; i++) {+ writeFileSync(join(root, 'brain/notes/n12.md'), `collectable probe ${i}`);+ commit(root, `collectable probe ${i}`);+ expect(await read()).toBe('patched');+ }+ Bun.gc(true);+ // The newest may still be reachable from its own stream's timers until they fire; every earlier one must be gone.+ expect(refs.slice(0, -1).map(ref => ref.deref() === undefined)).toEqual([true, true, true]);+ });+test('the oracle: GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 throws when a kept listing differs from a whole read (forced probe)', async () => {await withEnv({ GBRAIN_SYNC_LEVEL_REUSE_VERIFY: '1' }, async () => {const first = await pass('brain');@@ -185,4 +209,22 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a managedexpect(reuse.at(-1)).toBe('patched');expect((await live(engine)).map(([slug]) => slug)).toEqual(['notes/a', 'notes/c', 'notes/d', 'notes/e']);}, { databaseUrl, setup })), 300_000);++ test('#7358: the kept listing holds none of its pass; every earlier pass of the process is collectable', () => managedBrain(async ({ engine, root }) => {+ const refs: Array<WeakRef<object>> = [];+ const sync = async () => {+ const onProgress = () => {};+ refs.push(new WeakRef(onProgress));+ return (await performManagedSync(engine, { ...OPTS, onProgress })).status;+ };+ expect(await sync()).toBe('first_sync');+ for (const name of ['a', 'b', 'c']) {+ writeFileSync(join(root, `notes/${name}.md`), note(name, `The edited body of ${name}.`));+ commit(root, `edit ${name}`);+ expect(await sync()).toBe('synced');+ }+ Bun.gc(true);+ // The newest may still be reachable from its own stream's timers until they fire; every earlier one must be gone.+ expect(refs.slice(0, -1).map(ref => ref.deref() === undefined)).toEqual([true, true, true]);+ }, { databaseUrl, setup }), 300_000);});