Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): ghost-page report runs in the background, rate-limited per source (GBRA-133 2b.2)

garrytan0469b5d648f4
diff --git a/src/core/ghost-pages.ts b/src/core/ghost-pages.ts
index 5024f0b4fa..4a8075581c 100644
--- a/src/core/ghost-pages.ts
+++ b/src/core/ghost-pages.ts
@@ -170,9 +170,10 @@ async function sharedPackMemberGhost(engine: BrainEngine, owner: GhostOwner, gho
/**
* One source's ghosts in page-id order. `candidateLimit` bounds the full checks (default `GHOST_CHECK_LIMIT`);
- * anything past it, or past `GHOST_SCAN_LIMIT` live pages, sets `truncated`.
+ * anything past it, or past `GHOST_SCAN_LIMIT` live pages, sets `truncated`. An aborted `signal` throws its reason
+ * before the next statement (the post-sync background scan stops this way before its engine disconnects).
*/
-export async function scanGhostSource(engine: BrainEngine, sourceId: string, opts: { candidateLimit?: number } = {}): Promise<GhostSourceScan> {
+export async function scanGhostSource(engine: BrainEngine, sourceId: string, opts: { candidateLimit?: number; signal?: AbortSignal } = {}): Promise<GhostSourceScan> {
const limit = opts.candidateLimit ?? GHOST_CHECK_LIMIT;
const context = await sourceContext(engine, sourceId);
const scan: GhostSourceScan = { source_id: sourceId, status: 'known', ghosts: [], skill_paths: [], inspected: 0, file_backed: 0, candidates: 0, truncated: false };
@@ -182,6 +183,7 @@ export async function scanGhostSource(engine: BrainEngine, sourceId: string, opt
let after = 0;
let unchecked = 0;
for (;;) {
+ opts.signal?.throwIfAborted();
const rows = await engine.executeRaw<PageRow>(`SELECT id, slug, source_path, source_uri FROM pages
WHERE source_id=$1 AND deleted_at IS NULL AND id > $2 ORDER BY id LIMIT ${BATCH}`, [sourceId, after]);
for (const row of rows) {
@@ -193,6 +195,7 @@ export async function scanGhostSource(engine: BrainEngine, sourceId: string, opt
if (verdict.kind === 'ambiguous') return { ...scan, status: 'unknown', reason: 'ambiguous_storage' };
scan.candidates++;
if (scan.candidates > limit) { scan.truncated = true; unchecked++; continue; }
+ opts.signal?.throwIfAborted();
const result = await confirm(engine, context, sourceId, row.slug);
if (result.kind === 'unknown') return { ...scan, status: result.reason === 'not_owner_host' ? 'not_applicable' : 'unknown', reason: result.reason };
if (result.kind === 'ghost') (await sharedPackMemberGhost(engine, context.owner, result.ghost) ? scan.skill_paths : scan.ghosts).push(result.ghost);
diff --git a/src/core/persistence/sync-ghosts.ts b/src/core/persistence/sync-ghosts.ts
index a408e8a481..74d8102a45 100644
--- a/src/core/persistence/sync-ghosts.ts
+++ b/src/core/persistence/sync-ghosts.ts
@@ -5,28 +5,130 @@
* in progress or a mistake, and only a person decides which. A path that holds a sync hold (a held deletion) is the hold's
* to settle and is not counted. Bounded by the scan's own limits; off the owner host, or when the scan cannot tell, there
* is no count. Best effort: a failed scan never fails the sync.
+ *
+ * GBRA-133 2b.2: the scan reads every live page of the source (365 ms at 100k pages), and ghosts are outside the git
+ * delta, so it keeps its full walk but no longer runs inside the sync. `countSyncGhosts` answers from the source's last
+ * scan (one op_checkpoints row, op `sync-ghost-report`, fingerprint the source id) and, at most once per
+ * `GBRAIN_SYNC_GHOST_INTERVAL_MS` (default 5 minutes) per source across processes (an atomic claim on that row), starts
+ * the scan in the background, and only once a sync has landed since the last claim (`sources.last_sync_at`, which every
+ * successful sync stamps): a cancelled or never-landed sync writes nothing. The sync returns, and releases its drain lease and the serve's single-flight slot, without
+ * waiting; the next sync reports what the scan found. A CLI exit waits for an in-flight scan within the background-work
+ * drain budget; an engine disconnect aborts it before the next statement. Every decision is recorded
+ * (`syncGhostDecisions`) for tests.
*/
import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
+import { registerBackgroundWorkDrainer } from '../background-work.ts';
import { scanGhostSource } from '../ghost-pages.ts';
import { GIT_HOLD_OP, gitHoldFingerprint } from './sync-holds.ts';
/** Full checks per sync: the count is exact up to this many candidates, `truncated` past it. */
export const SYNC_GHOST_CHECK_LIMIT = 50;
+export const SYNC_GHOST_REPORT_OP = 'sync-ghost-report';
+export const SYNC_GHOST_INTERVAL_MS_DEFAULT = 300_000;
-export interface SyncGhostPages { count: number; truncated: boolean; samples: string[]; fix: Action }
+export interface SyncGhostPages { count: number; truncated: boolean; samples: string[]; fix: Action; observed_at?: string }
+export type SyncGhostDecision = { source_id: string; decision: 'scan_started' | 'rate_limited' | 'scan_in_flight' | 'scan_done' | 'scan_failed' | 'scan_aborted'; error?: string };
+/** The last decisions of this process, oldest first (bounded). */
+export const syncGhostDecisions: SyncGhostDecision[] = [];
+
+function decide(source_id: string, decision: SyncGhostDecision['decision'], error?: unknown): void {
+ syncGhostDecisions.push({ source_id, decision, ...(error === undefined ? {} : { error: error instanceof Error ? error.message : String(error) }) });
+ if (syncGhostDecisions.length > 200) syncGhostDecisions.splice(0, syncGhostDecisions.length - 200);
+}
+
+function scanIntervalMs(env: Record<string, string | undefined> = process.env): number {
+ const raw = env.GBRAIN_SYNC_GHOST_INTERVAL_MS;
+ const value = raw === undefined || raw === '' ? NaN : Number(raw);
+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : SYNC_GHOST_INTERVAL_MS_DEFAULT;
+}
+
+interface EngineScans { inFlight: Map<string, Promise<void>>; controller: AbortController; unregister: () => void }
+const scans = new Map<BrainEngine, EngineScans>();
+
+/** The ghost report from the source's last scan; starts a background scan when the source's interval has passed. */
export async function countSyncGhosts(engine: BrainEngine, sourceId: string): Promise<SyncGhostPages | null> {
- const scan = await scanGhostSource(engine, sourceId, { candidateLimit: SYNC_GHOST_CHECK_LIMIT }).catch(() => null);
- if (!scan || scan.status !== 'known' || (!scan.ghosts.length && !scan.truncated)) return null;
+ const inFlight = scans.get(engine)?.inFlight.has(sourceId) === true;
+ const [row] = await engine.executeRaw<{ report: SyncGhostPages[] | null; claimed: boolean }>(inFlight
+ ? 'SELECT completed_keys AS report, false AS claimed FROM op_checkpoints WHERE op=$1 AND fingerprint=$2'
+ : `WITH prior AS (SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2),
+ claim AS (INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)
+ SELECT $1, $2, '[]'::jsonb, now() WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2 AND last_sync_at IS NOT NULL)
+ ON CONFLICT (op, fingerprint) DO UPDATE SET updated_at = now()
+ WHERE op_checkpoints.updated_at <= now() - ($3::bigint * interval '1 millisecond')
+ AND EXISTS (SELECT 1 FROM sources WHERE id=$2 AND last_sync_at > op_checkpoints.updated_at) RETURNING 1)
+ SELECT (SELECT completed_keys FROM prior) AS report, EXISTS (SELECT 1 FROM claim) AS claimed`,
+ inFlight ? [SYNC_GHOST_REPORT_OP, sourceId] : [SYNC_GHOST_REPORT_OP, sourceId, scanIntervalMs()]).catch(() => []);
+ if (inFlight) decide(sourceId, 'scan_in_flight');
+ else if (row?.claimed) startScan(engine, sourceId);
+ else decide(sourceId, 'rate_limited');
+ const report = typeof row?.report === 'string' ? JSON.parse(row.report) as SyncGhostPages[] : row?.report;
+ return report?.[0] ?? null;
+}
+
+/** Resolves when every background scan of `engine` (default: every engine) has settled. */
+export async function settleSyncGhostScans(engine?: BrainEngine): Promise<void> {
+ const states = engine ? [scans.get(engine)].filter((state): state is EngineScans => !!state) : [...scans.values()];
+ await Promise.all(states.flatMap(state => [...state.inFlight.values()]));
+}
+
+function startScan(engine: BrainEngine, sourceId: string): void {
+ let state = scans.get(engine);
+ if (!state) {
+ const created: EngineScans = { inFlight: new Map(), controller: new AbortController(), unregister: () => {} };
+ created.unregister = engine.registerBeforeDisconnect(async () => {
+ created.controller.abort(new Error('engine disconnecting'));
+ await Promise.all(created.inFlight.values());
+ created.unregister();
+ if (scans.get(engine) === created) scans.delete(engine);
+ });
+ scans.set(engine, created);
+ state = created;
+ }
+ const owned = state;
+ decide(sourceId, 'scan_started');
+ const run = (async () => {
+ try {
+ const report = await scanReport(engine, sourceId, owned.controller.signal);
+ owned.controller.signal.throwIfAborted();
+ await engine.executeRaw('UPDATE op_checkpoints SET completed_keys=$3::text::jsonb, updated_at=now() WHERE op=$1 AND fingerprint=$2',
+ [SYNC_GHOST_REPORT_OP, sourceId, JSON.stringify(report ? [report] : [])]);
+ decide(sourceId, 'scan_done');
+ } catch (error) {
+ if (owned.controller.signal.aborted) decide(sourceId, 'scan_aborted');
+ else decide(sourceId, 'scan_failed', error);
+ } finally {
+ owned.inFlight.delete(sourceId);
+ }
+ })();
+ owned.inFlight.set(sourceId, run);
+}
+
+/** One full scan, held paths left out; null when nothing is to report or the scan could not tell. */
+async function scanReport(engine: BrainEngine, sourceId: string, signal: AbortSignal): Promise<SyncGhostPages | null> {
+ const scan = await scanGhostSource(engine, sourceId, { candidateLimit: SYNC_GHOST_CHECK_LIMIT, signal });
+ if (scan.status !== 'known' || (!scan.ghosts.length && !scan.truncated)) return null;
const incarnation = scan.owner?.source_incarnation ?? '';
const held = new Set(scan.ghosts.length ? (await engine.executeRaw<{ path: string }>(`SELECT completed_keys->0->>'path' AS path FROM op_checkpoints WHERE op=$1 AND fingerprint=ANY($2::text[])`,
[GIT_HOLD_OP, scan.ghosts.map(ghost => gitHoldFingerprint(sourceId, incarnation, ghost.path))])).map(row => row.path) : []);
const ghosts = scan.ghosts.filter(ghost => !held.has(ghost.path));
if (!ghosts.length && !scan.truncated) return null;
- return { count: ghosts.length, truncated: scan.truncated, samples: ghosts.slice(0, 5).map(ghost => ghost.slug),
+ return { count: ghosts.length, truncated: scan.truncated, samples: ghosts.slice(0, 5).map(ghost => ghost.slug), observed_at: new Date().toISOString(),
fix: { argv: ['gbrain', 'repair', 'ghost-pages', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/repair.md#ghost-pages',
why: `Lists the live pages of ${sourceId} whose canonical file is missing and writes nothing. Sync never deletes them: restore a file and sync to keep its page, `
+ 'or apply the printed removal only after the user agrees.',
verify: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] } } };
}
+
+registerBackgroundWorkDrainer({
+ name: 'sync-ghost-scans',
+ order: 45,
+ async drain(timeoutMs, mode): Promise<{ unfinished: number }> {
+ if (mode === 'disconnect') return { unfinished: 0 };
+ const pending = [...scans.values()].flatMap(state => [...state.inFlight.values()]);
+ if (!pending.length) return { unfinished: 0 };
+ await Promise.race([Promise.all(pending), new Promise<void>(resolve => { const timer = setTimeout(resolve, timeoutMs); timer.unref?.(); })]);
+ return { unfinished: [...scans.values()].reduce((sum, state) => sum + state.inFlight.size, 0) };
+ },
+});
diff --git a/test/sync-exits-l4-6712.test.ts b/test/sync-exits-l4-6712.test.ts
index c57cb52345..9706c985d8 100644
--- a/test/sync-exits-l4-6712.test.ts
+++ b/test/sync-exits-l4-6712.test.ts
@@ -19,7 +19,8 @@ import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, HOLD_ESCALATE_MS } from '
import { classifyTerminal } from '../src/core/persistence/terminal-classify.ts';
import { holdEscalation, readGitHold, recordHoldAttempt, writeGitHold, type GitHoldRecord } from '../src/core/persistence/sync-holds.ts';
import { nonPlainSyncFlags, readSoakCounters, recordSoakEvent, sweepNeedsHumanHolds } from '../src/core/persistence/soak-counters.ts';
-import { countSyncGhosts } from '../src/core/persistence/sync-ghosts.ts';
+import { countSyncGhosts, settleSyncGhostScans } from '../src/core/persistence/sync-ghosts.ts';
+import { withEnv } from './helpers/with-env.ts';
import { parseSince } from '../src/core/since.ts';
import { parseRepairArgs } from '../src/commands/repair.ts';
import { fileDriftRepair } from '../src/core/repair/file-drift.ts';
@@ -223,9 +224,12 @@ describe('#6712 PR 2 L4: ghost pages after a managed sync', () => {
await submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content: `---\ntype: note\ntitle: ${slug}\n---\n\n${slug} body.\n` } });
}
await disposePersistenceConsumer(engine);
- const clean = await sync();
+ // GBRA-133 2b.2: the scan runs in the background after a sync (interval 0 here: every sync starts one) and the next
+ // sync reports what it found.
+ const clean = await withEnv({ GBRAIN_SYNC_GHOST_INTERVAL_MS: '0' }, async () => { const r = await sync(); await settleSyncGhostScans(engine); return r; });
expect(clean.ghostPages).toBeUndefined();
unlinkSync(join(root, 'notes/gone.md'));
+ await withEnv({ GBRAIN_SYNC_GHOST_INTERVAL_MS: '0' }, async () => { await sync(); await settleSyncGhostScans(engine); });
const result = await sync();
expect(result.ghostPages).toMatchObject({ count: 1, truncated: false, samples: ['notes/gone'],
fix: { argv: ['gbrain', 'repair', 'ghost-pages', '--source', 'default'], actor: 'agent', consent: [] } });