Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): the legacy sweep resumes at a cursor and stays bounded per pass (#7189)
garrytan5e26846ee52d
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cda8c94855..bd324a475a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1021,6 +1021,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },+ { since: '0.60.339.0', text: 'A managed sync of a source with pages from before managed persistence (legacy pages) now screens at most 500 of them per pass, then imports the pass\'s real changes, and the next full round resumes the screen where the last one stopped (#7189). Before, the first full round screened every legacy page before importing anything, a page whose body no longer matched its file was never recorded, and a pass stopped by its deadline started over from the top, so a source with thousands of such pages stopped advancing. The pass row keeps the position in `obligations.legacy_sweep.cursor`.' },{ since: '0.60.333.0', text: '`gbrain doctor --tier quick` is the health gate for agents on large brains: the ops sections plus schema version, sync failures, queue health and partial embeddings under a 10 s deadline, with every other check reported from its last known result and its age (same status; `details.last_known`, `last_known_sections`). A brain-wide `gbrain doctor` run now records each check it finishes in `op_checkpoints` (op `doctor-last-known`), and a check that runs out of its budget reports that result instead of unknown while it is under 24 h old. Checks with no result that recent are named in one `doctor_last_known` warning, and a Postgres brain queues one background `doctor-refresh` job per hour to measure them (it needs a running jobs worker). `--only` and `--source` runs neither read nor record these results.' },{ since: '0.60.333.0', text: '`gbrain doctor --only sync_failures` now connects the brain instead of reporting that durable sync state is unavailable. `sync_failures` ignores, and counts, local-ledger rows that no sync can retry or clear: rows on a source that is not registered, and rows whose file was deleted from its source after it failed. A process running under `bun test` (NODE_ENV=test) with neither GBRAIN_SYNC_FAILURES_DIR nor GBRAIN_HOME set writes a scratch sync-failure ledger instead of the real one.' },{ since: '0.60.333.0', text: 'Behind a transaction-mode pooler, the "Prepared statements and statement pipelining disabled" banner prints once per database per gbrain home instead of on every call (`gbrain engine status` and doctor\'s `pgbouncer_prepare` still report it). A one-shot read command reads the config table once for its startup and once for the operation, and skips the retired managed-marker cleanup that only writes need.' },diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex 5b2b5a2c27..c2ba27027f 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -78,7 +78,8 @@ export interface PassApplyState {holds: { file_gone: number; tombstone_edited: number; purged_differs: number; settle_mismatch: number; origin_conflict: number; page_identity_changed: number; uncommitted: number };settleMismatch: string[];adopted: number;- swept: { screened: number; recorded: number };+ /** `paths`: what this pass screened, so a later round of the pass never screens a page again (#7189). */+ swept: { screened: number; recorded: number; paths: Set<string> };/** The first full round of the incarnation swept every legacy page (the pass records it in `obligations.legacy_sweep`). */sweptAll: boolean;withheld: DeletesWithheld | null;@@ -102,7 +103,7 @@ export interface PassApplyState {export function newPassApplyState(): PassApplyState {return { markersRetired: 0, holds: { file_gone: 0, tombstone_edited: 0, purged_differs: 0, settle_mismatch: 0, origin_conflict: 0, page_identity_changed: 0, uncommitted: 0 }, settleMismatch: [], adopted: 0,- swept: { screened: 0, recorded: 0 }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };+ swept: { screened: 0, recorded: 0, paths: new Set() }, sweptAll: false, withheld: null, withheldCount: 0, keepDb: { admitted: 0, pending: 0, paused: 0, refused: {} }, keepDbTaken: [], originHeld: new Set(), matchedSlugs: new Set(), classes: {}, summary: null, recorded: new Set() };}export interface PassApplyInput {@@ -418,30 +419,43 @@ 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`. 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.+ * Design §2.7: the bounded read-only legacy sweep; an equal page gets a record and is `matched`. A pass screens at most+ * PASS_LEGACY_SWEEP_MAX legacy pages, 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`). #7189: the sweep goes in path order from+ * `obligations.legacy_sweep.cursor`, the last path a slice screened, which is saved with the slice. A page that differs+ * gets no record, so without the cursor a pass stopped mid-sweep kept nothing and the next one screened the same pages+ * again: a first full round that had to screen every page in one pass never finished, and the round's real changes behind+ * it were never imported. The incarnation's first full sweep goes once to the end and records `first_full_at`; later+ * sweeps wrap around to the start.*/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);- 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);+ const legacy = (await filterYielding(level.paths, entry => entry.result.cls === 'legacy_unverified' && entry.pageId !== null && entry.revision !== null && entry.state.level !== null && entry.slug))+ .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);+ const sweep = input.obligations.legacy_sweep;+ // The pass that finishes the first full sweep does not wrap around in a later round.+ const firstFull = input.fullRound && (!sweep?.first_full_at || state.sweptAll);+ const cursor = sweep?.cursor;+ const from = cursor === undefined ? 0 : legacy.findIndex(entry => entry.path > cursor);+ const start = from < 0 ? legacy.length : from;+ const batch = [...legacy.slice(start), ...firstFull ? [] : legacy.slice(0, start)].filter(entry => !state.swept.paths.has(entry.path))+ .slice(0, Math.max(0, PASS_LEGACY_SWEEP_MAX - state.swept.screened));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);+ const slice = batch.slice(at, at + LEGACY_SWEEP_SLICE);+ await sweepSlice(engine, level, slice, screen, state);+ input.obligations.legacy_sweep = { ...input.obligations.legacy_sweep, cursor: slice[slice.length - 1]!.path };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;+ // A full round whose sweep reached the end (or found no legacy page left) has swept them all.+ if (firstFull && start + batch.length >= legacy.length) state.sweptAll = true;}/** 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;+ for (const entry of slice) state.swept.paths.add(entry.path);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>();diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.tsindex 909043c1e0..f820e5a0f6 100644--- a/src/core/persistence/sync-pass-row.ts+++ b/src/core/persistence/sync-pass-row.ts@@ -75,8 +75,11 @@ export interface ManagedSyncPassValue {/** When the current run of unhealthy endings (`blocked`, `not_converged`) began; kept across them, cleared at `synced`/`up_to_date`. The §3.7 readers age a stuck source from it. */stuck_since?: string | null;faults: Record<string, { level: string | null; class: string; attempts: number }>;- /** #6712 PR 4b (design §2.7): when the incarnation's first full round swept every `legacy_unverified` page; later passes sweep at most 500. */- legacy_sweep?: { first_full_at: string };+ /**+ * #6712 PR 4b (design §2.7): when the incarnation's first full sweep reached every `legacy_unverified` page. Each pass sweeps+ * at most 500, from `cursor` (#7189: the last path a committed slice screened), so a stopped pass's next one resumes.+ */+ legacy_sweep?: { first_full_at?: string; cursor?: string };/** #6712 PR 4b (design §2.7 (b1)): when the incarnation's legacy markers were written; until then each pass's first round writes them (idempotent). */legacy_markers_at?: string;/** #6712 PR 4b (design §2.6): the set hash of a withheld mass delete; with the env valve set the next tick runs a full round to apply it. */diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 191a3ad6a9..2080a4327b 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -794,7 +794,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait applyPassRound(engine, level, { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,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 (applied.sweptAll && !value.obligations.legacy_sweep?.first_full_at) 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;const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts });// Earlier passes' requests that committed since they stopped are this pass's imports (sync-pass-carried.ts).diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex ccf396b282..6f8a671deb 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -423,6 +423,7 @@ test/sync-landing-gaps.test.tstest/sync-legacy-holds.test.tstest/sync-legacy-retry-actions-6696.test.tstest/sync-legacy-slug-adoption-6727.test.ts+test/sync-legacy-sweep-resume-7189.test.tstest/sync-origin-live-wins-6517.test.tstest/sync-page-identity-hold-gbra130.test.tstest/sync-page-write-failed-gbra130.test.tsdiff --git a/test/sync-legacy-sweep-gbra108.test.ts b/test/sync-legacy-sweep-gbra108.test.tsindex cf17da0b4f..592433ec58 100644--- a/test/sync-legacy-sweep-gbra108.test.ts+++ b/test/sync-legacy-sweep-gbra108.test.ts@@ -143,7 +143,7 @@ for (const backend of testBackends()) {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 passRow(engine))?.obligations.legacy_sweep).toEqual({ cursor: `notes/n${String(LEGACY_SWEEP_SLICE - 1).padStart(3, '0')}.md` });expect((await performManagedSync(engine, OPTS)).status).not.toBe('blocked_by_failures');const row = await passRow(engine);diff --git a/test/sync-legacy-sweep-resume-7189.test.ts b/test/sync-legacy-sweep-resume-7189.test.tsnew file mode 100644index 0000000000..9f6dee8825--- /dev/null+++ b/test/sync-legacy-sweep-resume-7189.test.ts@@ -0,0 +1,89 @@+/**+ * #7189: a source whose legacy pages differ from their files never finished its first managed full round. The first full+ * round screened every legacy page before the round's real changes, and a page that differs gets no record, so a pass+ * stopped by its deadline mid-sweep kept nothing: the next pass screened the same pages from the top, stopped again, and+ * the commits waiting behind the sweep were never imported (each 3,600 s pass ended partial with 0 changes).+ *+ * Protects:+ * - a pass screens at most PASS_LEGACY_SWEEP_MAX legacy pages, then imports the round's real changes;+ * - the next full round resumes the sweep where the last one stopped (`obligations.legacy_sweep.cursor`), so the first+ * full sweep finishes even when no page it screens can be recorded, and records `first_full_at` once it reaches the end.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/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, PASS_LEGACY_SWEEP_MAX } 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 { testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const TOTAL = PASS_LEGACY_SWEEP_MAX + 20;+const names = Array.from({ length: TOTAL }, (_, i) => `n${String(i).padStart(3, '0')}`);+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const name of names) writeFileSync(join(root, `notes/${name}.md`), `---\ntype: concept\ntitle: notes/${name}\n---\n\nThe committed body of notes/${name}.\n`);+ commit(root, 'notes');+};++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 page = async (engine: BrainEngine, slug: string) => (await engine.executeRaw('SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', ['default', slug])).length > 0;++/** Turns the synced pages into pages an older gbrain imported whose body no longer matches the file: no import record, no pass row. */+async function differingLegacyPages(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} An edit the brain kept.`, row.timeline, JSON.stringify(row.frontmatter), `${row.content_hash}-older`, 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]);+ while ((await drainProjections(engine, { limit: 100 })).rebuilt > 0);+}++/** Every pass is stopped once it starts screening past PASS_LEGACY_SWEEP_MAX pages, as a deadline would stop it. */+function deadlinePastBudget(): void {+ let slices = 0;+ installFaultHook(async (point, context) => {+ if (point === 'sync:round_start' && (context as { round?: number }).round === 1) slices = 0;+ if (point === 'sync:legacy_slice' && ++slices > PASS_LEGACY_SWEEP_MAX / LEGACY_SWEEP_SLICE) throw new Error('deadline mid-sweep');+ });+}++afterEach(() => installFaultHook(undefined));++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ describe(`#7189: a first full round over legacy pages that differ (${backend})`, () => {+ test('a pass screens a bounded slice of the sweep, imports the waiting commit, and the next pass resumes the sweep', () => managedBrain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ await differingLegacyPages(engine);+ writeFileSync(join(root, 'notes/fresh.md'), '---\ntype: concept\ntitle: notes/fresh\n---\n\nA commit waiting behind the sweep.\n');+ commit(root, 'fresh');+ deadlinePastBudget();++ const first = await performManagedSync(engine, OPTS).then(result => result.status, (error: Error) => error.message);+ expect(first).not.toBe('deadline mid-sweep');+ expect(await page(engine, 'notes/fresh')).toBe(true);+ let row = await passRow(engine);+ expect(row.telemetry.counts).toMatchObject({ legacy_swept: PASS_LEGACY_SWEEP_MAX, legacy_recorded: 0 });+ expect(row.obligations.legacy_sweep).toEqual({ cursor: `notes/${names[PASS_LEGACY_SWEEP_MAX - 1]}.md` });++ // The first pass converged, so the next full round (here an explicit one) resumes the sweep at the cursor.+ await performManagedSync(engine, { ...OPTS, full: true });+ row = await passRow(engine);+ expect(row.telemetry.counts).toMatchObject({ legacy_swept: TOTAL - PASS_LEGACY_SWEEP_MAX, legacy_recorded: 0 });+ expect(row.obligations.legacy_sweep).toMatchObject({ first_full_at: expect.any(String) });+ }, { databaseUrl, setup }), 600_000);+ });+}