Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b fix 1: one episode-closure walk per key within a pass run

garrytan46a86e0420da
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index bd1a5ee828..ec40d429d1 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -43,7 +43,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6712 PR 4b: the level's overlapping reads, which share one loop budget (sync-yield.ts `turnYield`): a Git chunk as its
// records are visited (`read`: ls-tree or ls-files; a synchronous hook), an `I⋈P` result in hand before the shared budget
// decides whether it waits a turn, and the same result right before its rows are taken.
- | 'sync:level_chunk' | 'sync:level_result' | 'sync:level_take'
+ | 'sync:level_chunk' | 'sync:level_result' | 'sync:level_take' | 'sync:closure_walk'
// #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook
// that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.
| 'sync:pass_fold'
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.ts
index 7be0c9d166..0d5b8b0f0e 100644
--- a/src/core/persistence/sync-pass-episode.ts
+++ b/src/core/persistence/sync-pass-episode.ts
@@ -22,6 +22,7 @@ import { isReservedSkillBundlePath } from '../skill-reserved-paths.ts';
import { isSyncable, matchesAnyGlob } from '../sync.ts';
import { parseUsdLimit } from '../spend-posture.ts';
import { digest } from './digest.ts';
+import { faultPointNow } from './fault-points.ts';
import { walkTreeLevel } from './sync-git-stream.ts';
import { SYNC_PASS_COST_OP, type PassEpisode, type SyncSelection } from './sync-pass-row.ts';
@@ -85,6 +86,7 @@ export async function passEpisodeClosure(input: { gitRoot: string; root: string;
const closure: ClosureInput = { episode: input.episode.selection, pass: input.pass, configuredSelection: input.configuredSelection, configured: input.configured, scope, slugMode: input.slugMode };
const tally: ClosureTally = { included: true, covers: true, released: 0 };
let stretch: string[] = [];
+ faultPointNow('sync:closure_walk', { path: input.head });
await walkTreeLevel(input.gitRoot, input.head, '', path => {
stretch.push(path);
if (stretch.length === CLOSURE_STRETCH) { tallyClosure(closure, stretch, tally); stretch = []; }
@@ -94,6 +96,19 @@ export async function passEpisodeClosure(input: { gitRoot: string; root: string;
}
const CLOSURE_STRETCH = 2_048;
+/**
+ * One pass run's closures: a stamp whose closure inputs (the pinned head, the slug mode, the episode's and the pass's
+ * selections, `configured` and the configured selection) match the last one's reuses its walk; any difference walks again.
+ */
+export function passClosureMemo(): typeof passEpisodeClosure {
+ let last: { key: string; closure: Promise<EpisodeClosure> } | null = null;
+ return input => {
+ const key = JSON.stringify([input.gitRoot, input.root, input.head, input.slugMode, input.episode.selection, input.pass, input.configured, input.configuredSelection]);
+ if (last?.key !== key) last = { key, closure: passEpisodeClosure(input) };
+ return last.closure;
+ };
+}
+
/** What a pass's admissions reserve under (registered at pin, dropped at the pass's end). */
interface PassCostScope { sourceId: string; incarnation: string; scope: string; pricePerMTok: number }
const passCostScopes = new Map<string, PassCostScope>();
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 04dd50886f..75ce629eac 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -56,7 +56,7 @@ import { originMarkerFingerprint } from './sync-markers.ts';
import { SYNC_SLICE_OP } from './sync-slices.ts';
import { passResumeArgs } from './sync-pass-readers.ts';
import { applyPassRound, finishPassApply, holdPassIdentities, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';
-import { passCostDecision, passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';
+import { passClosureMemo, passCostDecision, type passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';
import { currentEmbeddingPricePerMTok } from '../embedding.ts';
import { SIZE_STATE_SAMPLE, type SyncSizeStates } from '../page-embedding-budget.ts';
import { massReconcileAllowed } from '../sync-reconcile.ts';
@@ -539,10 +539,11 @@ function addCounts(counts: Record<string, number>, add: Record<string, number |
/** The pass stamp (design v3.2 §3.3): what its converged checkpoint publishes; closing the open episode counts what it released. */
async function passStampFor(engine: BrainEngine, input: { context: ManagedSyncContext; head: string; slugMode: Cursor['slugMode']; episode: PassEpisode | undefined; selection: SyncSelection;
configured: boolean; mode: SyncSelection['mode']; leaseToken: string; retry: string[]; level: ShadowLevel; selectionFp: string; parserFp: string; pack: string | null; full: boolean;
- counts: { added: number; modified: number; deleted: number; renamed: number; episodeReleased: number }; extract: boolean; since: string; rescreen: boolean }): Promise<PassStamp> {
+ counts: { added: number; modified: number; deleted: number; renamed: number; episodeReleased: number }; extract: boolean; since: string; rescreen: boolean;
+ closures: typeof passEpisodeClosure }): Promise<PassStamp> {
const { context, episode, configured, counts } = input;
// Design §6: an open episode closes by inclusion (a) or at the configured selection (b); chunker_version only by (b) over U_config.
- const closure = episode ? await passEpisodeClosure({ gitRoot: context.gitRoot, root: context.root, head: input.head, slugMode: input.slugMode, episode, pass: input.selection, configured,
+ const closure = episode ? await input.closures({ gitRoot: context.gitRoot, root: context.root, head: input.head, slugMode: input.slugMode, episode, pass: input.selection, configured,
configuredSelection: passSelection(await selectionPatterns(engine, { sourceId: context.sourceId } as SyncOpts), { sourceId: context.sourceId } as SyncOpts, context, input.mode) }) : null;
const closesEpisode = closure?.closes === true;
if (closure?.released) counts.episodeReleased = closure.released;
@@ -651,8 +652,9 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
// #6926, folded into 4b: the head a round's last import stamped, and what the pass had done by then.
let folded: { head: string; done: string } | null = null, batchFolded = false;
const doneKey = () => JSON.stringify([counts, passApplyCounts(applied)]);
+ const closures = passClosureMemo();
const stampFor = (level: ShadowLevel) => passStampFor(engine, { context, head, slugMode: levelSlugMode, episode, selection, configured, mode, leaseToken: lease.token, retry, level, selectionFp, parserFp,
- pack, full: kind === 'full', counts, extract: !processingOptions.noExtract, since: value.telemetry.started_at, rescreen: legacyWaived.size > 0 });
+ pack, full: kind === 'full', counts, extract: !processingOptions.noExtract, since: value.telemetry.started_at, rescreen: legacyWaived.size > 0, closures });
const save = async (outcome: PassOutcome, stopReason: string | null, pin = false) => {
const ended = outcome !== 'open';
diff --git a/test/e2e/sync-pass-closure-memo-6712-postgres.test.ts b/test/e2e/sync-pass-closure-memo-6712-postgres.test.ts
new file mode 100644
index 0000000000..6fa9b80dd2
--- /dev/null
+++ b/test/e2e/sync-pass-closure-memo-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-closure-memo-6712.test.ts'));
diff --git a/test/sync-pass-closure-memo-6712.test.ts b/test/sync-pass-closure-memo-6712.test.ts
new file mode 100644
index 0000000000..38899aa384
--- /dev/null
+++ b/test/sync-pass-closure-memo-6712.test.ts
@@ -0,0 +1,82 @@
+/**
+ * #6712 PR 4b fix 1: one pass run computes the episode closure (design §6) once per key (sync-pass-episode.ts
+ * `passClosureMemo`). A writeback round's fold offer and its checkpoint both stamp at the run's pinned head, so they share
+ * one `ls-tree` walk; any change to what the closure depends on walks again.
+ *
+ * Protects:
+ * - a writeback one-file commit (two stamps at the same head) walks the tree once (`sync:closure_walk`);
+ * - each closure input (head, slug mode, the episode's and the pass's selections, `configured`, the configured selection)
+ * is part of the key: changing any one walks again and returns what a fresh walk returns.
+ *
+ * PGLite here; Postgres through test/e2e/sync-pass-closure-memo-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, 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 { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { passClosureMemo, passEpisodeClosure } from '../src/core/persistence/sync-pass-episode.ts';
+import type { PassEpisode, SyncSelection } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ for (const slug of ['a', 'b']) writeFileSync(join(root, `notes/${slug}.md`), `---\ntype: concept\ntitle: notes/${slug}\n---\n\nThe body of notes/${slug}.\n`);
+ commit(root, 'notes');
+};
+const countWalks = () => { const seen = { walks: 0 }; installFaultHook(point => { if (point === 'sync:closure_walk') seen.walks++; }); return seen; };
+
+afterEach(() => installFaultHook(undefined));
+
+test('each closure input is part of the key: a change walks again and matches a fresh walk', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-closure-memo-'));
+ try {
+ mkdirSync(join(root, 'notes'), { recursive: true }); mkdirSync(join(root, 'drafts'), { recursive: true }); git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes/a.md'), 'a\n'); writeFileSync(join(root, 'drafts/b.md'), 'b\n'); commit(root, 'one');
+ const first = git(root, 'rev-parse', 'HEAD');
+ writeFileSync(join(root, 'drafts/c.md'), 'c\n'); commit(root, 'two');
+ const second = git(root, 'rev-parse', 'HEAD');
+ const all: SyncSelection = { exclude: [], includeHidden: [], strategy: null, srcSubpath: null, mode: 'committed' };
+ const noDrafts: SyncSelection = { ...all, exclude: ['drafts/**'] };
+ const episode = (selection: SyncSelection): PassEpisode => ({ opened_at: '2026-01-01T00:00:00Z', selection, inherited: { noEmbed: true, noExtract: true, noSchemaPack: false, from: 'flag' } });
+ const base = { gitRoot: root, root, head: first, slugMode: 'git-root' as 'git-root' | 'source-root', episode: episode(all), pass: all, configuredSelection: all, configured: false };
+ const steps: Array<[string, typeof base]> = [
+ ['same key', base], ['same key again', base],
+ ['head', { ...base, head: second }],
+ ['episode selection', { ...base, head: second, episode: episode(noDrafts) }],
+ ['pass selection', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts }],
+ ['configured selection', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts }],
+ ['configured', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts, configured: true }],
+ ['slug mode', { ...base, head: second, episode: episode(noDrafts), pass: noDrafts, configuredSelection: noDrafts, configured: true, slugMode: 'source-root' }],
+ ];
+ const memo = passClosureMemo(), seen = countWalks(), walks: Record<string, number> = {};
+ for (const [label, input] of steps) {
+ const before = seen.walks, closure = await memo(input);
+ walks[label] = seen.walks - before;
+ installFaultHook(undefined); const fresh = await passEpisodeClosure(input); installFaultHook(point => { if (point === 'sync:closure_walk') seen.walks++; });
+ expect({ label, closure }).toEqual({ label, closure: fresh });
+ }
+ expect(walks).toEqual({ 'same key': 1, 'same key again': 0, head: 1, 'episode selection': 1, 'pass selection': 1, 'configured selection': 1, configured: 1, 'slug mode': 1 });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ describe(`#6712 PR 4b episode closure memo (${backend})`, () => {
+ test('a writeback one-file commit stamps twice at one head and walks the tree once', () => managedBrain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical');
+ const seen = countWalks();
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ const [stamps] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent ? 'stamp' AND state='committed'");
+ expect(stamps!.n).toBeGreaterThanOrEqual(3);
+ expect(seen.walks).toBe(1);
+ }, { ...(databaseUrl ? { databaseUrl } : {}), setup }), 120_000);
+ });
+}