Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b (GBRA-108): legacy sweep after activation reads shared state once per slice and keeps its progress

garrytana98c3b941725
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.md
index 3d1e7154e4..06760e91d4 100644
--- a/docs/architecture/key-files/canonical-reconciliation.md
+++ b/docs/architecture/key-files/canonical-reconciliation.md
@@ -20,11 +20,11 @@
- `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; 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, 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-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`.
-- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round, the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.
+- `src/core/persistence/sync-pass-apply.ts` — what a live pass round does besides admitting one-sided imports and deletes (#6712 PR 4b, design v3.2 §2.5–§2.7, §3.1, §5): holds with side and state for the two-sided and deleted rows (`file_drift` with `side`, `tombstone_edited`, `purged_differs`, `file_gone`), the `settle_mismatch` hold after three passes at one level, arm-1 adoption of a record without a revision on `fileSame`, the bounded legacy sweep (500 per round) that records equal legacy pages on the first full round (GBRA-108: in slices of `LEGACY_SWEEP_SLICE` (100) whose records commit before the next slice, each followed by a pass-row save and a `managed_sync.legacy_swept` progress event the drain's in-pass governor counts, so a pass stopped mid-sweep keeps its slices and the next pass sweeps only the rest; seam `sync:legacy_slice`; tests `test/sync-legacy-sweep-gbra108.test.ts` and its Postgres twin), the mass-delete valve (one `sync-deletes-withheld` record; imports and the stamp proceed), `keep_db` admission (200 per pass), deletion-marker retirement in full rounds, and the remote ending (`reconcile_host_required`: one-sided work commits, drift stays unsettled with no hold). Entry points: `applyPassRound`, `finishPassApply`, `summarizeRound`. Tests: `test/sync-pass-completion-6712.test.ts`.
- `src/core/persistence/sync-pass-episode.ts` — pass episodes and cost (#6712 PR 4b, design §6, §7): `episodeClosure` closes an episode by inclusion or at the configured selection (a narrower episode never stamps `chunker_version`; a widened one releases its extra paths), `passCostDecision` defers paid embedding when the envelope is unknown or spent, and `reservePassCost` writes one `sync-pass-cost` row per admitted group (fingerprint `<source>:<incarnation>:<episode_or_pass_id>:<group_id>`, insert-once) inside the group's admission transaction, so a kill keeps the reservation and a replay adds nothing. Tests: `test/sync-pass-completion-6712.test.ts`.
- `src/core/persistence/sync-pass-status.ts` — the live `convergence` block of `gbrain sync status` (#6712 PR 4b, design §9, `dry_run: false`): built from the pass row (one primary-key read), the withheld-delete record and `syncAdmissionStatus`, plus `passStatusState`, which keeps a source off `synced` while its newest pass is open or ended unconverged (reasons `pass_unfinished`, `not_converged`, `settle_mismatch`, `deletes_withheld`, `selection_scoped`, `admission_paused`, and `writeback_failed`: a writeback the stamp recorded in `converged.writeback` whose Git effect failed or parked, next step `gbrain sources writer retry-effects --dry-run`). Tests: `test/sync-pass-completion-6712.test.ts`, `test/sync-pass-writeback-fold-6712.test.ts`.
- `src/core/persistence/sync-markers.ts` — the deletion marker and the withheld mass-delete record of a managed Git source (#6712 PR 4b). `writeOriginDeletedMarker` runs in the transaction of every page-row deletion of a managed source (`page-purge.ts`, the purge-mirror replay; `test/page-row-deleters-guard-6712.test.ts` refuses any other deleter) and writes `sync-origin-deleted` (`<source>:<incarnation>:<origin>`, value `{kind:'deleted', blob_oids, page_id, slug}` from the import record) only when it can matter: the origin is in the `last_commit` tree (hardened `ls-tree`) or a file backs it on disk, no other live page records it, and the source is bound and not a company brain; an unreadable checkout counts as present. `retireOriginDeletedMarker` is compare-and-delete on the value read. `writeDeletesWithheld` / `readDeletesWithheld` / `clearDeletesWithheld` keep one `sync-deletes-withheld` record per incarnation (`{target, count, reconcilable, ratio, set_hash, samples≤20}`, `deleteSetHash`: sha256 over the sorted NUL-joined set). Seam: `purge:marker_written`.
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 0921e93be3..552ac37f5c 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -63,6 +63,9 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6712 PR 4b (#6926): inside the round's last import's publication, before its folded stamp's checks (sync-pass-fold.ts); a hook
// that throws models a failed check statement there: the stamp rolls back to its savepoint and the pass stamps by its checkpoint request.
| 'sync:pass_fold'
+ // GBRA-108: before each slice of a legacy sweep is screened (sync-pass-apply.ts); a hook that throws stops the pass mid-sweep,
+ // as a kill or the drain's governor does.
+ | 'sync:legacy_slice'
// #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior
// bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.
| 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 6fdf6fc315..d8f11ab23f 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -165,9 +165,11 @@ const STABLE_IN_PREPARATION = new Set([
* above and config values (`getConfig`, `getAllConfig`) are answered once for
* the whole preparation, as if every member were prepared at the same moment;
* publication re-checks what it relies on under its locks. It lives only for
- * one group's preparation; a failed read is not kept.
+ * one group's preparation; a failed read is not kept. `also` adds plain reads a
+ * caller's preparations repeat (GBRA-108: the legacy sweep's read-only screen).
*/
-export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads): BrainEngine {
+export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads, also: readonly string[] = []): BrainEngine {
+ const stable = also.length ? new Set([...STABLE_IN_PREPARATION, ...also.map(flat)]) : STABLE_IN_PREPARATION;
const reads = new Map<string, Promise<unknown>>();
const once = <T>(id: string, read: () => Promise<T>): Promise<T> => {
let value = reads.get(id) as Promise<T> | undefined;
@@ -180,7 +182,7 @@ export function preparationReads(engine: BrainEngine, imports?: ImportGroupReads
// A shared read takes no member's signal: a caller's own signal bypasses the memo, and (#6278) a bounded preparation read
// (`timeoutMs`, whose signal only covers its connection wait) is answered once with the member's bound and signal dropped.
if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) =>
- STABLE_IN_PREPARATION.has(flat(sql)) && (!opts?.signal || opts.timeoutMs !== undefined)
+ stable.has(flat(sql)) && (!opts?.signal || opts.timeoutMs !== undefined)
? once(JSON.stringify([flat(sql), params ?? null]), () => target.executeRaw(sql, params)) : target.executeRaw(sql, params, opts);
// GBRA-75 wave 10: every config key a member reads comes from one config read for the group (the same value per key).
if (key === 'getConfig') return (name: string) => once('config:*', () => target.getAllConfig()).then(all => Object.hasOwn(all, name) ? all[name]! : null);
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 39a95ab342..b5344b9be2 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -71,13 +71,15 @@ export async function graduationVerifyInheritsPersistence(engine: BrainEngine):
export async function persistenceEnabledForHealth(engine: BrainEngine): Promise<boolean> {
return await managedPersistenceEnabled(engine) || await graduationVerifyInheritsPersistence(engine);
}
-export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
- const [row] = await engine.executeRaw<WorktreeBinding>(`SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path,
+/** The source's binding as this host sees it; group-publish.ts's preparation memo answers this exact statement once. */
+export const WORKTREE_BINDING_SQL = `SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path,
s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state,
h.local_path,h.coordination_path,h.git_durability,w.manifest->>'prepared_at' AS prepared_at FROM persistence_source_bindings s
JOIN persistence_worktrees w ON w.id=s.worktree_id
LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid
- WHERE s.source_id=$1`, [sourceId, hostId]);
+ WHERE s.source_id=$1`;
+export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, hostId: string | null = localHostId()): Promise<WorktreeBinding | null> {
+ const [row] = await engine.executeRaw<WorktreeBinding>(WORKTREE_BINDING_SQL, [sourceId, hostId]);
return row ?? null;
}
/** `automatic` is only the ordinary first-write claim; the writer admin lock never blocks it. */
diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.ts
index 103ee75b38..118dc78eb2 100644
--- a/src/core/persistence/page-purge.ts
+++ b/src/core/persistence/page-purge.ts
@@ -381,9 +381,10 @@ export async function finishPagePurge(ctx: Pick<OperationContext, 'engine' | 'co
return { ...result, ...extra };
}
+export const PAGE_PURGE_TOMBSTONES_SQL = 'SELECT content_hash,slug FROM page_purges WHERE source_id=$1 ORDER BY purged_at DESC LIMIT $2';
/** Prefetch for import screens: every page tombstone of a source, content hash -> slug (bounded). */
export async function readPagePurgeTombstones(engine: BrainEngine, sourceId: string, limit = 10_000): Promise<Map<string, string>> {
- const rows = await engine.executeRaw<{ content_hash: string; slug: string }>('SELECT content_hash,slug FROM page_purges WHERE source_id=$1 ORDER BY purged_at DESC LIMIT $2', [sourceId, limit]);
+ const rows = await engine.executeRaw<{ content_hash: string; slug: string }>(PAGE_PURGE_TOMBSTONES_SQL, [sourceId, limit]);
return new Map(rows.map(r => [r.content_hash, r.slug]));
}
diff --git a/src/core/persistence/sync-convergence.ts b/src/core/persistence/sync-convergence.ts
index 38040152d6..0a0d96040d 100644
--- a/src/core/persistence/sync-convergence.ts
+++ b/src/core/persistence/sync-convergence.ts
@@ -28,6 +28,11 @@ import { managedSyncAuthority, type SyncProcessingOptions } from './sync-authori
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 { PAGE_PURGE_TOMBSTONES_SQL } from './page-purge.ts';
+import { WORKTREE_BINDING_SQL } from './ownership.ts';
+import { SOURCE_TRUST_CONFIG_SQL } from '../trust/channel.ts';
/** keep_db DB-wins writes one pass admits (design v3.2 §4, [estimated]); the rest are `keep_db_pending`. */
export const KEEP_DB_PASS_CAP = 200;
@@ -177,10 +182,16 @@ export async function buildConvergenceReceipt(engine: BrainEngine, level: Shadow
};
}
+/** Plain reads every screened preparation repeats beside group-publish.ts's `preparationReads` set: the binding, the owner trust config and the purge tombstones. */
+const SCREEN_STABLE_READS = [WORKTREE_BINDING_SQL, SOURCE_TRUST_CONFIG_SQL, PAGE_PURGE_TOMBSTONES_SQL];
+
/**
* The dry run's read-only `sameContentAtOrigin` (sync-run.ts): prepares each drift path's import as a screening request
* (`prepareManagedSyncMutation(..., { unsaved: true })`, never admitted or persisted) and reports `same` when the
- * preparer's own no-op verdict holds at the page's current revision.
+ * preparer's own no-op verdict holds at the revision the level read for the page. GBRA-108: one call's preparations
+ * share what each would read again (`preparationReads`: the writer, binding, root, managed mode, shared packs, config,
+ * trust config, purge tombstones) and read their pages in one batch (`importGroupReads`), so a call costs its pages'
+ * own reads plus a constant, not every shared read once per page.
*/
export function readOnlySameContentScreen(engine: BrainEngine, context: ManagedSyncContext, processingOptions: SyncProcessingOptions): ConvergenceScreen {
return async (level, paths) => {
@@ -188,22 +199,23 @@ 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);
for (const entry of paths) {
try {
const sourceRelative = level.scope ? entry.path.slice(level.scope.length + 1) : entry.path;
const disk = readSyncFile(level.root, sourceRelative);
const bytes = level.mode === 'committed' ? committed.get(entry.state.level!) ?? null : disk;
- const snapshot = entry.slug ? await engine.readPageSnapshot(entry.slug, { sourceId: level.sourceId, includeDeleted: true }) : null;
- if (!bytes || !snapshot || snapshot.page.deleted_at != null) { verdicts.set(entry.path, 'unknown'); continue; }
+ if (!bytes || !entry.slug || entry.pageId === null || entry.revision === null || entry.state.page?.live !== true) { verdicts.set(entry.path, 'unknown'); continue; }
const content = bytes.toString('utf8');
const lineEndingOnly = disk !== null && disk.equals(Buffer.from(disk.toString('utf8'))) && disk.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');
const sourcePath = level.slugMode === 'source-root' ? sourceRelative : entry.path;
- const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: snapshot.revision, sourcePath, path: sourceRelative, rawHash: disk ? sha256(disk) : null, content, lineEndingOnly,
+ const intent: SyncIntent = { kind: 'managed_sync_import', expected_revision: entry.revision, sourcePath, path: sourceRelative, rawHash: disk ? sha256(disk) : null, content, lineEndingOnly,
processingOptions, ownerEpoch: String(context.binding.owner_epoch), syncAuthority: authority, cursorKey: `convergence-shadow:${level.sourceId}`, runId,
slugMode: level.slugMode, index: 0, total: 1, from: level.baselineCommit, target: level.head, working: level.mode === 'working' };
- const prepared = await prepareManagedSyncMutation(engine, screeningRequest({ source_id: level.sourceId, source_incarnation: level.incarnation, slug: snapshot.page.slug,
- page_id: snapshot.page.id, worktree_id: context.binding.worktree_id, authority: authority.writer, intent }), { engine: engine.kind } as never, undefined, { unsaved: true });
- verdicts.set(entry.path, (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file && prepared.observedRevision === snapshot.revision ? 'same' : 'differs');
+ const prepared = await prepareManagedSyncMutation(reads, screeningRequest({ source_id: level.sourceId, source_incarnation: level.incarnation, slug: entry.slug,
+ page_id: entry.pageId, worktree_id: context.binding.worktree_id, authority: authority.writer, intent }), { engine: engine.kind } as never, undefined, { unsaved: true });
+ verdicts.set(entry.path, (prepared.contentUnchanged === true || prepared.noop === true) && !prepared.file && prepared.observedRevision === entry.revision ? 'same' : 'differs');
} catch {
verdicts.set(entry.path, 'unknown');
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index d1f664972c..29615a2a52 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -425,6 +425,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped, fallbacks: event.lanes.fallbacks };
// #6696 C4: the checkpoint commit is a commit; the tail after it is governed by its own budget.
if (event.phase === 'managed_sync.finish') { lastCommitAt = clock(); drops = 0; noteForwardProgress(); return; }
+ // GBRA-108: a pass's committed legacy-sweep slice (sync-pass-apply.ts) is progress, though it publishes no page.
+ if (event.phase === 'managed_sync.legacy_swept') { lastCommitAt = clock(); noteForwardProgress(); return; }
if (event.phase !== 'managed_sync.page_committed') return;
if (event.waived) waived++; else written++;
lastCommitAt = clock(); drops = 0;
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.ts
index a8206a8812..4a23d688c4 100644
--- a/src/core/persistence/sync-pass-apply.ts
+++ b/src/core/persistence/sync-pass-apply.ts
@@ -40,10 +40,11 @@ import { admitKeepDbReconcile, driftSkippedSlugs, freezeKeepDbReconcile, release
const KEEP_DB_CAPACITY_REFUSALS = new Set(['capacity', 'write_capacity_backpressure', 'queue_capacity', 'write_quota_exhausted', 'writer_busy', 'writer_pool_capacity']);
import type { SyncProcessingOptions } from './sync-authority.ts';
import type { SyncClassified } from './sync-classify.ts';
-import { readOnlySameContentScreen } from './sync-convergence.ts';
+import { readOnlySameContentScreen, type ConvergenceScreen } from './sync-convergence.ts';
import type { ManagedSyncContext } from './sync-discovery.ts';
import { sha256 } from './digest.ts';
import { readBlobs } from './sync-git-stream.ts';
+import { faultPoint } from './fault-points.ts';
import { RECOVERY_VERSION } from '../markdown.ts';
import { readSyncImportProvenances, recordSyncImportProvenances, syncImportParserFor, writeGitHold,
type GitHoldCode, type GitHoldMeta, type SyncImportProvenance } from './sync-holds.ts';
@@ -63,6 +64,8 @@ import { frontmatterIdentity } from '../sync-rename-identity.ts';
/** Legacy pages the sweep screens per pass after the incarnation's first full round (design §2.7, [estimated]). */
export const PASS_LEGACY_SWEEP_MAX = 500;
+/** GBRA-108: legacy pages one sweep slice screens and records before the next is screened. */
+export const LEGACY_SWEEP_SLICE = 100;
/** keep_db DB-wins writes a pass admits (design §4, [estimated]). */
export const PASS_KEEP_DB_MAX = 200;
/** The bootstrap Decision gate (design §2.7, [estimated]): file_drift Decisions per 10,000 pages. */
@@ -116,7 +119,9 @@ export interface PassApplyInput {
/** A remote caller's slug-prefix grant (null: source-wide): paths outside it are left unsettled and never counted (design §5). */
grantPrefixes?: readonly string[] | null;
/** Test seam: the read-only same-content screen (default `readOnlySameContentScreen`). */
- screen?: (level: ShadowLevel, paths: ShadowPath[]) => Promise<Map<string, 'same' | 'differs' | 'unknown'>>;
+ screen?: ConvergenceScreen;
+ /** GBRA-108: after each committed legacy-sweep slice (the pass saves its row and reports progress). */
+ onSwept?: () => Promise<void>;
}
/** The source-relative path (`SyncEntry.path`, the hold key) and the recorded origin of a level path. */
@@ -391,19 +396,32 @@ async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: Pass
state.adopted += (await writeRecords(engine, level, writes, state.recorded)).size;
}
-/** Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. */
+/**
+ * Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. The first full round
+ * sweeps every legacy page, LEGACY_SWEEP_SLICE at a time (GBRA-108): each slice's records commit before the next
+ * slice is screened and the slice is reported as progress (`onSwept`), so a pass stopped mid-sweep keeps what it
+ * recorded (those pages classify `matched` and the next pass sweeps the rest) and a long sweep is never a stalled pass.
+ */
async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassApplyInput, state: PassApplyState): Promise<void> {
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);
const batch = legacy.slice(0, budget);
- if (!batch.length) return;
- const screen = input.screen ?? readOnlySameContentScreen(engine, input.context, input.processingOptions);
- const verdicts = await screen(level, batch);
- state.swept.screened += batch.length;
+ const screen = batch.length ? input.screen ?? readOnlySameContentScreen(engine, input.context, input.processingOptions) : null;
+ for (let at = 0; screen && at < batch.length; at += LEGACY_SWEEP_SLICE) {
+ await faultPoint('sync:legacy_slice', { sourceId: level.sourceId });
+ await sweepSlice(engine, level, batch.slice(at, at + LEGACY_SWEEP_SLICE), screen, state);
+ await input.onSwept?.();
+ }
+ // A full round that finds no legacy page left (an earlier pass recorded them before it stopped) has swept them all too.
if (sweepAll) state.sweptAll = true;
- const same = batch.filter(entry => verdicts.get(entry.path) === 'same');
+}
+
+/** One sweep slice: screen it, then record its equal pages (fenced on the revision the level read). */
+async function sweepSlice(engine: BrainEngine, level: ShadowLevel, slice: ShadowPath[], screen: ConvergenceScreen, state: PassApplyState): Promise<void> {
+ const verdicts = await screen(level, slice);
+ state.swept.screened += slice.length;
+ const same = slice.filter(entry => verdicts.get(entry.path) === 'same');
if (!same.length) return;
const blobs = level.mode === 'committed' ? await readBlobs(level.gitRoot, [...new Set(same.map(entry => entry.state.level!))], LEVEL_BLOB_MAX_BYTES) : new Map<string, Buffer>();
const writes = same.flatMap((entry): RecordWrite[] => {
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index b9d69935b6..0e15a6bfb3 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -672,6 +672,8 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (outcome === 'blocked' || stopReason === 'not_converged') value.obligations.stuck_since ??= new Date().toISOString();
await engine.transaction(async tx => { await assertDrainLease(tx, sourceId); await writePassRow(tx, value, { pin }); });
};
+ // GBRA-108: a committed legacy-sweep slice is progress: the row a follower watches and the drain's in-pass governor see it.
+ const onSwept = async () => { assertActive(); await save('open', null); opts.onProgress?.({ phase: 'managed_sync.legacy_swept', bankedFiles: sliceBase.pages }); };
const identityDowngrades: DowngradedRename[] = [];
const fileRefusals = new Map<string, SyncFileRefusal>();
const keptCount = () => lastLevel?.paths.filter(entry => entry.result.cls === 'kept').length ?? 0;
@@ -785,7 +787,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
value.obligations.legacy_markers_at = new Date().toISOString();
}
await applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,
- grantPrefixes: remote ? authority.writer.slugPrefixes : null }, applied);
+ grantPrefixes: remote ? authority.writer.slugPrefixes : null, onSwept }, applied);
assertActive();
if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };
if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;
diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.ts
index b3cff4e2b6..7b528cc636 100644
--- a/src/core/trust/channel.ts
+++ b/src/core/trust/channel.ts
@@ -209,6 +209,9 @@ export function stampTrustMarker(frontmatter: Record<string, unknown>, tier: Tru
return { ...frontmatter, trust_tier: marker };
}
+/** The source config `ownerImportTrust` reads. */
+export const SOURCE_TRUST_CONFIG_SQL = 'SELECT config FROM sources WHERE id = $1';
+
/**
* The tier of a journaled owner-source write of one page (managed sync,
* import, reconcile, file repair, grandfather): `ownerPageTrust` from the
@@ -216,7 +219,7 @@ export function stampTrustMarker(frontmatter: Record<string, unknown>, tier: Tru
*/
export async function ownerImportTrust(engine: Pick<BrainEngine, 'executeRaw'>, row: Pick<WriteRequest, 'id' | 'source_id' | 'authority' | 'intent' | 'operation'>,
frontmatter: Record<string, unknown> | null | undefined, sourceUri?: string | null): Promise<WriteTrust> {
- const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string | null }>('SELECT config FROM sources WHERE id = $1', [row.source_id]);
+ const [source] = await engine.executeRaw<{ config: Record<string, unknown> | string | null }>(SOURCE_TRUST_CONFIG_SQL, [row.source_id]);
const config = typeof source?.config === 'string' ? JSON.parse(source.config) as Record<string, unknown> : source?.config ?? null;
const trust = ownerPageTrust({ frontmatter, sourceConfig: config, channel: requestChannel(row), requestId: row.id, sourceUri });
return row.authority?.remote === true ? { ...trust, tier: minTrust(trust.tier, 'agent_written') } : trust;
diff --git a/test/e2e/sync-legacy-sweep-gbra108-postgres.test.ts b/test/e2e/sync-legacy-sweep-gbra108-postgres.test.ts
new file mode 100644
index 0000000000..41fe0fa89b
--- /dev/null
+++ b/test/e2e/sync-legacy-sweep-gbra108-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-legacy-sweep-gbra108.test.ts'));
diff --git a/test/sync-legacy-sweep-gbra108.test.ts b/test/sync-legacy-sweep-gbra108.test.ts
new file mode 100644
index 0000000000..155e57195a
--- /dev/null
+++ b/test/sync-legacy-sweep-gbra108.test.ts
@@ -0,0 +1,144 @@
+/**
+ * GBRA-108 (GBRA-133 latency §6.14): the first managed sync after activating a classic brain sweeps every legacy page
+ * (design §2.7) through the read-only same-content screen. Before the fix each screened page re-read the config table,
+ * the source's config, its binding, root, writer, managed mode, shared packs and purge tombstones, and its own page three
+ * times (about 18 statements a page), and the sweep recorded nothing until it had screened the whole source: at 100k
+ * pages on Postgres it outlived the drain's 300 s no-progress window, the pass was abandoned with nothing kept, and the
+ * 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;
+ * - 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.
+ *
+ * PGLite here (statements counted at the PGLite protocol); Postgres through
+ * test/e2e/sync-legacy-sweep-gbra108-postgres.test.ts (the wire trace, src/core/sql-trace.ts).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+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 { 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';
+import { countPgliteStatements, readSqlTrace, type StatementRecord } from './helpers/statement-counter.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const names = (count: number) => Array.from({ length: count }, (_, i) => `n${String(i).padStart(3, '0')}`);
+const setupNotes = (count: number) => ({ root }: { root: string }) => {
+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
+ 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;
+/** Reads every screened preparation repeats; the sweep answers each once per slice, never once per page. */
+const INVARIANT = [/\bFROM config\b/, /SELECT config FROM sources\b/, /FROM persistence_brain\b/, /FROM persistence_local_writers\b/, /FROM page_purges\b/,
+ /FROM shared_skill_packs\b/, /SELECT local_path FROM sources\b/, /FROM persistence_source_bindings s\b/];
+
+const passRow = async (engine: BrainEngine) => (await engine.executeRaw<{ value: any }>('SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1', [MANAGED_SYNC_PASS_OP]))[0]?.value ?? null;
+const recorded = async (engine: BrainEngine) => (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM op_checkpoints WHERE op=$1', [SYNC_IMPORT_PROVENANCE_OP]))[0]!.n;
+
+/** Turns the synced pages into pages an older gbrain imported: the same rows with no import record, and no pass row. */
+async function legacyPages(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ const cols = 'source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, source_path';
+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT ${cols} FROM pages WHERE source_id='default'`);
+ await engine.executeRaw("DELETE FROM pages WHERE source_id='default'");
+ for (const row of rows) await engine.executeRaw(`INSERT INTO pages(${cols}) VALUES($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9)`,
+ [row.source_id, row.slug, row.type, row.title, row.compiled_truth, row.timeline, JSON.stringify(row.frontmatter), row.content_hash, row.source_path]);
+ } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op IN ($1,$2)', [SYNC_IMPORT_PROVENANCE_OP, MANAGED_SYNC_PASS_OP]);
+ // The rewritten rows' projection rebuilds run now, not inside the measured sync.
+ while ((await drainProjections(engine, { limit: 100 })).rebuilt > 0);
+}
+
+/** The statements `run` sends: the PGLite protocol, or the Postgres wire trace's records inside its window. */
+async function counted(engine: BrainEngine, trace: string, run: () => Promise<unknown>): Promise<StatementRecord[]> {
+ if (engine.kind === 'pglite') {
+ const counter = countPgliteStatements(engine as PGLiteEngine);
+ try { await run(); } finally { counter.stop(); }
+ return counter.records;
+ }
+ const started = performance.timeOrigin + performance.now();
+ await run();
+ const ended = performance.timeOrigin + performance.now();
+ // The trace flushes every second.
+ await Bun.sleep(1500);
+ return readSqlTrace(trace).filter(record => record.t >= started && record.t <= ended && (record.kind === 'execute' || record.kind === 'simple'));
+}
+
+/** The first managed sync after the pages turned legacy: its statements, telemetry and records. */
+async function sweep(count: number, databaseUrl: string | undefined, trace: string) {
+ let out: { records: StatementRecord[]; counts: Record<string, number>; recorded: number; legacySweep: unknown } | null = null;
+ await managedBrain(async ({ engine }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await legacyPages(engine);
+ const records = await counted(engine, trace, async () => { expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures'); });
+ const row = await passRow(engine);
+ out = { records, counts: row.telemetry.counts, recorded: await recorded(engine), legacySweep: row.obligations.legacy_sweep ?? null };
+ }, { databaseUrl, setup: setupNotes(count) });
+ return out!;
+}
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ describe(`GBRA-108: the legacy sweep after activation (${backend})`, () => {
+ test('the sweep costs a bounded number of statements per legacy page, and no pass-invariant read runs per page', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-legacy-sweep-'));
+ const trace = join(home, 'trace.jsonl');
+ try {
+ await withEnv({ GBRAIN_SQL_TRACE: databaseUrl ? trace : undefined, GBRAIN_SQL_TRACE_LABEL: databaseUrl ? 'legacy-sweep' : undefined }, async () => {
+ const small = await sweep(12, databaseUrl, trace), large = await sweep(48, databaseUrl, trace);
+ for (const [run, n] of [[small, 12], [large, 48]] as const) {
+ expect(run.counts).toMatchObject({ legacy_swept: n, legacy_recorded: n });
+ expect(run.recorded).toBe(n);
+ expect(run.legacySweep).toMatchObject({ first_full_at: expect.any(String) });
+ }
+ // The counter saw both syncs (each reads its pages at least once).
+ expect(small.records.length).toBeGreaterThan(12);
+ const perPage = (large.records.length - small.records.length) / (48 - 12);
+ expect(perPage).toBeLessThanOrEqual(PER_PAGE_BUDGET);
+ const uses = (records: StatementRecord[]) => INVARIANT.map(pattern => [String(pattern), records.filter(record => pattern.test(record.sql)).length]);
+ expect(uses(large.records)).toEqual(uses(small.records));
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 300_000);
+
+ test('a pass stopped mid-sweep keeps the slices it recorded; the next pass sweeps only the rest and records the first full sweep', () => managedBrain(async ({ engine }) => {
+ const total = LEGACY_SWEEP_SLICE + 20;
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ await legacyPages(engine);
+ let slices = 0;
+ installFaultHook(async point => { if (point === 'sync:legacy_slice' && ++slices === 2) throw new Error('killed mid-sweep'); });
+ const stopped = await performManagedSync(engine, OPTS).then(result => result.status, (error: Error) => error.message);
+ expect(stopped).not.toMatch(/^(synced|up_to_date)$/);
+ installFaultHook(undefined);
+ // The first slice's records committed before the stop; the pass recorded no full sweep.
+ expect(await recorded(engine)).toBe(LEGACY_SWEEP_SLICE);
+ expect((await passRow(engine))?.obligations.legacy_sweep ?? null).toBeNull();
+
+ expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures');
+ const row = await passRow(engine);
+ expect(row.telemetry.counts).toMatchObject({ legacy_swept: total - LEGACY_SWEEP_SLICE, legacy_recorded: total - LEGACY_SWEEP_SLICE });
+ expect(row.obligations.legacy_sweep).toMatchObject({ first_full_at: expect.any(String) });
+ expect(row.telemetry.summary.legacy_unverified).toBe(0);
+ expect(await recorded(engine)).toBe(total);
+ }, { databaseUrl, setup: setupNotes(LEGACY_SWEEP_SLICE + 20) }), 300_000);
+ });
+}