Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a round with imports sweeps legacy pages after its batches drain (#7338)
garrytan1d383dd9f798
diff --git a/src/core/persistence/sync-pass-apply.ts b/src/core/persistence/sync-pass-apply.tsindex c2ba27027f..e2703b27db 100644--- a/src/core/persistence/sync-pass-apply.ts+++ b/src/core/persistence/sync-pass-apply.ts@@ -161,7 +161,9 @@ export async function applyPassRound(engine: BrainEngine, level: ShadowLevel, in}await writePassHolds(engine, level, input, state);await adoptRecords(engine, level, state);- await sweepLegacy(engine, level, input, state);+ // #7338: a round with imports or deletes sweeps after its batches drain (the pass calls sweepLegacy), so the bounded+ // sweep never delays the round's changes becoming visible.+ if (!roundHasWork(level)) await sweepLegacy(engine, level, input, state);await admitKeepDb(engine, level, input, state);// Only a matched page the concept side skipped for drift has a skip to release: a 600k level keeps no set of every slug.const skipped = await driftSkippedSlugs(engine, level.sourceId);@@ -428,7 +430,7 @@ async function adoptRecords(engine: BrainEngine, level: ShadowLevel, state: Pass* 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> {+export 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)).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);const sweep = input.obligations.legacy_sweep;@@ -449,6 +451,12 @@ async function sweepLegacy(engine: BrainEngine, level: ShadowLevel, input: PassA}// 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;+ if (state.sweptAll && !input.obligations.legacy_sweep?.first_full_at) input.obligations.legacy_sweep = { ...input.obligations.legacy_sweep, first_full_at: new Date().toISOString() };+}++/** Whether the round has a path the pass will import or delete (sync-pass-run.ts `triageRound`). */+function roundHasWork(level: ShadowLevel): boolean {+ return level.paths.some(({ result: r }) => !r.settled && !r.inFlight && (r.action === 'delete' || r.action === 'import' || r.action === 'reparse' || r.cls === 'drift' || r.cls === 'dirty'));}/** One sweep slice: screen it, then record its equal pages (fenced on the revision the level read). */diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.tsindex 831938998e..61ef8fea78 100644--- a/src/core/persistence/sync-pass-run.ts+++ b/src/core/persistence/sync-pass-run.ts@@ -57,7 +57,7 @@ import { databaseOnlyPageSql } from './unbound-pages.ts';import { originMarkerFingerprint } from './sync-markers.ts';import { SYNC_SLICE_OP } from './sync-slices.ts';import { passResumeArgs } from './sync-pass-readers.ts';-import { applyPassRound, finishPassApply, holdPassIdentities, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';+import { applyPassRound, sweepLegacy, finishPassApply, holdPassIdentities, newPassApplyState, passApplyCounts, remoteReconcile } from './sync-pass-apply.ts';import { passClosureMemo, passCostDecision, type passEpisodeClosure, readReservedUsd, registerPassCost, unregisterPassCost } from './sync-pass-episode.ts';import { currentEmbeddingPricePerMTok } from '../embedding.ts';import { SIZE_STATE_SAMPLE, type SyncSizeStates } from '../page-embedding-budget.ts';@@ -828,10 +828,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Prawait writeLegacyMarkers(engine, level);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, onSwept }, applied);+ const roundInput = { passId, observedAt: startedAt, remote, admission, fullRound: kind === 'full', obligations: value.obligations, context, processingOptions,+ grantPrefixes: remote ? authority.writer.slugPrefixes : null, onSwept };+ await applyPassRound(engine, level, roundInput, applied);assertActive();- 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, consumeRetry });// Earlier passes' requests that committed since they stopped are this pass's imports (sync-pass-carried.ts).@@ -922,6 +922,7 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr// Every candidate of the round settled: committed, waived, held, deferred to a hold, a collision, or (a rename's// deletion) carried by its import.for (const entry of [...deletes, ...imports]) if (!S.has(settledKey(entry.path, entry.state.level))) S.set(settledKey(entry.path, entry.state.level), 'settled');+ if (!remote) await sweepLegacy(engine, level, roundInput, applied);roundSettled = 0;lastMismatch = [];}diff --git a/test/sync-legacy-edit-import-7338.test.ts b/test/sync-legacy-edit-import-7338.test.tsindex 8f02850ab3..ae1aa9d622 100644--- a/test/sync-legacy-edit-import-7338.test.ts+++ b/test/sync-legacy-edit-import-7338.test.ts@@ -3,6 +3,8 @@* number per pass (#7189). Before the fix, a Git edit to a page the sweep had not reached yet classified `drift` with an* unknown side and was held `file_drift`, so the edit never became searchable. That's what turned the managed serve-watch* freshness cells red. A page that still holds its file at the baseline commit changed only in Git, so the edit imports.+ * The sweep itself also ran before the round's imports, adding its cost to every commit's latency until it finished; a+ * round with imports now sweeps after them.*/import { expect, test } from 'bun:test';import { execFileSync } from 'node:child_process';@@ -10,6 +12,7 @@ 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 { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';import { PASS_LEGACY_SWEEP_MAX } from '../src/core/persistence/sync-pass-apply.ts';@@ -51,7 +54,14 @@ for (const backend of testBackends()) {writeFileSync(join(root, `notes/${name(last)}.md`), body(last, 'An edited body naming acme-example.'));git(root, 'add', '-A'); git(root, 'commit', '-qm', 'edit');- const result = await performManagedSync(engine, OPTS);+ // The bounded legacy sweep runs after the round's import, so it never delays the edit becoming visible.+ const seenAtSlice: boolean[] = [];+ installFaultHook(async point => {+ if (point === 'sync:legacy_slice') seenAtSlice.push(((await engine.getPage(slug, { sourceId: 'default' }))?.compiled_truth ?? '').includes('acme-example'));+ });+ const result = await performManagedSync(engine, OPTS).finally(() => installFaultHook(undefined));+ expect(seenAtSlice.length).toBeGreaterThan(0);+ expect(seenAtSlice.every(Boolean)).toBe(true);expect(result.status).toBe('synced');const holds = await engine.executeRaw<{ code: string }>("SELECT completed_keys->0->>'code' AS code FROM op_checkpoints WHERE op='sync-hold' AND completed_keys->0->>'path'=$1", [`notes/${name(last)}.md`]);expect(holds).toEqual([]);