Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(GBRA-108): the sweep reads each kind of page read once per slice

garrytan4498e1f77a3e
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 06760e91d4..4244727fe8 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -20,7 +20,7 @@
- `src/core/persistence/sync-git-stream.ts` — the managed-sync reconcile's Git level reads (#6712), all through `hardenedGitStream` (allow-listed, filter-free plumbing; the checkout's clean/process filters and textconv never run) and parsed as they stream, so memory is the result maps. `readTreeLevel` (`ls-tree -r -z <commit> -- <scope>`: blobs plus symlinks and gitlinks with their mode), `readIndexLevel` (`ls-files -s -z`, the index only; a conflicted path keeps its highest stage) and `readRenameHints` (`diff-tree -r -z --no-renames`: a deleted and an added regular file paired only when their blob OID is unique to them; hints, never candidates) throw `SyncTreeReadIncomplete` (code `reconcile_read_incomplete`) unless Git exited 0, was not signalled and its output ended at a NUL. `readBlobs` reads contents through one `cat-file --batch`, leaving out missing, oversized and over-total objects. `probeDirtiness` is the batched `hardenedPathDirty` (`Dp`): per batch of 2,000 paths one `hash-object --no-filters --stdin-paths` and one `check-attr -z --stdin`, presence and bytes from `readSyncFile`; verdicts in order `untracked`, `staged` (index and tree differ in OID or mode, a non-zero stage, or one side missing), `deleted`, `unknown` (symlink or gitlink, unreadable file, a path with a newline or a leading quote, any Git failure, an OID that disagrees with the bytes read), then `clean` (raw OID equals the tree with the executable bit matching), `clean_eol` (only `text`/`eol` set and the CRLF-folded bytes hash to the tree), `clean_lfs` (a valid pointer whose sha256 and size match the bytes) or `modified`; another filter, `working-tree-encoding`, an executable-bit-only change or CRLF bytes that fold to the tree with no attribute are `unknown`, never clean. Tests: `test/hardened-git-stream-6712.test.ts` (every verdict, completeness, and a forced probe that 1,000 passes of every read never run a configured filter or textconv while `git status`/`git diff` on the same checkout do). Working mode: `probeDirtiness(..., { working: true })` never reads the index (a path with no file is `deleted`, a present file outside the tree `untracked` with its raw OID, every other present file judged from its bytes against the tree through the same `clean_eol`/`clean_lfs` domains), so a staged edit, a staged new file, `git rm --cached`, a staged deletion and a staged file removed from disk probe as the same disk does with a pristine index: the working level is the physical bytes (design v3.2 §2.1). `hashWorkingLevel` hashes every path of a working round that way with hash-then-restat (a path whose bigint `lstat` moved across the hash is rehashed, up to three attempts) and returns the stat cache it leaves: `WorkingStatCache` is plain JSON (`{v: 1, root, entries: {path: 'dev:ino:mode:uid:size:mtime_ns:ctime_ns' | 'absent'}}`), an entry is written only for a stable stat whose `mtime` and `ctime` are older than 2 s before the attempt began (Git's racy rule) and a probe with a level, and at most `WORKING_STAT_CACHE_MAX_ENTRIES` (100,000) entries are kept in path order. `workingChanged(cache, paths)` is the idle tick's check: a path the cache does not hold, a moved stat, a failed stat, a zero `ctime`, a missing cache or a moved root all read as changed, never as unchanged. `parseWorkingStatCache` validates a serialized copy (junk is null, so everything reads changed); `rememberWorkingStatCache`/`recallWorkingStatCache` keep up to 64 caches per process. Working-mode tests: `test/sync-working-level-6712.test.ts` (probe 41, on the Git reads and on a managed PGLite pass), `test/sync-working-stat-cache-6712.test.ts` (probe 42); the probe 28 marker test also runs `hashWorkingLevel`.
- `src/core/persistence/sync-classify.ts` — the managed-sync level classifier (#6712 PR 4, design v3.2 §2.3): pure (no I/O), total, ordered, first match over one path's facts (`SyncPathState`: mode, `T[p]`, the level `L`, presence, `Dp`, the page and its import record, the attestation of its revision, hold, deletion marker, baseline blob, open work). Rows in order: `held`, `spelling`, `untracked`, `kept`, `delete`, `delete_drift`, `gone`, `deleted_same`, `deleted_edited`, `legacy_same`, `dirty`, `matched`, `adopt`, `reparse`, `db_ahead` (sub-labels `pending`/`db_only`/`unproven`; keep_db writes only `db_only` on a clean committed path; an open full obligation skips `db_only`/`unproven`), `import`, `legacy_unverified`, `keep_db`, `drift` (side `both` or `unknown`); then the overlay (unsettled with open work is `in_flight`). `syncClassAction` is the glossary tag (`none`, `owner`, `repair`); `syncPassKind` decides `idle`, `hold_only` or `full` from the converged state and every obligation. Tests: `test/sync-classify-6712.test.ts` (each row, and the cross product against a reference model built from the state space).
- `src/core/persistence/sync-pass.ts` — the read-only shadow of the level-triggered pass (#6712 PR 4a): `readShadowLevel` reads one managed source's level (`T` via `readTreeLevel`, `X`, working-mode untracked files, `Dp` for committed candidates only or every path in working mode, pages keyset on `pages.id` with the import record by a LATERAL primary-key probe and the revision's attestation in the same statement, holds and retry rows, open requests and pending Git effects, deletion markers) and classifies every path with `sync-classify.ts`; it writes and admits nothing. Postgres reads share one `REPEATABLE READ, READ ONLY` transaction; PGLite runs bounded 2,000-row statements. A company-brain source returns null (it keeps its frozen manifest). `shadowConvergence` wraps it in the receipt, `dryRunConvergence` backs `gbrain sync --dry-run --json`'s `convergence` (with the read-only screen), `statusConvergence` backs `sync status --detail` and doctor, and `idleTickProbe` times the idle tick's reads for the bench (`scripts/bench/sync-convergence.ts`). Tests: `test/sync-pass-shadow-6712.test.ts`.
-- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, and read their pages through `importGroupReads`' batch, so a page costs only its own reads (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.
+- `src/core/persistence/sync-convergence.ts` — the convergence receipt (#6712 PR 4a, schema `convergence/1`, always `dry_run: true`): per-class `counts` and `classes` with action tags (`in_flight`, `keep_db_pending` beyond 200 per pass, and `deletes_withheld` when #2828's valve trips are classes too), predicted `decisions` by side after `readOnlySameContentScreen` (the dry run's `sameContentAtOrigin`: a screening request through `prepareManagedSyncMutation(..., { unsaved: true })`, at most 200 paths; one call's preparations share group-publish.ts's `preparationReads` memo plus the binding, trust-config and purge-tombstone reads, read their pages through `importGroupReads`' batch (`reread`), and answer each page's origin, timeline, take-collision and safe-chunk-fence reads from one read per kind per call (`sliceReads`), so a call costs a constant, not a statement per page (GBRA-108); equal content is `same_content_noops`, unscreened is `screen_unknown`), `would_hold`, `db_ahead` by prefix, `legacy_unverified`, `legacy_pageless`, `deletes` with the valve verdict and set hash, up to 20 samples per non-matched class, timings and statement count. `--redact-paths` replaces paths with sha256 prefixes and drops slugs.
- `src/core/persistence/sync-pass-run.ts` — the live level-triggered pass of a managed, non-company source (#6712 PR 4b, design v3.2 §2.2, §3.1–§3.5, §8, §9), run under the source's drain lease. `runSyncPass` retires an unfinished legacy cursor first (its options seed the episode), pins the pass row (`sync.admission`, `HEAD`, the mode; the row is written with the lease token), decides the kind (`idle` stamps only `last_sync_at` as `up_to_date`; `hold_only`; `full`), then runs at most `PASS_MAX_ROUNDS` (4) rounds: read and classify the level (`sync-pass.ts`), admit `C_k = unsettled − S` in batches of at most `PASS_BATCH_MAX` (10,000; deletes, then imports) through sync-run.ts's cursor machinery on an in-memory batch, and add each settled `(path, level)` to `S` (never admitted twice in one pass). With nothing unsettled and nothing in flight it stamps through `applyPassCheckpoint`; four rounds without converging stop `resumable` / `not_converged`. Every stop records its outcome, stop reason, `settled` and `remaining` on the pass row (a stop mid-batch counts the entries its batch passed); a blocked page refusal is replayed with no new request while nothing that decided it changed. Tests: `test/sync-pass-live-6712.test.ts`, `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-outcomes-6712.test.ts`.
- `src/core/persistence/sync-pass-row.ts` — the pass row and the rows beside it (#6712 PR 4b, design §3.4), free of heavy imports so doctor, status, the lease, compaction and GC read it without loading the pass. `managed-sync-pass` (fingerprint `<source>:<incarnation>`) holds `obligations` (baseline, episode, cost, the converged state, mismatch and not-converged streaks, page faults, a blocked request to replay) and `telemetry` (the newest pass's kind, round, outcome, stop reason, candidates, settled, remaining, counts, timings). `writePassRow` writes it at pin under `assertDrainLease` and afterwards only `WHERE lease_token = $token`. Beside it: `sync-origin-deleted` (deletion markers), `sync-deletes-withheld` (the mass-delete trip) and `sync-pass-cost` (one reservation per group); `SYNC_PASS_ROW_OPS` lists the ops the checkpoint GC keeps for a live incarnation. `passHealth` is the one health rule (`blocked`, `not_converged`, `settle_mismatch`, `open_stalled`, `nothing_pending`); `SETTLE_MISMATCH_STREAK` and `NOT_CONVERGED_REPORT_STREAK` are 3.
- `src/core/persistence/sync-pass-readers.ts` — the pass row as the former cursor readers see it (#6712 PR 4b, design §3.7): doctor's movement, git-holds and terminal-failure checks, the drain backlog (`readManagedSyncBacklog`), the blocked-run reader and `sources status` read a non-company source's pass row through `readPassReadings` (`passHealth` plus the checkout HEAD from a hardened `rev-parse` on this host; no checkout means `head: null` and the recorded converged target is trusted). `passResumeArgs` is the plain sync that continues the pass, with the open episode's inherited options; `passStopCode` and `passStuckSince` name a stuck pass. Company sources and unretired legacy cursors keep their cursor arm in each reader. Tests: `test/sync-pass-readers-6712.test.ts`, `test/sync-pass-reader-gaps-6712.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 8d6b1dc2ac..c33aa44ad5 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -35,7 +35,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/noop-kernel.ts` — the #5470 no-op kernel. `inspectUnchanged` takes a preparer's `PreparedMutation` for an unadmitted `screeningRequest` and returns `contentUnchanged`, `projectionWorkRequired` (safe-chunk fence, text projection behind the knowledge revision, embedded page without a contextual mode), `metadataWorkRequired` (source path) and `observedRevision`; bound pages also need local file bytes equal to the serialized page. The page's current `knowledge_revision`, read with the projection flags, must still equal the snapshot's revision (a write after the screen's snapshot admits as `revision_moved`). Callers run the preparer's own `validate` before counting a skip. An optional `waive` list (#5751) lets a caller skip two admit reasons its no-op publication can never resolve, a pending contextual-mode stamp and file bytes that differ from the prepared content (never a missing file); the result lists each waiver applied in `waived`; only managed working-tree sync entries and `put-page-screen.ts` pass it. Used by connector sync, `import-mutations.ts`, `sync-run.ts` (working-tree and company-profile entries; renames and overlays always admit) and `put-page-screen.ts` (the managed transcript import's `put_page`, waiving `canonical_file_differs` for a file the preparer accepted). Tests: `test/noop-kernel-paths.test.ts`, `test/connector-wave3.test.ts`.
- `src/core/persistence/put-page-screen.ts` — #6741 B: `unchangedPutPage` screens a trusted local put_page (the transcript import) through `preparePageAdmission` (unadmitted), the page publication preparer and the no-op kernel; skips admission only on a genuine no-op with no pending request, no segmented body and no projection work. Tests: `test/transcripts-managed-noop.test.ts`.
-- `src/core/persistence/import-reads.ts` — GBRA-75 wave 10: `readImportSnapshots` reads a run of pages as `readPageSnapshot(slug, { sourceId, includeDeleted: true })` returns each (soft-deleted rows, withdrawals and purge markers included) through `readPageSnapshotsBatch({ includeDeleted, absentIsNull })`, looping over its byte-budget prefixes; the managed import screen uses it for two or more new members. `importGroupReads` serves an import group's preparation (`group-publish.ts` `preparationReads`): each member's first own snapshot read comes from one batch, and `findDuplicatePage` calls that arrive together (all members, or a 2 ms window) are answered by one `findDuplicatePages` (`engine-sql/pages.ts`, same predicate and ranking per input); a failed batch falls back to each member's single read. Tests: `test/import-reads.test.ts`, Postgres arm `test/e2e/import-reads.test.ts`.
+- `src/core/persistence/import-reads.ts` — GBRA-75 wave 10: `readImportSnapshots` reads a run of pages as `readPageSnapshot(slug, { sourceId, includeDeleted: true })` returns each (soft-deleted rows, withdrawals and purge markers included) through `readPageSnapshotsBatch({ includeDeleted, absentIsNull })`, looping over its byte-budget prefixes; the managed import screen uses it for two or more new members. `importGroupReads` serves an import group's preparation (`group-publish.ts` `preparationReads`): each member's first own snapshot read comes from one batch, and `findDuplicatePage` calls that arrive together (all members, or a 2 ms window) are answered by one `findDuplicatePages` (`engine-sql/pages.ts`, same predicate and ranking per input); a failed batch falls back to each member's single read; with `reread` (the read-only screen) a member's later reads of its page come from the batch too. GBRA-108: `sliceReads` answers a screened slice's per-page reads (the origin claimants of `sync-origin.ts`, the stored timeline and take collisions of `canonical-projections.ts`, the safe-chunk fence of `page-state/projections.ts`, matched by their exported statements) from one statement per kind over the slice, row for row; a page with stored takes, a page or path outside the slice, a signalled call or a failed slice read runs its own statement (test `test/sync-legacy-sweep-gbra108.test.ts`). Tests: `test/import-reads.test.ts`, Postgres arm `test/e2e/import-reads.test.ts`.
- `src/core/persistence/screening-paths.ts` — GBRA-75 wave 7: `withScreeningPaths(run)` opens one screening batch's memo of root-level filesystem facts and `screeningPath(key, compute)` resolves each once inside it: other sources' root realpaths (`assertImportPaths`), shared skillpack root canonical paths and the source root's Git scope (`knowledge-guard.ts`). Per-file paths are never memoized; a nested batch joins the open one; the memo closes with `run`, so work that outlives it computes fresh; a throwing compute is never memoized. Opened by the managed import plan and screen loops (`import-mutations.ts`), each sync waiver screen (`screenWaiver`) and `sync-run.ts` `waiveRun`'s screens. Tests: `test/persistence-skip-cost.test.ts`.
- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. #6278: the lookup also matches the entry's file path, origin and a rename from that origin (`unfinishedPageRequestParams`), so the hold gate in `sync-run.ts` shares it. `unchangedSyncImport` (and so `sameContentAtOrigin`'s preparation) runs the sync preparer under `raceSyncBudget` against `persistence.sync_preparation_ms` (`syncPreparationBudgetMs`, read at most every 5 s, default 120 s) and the run's signal: past the budget nothing is waived and the origin refusal stands (fail open, nothing counted or held, `SyncPreparationBudgetExceeded`); a cancelled run propagates. GBRA-75 wave 8: `unchangedSyncImport` prepares with `{ unsaved: true }`, so its validation also accepts this run's cursor with nothing pending; before that every import waiver-run screen failed the cursor check and each unchanged file took a pending save, a second screen and its own waiver transaction. `waiveNoopRun` (up to 64 entries, one cursor write) re-reads the owner epoch under its lock (a change passes nothing; the per-entry path then refuses it) and each import's file bytes (an edit ends the prefix). Both waiver transactions read a waived import's file (a raw hash that no longer matches admits the entry) and write its `sync-import-provenance` record from the preparation's `importProvenance` (`waivedProvenance`: disk hash and blob id of those bytes, the page's current revision), so a waived page carries the same record a publication writes. Tests: `test/sync-waiver-budget.test.ts`, `test/sync-waiver-run-imports.test.ts`, `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget. `publicationHold(error)` returns `pending` for such a receipt or `contention` for an OperationError `storage_error` with detail `database_contention` and no receipt (admission rolled back, nothing recorded), else null — never from a message, a terminal receipt, a contention error carrying a receipt or a permission refusal; `publishOrHold(fn)` runs one publication and returns null on commit, the hold when there is one, and rethrows anything else. Used by the patterns, drift and synthesize dream phases.
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 5618e147d4..97aa8c27b1 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -361,10 +361,12 @@ export async function queuePageProjection(engine: Pick<BrainEngine, 'executeRaw'
ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason,updated_at=now()`, [sourceId, slug, reason]);
}
+/** A live, unsegmented page's chunker version (`projectionBelowSafeFence`). */
+export const SAFE_FENCE_SQL = "SELECT chunker_version FROM pages WHERE id=$1 AND deleted_at IS NULL AND body_storage IS DISTINCT FROM 'segmented'";
+
/** #5050/#5247: whether a live page's installed chunks predate the safe-chunk fence. */
export async function projectionBelowSafeFence(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<boolean> {
- const [row] = await engine.executeRaw<{ chunker_version: number | null }>(
- "SELECT chunker_version FROM pages WHERE id=$1 AND deleted_at IS NULL AND body_storage IS DISTINCT FROM 'segmented'", [pageId]) ?? [];
+ const [row] = await engine.executeRaw<{ chunker_version: number | null }>(SAFE_FENCE_SQL, [pageId]) ?? [];
return row !== undefined && belowSafeChunkFence(row.chunker_version === null ? null : Number(row.chunker_version));
}
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index 37d863aa7d..214ed6d27b 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -306,9 +306,16 @@ export function materializedHistoryRanges(body: string): Array<[number, number]>
interface StoredTimelineRow { id: number; date: string; source: string; summary: string; detail: string }
+/** The page's stored takes a fence's new rows (`$2`) would collide with: the same row number, another claim, kind or holder. */
+export const TAKE_COLLISIONS_SQL = `SELECT k.row_num FROM takes k
+ JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num
+ WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3`;
+
+/** A page's own (non-event) timeline rows, in date order. */
+export const STORED_TIMELINE_SQL = 'SELECT id,date::text AS date,source,summary,detail FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL ORDER BY date,id';
+
function storedTimeline(engine: BrainEngine, pageId: number): Promise<StoredTimelineRow[]> {
- return engine.executeRaw<StoredTimelineRow>(`SELECT id,date::text AS date,source,summary,detail FROM timeline_entries
- WHERE page_id=$1 AND event_page_id IS NULL ORDER BY date,id`, [pageId]);
+ return engine.executeRaw<StoredTimelineRow>(STORED_TIMELINE_SQL, [pageId]);
}
/**
@@ -545,9 +552,7 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
: priorTakes;
const newTakes = JSON.stringify(takes.filter(t => !priorCanonical.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));
const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));
- const collisions = async (db: BrainEngine, pageId: number) => (await db.executeRaw<{ row_num: number }>(`SELECT k.row_num FROM takes k
- JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num
- WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3`, [pageId, newTakes, FENCE_ROWS_MAX])).map(r => Number(r.row_num));
+ const collisions = async (db: BrainEngine, pageId: number) => (await db.executeRaw<{ row_num: number }>(TAKE_COLLISIONS_SQL, [pageId, newTakes, FENCE_ROWS_MAX])).map(r => Number(r.row_num));
const refuseCollisions = async (db: BrainEngine, pageId: number) => {
const rows = await collisions(db, pageId);
if (rows.length) throw takeCollision(rows, sections.takes, slug, sourceId);
diff --git a/src/core/persistence/import-reads.ts b/src/core/persistence/import-reads.ts
index 8484aef78e..0f85ae0d38 100644
--- a/src/core/persistence/import-reads.ts
+++ b/src/core/persistence/import-reads.ts
@@ -18,6 +18,9 @@
*/
import type { BrainEngine, PageSnapshot } from '../engine.ts';
import { pageSnapshotKey } from '../page-snapshot-batch.ts';
+import { SAFE_FENCE_SQL } from '../page-state/projections.ts';
+import { STORED_TIMELINE_SQL, TAKE_COLLISIONS_SQL } from './canonical-projections.ts';
+import { SYNC_ORIGIN_PAGES_SQL } from './sync-origin.ts';
type DuplicateInput = { hash: string; frontmatterId?: string | null; excludeSlug?: string };
type Duplicate = { slug: string; id: number } | null;
@@ -41,7 +44,8 @@ export interface ImportGroupReads {
findDuplicate(sourceId: string, opts: DuplicateInput): Promise<Duplicate>;
}
-export function importGroupReads(engine: BrainEngine, rows: ReadonlyArray<{ slug: string; source_id: string }>): ImportGroupReads {
+/** `reread`: a member's later reads of its page are answered from the batch too (the read-only screen, which publishes nothing). */
+export function importGroupReads(engine: BrainEngine, rows: ReadonlyArray<{ slug: string; source_id: string }>, mode: { reread?: boolean } = {}): ImportGroupReads {
const refs = rows.map(row => ({ slug: row.slug, sourceId: row.source_id }));
const unread = new Set(refs.map(ref => pageSnapshotKey(ref.sourceId, ref.slug)));
let batch: Promise<Map<string, PageSnapshot>> | undefined;
@@ -66,7 +70,7 @@ export function importGroupReads(engine: BrainEngine, rows: ReadonlyArray<{ slug
const read = opts as { sourceId?: unknown; includeDeleted?: unknown } | undefined;
if (!read || Object.keys(read).length !== 2 || read.includeDeleted !== true || typeof read.sourceId !== 'string') return undefined;
const key = pageSnapshotKey(read.sourceId, slug);
- if (!unread.delete(key)) return undefined;
+ if (!(mode.reread ? unread.has(key) : unread.delete(key))) return undefined;
batch ??= readImportSnapshots(engine, refs);
return batch.then(snapshots => snapshots.get(key) ?? null, () => engine.readPageSnapshot(slug, { sourceId: read.sourceId as string, includeDeleted: true }));
},
@@ -80,3 +84,63 @@ export function importGroupReads(engine: BrainEngine, rows: ReadonlyArray<{ slug
},
};
}
+
+const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();
+const ORIGIN = flat(SYNC_ORIGIN_PAGES_SQL), TIMELINE = flat(STORED_TIMELINE_SQL), TAKES = flat(TAKE_COLLISIONS_SQL), FENCE = flat(SAFE_FENCE_SQL);
+
+/**
+ * GBRA-108: the legacy sweep's screen (sync-convergence.ts) prepares a slice of pages one after another, and each
+ * preparation reads its own page's origin claimants, timeline rows, take collisions and safe-chunk fence. Here each kind
+ * is read once for the slice (the first call sends it) and every call it covers is answered row for row as its own
+ * statement would answer: the origin read is the same statement over the slice's paths, filtered to the call's; a page
+ * with no stored takes has no collision; the timeline and fence reads are their statements over the slice's page ids.
+ * A call the slice read does not cover (another page or path, a page with takes rows, a caller's signal) runs its own
+ * statement, and a failed slice read falls back to each call's own.
+ */
+export function sliceReads(engine: BrainEngine, slice: { sourceId: string; pageIds: readonly number[]; origins: readonly string[] }): BrainEngine {
+ const ids = new Set(slice.pageIds.map(String)), origins = new Set(slice.origins);
+ const batches = new Map<string, Promise<Map<string, unknown[]>>>();
+ const once = (kind: string, read: () => Promise<Map<string, unknown[]>>) => {
+ let batch = batches.get(kind);
+ if (!batch) { batch = read(); batches.set(kind, batch); }
+ return batch;
+ };
+ const byKey = <R extends Record<string, unknown>>(rows: R[], key: keyof R, strip = false) => {
+ const out = new Map<string, unknown[]>();
+ for (const row of rows) {
+ const { [key]: k, ...rest } = row;
+ const list = out.get(String(k)) ?? [];
+ list.push(strip ? rest : row);
+ out.set(String(k), list);
+ }
+ return out;
+ };
+ const pageIds = [...ids].map(Number);
+ const answer = (kind: string, sql: string, params: unknown[]): Promise<unknown[]> | undefined => {
+ if (kind === ORIGIN) {
+ const wanted = params[1] as unknown;
+ if (params[0] !== slice.sourceId || !Array.isArray(wanted) || !wanted.every(path => origins.has(path as string))) return undefined;
+ return once(kind, async () => new Map([['*', await engine.executeRaw(SYNC_ORIGIN_PAGES_SQL, [slice.sourceId, [...origins]])]]))
+ .then(rows => rows.get('*')!.filter(row => wanted.includes((row as { source_path: string }).source_path)));
+ }
+ const id = String(params[0]);
+ if (!ids.has(id)) return undefined;
+ if (kind === TIMELINE) return once(kind, async () => byKey(await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT page_id,id,date::text AS date,source,summary,detail FROM timeline_entries WHERE page_id=ANY($1::bigint[]) AND event_page_id IS NULL ORDER BY page_id,date,id', [pageIds]), 'page_id', true))
+ .then(rows => rows.get(id) ?? []);
+ if (kind === FENCE) return once(kind, async () => byKey(await engine.executeRaw<Record<string, unknown>>(
+ "SELECT id,chunker_version FROM pages WHERE id=ANY($1::bigint[]) AND deleted_at IS NULL AND body_storage IS DISTINCT FROM 'segmented'", [pageIds]), 'id', true))
+ .then(rows => rows.get(id) ?? []);
+ return once(kind, async () => byKey(await engine.executeRaw<Record<string, unknown>>('SELECT DISTINCT page_id FROM takes WHERE page_id=ANY($1::bigint[])', [pageIds]), 'page_id'))
+ .then(rows => rows.has(id) ? engine.executeRaw(sql, params) : []);
+ };
+ return new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {
+ const kind = flat(sql);
+ const answered = !opts?.signal && params && [ORIGIN, TIMELINE, TAKES, FENCE].includes(kind) ? answer(kind, sql, params) : undefined;
+ return answered ? answered.catch(() => target.executeRaw(sql, params, opts)) : target.executeRaw(sql, params, opts);
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
+}
diff --git a/src/core/persistence/sync-convergence.ts b/src/core/persistence/sync-convergence.ts
index 0a0d96040d..62fe94b2d7 100644
--- a/src/core/persistence/sync-convergence.ts
+++ b/src/core/persistence/sync-convergence.ts
@@ -29,7 +29,7 @@ import { screeningRequest } from './noop-kernel.ts';
import { prepareManagedSyncMutation, type SyncIntent } from './sync-prepare.ts';
import { sha256 } from './digest.ts';
import { preparationReads } from './group-publish.ts';
-import { importGroupReads } from './import-reads.ts';
+import { importGroupReads, sliceReads } from './import-reads.ts';
import { PAGE_PURGE_TOMBSTONES_SQL } from './page-purge.ts';
import { WORKTREE_BINDING_SQL } from './ownership.ts';
import { SOURCE_TRUST_CONFIG_SQL } from '../trust/channel.ts';
@@ -199,11 +199,17 @@ export function readOnlySameContentScreen(engine: BrainEngine, context: ManagedS
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, context.root);
const committed = level.mode === 'committed' ? await readBlobs(level.gitRoot, [...new Set(paths.map(entry => entry.state.level!).filter(Boolean))], 8 * 1024 * 1024) : new Map<string, Buffer>();
const runId = randomUUID();
- const pages = importGroupReads(engine, paths.flatMap(entry => entry.slug ? [{ slug: entry.slug, source_id: level.sourceId }] : []));
- const reads = preparationReads(engine, { snapshot: pages.snapshot, findDuplicate: (sourceId, input) => engine.findDuplicatePage?.(sourceId, input) ?? Promise.resolve(null) }, SCREEN_STABLE_READS);
+ const pages = importGroupReads(engine, paths.flatMap(entry => entry.slug ? [{ slug: entry.slug, source_id: level.sourceId }] : []), { reread: true });
+ const relative = (entry: ShadowPath) => level.scope ? entry.path.slice(level.scope.length + 1) : entry.path;
+ const origins = paths.flatMap(entry => {
+ const origin = level.slugMode === 'source-root' ? relative(entry) : entry.path;
+ return level.slugMode === 'source-root' && level.scope ? [origin, `${level.scope}/${origin}`] : [origin];
+ });
+ const reads = sliceReads(preparationReads(engine, { snapshot: pages.snapshot, findDuplicate: (sourceId, input) => engine.findDuplicatePage?.(sourceId, input) ?? Promise.resolve(null) },
+ SCREEN_STABLE_READS), { sourceId: level.sourceId, pageIds: paths.flatMap(entry => entry.pageId === null ? [] : [entry.pageId]), origins });
for (const entry of paths) {
try {
- const sourceRelative = level.scope ? entry.path.slice(level.scope.length + 1) : entry.path;
+ const sourceRelative = relative(entry);
const disk = readSyncFile(level.root, sourceRelative);
const bytes = level.mode === 'committed' ? committed.get(entry.state.level!) ?? null : disk;
if (!bytes || !entry.slug || entry.pageId === null || entry.revision === null || entry.state.page?.live !== true) { verdicts.set(entry.path, 'unknown'); continue; }
diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.ts
index 13cc413631..b5d2f1b5db 100644
--- a/src/core/persistence/sync-origin.ts
+++ b/src/core/persistence/sync-origin.ts
@@ -93,15 +93,17 @@ export function sharedOriginExit(sourceId: string, slugs: readonly string[]): st
return `Soft-delete the page that should not own the file (gbrain delete <slug> --source-id ${sourceId} --expected-revision <rev>, one of ${slugs.join(', ')}): a page whose file another live page records is hidden without touching the file, which the surviving page keeps.`;
}
+/** `assertSyncPageOrigin`'s read (the POSIX spelling): the source's pages recording one of the candidate origins. */
+export const SYNC_ORIGIN_PAGES_SQL = 'SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND source_path=ANY($2::text[])';
+
export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: string, sourcePath: string, pageId: number | null, requireOrigin = false,
context?: SyncOriginScope): Promise<void> {
const origin = syncOriginPath(sourcePath);
const legacy = legacySyncOrigin(context, origin);
const candidates = [origin, ...(legacy ? [legacy] : [])];
- const pathSql = process.platform === 'win32' ? "lower(replace(source_path,chr(92),'/'))=ANY($2::text[])" : 'source_path=ANY($2::text[])';
const key = (path: string) => process.platform === 'win32' ? syncOriginPath(path).toLowerCase() : syncOriginPath(path);
- const rows = await engine.executeRaw<{ id: number; slug: string; source_path: string; deleted_at: Date | string | null }>(
- `SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND ${pathSql}`, [sourceId, candidates.map(key)]);
+ const rows = await engine.executeRaw<{ id: number; slug: string; source_path: string; deleted_at: Date | string | null }>(process.platform === 'win32'
+ ? "SELECT id,slug,source_path,deleted_at FROM pages WHERE source_id=$1 AND lower(replace(source_path,chr(92),'/'))=ANY($2::text[])" : SYNC_ORIGIN_PAGES_SQL, [sourceId, candidates.map(key)]);
const pages = rows.filter(page => legacy === null || key(page.source_path) !== key(legacy) || sameSyncOrigin(page.source_path, origin, context, page.slug));
const { winner, ambiguous } = selectOriginClaimant(pages);
if (ambiguous || requireOrigin && pageId !== null && !winner ||
diff --git a/test/sync-legacy-sweep-gbra108.test.ts b/test/sync-legacy-sweep-gbra108.test.ts
index 8023866979..cf17da0b4f 100644
--- a/test/sync-legacy-sweep-gbra108.test.ts
+++ b/test/sync-legacy-sweep-gbra108.test.ts
@@ -7,9 +7,9 @@
* next pass started the sweep over.
*
* Protects:
- * - the sweep's statements grow by a bounded number per legacy page (its pages' own reads and record writes), and no
- * pass-invariant read (config, source config, binding, root, writer, managed mode, shared packs, purge tombstones)
- * runs more often for more pages;
+ * - within a slice the sweep's statements do not grow with its legacy pages: each kind of page read (snapshot, origin,
+ * timeline, takes, chunker fence) and the record writes run once a slice, and no pass-invariant read (config, source
+ * config, binding, root, writer, managed mode, shared packs, purge tombstones) runs more often for more pages;
* - a pass stopped mid-sweep keeps the records of the slices it finished: the next pass screens only the rest, records
* the first full sweep and leaves no legacy page unverified.
*
@@ -27,6 +27,11 @@ import { drainProjections } from '../src/core/page-state/projections.ts';
import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { SYNC_IMPORT_PROVENANCE_OP } from '../src/core/persistence/sync-holds.ts';
import { LEGACY_SWEEP_SLICE } from '../src/core/persistence/sync-pass-apply.ts';
+import { sliceReads } from '../src/core/persistence/import-reads.ts';
+import { STORED_TIMELINE_SQL, TAKE_COLLISIONS_SQL } from '../src/core/persistence/canonical-projections.ts';
+import { SYNC_ORIGIN_PAGES_SQL } from '../src/core/persistence/sync-origin.ts';
+import { SAFE_FENCE_SQL } from '../src/core/page-state/projections.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';
import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { managedBrain } from './helpers/managed-brain.ts';
@@ -42,8 +47,12 @@ const setupNotes = (count: number) => ({ root }: { root: string }) => {
for (const name of names(count)) writeFileSync(join(root, `notes/${name}.md`), `---\ntype: concept\ntitle: notes/${name}\n---\n\nThe committed body of notes/${name}.\n`);
git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
};
-/** Statements a legacy page may add to its sweep: its own five reads (origin, snapshot, chunker fence, timeline, takes) plus headroom; about 18 before GBRA-108. */
-const PER_PAGE_BUDGET = 6;
+/**
+ * Statements a legacy page may add to its sweep: none. Its slice reads each kind once (snapshot, origin, timeline, takes,
+ * chunker fence) and writes its records together, so a slice costs a constant; the half statement a page is headroom for
+ * the background work the counter also sees. A read per page coming back costs at least one a page (about 18 before GBRA-108).
+ */
+const PER_PAGE_BUDGET = 0.5;
/**
* Reads every screened preparation repeats; the sweep answers each once per slice, never once per page. The config read is
* the plain `SELECT … FROM config`: the projection drain's statement, which also reads config, runs on its own timer.
@@ -143,5 +152,28 @@ for (const backend of testBackends()) {
expect(row.telemetry.summary.legacy_unverified).toBe(0);
expect(await recorded(engine)).toBe(total);
}, { databaseUrl, setup: setupNotes(LEGACY_SWEEP_SLICE + 20) }), 300_000);
+
+ test('a slice read answers each page read as the page\'s own statement does, and a read it does not cover runs its own', () => managedBrain(async ({ engine }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ const pages = await engine.executeRaw<{ id: number; source_path: string }>("SELECT id, source_path FROM pages WHERE source_id='default' ORDER BY id");
+ const [taken, plain, outside] = [pages.find(p => p.source_path === 'notes/n000.md')!, pages.find(p => p.source_path === 'notes/n001.md')!, pages.find(p => p.source_path === 'notes/n002.md')!];
+ expect(await engine.executeRaw('SELECT 1 FROM takes WHERE page_id=$1', [taken.id])).not.toEqual([]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const [date, summary] of [['2024-03-02', 'second'], ['2024-01-05', 'first']]) await engine.executeRaw('INSERT INTO timeline_entries(page_id,date,summary) VALUES($1,$2,$3)', [plain.id, date, summary]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const slice = sliceReads(engine, { sourceId: 'default', pageIds: [taken.id, plain.id], origins: ['notes/n000.md', 'notes/n001.md'] });
+ const collide = JSON.stringify([{ row_num: 1, claim: 'another claim', kind: 'take', holder: 'brain' }]);
+ const reads: Array<[string, unknown[]]> = [
+ [SYNC_ORIGIN_PAGES_SQL, ['default', ['notes/n000.md']]], [SYNC_ORIGIN_PAGES_SQL, ['default', ['notes/n000.md', 'notes/n001.md']]], [SYNC_ORIGIN_PAGES_SQL, ['default', ['notes/n002.md']]],
+ ...[taken, plain, outside].flatMap(page => [[STORED_TIMELINE_SQL, [page.id]], [SAFE_FENCE_SQL, [page.id]], [TAKE_COLLISIONS_SQL, [page.id, collide, 50]]] as Array<[string, unknown[]]>)];
+ const byId = (rows: unknown[]) => [...rows].sort((a, b) => Number((a as { id?: number }).id ?? 0) - Number((b as { id?: number }).id ?? 0));
+ for (const [sql, params] of reads) expect(byId(await slice.executeRaw(sql, params))).toEqual(byId(await engine.executeRaw(sql, params)));
+ expect((await slice.executeRaw<{ row_num: number }>(TAKE_COLLISIONS_SQL, [taken.id, collide, 50])).map(row => Number(row.row_num))).toEqual([1]);
+ expect((await slice.executeRaw(STORED_TIMELINE_SQL, [plain.id])).map(row => (row as { summary: string }).summary)).toEqual(['first', 'second']);
+ }, { databaseUrl, setup: ({ root }) => {
+ setupNotes(3)({ root });
+ writeFileSync(join(root, 'notes/n000.md'), `---\ntype: concept\ntitle: notes/n000\n---\n\nA page with a take.\n\n${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n| 1 | a durable hunch | take | brain | 0.8 | 2026-04 | note |\n${TAKES_FENCE_END}\n`);
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'take');
+ } }), 300_000);
});
}