Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): age a managed sync cursor that has not advanced from its discovery (#6763)
garrytan9f363ae6cb89
diff --git a/src/commands/doctor/checks/managed-sync-backlog.ts b/src/commands/doctor/checks/managed-sync-backlog.tsindex d77471a8d9..c1ff1d3306 100644--- a/src/commands/doctor/checks/managed-sync-backlog.ts+++ b/src/commands/doctor/checks/managed-sync-backlog.ts@@ -4,12 +4,19 @@ import { formatManagedSyncBacklog, readManagedSyncBacklog } from '../../../core/const IDLE_MS = 60 * 60_000;-/** #5984: unfinished managed sync cursors, their remaining entries and ETA; warns when one has not advanced for an hour. */+/**+ * #5984: unfinished managed sync cursors, their remaining entries and ETA; warns when one has not advanced for an hour.+ * #6763: a cursor that has not advanced yet is aged from its discovery, so a fresh one does not warn; one with neither+ * time, or an unreadable one, still warns.+ */export async function checkManagedSyncBacklog(engine: BrainEngine | null, sourceIds?: string[]): Promise<Check | null> {if (!engine) return null;const backlog = await readManagedSyncBacklog(engine, sourceIds);if (!backlog.length) return null;- const idle = backlog.filter(b => !b.last_progress_at || Date.now() - Date.parse(b.last_progress_at) > IDLE_MS);+ const idle = backlog.filter(b => {+ const since = Date.parse(b.last_progress_at ?? b.discovered_at ?? '');+ return Number.isNaN(since) || Date.now() - since > IDLE_MS;+ });const lines = backlog.map(formatManagedSyncBacklog).join('; ');return { name: 'managed_sync_backlog', status: idle.length ? 'warn' : 'ok',message: idle.lengthdiff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 35a5f5ee35..a77480c9ef 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -1085,6 +1085,8 @@ export interface ManagedSyncBacklog {rate_pages_per_min: number | null;eta_seconds: number | null;last_progress_at: string | null;+ /** #6763: when the cursor's discovery ran (frozen with the manifest); the no-progress age origin until `last_progress_at` exists. */+ discovered_at: string | null;/** #6317: entries this cursor advanced past as holds (no page committed for them). */held: number;resume_command: string;@@ -1097,7 +1099,7 @@ export interface ManagedSyncBacklog {* their latest drain window (CEO-A18), readable from any process.*/export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {- const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };+ const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; discoveredAt?: string; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };counts?: { held?: number }; processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] } }>(`SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {@@ -1106,7 +1108,7 @@ export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: stconst estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };const args = managedSyncResumeArgs({ sourceId: h.sourceId, processingOptions: h.processingOptions, syncOptions: h.syncOptions });return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,- last_progress_at: p ? new Date(p.lastAt).toISOString() : null, held: Number(h.counts?.held ?? 0), resume_command: syncResumeCommand(args), resume_args: args };+ last_progress_at: p ? new Date(p.lastAt).toISOString() : null, discovered_at: h.discoveredAt ?? null, held: Number(h.counts?.held ?? 0), resume_command: syncResumeCommand(args), resume_args: args };});}diff --git a/test/doctor-managed-sync-backlog-6763.test.ts b/test/doctor-managed-sync-backlog-6763.test.tsnew file mode 100644index 0000000000..eabb479864--- /dev/null+++ b/test/doctor-managed-sync-backlog-6763.test.ts@@ -0,0 +1,47 @@+/**+ * #6763: doctor's managed_sync_backlog check warned "not advanced for over an hour" on a cursor discovered moments ago,+ * because a cursor that has not advanced yet has no progress stamp. The age origin is now the last advance, else the+ * cursor's discovery; a cursor with neither, or with an unreadable time, still warns, and the hour stays an hour.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkManagedSyncBacklog } from '../src/commands/doctor/checks/managed-sync-backlog.ts';++const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();+const progress = (minutes: number) => { const at = Date.now() - minutes * 60_000; return { startedAt: at - 60_000, startIndex: 0, lastAt: at, lastIndex: 1 }; };+const fake = (headers: Record<string, unknown>[]) => ({ executeRaw: async () => headers.map(header => ({ header })) }) as unknown as BrainEngine;+const status = async (header: Record<string, unknown>) => (await checkManagedSyncBacklog(fake([{ sourceId: 'example-source', index: 0, total: 3, done: false, ...header }])))?.status;++test('#6763 a cursor that has not advanced yet is aged from its discovery', async () => {+ expect(await status({ total: 0, discoveredAt: minutesAgo(0) })).toBe('ok');+ expect(await status({ discoveredAt: minutesAgo(0) })).toBe('ok');+ expect(await status({ discoveredAt: minutesAgo(59) })).toBe('ok');+ expect(await status({ discoveredAt: minutesAgo(61) })).toBe('warn');+ expect(await status({ total: 0, discoveredAt: minutesAgo(61) })).toBe('warn');+});++test('#6763 the last advance, when there is one, is the age origin; a missing or unreadable time still warns', async () => {+ expect(await status({ index: 1, discoveredAt: minutesAgo(600), progress: progress(5) })).toBe('ok');+ expect(await status({ index: 1, discoveredAt: minutesAgo(5), progress: progress(61) })).toBe('warn');+ expect(await status({})).toBe('warn');+ expect(await status({ discoveredAt: 'not a time' })).toBe('warn');+ const check = await checkManagedSyncBacklog(fake([{ sourceId: 'a-example', index: 0, total: 2, discoveredAt: minutesAgo(1) }, { sourceId: 'b-example', index: 0, total: 2, discoveredAt: minutesAgo(90) }]));+ expect(check).toMatchObject({ status: 'warn' });+ expect(check!.message).toStartWith('1 managed sync cursor(s) have not advanced for over an hour.');+});++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });++test('#6763 a stored cursor: a fresh row write never hides an old discovery, and a done cursor is not a backlog', async () => {+ const put = (fingerprint: string, header: Record<string, unknown>) => engine.executeRaw(+ "INSERT INTO op_checkpoints(op, fingerprint, completed_keys, updated_at) VALUES('managed-sync', $1, jsonb_build_array($2::jsonb), now())", [fingerprint, JSON.stringify(header)]);+ await put('fresh', { sourceId: 'fresh-example', index: 0, total: 0, done: false, discoveredAt: minutesAgo(0) });+ expect(await checkManagedSyncBacklog(engine, ['fresh-example'])).toMatchObject({ status: 'ok' });+ await put('old', { sourceId: 'old-example', index: 0, total: 4, done: false, discoveredAt: minutesAgo(120) });+ expect(await checkManagedSyncBacklog(engine, ['old-example'])).toMatchObject({ status: 'warn' });+ await put('done', { sourceId: 'done-example', index: 4, total: 4, done: true, discoveredAt: minutesAgo(120) });+ expect(await checkManagedSyncBacklog(engine, ['done-example'])).toBeNull();+}, 60_000);