Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 1: pinned windows cover aligned manifest blocks; the prescreen's listing seeds the first window
garrytana06b824723ba
diff --git a/src/core/persistence/sync-blobs.ts b/src/core/persistence/sync-blobs.tsindex 16c0119dbf..670325757d 100644--- a/src/core/persistence/sync-blobs.ts+++ b/src/core/persistence/sync-blobs.ts@@ -92,6 +92,25 @@ export function __setPinnedWindowForTests(size: number | null): () => void {return () => { pinnedWindowSize = previous; pinned = null; };}+/**+ * The aligned block of manifest indexes whose committed imports one pinned window lists. Every entry of a block asks+ * for the same window, so concurrent follower freezes, which reach their pinned read in any order, never list it twice.+ */+export function pinnedWindowBlock(index: number): { start: number; end: number } {+ const start = pinnedWindowSize ? index - index % pinnedWindowSize : index;+ return { start, end: start + (pinnedWindowSize || PINNED_WINDOW) };+}++/**+ * #6712 PR 1: installs a window another reader already listed (the discovery prescreen's `ls-tree` of the frozen+ * manifest's first block), so the run's first pinned read does not list the same paths again.+ */+export function seedPinnedWindow(gitRoot: string, target: string, paths: string[], found: ReadonlyMap<string, TreeBlob>): void {+ if (!pinnedWindowSize || !COMMIT_ID.test(target) || !paths.length) return;+ const kept = paths.slice(0, pinnedWindowSize);+ pinned = { gitRoot, target, paths: kept, blobs: new Map(kept.map(path => [path, found.get(path) ?? null])), slices: null, loaded: [] };+}+function pinnedWindow(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]) {if (pinned?.gitRoot === gitRoot && pinned.target === target && pinned.blobs.has(gitPath)) return pinned;const paths = [gitPath, ...new Set(upcoming().filter(path => path !== gitPath))].slice(0, pinnedWindowSize);@@ -121,8 +140,8 @@ function windowSlices(window: PinnedWindow): number[] {/*** The blob of `gitPath` at the pinned `target`, or null when the commit has no* blob there: the answer of `readTreeBlobs` for that one path. `upcoming` lists- * the Git paths the run reads next; a path outside the current window lists- * itself and up to `PINNED_WINDOW` of them in one `ls-tree`.+ * the Git paths of the entry's aligned block (`pinnedWindowBlock`); a path+ * outside the current window lists itself and them in one `ls-tree`.*/export function readPinnedBlob(gitRoot: string, target: string, gitPath: string, upcoming: () => string[]): TreeBlob | null {const window = pinnedWindowSize && COMMIT_ID.test(target) ? pinnedWindow(gitRoot, target, gitPath, upcoming) : null;diff --git a/src/core/persistence/sync-prescreen.ts b/src/core/persistence/sync-prescreen.tsindex 23936347ee..39d3920846 100644--- a/src/core/persistence/sync-prescreen.ts+++ b/src/core/persistence/sync-prescreen.ts@@ -28,7 +28,7 @@ import type { BrainEngine } from '../engine.ts';import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';import { isKeepDbSlug, loadStorageConfig } from '../storage-config.ts';import { readSyncImportProvenances, syncImportParserFor, type SyncImportParser, type SyncImportProvenance } from './sync-holds.ts';-import { readTreeBlobs, type TreeBlob } from './sync-blobs.ts';+import { pinnedWindowBlock, readTreeBlobs, seedPinnedWindow, type TreeBlob } from './sync-blobs.ts';import { syncOriginPath } from './sync-origin.ts';import { liveFileDrift, recordDriftSkip } from './drift-conflicts.ts';import type { SyncDiscovery, SyncEntry } from './sync-discovery.ts';@@ -68,7 +68,11 @@ export async function prescreenSyncEntries(engine: BrainEngine, discovered: Syncif (!candidates.length) return;const nativeRoot = realpathSync.native(discovered.root), nativeGitRoot = realpathSync.native(discovered.gitRoot);const gitPathOf = (entry: SyncEntry) => relative(nativeGitRoot, join(nativeRoot, entry.path)).split(sep).join('/');- const blobs = readTreeBlobs(discovered.gitRoot, discovered.target, candidates.map(gitPathOf));+ // One listing answers the candidates and seeds the run's first pinned window (the manifest's first block of committed+ // imports), so the prescreen adds no `ls-tree` to the run.+ const block = pinnedWindowBlock(0), first = discovered.entries.slice(block.start, block.end).filter(entry => entry.action === 'import' && !entry.working).map(gitPathOf);+ const blobs = readTreeBlobs(discovered.gitRoot, discovered.target, [...new Set([...first, ...candidates.map(gitPathOf)])]);+ seedPinnedWindow(discovered.gitRoot, discovered.target, first, blobs);const records = new Map<number, SyncImportProvenance>();for (let i = 0; i < candidates.length; i += PROVENANCE_CHUNK) {const read = await readSyncImportProvenances(engine, discovered.sourceId, discovered.incarnation, candidates.slice(i, i + PROVENANCE_CHUNK).map(entry => Number(entry.pageId)));diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 6b0a4c5c21..6d9482fb48 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -29,7 +29,7 @@ import { VERSION } from '../../version.ts';import { sha256 } from './digest.ts';import { readPagePurgeTombstones } from './page-purge.ts';import { readSyncContent, readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from './sync-discovery.ts';-import { PINNED_WINDOW, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';+import { pinnedWindowBlock, readBlobBytes, readBlobContents, readPinnedBlob, readPinnedBytes, readPinnedContent, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';@@ -60,11 +60,11 @@ export function isSyncReadBound(error: unknown): boolean {type PinnedCursor = Pick<SyncDiscovery, 'root' | 'gitRoot' | 'target' | 'entries'> & { index: number };-/** Git paths of the committed imports from the cursor's entry on: the window one pinned read lists. */+/** Git paths of the committed imports in the cursor entry's aligned block (`pinnedWindowBlock`): the window one pinned read lists. */function upcomingGitPaths(cursor: PinnedCursor): () => string[] {return () => {- const gitRoot = realpathSync.native(cursor.gitRoot), root = realpathSync.native(cursor.root);- return cursor.entries.slice(cursor.index, cursor.index + PINNED_WINDOW).filter(entry => entry.action === 'import' && !entry.working)+ const gitRoot = realpathSync.native(cursor.gitRoot), root = realpathSync.native(cursor.root), block = pinnedWindowBlock(cursor.index);+ return cursor.entries.slice(block.start, block.end).filter(entry => entry.action === 'import' && !entry.working).map(entry => relative(gitRoot, resolve(root, entry.path)).split(sep).join('/'));};}diff --git a/test/managed-sync-pinned-reads.test.ts b/test/managed-sync-pinned-reads.test.tsindex 69dcda1c09..51d1907ba0 100644--- a/test/managed-sync-pinned-reads.test.ts+++ b/test/managed-sync-pinned-reads.test.ts@@ -31,6 +31,7 @@ import { performSync } from '../src/commands/sync/perform.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { __setPinnedWindowForTests } from '../src/core/persistence/sync-blobs.ts';import { syncGitTopLevel } from '../src/core/persistence/sync-prepare.ts';+import { pinnedBlob } from '../src/core/persistence/sync-screen.ts';import { withEnv } from './helpers/with-env.ts';import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';@@ -290,6 +291,63 @@ for (const [backend, open] of backends) {}, 600_000);}+/**+ * #6712 PR 1 (the forced probes for the windowed bound): the discovery prescreen's `ls-tree` seeds the run's first+ * pinned window, so a delta round over existing pages lists its pinned tree once; and the entries of one aligned block+ * share a window whichever of them reaches its pinned read first (concurrent follower freezes finish in any order).+ * Before: the prescreen listed the tree and the first freeze listed it again (2), and a follower whose freeze read first+ * started the window at its own index, so the head missed it and listed it again (2).+ */+for (const [backend, open] of backends) {+ test(`${backend}: a delta round over existing pages lists its pinned tree once (the prescreen seeds the window)`, async () => {+ if (backend === 'postgres' && !process.env.DATABASE_URL) return;+ const dir = join(home, `${backend}-seeded`), root = join(dir, 'repo');+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ const note = (i: number, body: string) => `---\ntitle: Seeded ${i}\ntype: note\n---\n${body}\n`;+ write(root, { ...Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`vault/notes/s${pad(i)}.md`, note(i, `A synthetic note ${i}.`)])), 'outside/readme.md': '# Not in the source\n' }); commit(root);+ const sourceRoot = join(root, 'vault');+ const { engine, close } = await open();+ const counter = gitCounter(dir);+ const restore = __setPinnedWindowForTests(null);+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), PATH: counter.path }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [SOURCE, sourceRoot]);+ await claimWorktree(engine, SOURCE, sourceRoot);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect((await performSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, drain: true })).status).toBe('first_sync');+ write(root, { ...Object.fromEntries([1, 2, 3].map(i => [`vault/notes/s${pad(i)}.md`, note(i, `An edited synthetic note ${i}.`)])), 'vault/notes/s006.md': note(6, 'A new synthetic note.') });+ commit(root);+ const before = counter.calls().length;+ const delta = await performSync(engine, { sourceId: SOURCE, noPull: true, noEmbed: true, drain: true });+ expect(delta).toMatchObject({ status: 'synced', added: 1, modified: 3 });+ expect(counter.calls().slice(before).filter(call => / ls-tree -l /.test(call))).toHaveLength(1);+ await disposePersistenceConsumer(engine);+ });+ } finally { restore(); await close(); }+ }, 120_000);+}++test('the entries of one aligned block share a pinned window whichever of them reads first', async () => {+ if (process.platform === 'win32') return;+ const dir = join(home, 'block'), root = join(dir, 'repo');+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ write(root, { ...Object.fromEntries(Array.from({ length: 5 }, (_, i) => [`vault/notes/b${pad(i)}.md`, `---\ntitle: Block ${i}\n---\nBody ${i}.\n`])), 'outside/readme.md': '# Not in the source\n' }); commit(root);+ const entries = Array.from({ length: 5 }, (_, i) => ({ path: `notes/b${pad(i)}.md`, sourcePath: `notes/b${pad(i)}.md`, action: 'import' as const, working: false }));+ const cursor = { root: join(root, 'vault'), gitRoot: root, target: git(root, 'rev-parse', 'HEAD'), entries };+ const counter = gitCounter(dir);+ const restore = __setPinnedWindowForTests(null);+ try {+ await withEnv({ PATH: counter.path }, async () => {+ // A follower (index 1) reaches its pinned read before the head (index 0), as concurrent follower freezes may.+ expect(pinnedBlob({ ...cursor, index: 1 }, entries[1]!.path)).not.toBeNull();+ expect(pinnedBlob({ ...cursor, index: 0 }, entries[0]!.path)).not.toBeNull();+ expect(pinnedBlob({ ...cursor, index: 4 }, entries[4]!.path)).not.toBeNull();+ });+ expect(counter.calls().filter(call => / ls-tree -l /.test(call))).toHaveLength(1);+ } finally { restore(); }+});+test('the Git top level is read once per root and run, and again when the checkout\'s .git changes', async () => {mkdirSync(join(home, 'top-level', 'a', 'b'), { recursive: true });const repo = realpathSync(join(home, 'top-level')), nested = join(repo, 'a', 'b');