Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): #6712 PR 4b a 600k pass reads pages through a cursor and keeps matched paths compact
garrytan0a9f46aba0aa
diff --git a/src/core/persistence/sync-git-stream.ts b/src/core/persistence/sync-git-stream.tsindex aaf383528a..572ea77da5 100644--- a/src/core/persistence/sync-git-stream.ts+++ b/src/core/persistence/sync-git-stream.ts@@ -110,6 +110,35 @@ export async function readIndexLevel(gitRoot: string): Promise<Map<string, GitInreturn index;}+/**+ * `X` as committed mode reads it: only the tree paths whose index entry differs from `T` (OID, mode or a non-zero stage,+ * the highest stage kept; null: absent from the index). A 600k-path checkout whose index matches its tree holds no second+ * map of every path. Paths outside `tree` are not kept; when some tree path never appeared, the index is read whole+ * once more to name them.+ */+export async function readIndexDelta(gitRoot: string, tree: Map<string, GitTreeEntry>): Promise<Map<string, GitIndexEntry | null>> {+ const delta = new Map<string, GitIndexEntry | null>();+ let same = 0;+ await readRecords(gitRoot, ['ls-files', '-s', '-z'], 'ls-files', record => {+ const fields = headerFields(record);+ if (!fields || !OID.test(fields.a) || !/^[0-3]$/.test(fields.b)) throw malformed('ls-files', record.toString('utf8'));+ const committed = tree.get(fields.path);+ if (!committed) return;+ const stage = Number(fields.b);+ if (stage === 0 && fields.a === committed.oid && fields.mode === committed.mode) { same++; return; }+ if ((delta.get(fields.path)?.stage ?? -1) < stage) delta.set(fields.path, { mode: fields.mode, oid: fields.a, stage });+ });+ if (same + delta.size === tree.size) return delta;+ const index = await readIndexLevel(gitRoot);+ const whole = new Map<string, GitIndexEntry | null>();+ for (const [path, committed] of tree) {+ const indexed = index.get(path);+ if (!indexed) whole.set(path, null);+ else if (indexed.stage !== 0 || indexed.oid !== committed.oid || indexed.mode !== committed.mode) whole.set(path, indexed);+ }+ return whole;+}+/*** Exact-OID rename hints from `from` to `to`: a deleted and an added regular* file with the same blob, only when that OID has exactly one of each. Hintsdiff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex 43bad2eeed..a9e6103ae7 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -32,7 +32,7 @@ import { VERSION } from '../../version.ts';import type { BrainEngine } from '../engine.ts';import { resolveSlugForPath } from '../sync.ts';import { massReconcileAllowed, planReconcileDeletes } from '../sync-reconcile.ts';-import { loopYield } from './sync-yield.ts';+import { filterYielding, loopYield } from './sync-yield.ts';import { admitKeepDbReconcile, freezeKeepDbReconcile, releaseMatchedDriftSkips } from '../repair/keep-db-policy.ts';import type { SyncProcessingOptions } from './sync-authority.ts';import type { SyncClassified } from './sync-classify.ts';@@ -76,7 +76,7 @@ export interface PassApplyState {keepDb: { admitted: number; pending: number; paused: number; refused: Record<string, number> };/** keep_db paths admitted in this pass: never admitted twice. */keepDbTaken: string[];- matchedSlugs: string[];+ matchedSlugs: Set<string>;/** The newest round's classes and summary (design §9), after this module settled what it finished. */classes: Record<string, { count: number; action: SyncClassAction }>;summary: PassRoundSummary | null;@@ -84,7 +84,7 @@ export interface PassApplyState {export function newPassApplyState(): PassApplyState {return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0 }, settleMismatch: [], adopted: 0,- swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: [], classes: {}, summary: null };+ swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], matchedSlugs: new Set(), classes: {}, summary: null };}export interface PassApplyInput {@@ -123,7 +123,11 @@ function levelMeta(level: ShadowLevel, entry: ShadowPath): Partial<GitHoldMeta>export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {if (input.fullRound && !input.remote) await retireMarkers(engine, level, state);if (input.remote && input.grantPrefixes) {- for (const entry of level.paths) if (!grantSees(level, entry, input.grantPrefixes) && !entry.result.settled) settleAs(entry, { settled: true, action: 'none', classAction: 'none' });+ const step = loopYield();+ for (const entry of level.paths) {+ if (step.due()) await step.pause();+ if (!grantSees(level, entry, input.grantPrefixes) && !entry.result.settled) settleAs(entry, { settled: true, action: 'none', classAction: 'none' });+ }}await applyDeleteValve(engine, level, input, state);if (input.remote) { summarizeRound(level, state); return; }@@ -134,7 +138,7 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, inconst step = loopYield();for (const entry of level.paths) {if (step.due()) await step.pause();- if (entry.result.cls === 'matched' && entry.slug) state.matchedSlugs.push(entry.slug);+ if (entry.result.cls === 'matched' && entry.slug) state.matchedSlugs.add(entry.slug);}summarizeRound(level, state);}@@ -166,7 +170,7 @@ export function summarizeRound(level: ShadowLevel, state: PassApplyState): void/** Design §2.5: retire markers whose origin left both `T` and the disk, or that a live page claims again (compare-and-delete). */async function retireMarkers(engine: BrainEngine, level: ShadowLevel, state: PassApplyState): Promise<void> {- const retire = level.paths.filter(entry => entry.state.marker && !entry.legacyPageless+ const retire = await filterYielding(level.paths, entry => entry.state.marker && !entry.legacyPageless&& ((entry.state.tree === null && !entry.state.present) || entry.state.page?.live === true));if (!retire.length) return;await engine.transaction(async tx => {@@ -188,11 +192,11 @@ async function readStoredMarker(exec: Pick<BrainEngine, 'executeRaw'>, level: Sh/** Design §2.6: the round's deletes through #2828's valve; a trip withholds them all under one source-level record. */async function applyDeleteValve(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {- const deletes = level.paths.filter(entry => entry.result.action === 'delete' && !entry.result.settled && !entry.result.inFlight);+ const deletes = await filterYielding(level.paths, entry => entry.result.action === 'delete' && !entry.result.settled && !entry.result.inFlight);// The valve plans over every live page only when the round deletes something (no delete never trips it).- const plan = deletes.length ? (() => {+ const plan = deletes.length ? await (async () => {const deleting = new Set(deletes.map(entry => entry.path));- const live = level.paths.filter(entry => entry.state.page?.live === true && entry.slug);+ const live = await filterYielding(level.paths, entry => entry.state.page?.live === true && !!entry.slug);return planReconcileDeletes(live.map(entry => ({ slug: entry.slug!, source_path: entry.path })), live.filter(entry => !deleting.has(entry.path)).map(entry => entry.path), () => true);})() : null;const tripped = !!plan?.massDelete && (input.remote || !massReconcileAllowed());@@ -219,7 +223,9 @@ async function writePassHolds(engine: BrainEngine, level: ShadowLevel, input: Paconst pending: Pending[] = [];// A held rename's origin waits for its destination's hold (#5988), whatever its page did meanwhile.const heldRenameOrigins = new Set(level.heldRenames.map(held => syncOriginPath(held.rename.sourcePath)));+ const step = loopYield();for (const entry of level.paths) {+ if (step.due()) await step.pause();const r = entry.result;if (r.settled || r.inFlight) continue;const { path } = passEntryPaths(level, entry.path);@@ -277,7 +283,7 @@ async function writeRecords(engine: BrainEngine, level: ShadowLevel, writes: Rec/** Row 13: adopt the level into the page's record, keeping `r.parser` (arm 1: revision only, on `fileSame`). */async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: PassApplyState): Promise<void> {- const adopt = level.paths.filter(entry => entry.result.cls === 'adopt' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null);+ const adopt = await filterYielding(level.paths, entry => entry.result.cls === 'adopt' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null);if (!adopt.length) return;const records = await readSyncImportProvenances(engine, level.sourceId, level.incarnation, adopt.map(entry => entry.pageId!));const writes = adopt.map((entry): RecordWrite => {@@ -292,7 +298,7 @@ async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: Pass/** Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. */async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {- const legacy = level.paths.filter(entry => entry.result.cls === 'legacy_unverified' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null && entry.slug);+ const legacy = await filterYielding(level.paths, entry => entry.result.cls === 'legacy_unverified' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null && entry.slug);if (!legacy.length) return;const sweepAll = input.fullRound && !input.obligations.legacy_sweep?.first_full_at;const budget = sweepAll ? legacy.length : Math.max(0, PASS_LEGACY_SWEEP_MAX - state.swept.screened);@@ -322,7 +328,7 @@ async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassA/** Rows 15 and 18 under keep_db (§4): freeze to `T[p]`'s bytes and admit the DB-wins reconcile of the pass, bounded per pass. */async function admitKeepDb(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {const taken = new Set(state.keepDbTaken);- const want = level.paths.filter(entry => !entry.result.inFlight && !taken.has(entry.path) && entry.pageId !== null && entry.revision !== null && entry.slug && entry.state.level !== null+ const want = await filterYielding(level.paths, entry => !entry.result.inFlight && !taken.has(entry.path) && entry.pageId !== null && entry.revision !== null && entry.slug && entry.state.level !== null&& ((entry.result.cls === 'keep_db' && !entry.result.settled) || (entry.result.cls === 'db_ahead' && entry.result.keepDbWrite === true)));if (!want.length) return;if (input.admission !== 'normal') {@@ -391,7 +397,7 @@ export function remoteReconcile(level: ShadowLevel, input: { committed: number;/** Once per pass: release the concept drift skips of pages the pass classified `matched` (§4). */export async function finishPassApply(engine: BrainEngine, sourceId: string, state: PassApplyState): Promise<number> {- return state.matchedSlugs.length ? releaseMatchedDriftSkips(engine, sourceId, state.matchedSlugs) : 0;+ return state.matchedSlugs.size ? releaseMatchedDriftSkips(engine, sourceId, state.matchedSlugs) : 0;}/** The pass row's telemetry counts of what the rounds applied. */diff --git a/src/core/persistence/sync-pass.ts b/src/core/persistence/sync-pass.tsindex 688604a3f4..a014f87db4 100644--- a/src/core/persistence/sync-pass.ts+++ b/src/core/persistence/sync-pass.ts@@ -11,8 +11,8 @@* records), `H` (holds and retry rows), `U_db` (open requests and pending Git effects), deletion markers, and `A` (the* attestation of the current revision) for the pages whose class needs a proof. The Git reads, the database snapshot and* the holds run concurrently (`reads` is their wall time). On Postgres the snapshot reads share one `REPEATABLE READ,- * READ ONLY` transaction and `I⋈P` is one set-based statement; PGLite admits one transaction at a time, so there- * they run as bounded statements of at most 2,000 rows with writers between them.+ * READ ONLY` transaction and `I⋈P` is one set-based statement read through a cursor; PGLite admits one transaction at a+ * time, so there they run as bounded statements of at most 2,000 rows with writers between them.*/import { realpathSync } from 'node:fs';import { relative, sep } from 'node:path';@@ -33,7 +33,7 @@ import { holdBasisMoved, holdRescreenDue, readGitHoldRetryPaths, readGitSourceHotype GitHoldRecord, type SyncImportProvenance } from './sync-holds.ts';import { movedDriftHolds, sameParser } from './sync-prescreen.ts';import { syncOriginPath } from './sync-origin.ts';-import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexLevel, readTreeLevel, workingChanged, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.ts';+import { hashWorkingLevel, probeDirtiness, readBlobs, readIndexDelta, readIndexLevel, readTreeLevel, workingChanged, type GitIndexEntry, type GitTreeEntry, type WorkingStatCache } from './sync-git-stream.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';@@ -64,8 +64,10 @@ export interface PassLevelInput {/** The pass's own cache (it dies with the pass): the eligible tree of the commit and selection its last round read. */cache?: PassLevelCache;}-/** PGLite's keyset page size (design v3.2 §2.1); Postgres reads `I⋈P` in one statement of its snapshot. */+/** PGLite's keyset page size (design v3.2 §2.1). */const PGLITE_KEYSET_ROWS = 2_000;+/** Rows per `FETCH` of Postgres's `I⋈P` cursor: decoding one fetch stays well under the event-loop budget at 600k pages. */+const POSTGRES_FETCH_ROWS = 25_000;/** Blob bytes read for adoption by hash and the screen, per blob. */const LEVEL_BLOB_MAX_BYTES = 8 * 1024 * 1024;const SYNC_WRITE_KINDS = ['managed_sync_import', 'managed_sync_delete'];@@ -91,6 +93,38 @@ export interface ShadowPath { path: string; slug: string | null; pageId: number/** A page-less path unchanged since the baseline whose page a committed request deleted: the bootstrap writes it a `legacy` marker (`legacy_pageless`). */legacyPageless?: true }+/**+ * A `matched` path whose state is the converged one (a live page whose record proves the level's blob and revision, nothing+ * held, marked, owed or open): it keeps the few fields that vary and rebuilds the same `SyncPathState` on read. Most paths+ * of a large converged source are these; a level of 600k holds them in about a fifth of a full entry's memory.+ */+class MatchedPath implements ShadowPath {+ constructor(public path: string, public slug: string | null, public pageId: number | null, public revision: string, public result: SyncClassified,+ private readonly treeOid: string | null, private readonly levelOid: string, private readonly dirty: SyncPathState['dirty'], private readonly diskRecorded: boolean,+ private readonly shared: { mode: SyncPathState['mode']; fullObligation: boolean }) {}++ /** Whether `state` is the one `state` would rebuild for a page at `revision`. */+ static fits(state: SyncPathState, revision: string | null, shared: MatchedPath['shared']): revision is string {+ return revision !== null && state.mode === shared.mode && state.fullObligation === shared.fullObligation && state.level !== null && state.present+ && state.diskOid === null && state.levelSha256 === null && !state.published && state.attested === null && state.hold === null && state.marker === null+ && state.baseline === null && !state.spelling && !state.episodeUnsatisfied && !state.keepDb && !state.openWork+ && state.page?.live === true && state.page.revision === revision && state.page.originMatches+ && state.record?.revision === revision && state.record.parserSame && state.record.blobOids.length <= 2 && state.record.blobOids.length > 0+ && state.record.blobOids.every(oid => oid === state.level);+ }++ get state(): SyncPathState {+ return { mode: this.shared.mode, tree: this.treeOid, level: this.levelOid, present: true, dirty: this.dirty, diskOid: null,+ page: { live: true, revision: this.revision, originMatches: true }, record: { blobOids: this.diskRecorded ? [this.levelOid, this.levelOid] : [this.levelOid], revision: this.revision, parserSame: true },+ attested: null, levelSha256: null, published: false, hold: null, marker: null, baseline: null, spelling: false, episodeUnsatisfied: false,+ fullObligation: this.shared.fullObligation, keepDb: false, openWork: false };+ }++ set state(value: SyncPathState) {+ Object.defineProperty(this, 'state', { value, writable: true, enumerable: true, configurable: true });+ }+}+export interface ShadowLevel {sourceId: string; incarnation: string; root: string; gitRoot: string; scope: string; slugMode: 'git-root' | 'source-root';mode: 'committed' | 'working'; head: string; baselineCommit: string | null; full: boolean;@@ -117,8 +151,12 @@ export interface ShadowLevel {interface PageRow { id: number | string; slug: string; source_path: string; revision: string; deleted: boolean; request_id: string | null;record: (Pick<SyncImportProvenance, 'origin' | 'blob_oid' | 'disk_blob_oid' | 'revision' | 'parser'> & { full_episode?: string | null }) | null; arm1: boolean | null; attested_hash: string | null }-const recordOids = (record: PageRow['record']): string[] =>- record ? [record.blob_oid, record.disk_blob_oid].filter((oid): oid is string => typeof oid === 'string' && oid.length > 0) : [];+/** The record's blob ids; one equal to `level` is `level`'s own string, so a converged page keeps one copy of its blob id. */+const recordOids = (record: PageRow['record'], level?: string | null): string[] => {+ const oids: string[] = [];+ for (const oid of record ? [record.blob_oid, record.disk_blob_oid] : []) if (typeof oid === 'string' && oid.length > 0) oids.push(oid === level ? level : oid);+ return oids;+};type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -136,25 +174,33 @@ async function withRoundSnapshot<T>(engine: BrainEngine, fn: (exec: Exec) => Pro/*** `I⋈P`: every page of the source with a recorded origin and the fields of its import record the classifier reads. Postgres- * reads it as one set-based statement inside the round's snapshot (the planner hash-joins pages with their records; a- * keyset with a per-row primary-key probe made the 61k read plan-bound, about 1.7 s of server time); PGLite reads bounded- * keyset statements so writers interleave.+ * plans it as one set-based statement inside the round's snapshot (the planner hash-joins pages with their records; a+ * keyset with a per-row primary-key probe made the 61k read plan-bound, about 1.7 s of server time) and reads it through a+ * cursor, `POSTGRES_FETCH_ROWS` at a time with the next fetch in flight: one result of 600k rows decoded in a single+ * stretch of about a second and held every raw row at once. `cursor_tuple_fraction = 1` keeps the whole-result plan.+ * PGLite reads bounded keyset statements so writers interleave.*/async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: string, incarnation: string): Promise<{ rows: PageRow[]; statements: number }> {// A record's fields usually repeat the page's (origin = source_path, disk = blob, revision = the page's), so those come back// as a flag instead of a second copy of the string, and the parser as text parsed once per distinct value: a 600k-page// read then holds about one string per field per page.+ // The record's fields come out of its JSON once, in a subquery. On Postgres `OFFSET 0` keeps it unflattened, so the hash+ // join builds over those few text columns instead of the whole record (600k: about 3.1 s of serial server time to 2.0 s);+ // PGLite's keyset statements need it flattened, so each probes the record by primary key.const select = `SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted,- p.revision_write_request_id::text AS request_id, c.completed_keys IS NOT NULL AS has_record,- c.completed_keys->0->>'origin' IS NOT DISTINCT FROM p.source_path AS rec_origin_same,- CASE WHEN c.completed_keys->0->>'origin' IS DISTINCT FROM p.source_path THEN c.completed_keys->0->>'origin' END AS rec_origin,- c.completed_keys->0->>'blob_oid' AS rec_blob_oid,- c.completed_keys->0->>'disk_blob_oid' IS NOT DISTINCT FROM c.completed_keys->0->>'blob_oid' AS rec_disk_same,- CASE WHEN c.completed_keys->0->>'disk_blob_oid' IS DISTINCT FROM c.completed_keys->0->>'blob_oid' THEN c.completed_keys->0->>'disk_blob_oid' END AS rec_disk_blob_oid,- c.completed_keys->0->>'revision' IS NULL AS rec_revision_null,- NULLIF(c.completed_keys->0->>'revision', p.knowledge_revision::text) AS rec_revision,- (c.completed_keys->0->'parser')::text AS rec_parser, c.completed_keys->0->>'full_episode' AS rec_full_episode- FROM pages p LEFT JOIN op_checkpoints c ON c.op=$2 AND c.fingerprint=$3||p.id::text+ p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record,+ c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same,+ CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin,+ c.blob_oid AS rec_blob_oid,+ c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same,+ CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid,+ c.revision IS NULL AS rec_revision_null,+ NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision,+ c.parser AS rec_parser, c.full_episode AS rec_full_episode+ FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid,+ completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision,+ (completed_keys->0->'parser')::text AS parser, completed_keys->0->>'full_episode' AS full_episode+ FROM op_checkpoints WHERE op=$2${kind === 'postgres' ? ' OFFSET 0' : ''}) c ON c.fingerprint=$3||p.id::textWHERE p.source_id=$1 AND p.source_path IS NOT NULL`;const params = [sourceId, SYNC_IMPORT_PROVENANCE_OP, `${sourceId}:${incarnation}:`];type Raw = Omit<PageRow, 'record' | 'arm1' | 'attested_hash'> & { has_record: boolean; rec_origin_same: boolean; rec_origin: string | null; rec_blob_oid: string | null;@@ -172,8 +218,22 @@ async function readPages(exec: Exec, kind: 'postgres' | 'pglite', sourceId: stridisk_blob_oid: raw.rec_disk_same ? raw.rec_blob_oid : raw.rec_disk_blob_oid, revision: raw.rec_revision_null ? undefined : raw.rec_revision ?? raw.revision,parser: parserOf(raw.rec_parser), full_episode: raw.rec_full_episode } : null });};- if (kind === 'postgres') { take(await exec.executeRaw<Raw>(select, params)); return { rows, statements: 1 }; }- let after = 0, statements = 0;+ let statements = 0;+ if (kind === 'postgres') {+ await exec.executeRaw('SET LOCAL cursor_tuple_fraction = 1');+ await exec.executeRaw(`DECLARE sync_pass_pages NO SCROLL CURSOR FOR ${select}`, params);+ statements += 2;+ const fetch = () => { statements++; return exec.executeRaw<Raw>(`FETCH ${POSTGRES_FETCH_ROWS} FROM sync_pass_pages`); };+ let next = fetch();+ for (;;) {+ const page = await next;+ const more = page.length === POSTGRES_FETCH_ROWS;+ if (more) next = fetch();+ take(page);+ if (!more) return { rows, statements };+ }+ }+ let after = 0;for (;;) {statements++;const page = await exec.executeRaw<Raw>(`${select} AND p.id>$4 ORDER BY p.id LIMIT ${PGLITE_KEYSET_ROWS}`, [...params, after]);@@ -357,7 +417,10 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst timed = async <T>(key: string, read: () => Promise<T>): Promise<T> => { const st = timer(); try { return await read(); } finally { timings[key] = st(); } };t = timer();const [gitLevel, snapshot, held] = await Promise.all([- Promise.all([timed('T', eligibleTree), timed('X', () => readIndexLevel(gitRoot)),+ // Working mode reads the whole index (its paths join the domain); committed mode only where it differs from T, read+ // after T so the two are never held whole together.+ Promise.all([timed('T', eligibleTree).then(async tree => ({ tree, indexDelta: mode === 'committed' ? await timed('X', () => readIndexDelta(gitRoot, tree)) : null })),+ mode === 'working' ? timed('X', () => readIndexLevel(gitRoot)) : Promise.resolve(new Map<string, GitIndexEntry>()),timed('U', async () => (mode === 'working' ? (await readUntracked(gitRoot, scope)).filter(eligible) : []))]),// Issued together, the snapshot's statements pipeline on its one connection (PGLite runs them in turn).timed('I⋈P', () => withRoundSnapshot(engine, async exec => {@@ -375,7 +438,15 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st}),]);timings.reads = t();- const [tree, index, untrackedPaths] = gitLevel;+ const [{ tree, indexDelta }, index, untrackedPaths] = gitLevel;+ // Committed mode: the index entry of a tree path, its own where it differs from T, else T's at stage 0 (undefined: absent).+ const indexed = (path: string): GitIndexEntry | undefined => {+ if (!indexDelta) return index.get(path);+ const delta = indexDelta.get(path);+ if (delta !== undefined) return delta ?? undefined;+ const committed = tree.get(path);+ return committed ? { ...committed, stage: 0 } : undefined;+ };const inLevel = (path: string) => tree.has(path) || eligible(path);const untracked = new Set(untrackedPaths);const { open, markers, passRow, statements } = snapshot;@@ -483,7 +554,7 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: st// Presence decides only rows 4-6 (a level of absent); a committed path in T is not read here (Dp covers it).const presentNow = mode === 'working' ? level !== null : level === null ? readPresent(root, path, scope) : true;const record = row?.record ?? null;- const recordBlobOids = recordOids(record);+ const recordBlobOids = recordOids(record, level);const attested = row && (row.arm1 || row.attested_hash) ? { hash: row.attested_hash ?? null, arm1: row.arm1 === true } : null;const hold = holdByGitPath.get(path);const marker = markers.get(origin) ?? null;@@ -534,20 +605,32 @@ export async function readShadowLevel(engine: BrainEngine, input: { sourceId: stconst paths: ShadowPath[] = [];const candidates: string[] = [], candidateAt: number[] = [];const settledBeforeDirtiness = new Set(['held', 'spelling', 'untracked', 'kept', 'delete', 'delete_drift', 'gone', 'deleted_same', 'deleted_edited', 'legacy_same', 'matched']);+ const shared = { mode, fullObligation: input.pass ? !!input.pass.episodeFullId : input.full === true };for (const path of await sortYielding([...domain], step)) {if (step.due()) await step.pause();const probe = probes.get(path);const { state, row, legacyPageless } = stateOf(path, mode === 'committed' && tree.has(path) ? 'clean' : null, probe);const result = sharedResult(classifySyncPath(state));// Rows 1-10 precede row 11 and `matched` settles either way, so only the rest are Dp candidates (design v3.2 §2.1).- const staged = mode === 'committed' && tree.has(path) && (index.get(path)?.oid !== tree.get(path)!.oid || (index.get(path)?.stage ?? 0) !== 0);+ const staged = mode === 'committed' && tree.has(path) && !!indexDelta?.has(path) && (indexed(path)?.oid !== tree.get(path)!.oid || (indexed(path)?.stage ?? 0) !== 0);+ const revision = row?.revision ?? null;if (mode === 'committed' && tree.has(path) && (!settledBeforeDirtiness.has(result.cls) || staged)) { candidates.push(path); candidateAt.push(paths.length); }- paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision: row?.revision ?? null, state, result, ...(legacyPageless ? { legacyPageless } : {}) });+ else {+ // The row's fields the level keeps are copied onto the entry; only a candidate's row is read again (its dirtiness re-classifies it).+ byOrigin.delete(path);+ if (result.cls === 'matched' && !legacyPageless && MatchedPath.fits(state, revision, shared)) {+ paths.push(new MatchedPath(path, row!.slug, Number(row!.id), revision, result, state.tree, state.level!, state.dirty, state.record!.blobOids.length === 2, shared));+ continue;+ }+ }+ paths.push({ path, slug: row?.slug ?? null, pageId: row ? Number(row.id) : null, revision, state, result, ...(legacyPageless ? { legacyPageless } : {}) });}timings.classify = t();if (candidates.length) {t = timer();- const probed = await probeDirtiness(root, gitRoot, candidates, tree, index);+ const candidateIndex = new Map<string, GitIndexEntry>();+ for (const path of candidates) { const entry = indexed(path); if (entry) candidateIndex.set(path, entry); }+ const probed = await probeDirtiness(root, gitRoot, candidates, tree, candidateIndex);timings.Dp = (timings.Dp ?? 0) + t();t = timer();for (const [k, path] of candidates.entries()) {diff --git a/src/core/persistence/sync-yield.ts b/src/core/persistence/sync-yield.tsindex 5413a8e0d3..f5568a1d85 100644--- a/src/core/persistence/sync-yield.ts+++ b/src/core/persistence/sync-yield.ts@@ -25,6 +25,16 @@ export function loopYield(): LoopYield {};}+/** `items.filter(keep)` with yields between stretches. */+export async function filterYielding<T>(items: readonly T[], keep: (item: T) => unknown, step: LoopYield = loopYield()): Promise<T[]> {+ const kept: T[] = [];+ for (const item of items) {+ if (step.due()) await step.pause();+ if (keep(item)) kept.push(item);+ }+ return kept;+}+/** `items.sort()` (code-unit order, as the default comparator) in runs merged with yields between stretches. */export async function sortYielding(items: string[], step: LoopYield): Promise<string[]> {const RUN = 16_384;diff --git a/src/core/repair/keep-db-policy.ts b/src/core/repair/keep-db-policy.tsindex 924fe582fa..304ed2761e 100644--- a/src/core/repair/keep-db-policy.ts+++ b/src/core/repair/keep-db-policy.ts@@ -192,13 +192,18 @@ export async function admitKeepDbReconcile(engine: BrainEngine, artifact: KeepDb/*** Releases the concept drift skips (`dream.concepts.drift_skips`) of pages the pass classified `matched` in `sourceId`:- * one read of the skips, and one release per matched page that has one.+ * one read of the skips, and one release per matched page that has one. It walks the source's skips, not the matched+ * slugs, so a 600k-page pass with no skip does no per-page work.*/export async function releaseMatchedDriftSkips(engine: BrainEngine, sourceId: string, matchedSlugs: Iterable<string>): Promise<number> {const skips = await readDriftSkips(engine);+ const prefix = `${sourceId}:`;+ const skipped = Object.keys(skips).filter(key => key.startsWith(prefix)).map(key => key.slice(prefix.length));+ if (!skipped.length) return 0;+ const matched = matchedSlugs instanceof Set ? matchedSlugs as Set<string> : new Set(matchedSlugs);let released = 0;- for (const slug of new Set(matchedSlugs)) {- if (!skips[`${sourceId}:${slug}`]) continue;+ for (const slug of skipped) {+ if (!matched.has(slug)) continue;await releaseDriftSkip(engine, sourceId, slug);released++;}diff --git a/test/overwritten-edits-6712.test.ts b/test/overwritten-edits-6712.test.tsindex 40b97fd25f..2e0da26947 100644--- a/test/overwritten-edits-6712.test.ts+++ b/test/overwritten-edits-6712.test.ts@@ -3,9 +3,11 @@** The overwrite is seeded the way it happens on a released brain: a database-only `put_page` (`sync.write_through`* off), then a committed edit of the same file, then an incremental sync that publishes the file over the edit with no- * hold. On a base without #6887 any page reproduces it; the seed also drops the page's import provenance record (a page- * last imported before PR 0 recorded one), which no released classifier guards in a delta sync, so the seed reproduces- * with or without #6887 and these tests never depend on that fix.+ * hold. On a base without #6887 any page reproduces it. The live pass (#6712 PR 4b) holds a both-moved page whose import+ * record is missing or honest, so the seed rewrites the record to name the database edit's revision: a record that no+ * longer proves the page and that no classifier can tell from a true one. The pass then publishes the file over the+ * edit through a pass import (intent kind `managed_sync_import` with a `passId`), which is what the detector reads, and+ * these tests never depend on #6887.** Protects:* - a seeded overwrite is detected `high` (also after receipt compaction nulled every intent), and `repair@@ -73,7 +75,8 @@ async function seedOverwrite(engine: BrainEngine, ctx: OperationContext, root: sawait putPage(engine, ctx, slug, 'DBONLYMARKER the agent edit.');await engine.setConfig('sync.write_through', 'true');const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);- await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`]);+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,revision}', to_jsonb($3::text)) WHERE op=$1 AND fingerprint=$2`,+ [SYNC_IMPORT_PROVENANCE_OP, `default:${await incarnationOf(engine)}:${page!.id}`, await revisionOf(engine, slug)]);writeFileSync(join(root, `${slug}.md`), note(slug, 'The second committed body.'));commit(root, `edit ${slug}`);await performManagedSync(engine, OPTS);@@ -91,6 +94,9 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATconst scan = await scanOverwrittenEdits(engine, 'default');expect(scan.edits.map(edit => [edit.slug, edit.confidence, edit.db_operation])).toEqual([['notes/a', 'high', 'put_page']]);+ const [imported] = await engine.executeRaw<{ kind: string; pass: boolean }>(+ "SELECT intent->>'kind' AS kind, intent ? 'passId' AS pass FROM persistence_requests WHERE id::text=$1", [scan.edits[0]!.import_request_id]);+ expect(imported).toEqual({ kind: 'managed_sync_import', pass: true });const warned = await doctor(engine);expect(warned.status).toBe('warn');expect(warned.details).toMatchObject({ count: 1, unknown: 0, sources: [{ source_id: 'default', count: 1, slugs: ['notes/a'] }] });diff --git a/test/sync-pass-compact-level-6712.test.ts b/test/sync-pass-compact-level-6712.test.tsnew file mode 100644index 0000000000..4423d7df40--- /dev/null+++ b/test/sync-pass-compact-level-6712.test.ts@@ -0,0 +1,55 @@+/**+ * #6712 PR 4b ruling 3 (memory at 600k): a level keeps a `matched` path whose state is the converged one in a compact+ * entry and rebuilds its `SyncPathState` on read (sync-pass.ts `MatchedPath`), instead of a full state per path.+ *+ * Protects: the rebuilt state is the one the level read classified: its blob is the file's committed blob, its page+ * revision and record revision are the page's, and it classifies to the entry's result; a path whose state is not the+ * converged one (here an edited file) keeps its full state. A real PGLite managed brain and a real Git level.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { classifySyncPath } from '../src/core/persistence/sync-classify.ts';+import { readShadowLevel } from '../src/core/persistence/sync-pass.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (slug: string, body: string) => `---\ntype: concept\ntitle: ${slug}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ git(root, 'init', '-q');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(root, `${name}.md`), note(name, `The committed body of ${name}.`));+ commit(root, 'notes');+};++describe('#6712 PR 4b: a compact matched entry rebuilds the state it was classified on', () => {+ test('converged paths read back their blob, page and record; an edited path keeps its own state', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writeFileSync(join(root, 'c.md'), note('c', 'An edited body of c.'));+ commit(root, 'edit c');++ const level = (await readShadowLevel(engine, { sourceId: 'default' }))!;+ const pages = new Map((await engine.executeRaw<{ slug: string; revision: string }>("SELECT slug, knowledge_revision::text AS revision FROM pages WHERE source_id='default'"))+ .map(row => [row.slug, row.revision]));+ for (const name of ['a', 'b']) {+ const entry = level.paths.find(path => path.path === `${name}.md`)!;+ const blob = git(root, 'rev-parse', `HEAD:${name}.md`);+ expect(entry.result.cls).toBe('matched');+ // Compact: the entry stores no state of its own; the read below rebuilds it.+ expect(Object.keys(entry)).not.toContain('state');+ expect(entry.revision).toBe(pages.get(name)!);+ expect(entry.state).toEqual({ mode: 'committed', tree: blob, level: blob, present: true, dirty: 'clean', diskOid: null,+ page: { live: true, revision: pages.get(name)!, originMatches: true }, record: { blobOids: [blob, blob], revision: pages.get(name)!, parserSame: true },+ attested: null, levelSha256: null, published: false, hold: null, marker: null, baseline: null, spelling: false, episodeUnsatisfied: false,+ fullObligation: false, keepDb: false, openWork: false });+ }+ const edited = level.paths.find(path => path.path === 'c.md')!;+ expect(edited.result.cls).not.toBe('matched');+ expect(Object.keys(edited)).toContain('state');+ expect(edited.state.level).toBe(git(root, 'rev-parse', 'HEAD:c.md'));+ for (const entry of level.paths) expect(classifySyncPath(entry.state)).toEqual({ ...entry.result });+ }, { setup }));+});