Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: reuse I⋈P across passes, proven per round (sync.level_reuse)
garrytanbb60aa47ed8b
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex c1faebfe18..476012adb6 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -145,8 +145,19 @@ listing instead of listing the whole tree; it still judges every path. Anydoubt reads the tree whole: a new process, another source or incarnation, apass that failed before it walked the listing, a listing unused for 10minutes, a diff larger than a quarter of the tree (and over 2,000 paths), a-scope with pathspec characters, or a Git error. `gbrain config set-sync.level_reuse false` turns reuse off and every pass reads the whole tree;+scope with pathspec characters, or a Git error.++The same process also keeps the pages-and-import-records read (`I⋈P`) of its+last pass that ended synced. The next pass's first round proves, in its own+database snapshot, which page rows and import records changed since that read,+from any writer (a write still in flight at that read counts as changed), and+re-reads only those. It reads everything whole when the page or record counts+do not add up (a deletion leaves no other trace), when the changed pages pass a+quarter of the source (and 2,000), when the transaction-id span is too wide to+judge, when any statement fails, after a pass that did not end synced, or when+the kept read is older than 10 minutes. Holds, markers, open work and the Git+level are read every round as before. `gbrain config set+sync.level_reuse false` turns both off and every pass reads the whole tree and `I⋈P`;`true` or unset keeps it on. `GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also readsevery reused listing whole and fails the pass on any difference (tests and thenightly freshness cell use it).diff --git a/llms-full.txt b/llms-full.txtindex bd25ecbff0..7063db5458 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -6993,8 +6993,19 @@ listing instead of listing the whole tree; it still judges every path. Anydoubt reads the tree whole: a new process, another source or incarnation, apass that failed before it walked the listing, a listing unused for 10minutes, a diff larger than a quarter of the tree (and over 2,000 paths), a-scope with pathspec characters, or a Git error. `gbrain config set-sync.level_reuse false` turns reuse off and every pass reads the whole tree;+scope with pathspec characters, or a Git error.++The same process also keeps the pages-and-import-records read (`I⋈P`) of its+last pass that ended synced. The next pass's first round proves, in its own+database snapshot, which page rows and import records changed since that read,+from any writer (a write still in flight at that read counts as changed), and+re-reads only those. It reads everything whole when the page or record counts+do not add up (a deletion leaves no other trace), when the changed pages pass a+quarter of the source (and 2,000), when the transaction-id span is too wide to+judge, when any statement fails, after a pass that did not end synced, or when+the kept read is older than 10 minutes. Holds, markers, open work and the Git+level are read every round as before. `gbrain config set+sync.level_reuse false` turns both off and every pass reads the whole tree and `I⋈P`;`true` or unset keeps it on. `GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1` also readsevery reused listing whole and fails the pass on any difference (tests and thenightly freshness cell use it).diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex e1008a866c..fb3f42933a 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -100,7 +100,7 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect*//** `writeId` is the write request row: rows of a caller-bound replay share one `requestId` (crash-robot per-request seams key on the row). */export interface FaultDetail { requestId?: string; writeId?: string; effectId?: string; sourceId?: string; operation?: string | null; signal?: AbortSignal; slug?: string; path?: string;- round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number; narrow?: string } | null; reused?: number;+ round?: number; read?: string; level?: { statements: number; confirm: { taken: boolean; reason: string | null; rows: number; narrow?: string; across?: true } | null; reused?: number;/** `sync:level_read`: the level and the input it was read with (sync-pass.ts `readShadowLevel`), for probes that read it again. */shadow?: unknown; input?: unknown } }/** Postgres returns `persistence_effects.id` (bigserial) as a BigInt; `faultPoint` hands hooks its decimal string (#6584). */diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.tsindex eb0ad8dea8..f3e8439a37 100644--- a/src/core/persistence/sync-pass-confirm.ts+++ b/src/core/persistence/sync-pass-confirm.ts@@ -41,6 +41,14 @@* without S1's snapshot (a stamp frozen before it was recorded) judges by `xmin` alone. `age` and* the `txid_*` snapshot functions exist on every supported Postgres and on PGLite, where one connection leaves S1's list* empty. More than 2^31 xids between S1's `xmin` and S2's `xmax` takes the full read (`age` would wrap).+ *+ * Across passes (GBRA-133 wave 4, `across`; GBRA-108 widened Q4 under the same standing approval): the next pass's first round+ * reuses the `I⋈P` of the last round of a pass that ended synced in the same process (sync-tree-reuse.ts), with S1 that round's+ * mark. Nothing is attributed: every `pages` row S1 does not prove unchanged, from any writer, and the page of every import+ * record S1 does not prove unchanged are re-read, and the count of pages with an origin and the count of import records+ * must equal what the patched table accounts for (a deletion leaves no `xmin`). Only `I⋈P` is reused: holds, markers, open+ * work, the pass row, `A` and the Git level are read as every round reads them, and the round keeps no classification or+ * domain from the last pass. The visibility arms, the xid span bound and the full read on any failed statement are the same.*/import { GIT_HOLD_OP, GIT_HOLD_RETRY_OP, GIT_HOLD_SUMMARY_OP, SYNC_IMPORT_PROVENANCE_OP } from './sync-holds.ts';import { MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';@@ -134,14 +142,14 @@ async function parallelProof(exec: Exec, sourceId: string, params: unknown[]): P* What the pass may reuse: the pages it wrote since S1 (`pages`, by id), which of them changed their import record* (`records`), the source's count of pages with an origin, and S2's mark for the next round; or why the full read.*/-export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; records: Set<string>; pageCount: number; summary: boolean } | { ok: false; reason: string; mark: LevelMark | null };+export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; records: Set<string>; pageCount: number; summary: boolean; across?: true } | { ok: false; reason: string; mark: LevelMark | null };/*** Proves, in S2 (the round's snapshot), that every change since `base` (S1) to what the level read consumes is the pass's* own write (see the header). The counts still need the reused rows: `countsMatch` checks them after the delta read.*/export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number>; postgres: boolean;- parallel?: boolean; self?: string }): Promise<ConfirmProof> {+ parallel?: boolean; self?: string; across?: boolean }): Promise<ConfirmProof> {const scope = `${input.sourceId}:${input.incarnation}`;const params = [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null, input.base.snapshot ?? null, input.base.own ?? null];// Two plain scans: compiling them (JIT, which the planner's cost picks at 600k) cost more than running them (about 200 ms).@@ -151,6 +159,12 @@ export async function proveConfirm(exec: Exec, input: { sourceId: string; incarnawait jit;const mark: LevelMark = { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds, snapshot: row!.snapshot, own: row!.own };if (!(Number(row!.span) >= 0 && Number(row!.span) < 2 ** 31)) return { ok: false, reason: 'xid_span', mark };+ if (input.across) {+ // Across passes nothing is attributed: every changed page, and the page of every changed import record, is re-read.+ const records = new Set(row!.ops_changed.filter(([op, fingerprint]) => op === SYNC_IMPORT_PROVENANCE_OP && fingerprint.startsWith(`${scope}:`))+ .map(([, fingerprint]) => fingerprint.slice(scope.length + 1)));+ return { ok: true, mark, pages: [...new Set([...row!.pages_changed.map(([id]) => id), ...records])], records, pageCount: Number(row!.pages), summary: false, across: true };+ }const revisions = new Map<string, string>();for (const [id, ours, revision] of row!.pages_changed) {if (!ours) return { ok: false, reason: 'foreign_page_write', mark };@@ -179,13 +193,13 @@ export async function proveConfirm(exec: Exec, input: { sourceId: string; incarn/*** The counts S2 must show: the reused rows plus the new pages the delta read (`pages`), and S1's op counts plus the import* records the pass inserted (`newRecords`), its pass row if S1 had none and the hold summary its holds created. Anything else- * (a deletion) is a mismatch.+ * (a deletion) is a mismatch. Across passes only the pages and the import records count: nothing else is reused.*/export function countsMatch(base: LevelMark, proof: Extract<ConfirmProof, { ok: true }>, added: { pages: number; newRecords: number }): boolean {if (proof.pageCount !== added.pages) return false;for (const op of CONFIRM_OPS) {const before = base.ops[op] ?? 0, after = proof.mark.ops[op] ?? 0;- if (op === GIT_HOLD_OP) continue;+ if (op === GIT_HOLD_OP || proof.across && op !== SYNC_IMPORT_PROVENANCE_OP) continue;// The pass row, and the hold summary a hold of the pass created, may be new.const created = before === 0 && after === 1 && (op === MANAGED_SYNC_PASS_OP || op === GIT_HOLD_SUMMARY_OP && proof.summary);if (op === SYNC_IMPORT_PROVENANCE_OP ? after !== before + added.newRecords : after !== before && !created) return false;diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 24ec8f1281..f58200784b 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -53,6 +53,7 @@ import { pipelined } from '../page-state/transactions.ts';import { principalAttribution } from './attribution.ts';import { isCodeFilePath, readMetafilePagesMode, resolveSlugForPath } from '../sync.ts';import { readPassSwitches } from './sync-held-deletions.ts';+import { keepPassPages, takePassPages } from './sync-tree-reuse.ts';import { syncOriginPath } from './sync-origin.ts';import { databaseOnlyPageSql } from './unbound-pages.ts';import { originMarkerFingerprint } from './sync-markers.ts';@@ -666,6 +667,16 @@ async function pinPassRow(engine: BrainEngine, value: ManagedSyncPassValue, inpu}}+/**+ * The pass's level cache: its next round at the same commit reuses the tree; it dies with the pass. With `sync.level_reuse` its+ * first round starts from the `I⋈P` of this process's last pass of the source that ended synced (sync-tree-reuse.ts; taken+ * either way, so off drops it), and a synced end keeps its own.+ */+function openPassLevelCache(sourceId: string, incarnation: string, levelReuse: boolean): PassLevelCache {+ const kept = takePassPages<NonNullable<PassLevelCache['pages']>>([sourceId, incarnation]);+ return { pages: levelReuse ? kept : undefined };+}+/** Design §7 (v3 §7): whether this batch crossed the approved envelope, which defers embeddings for the rest of the pass. */async function envelopeCrossed(engine: BrainEngine, value: ManagedSyncPassValue, costScope: string, processingOptions: SyncProcessingOptions): Promise<boolean> {const envelope = value.obligations.cost;@@ -784,10 +795,12 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr}return await consumeRetry(entries.slice(0, drained.managedCursor?.index ?? 0).map(entry => entry.path)).then(() => drained);};+ const levelCache = openPassLevelCache(sourceId, incarnation, levelReuse);/** The pass ended on its stamp; a folded one (sync-pass-fold.ts) saves the round's telemetry beside the obligations it wrote. */const synced = async (onFold: boolean): Promise<SyncResult> => {if (onFold) await save('synced', configured ? null : 'selection_scoped');rememberLevel();+ if (levelReuse && levelCache.pages) keepPassPages([sourceId, incarnation], { ...levelCache.pages, key: levelCache.pages.acrossKey, across: true });await clearPassFailures(engine, sourceId, incarnation);await finishPassApply(engine, sourceId, applied);return result(configured && context.source.last_commit === null ? 'first_sync' : 'synced', configured ? undefined : 'selection_scoped');@@ -825,8 +838,6 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prconst drained = await input.drainBatch(`${PASS_BATCH_KEY_PREFIX}${passId}:${batchNo++}`, replay, sliceBase);if (!('entries' in drained)) return await stop(drained);}- // The pass's level cache: its next round at the same commit reuses the tree; it dies with the pass.- const levelCache: PassLevelCache = {};for (let round = 1; round <= PASS_MAX_ROUNDS; round++) {assertActive();value.telemetry.round = round;diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex b7c2b71aaf..5671375d82 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -38,7 +38,7 @@ import { movedDriftHolds, sameParser } from './sync-prescreen.ts';import { sameSyncOrigin, selectOriginClaimant, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexDelta, readIndexLevel, readTreeLevel, workingChanged, type GitIndexEntry, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';import { readOriginEvidence } from './sync-origin-evidence.ts';-import { readTreeLevelReusing, type TreeReuse } from './sync-tree-reuse.ts';+import { levelReuseVerify, readTreeLevelReusing, reportLevelReuseCheck, type TreeReuse } from './sync-tree-reuse.ts';import { classifySyncPath, syncPassKind, type SyncClassified, type SyncIdleBlocker, type SyncPathState } from './sync-classify.ts';import { buildConvergenceReceipt, readOnlySameContentScreen, type ConvergenceReceipt, type ConvergenceScreen } from './sync-convergence.ts';import { readManagedMode } from './ownership.ts';@@ -99,8 +99,11 @@ const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];/** What one pass reuses between its rounds: a commit's tree never changes, so the next round at the same commit and selection reads it from here. */export interface PassLevelCache {tree?: { key: string; tree: Map<string, GitTreeEntry>; colon: string[] };- /** The last committed-mode round's `I⋈P` and its mark (S1), keyed by source, incarnation, worktree, HEAD and expected parser. */- pages?: { key: string; mark: LevelMark; table: PageTable };+ /**+ * The last committed-mode round's `I⋈P` and its mark (S1), keyed by source, incarnation, worktree, HEAD and expected parser;+ * `across`: the last pass's, kept by its process (sync-tree-reuse.ts), keyed without HEAD (`acrossKey`).+ */+ pages?: { key: string; acrossKey: string; mark: LevelMark; table: PageTable; across?: true };/** The last committed-mode round's classified paths, keyed by every level-wide input the classifier reads (`classifiedKey`). */classified?: { key: string; treeKey: string; paths: ShadowPath[] };/** The last committed-mode round's origin domain, which a taken confirm round at its tree patches (sync-pass-narrow.ts). */@@ -274,7 +277,7 @@ export interface ShadowLevel {timings_ms: Record<string, number>;statements: number;/** A round after a pass's first: whether it reused the previous round's `I⋈P` (`rows` re-read), or why it read it whole. */- confirm?: { taken: boolean; reason: string | null; rows: number;+ confirm?: { taken: boolean; reason: string | null; rows: number; across?: true;/** A taken confirm round: `taken` when it patched the previous round's domain and classification, else why it built them whole. */narrow?: string };/** A taken confirm round: the paths whose previous-round classification it kept (`reusableMatched`). */@@ -953,15 +956,17 @@ const confirmGuard = <T>(read: Promise<T>) => read.catch((error: unknown) => { tasync function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; worktreeId: string; parser: SyncImportParser; step: LoopYield;reuse?: { cache: PassLevelCache; passId: string; recorded?: ReadonlySet<number>; working: boolean; head: string } }, timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {const { kind, sourceId, incarnation, worktreeId, reuse } = input;- // Reused only at the same commit, worktree and parser, in committed mode: working mode always reads `I⋈P` whole.- const key = JSON.stringify([sourceId, incarnation, worktreeId, reuse?.head, input.parser]);- const unkeyed = reuse?.cache.pages && (reuse.working || reuse.cache.pages.key !== key) ? { taken: false, reason: reuse.working ? 'working' : 'key', rows: 0 } : undefined;+ // Reused only at the same commit (a pass's own rounds; across passes any), worktree and parser, in committed mode: working mode always reads `I⋈P` whole.+ const key = JSON.stringify([sourceId, incarnation, worktreeId, reuse?.head, input.parser]), acrossKey = JSON.stringify([sourceId, incarnation, worktreeId, input.parser]);+ const cached = reuse?.cache.pages, across = cached?.across;+ const unkeyed = cached && (reuse!.working || cached.key !== (across ? acrossKey : key)) ? { taken: false, reason: reuse!.working ? 'working' : 'key', rows: 0, ...(across ? { across } : {}) } : undefined;let prior = reuse && !unkeyed ? reuse.cache.pages : undefined;const confirming = prior !== undefined;if (reuse) reuse.cache.pages = undefined;const round = (marking: boolean) => withRoundSnapshot(engine, async exec => {const base = marking ? prior?.mark : undefined;- const proof = base ? confirmGuard(timed('confirm', () => proveConfirm(exec, { sourceId, incarnation, passId: reuse!.passId, base, recorded: reuse!.recorded, postgres: kind === 'postgres', parallel: true }))) : null;+ const proof = base ? confirmGuard(timed('confirm', () => proveConfirm(exec, { sourceId, incarnation, passId: reuse!.passId, base, recorded: reuse!.recorded, postgres: kind === 'postgres', parallel: true,+ ...(across ? { across } : {}) }))) : null;const marked = marking && !base ? confirmGuard(readLevelMark(exec, sourceId, incarnation)) : null;// PGLite has no snapshot: the mark (or the proof, the next round's mark) runs before the reads it vouches for.if (kind === 'pglite') await (proof ?? marked)?.catch(() => undefined);@@ -974,8 +979,9 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'// A failed mark fails what was pipelined after it: the mark's failure is the one to report.const read = confirmed?.read ?? await timed('pages', () => readPages(exec, kind, sourceId, incarnation, input.parser, undefined, input.step)).catch(async (error: unknown) => { await marked; throw error; });const mark = confirmed?.mark ?? (marked ? await marked : null);+ if (confirmed?.read && levelReuseVerify()) await verifyReusedPages(exec, { kind, sourceId, incarnation, parser: input.parser, table: confirmed.read.pages, how: across ? 'across passes' : 'in a pass' });const [work, markers, passRow] = await others;- if (reuse && mark) reuse.cache.pages = { key, mark, table: read!.pages };+ if (reuse && mark) reuse.cache.pages = { key, acrossKey, mark, table: read!.pages };const confirm = confirmed?.confirm ?? unkeyed;return { pages: read!.pages, open: work, markers, passRow, statements: read!.statements + work.statements + 2 + (marked ? 1 : proof ? (kind === 'postgres' ? 6 : 1) : 0), ...(confirm ? { confirm } : {}),...(confirmed?.read ? { changed: confirmed.changed } : {}) };@@ -984,7 +990,7 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'try { return await round(true); } catch (error) {if (!(error instanceof ConfirmFailure)) throw error;prior = undefined;- return { ...await round(false), ...(confirming ? { confirm: { taken: false, reason: 'error', rows: 0 } } : {}) };+ return { ...await round(false), ...(confirming ? { confirm: { taken: false, reason: 'error', rows: 0, ...(across ? { across } : {}) } } : {}) };}}@@ -993,10 +999,27 @@ async function readRoundSnapshot(engine: BrainEngine, input: { kind: 'postgres'* re-read into them, when the counts then account for every row (no deletion); else `read: null` and the caller reads* whole. Either way S2's mark is the next round's.*/+/** Pages a cross-pass delta may re-read whatever the table's size. */+const LEVEL_REUSE_DELTA_MIN = 2_000;++/** GBRAIN_SYNC_LEVEL_REUSE_VERIFY: the reused `I⋈P` against a whole read in the same snapshot, page by page (sync-tree-reuse.ts). */+async function verifyReusedPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; parser: SyncImportParser; table: PageTable; how: string }): Promise<void> {+ const whole = (await readPages(exec, input.kind, input.sourceId, input.incarnation, input.parser))!.pages;+ const rows = (table: PageTable) => new Map(Array.from({ length: table.length }, (_, i) => {+ const { arm1: _a, attested_hash: _h, ...row } = table.row(i);+ return [String(row.id), JSON.stringify(row)] as const;+ }));+ const reused = rows(input.table), fresh = rows(whole);+ reportLevelReuseCheck('I⋈P', input.how, reused.size !== fresh.size ? `${reused.size} pages, whole read ${fresh.size}`+ : [...fresh].find(([id, row]) => reused.get(id) !== row)?.[0]);+}+async function confirmPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; sourceId: string; incarnation: string; parser: SyncImportParser;prior: NonNullable<PassLevelCache['pages']>; proof: Promise<ConfirmProof> }, timed: <T>(key: string, read: () => Promise<T>) => Promise<T>) {- const proof = await input.proof, { table } = input.prior;- if (!proof.ok) return { read: null, mark: proof.mark, confirm: { taken: false, reason: proof.reason, rows: 0 } };+ const proof = await input.proof, { table } = input.prior, across = input.prior.across ? { across: input.prior.across } : {};+ if (!proof.ok) return { read: null, mark: proof.mark, confirm: { taken: false, reason: proof.reason, rows: 0, ...across } };+ // Across passes a delta past a quarter of the table (and LEVEL_REUSE_DELTA_MIN pages) reads whole: cheaper, and no larger a risk.+ if (proof.across && proof.pages.length > Math.max(LEVEL_REUSE_DELTA_MIN, table.length / 4)) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'delta_large', rows: 0, ...across } };const want = new Set(proof.pages), slots = new Map<string, number>();const step = loopYield();for (let i = 0; i < table.length && slots.size < want.size; i++) {@@ -1011,9 +1034,9 @@ async function confirmPages(exec: Exec, input: { kind: 'postgres' | 'pglite'; soconst changed = { rewritten: [...slots.values()].map(slot => ({ slot, sourcePath: table.sourcePath[slot]!, slug: table.slug[slot]! })), from: table.length };const read = proof.pages.length ? await confirmGuard(timed('pages', () => readPages(exec, input.kind, input.sourceId, input.incarnation, input.parser, { table, ids: proof.pages, slots }))): { pages: table, statements: 0 };- if (!read) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'page_left_level', rows: 0 } };- if (!countsMatch(input.prior.mark, proof, { pages: read.pages.length, newRecords })) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'counts', rows: 0 } };- return { read, mark: proof.mark, confirm: { taken: true, reason: null, rows: proof.pages.length }, changed };+ if (!read) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'page_left_level', rows: 0, ...across } };+ if (!countsMatch(input.prior.mark, proof, { pages: read.pages.length, newRecords })) return { read: null, mark: proof.mark, confirm: { taken: false, reason: 'counts', rows: 0, ...across } };+ return { read, mark: proof.mark, confirm: { taken: true, reason: null, rows: proof.pages.length, ...across }, changed };}/**diff --git a/src/core/persistence/sync-tree-reuse.ts b/src/core/persistence/sync-tree-reuse.tsindex 3562504000..4dbbbfe701 100644--- a/src/core/persistence/sync-tree-reuse.ts+++ b/src/core/persistence/sync-tree-reuse.ts@@ -58,20 +58,49 @@ export async function readTreeLevelReusing(gitRoot: string, head: string, scope:for (const { path, entry } of changes) { if (entry) prior.tree.set(path, entry); else prior.tree.delete(path); }reuse = 'patched';}- if (process.env.GBRAIN_SYNC_LEVEL_REUSE_VERIFY === '1') {+ if (levelReuseVerify()) {const fresh = await readTreeLevel(gitRoot, head, scope, opts.shared);- const differs = fresh.size !== prior.tree.size ? `${prior.tree.size} paths, whole read ${fresh.size}`- : [...fresh].find(([path, entry]) => { const own = prior.tree.get(path); return own?.oid !== entry.oid || own.mode !== entry.mode; })?.[0];- // One stderr line per check, so the nightly oracle cell can count them in the serve's log.- const verdict = differs ? new LevelReuseMismatch('T', `${reuse} from ${prior.head} to ${head}: ${differs}`) : null;- console.error(verdict ? `[level_reuse] level_reuse_mismatch ${verdict.message}` : `[level_reuse] level_reuse_verified T ${reuse} at ${head}`);- if (verdict) throw verdict;+ reportLevelReuseCheck('T', `${reuse} from ${prior.head} to ${head}`, fresh.size !== prior.tree.size ? `${prior.tree.size} paths, whole read ${fresh.size}`+ : [...fresh].find(([path, entry]) => { const own = prior.tree.get(path); return own?.oid !== entry.oid || own.mode !== entry.mode; })?.[0]);}return { tree: prior.tree, reuse, keep: keep(prior.tree) };}-/** Drops every kept listing (tests). */+/** Whether every reused level read is compared with a whole read (tests and the nightly oracle cell). */+export const levelReuseVerify = (): boolean => process.env.GBRAIN_SYNC_LEVEL_REUSE_VERIFY === '1';++/** One `[level_reuse]` stderr line per verified read (the nightly oracle counts them); a difference throws. */+export function reportLevelReuseCheck(read: string, how: string, differs: string | null | undefined): void {+ const verdict = differs ? new LevelReuseMismatch(read, `${how}: ${differs}`) : null;+ console.error(verdict ? `[level_reuse] level_reuse_mismatch ${verdict.message}` : `[level_reuse] level_reuse_verified ${read} ${how}`);+ if (verdict) throw verdict;+}++/**+ * `I⋈P` across passes (sync-pass.ts `readRoundSnapshot`): the pages table and mark (S1) of a pass that ended synced, for the next+ * pass's first round to prove and patch (sync-pass-confirm.ts, `across`). Same rules as a listing: taken while used, dropped+ * when unused for TREE_REUSE_MAX_AGE_MS, keyed by source and incarnation.+ */+const passPages = new Map<string, { value: unknown; at: number; expiry: ReturnType<typeof setTimeout> }>();+export function keepPassPages<T extends object>(key: readonly string[], value: T): void {+ const 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 });+}+export function takePassPages<T>(key: readonly string[]): T | undefined {+ const k = JSON.stringify(key), entry = passPages.get(k);+ if (!entry) return undefined;+ clearTimeout(entry.expiry);+ passPages.delete(k);+ return Date.now() - entry.at > TREE_REUSE_MAX_AGE_MS ? undefined : entry.value as T;+}++/** Drops every kept listing and pages table (tests). */export function __resetTreeReuseForTests(): void {- for (const entry of entries.values()) clearTimeout(entry.expiry);+ for (const entry of [...entries.values(), ...passPages.values()]) clearTimeout(entry.expiry);entries.clear();+ passPages.clear();}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 7c8c5b31f4..3e79f1bf9e 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -451,6 +451,7 @@ test/sync-legacy-holds.test.tstest/sync-legacy-retry-actions-6696.test.tstest/sync-legacy-slug-adoption-6727.test.tstest/sync-legacy-sweep-resume-7189.test.ts+test/sync-level-reuse-across-gbra133.test.tstest/sync-metafile-foreign-slug-7341.test.tstest/sync-origin-live-wins-6517.test.tstest/sync-page-identity-hold-gbra130.test.tsdiff --git a/test/sync-level-reuse-across-gbra133.test.ts b/test/sync-level-reuse-across-gbra133.test.tsnew file mode 100644index 0000000000..ec5d68de95--- /dev/null+++ b/test/sync-level-reuse-across-gbra133.test.ts@@ -0,0 +1,156 @@+/**+ * GBRA-133 wave 4: `I⋈P` across passes (GBRA-108's conditions). A pass that ends synced keeps its last round's pages+ * table and mark (S1) in its process; the next pass's first round proves, in its own snapshot, which pages and import+ * records changed since S1, from any writer, re-reads only those, and checks the page and record counts.+ * - Equivalence oracle (GBRAIN_SYNC_LEVEL_REUSE_VERIFY=1 on every test): each reused table is compared with a whole read+ * in the same snapshot and a difference fails the pass.+ * - Taken: a commit, and a page written by another writer between passes, are re-read; the level matches.+ * - Forced probes: a writer in another session in flight at S1 and committed before the next pass (Postgres: one+ * connection cannot have one on PGLite) is re-read; a page deleted outside any write path, caught only by the count,+ * reads whole (`counts`); a restart (a new process: nothing kept), a failed pass and `sync.level_reuse false` read whole.+ * Before: every pass's first round read `I⋈P` whole.+ * Real PGLite (and Postgres when DATABASE_URL is set), real managed syncs and real Git.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { __resetTreeReuseForTests } from '../src/core/persistence/sync-tree-reuse.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]',+ '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+type Confirm = { taken: boolean; reason: string | null; rows: number; across?: true } | null;++afterEach(() => { installFaultHook(undefined); __resetTreeReuseForTests(); });++for (const backend of testBackends()) describe(`[${backend}] GBRA-133: I⋈P across passes`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ let url: string | undefined;+ const open = databaseUrl ? async () => { const pg = await isolatedPersistencePostgres(databaseUrl); url = pg.databaseUrl; return pg; } : undefined;+ const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${name}.md`), note(name, `The body of ${name}.`));+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'notes');+ };+ /** Each sync's first-round confirm (null: no reuse attempted). */+ const firstRounds = (): Confirm[] => {+ const seen: Confirm[] = [];+ installFaultHook((point, detail) => { if (point === 'sync:level_read' && detail.round === 1) seen.push(detail.level?.confirm ?? null); });+ return seen;+ };+ const edit = (root: string, name: string, body: string) => { writeFileSync(join(root, `notes/${name}.md`), note(name, body)); git(root, 'add', '-A'); git(root, 'commit', '-qm', `edit ${name}`); };+ const coordinated = (engine: BrainEngine, sql: string, params: unknown[] = []) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(sql, params), TEST_WRITE_ATTRIBUTION));+ const titles = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string; title: string }>(+ "SELECT slug, title FROM pages WHERE source_id='default' AND deleted_at IS NULL AND slug LIKE 'notes/%' ORDER BY slug")).map(row => `${row.slug}=${row.title}`);+ const brain = (run: Parameters<typeof managedBrain>[0]) => withEnv({ GBRAIN_SYNC_LEVEL_REUSE_VERIFY: '1' }, () => managedBrain(run, { databaseUrl, ...(open ? { open } : {}), setup }));++ test('the next pass patches the last pass\'s I⋈P: a commit and another writer\'s page are re-read', () => brain(async ({ engine, root }) => {+ const seen = firstRounds();+ await performManagedSync(engine, OPTS);+ edit(root, 'a', 'The edited body of a.');+ await performManagedSync(engine, OPTS);+ expect(seen.at(-1)).toMatchObject({ taken: true, across: true });+ // Another writer between passes: a page row the pass did not write.+ await coordinated(engine, "UPDATE pages SET title = 'Retitled b', knowledge_revision = $1::uuid WHERE source_id='default' AND slug='notes/b'", [randomUUID()]);+ edit(root, 'c', 'The edited body of c.');+ await performManagedSync(engine, OPTS);+ expect(seen.at(-1)).toMatchObject({ taken: true, across: true });+ expect(seen.at(-1)!.rows).toBeGreaterThanOrEqual(1);+ expect(await titles(engine)).toContain('notes/b=Retitled b');+ }), 300_000);++ test('a page deleted outside any write path is caught by the count alone and reads whole', () => brain(async ({ engine, root }) => {+ const seen = firstRounds();+ await performManagedSync(engine, OPTS);+ edit(root, 'a', 'Edited once.');+ await performManagedSync(engine, OPTS);+ // No row of the source changes: the deleted row leaves no xmin, only the count moves.+ await coordinated(engine, "DELETE FROM pages WHERE source_id='default' AND slug='notes/b'");+ edit(root, 'c', 'Edited once.');+ await performManagedSync(engine, OPTS);+ expect(seen.at(-1)).toMatchObject({ taken: false, reason: 'counts', across: true });+ }), 300_000);++ test('a restart, a failed pass and sync.level_reuse false read whole', () => brain(async ({ engine, root }) => {+ const seen = firstRounds();+ await performManagedSync(engine, OPTS);+ // A restart: a new process keeps nothing.+ __resetTreeReuseForTests();+ edit(root, 'a', 'After a restart.');+ await performManagedSync(engine, OPTS);+ expect(seen.at(-1)).toBeNull();+ // A pass that fails keeps nothing.+ edit(root, 'b', 'Before a failed pass.');+ installFaultHook((point, detail) => { if (point === 'sync:level_read' && detail.round === 1) throw new Error('synthetic pass failure'); });+ await expect(performManagedSync(engine, OPTS)).rejects.toThrow('synthetic pass failure');+ const again = firstRounds();+ await performManagedSync(engine, OPTS);+ expect(again.at(-1)).toBeNull();+ // Off: the next pass reads whole, and keeps nothing for the one after.+ await engine.setConfig('sync.level_reuse', 'false');+ edit(root, 'c', 'Reuse off.');+ await performManagedSync(engine, OPTS);+ expect(again.at(-1)).toBeNull();+ await engine.setConfig('sync.level_reuse', 'true');+ edit(root, 'a', 'Reuse on again.');+ await performManagedSync(engine, OPTS);+ expect(again.at(-1)).toBeNull();+ edit(root, 'b', 'Reused.');+ await performManagedSync(engine, OPTS);+ expect(again.at(-1)).toMatchObject({ taken: true, across: true });+ }), 300_000);++ test.skipIf(backend !== 'postgres')('a write in flight in another session at S1 and committed before the next pass is re-read', () => brain(async ({ engine, root }) => {+ const seen = firstRounds();+ await performManagedSync(engine, OPTS);+ const other = new PostgresEngine();+ await other.connect({ database_url: url!, poolSize: 1 });+ try {+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let started!: () => void;+ const written = new Promise<void>(resolve => { started = resolve; });+ // The writer's transaction holds its id (and no lock) across S1, then writes the row with that id as its xmin.+ const writer = other.transaction(async tx => {+ await tx.executeRaw('SELECT txid_current()');+ started();+ await gate;+ await withCoordinatedWrite(tx, ['default'], () => tx.executeRaw("UPDATE pages SET title = 'Written in flight', knowledge_revision = $1::uuid WHERE source_id='default' AND slug='notes/b'",+ [randomUUID()]), TEST_WRITE_ATTRIBUTION);+ });+ await written;+ edit(root, 'a', 'Synced while another session writes.');+ // The pass's last round marks S1 while the write is in flight; it commits once the pass has read its level.+ // Round 2 is the pass's last (its confirm round): its read is S1.+ let rounds = 0;+ installFaultHook((point, detail) => {+ if (point !== 'sync:level_read') return;+ rounds = detail.round!;+ if (detail.round === 1) seen.push(detail.level?.confirm ?? null);+ if (detail.round === 2) release();+ });+ await performManagedSync(engine, OPTS);+ expect(rounds).toBe(2);+ await writer;+ edit(root, 'c', 'The next pass.');+ await performManagedSync(engine, OPTS);+ // The in-flight row's xmin is in S1's in-progress list: the proof re-reads it (a commit and that page).+ expect(seen.at(-1)).toMatchObject({ taken: true, across: true });+ expect(seen.at(-1)!.rows).toBeGreaterThanOrEqual(2);+ expect(await titles(engine)).toContain('notes/b=Written in flight');+ } finally { await other.disconnect(); }+ }), 300_000);+});