Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync status): last_sync_at and last_committed_at beside last_commit; freshness waiting_commits (GBRA-133 PR 3a, #7243)
garrytancb2a58e83a22
diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex 9e911527a1..f29f606098 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -214,6 +214,7 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisconsole.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);// #7243: the applied-through commit, the job doing the work, and what the newest pass pinned against what a stamp backs.console.log(` last synced commit: ${status.last_commit?.slice(0, 8) ?? 'none yet'}`);+ console.log(` last converged: ${status.last_sync_at ?? 'never'}; last committed write: ${status.last_committed_at ?? 'none yet'}${status.last_committed_at && (!status.last_sync_at || status.last_committed_at > status.last_sync_at) ? ' (still importing since it last converged)' : ''}`);const live = status.live;console.log(` live: ${live ? `${live.kind}${live.job_id !== null ? ` job #${live.job_id}` : live.id ? ` ${live.id}` : ''}${live.pid ? ` (PID ${live.pid})` : ''} holds the drain lease since ${live.started_at ?? '?'}`+ `${live.progress ? `, ${live.progress.committed} page(s) committed since` : ''}${live.stalled ? ', STALLED (no commit or save for the stall window)' : ''}` : 'nothing holds the drain lease'}`);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex ebbec4a066..8c271a5507 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1081,6 +1081,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A managed sync drain stopped by its governor drops the abandoned pass\'s late progress events (no late `[sync] N processed` line, no count added after the stop), and a stop whose head owner reports restart_required now says so: `drain.stall.cause` is `owner_restart_required` with the owner\'s heartbeat row, and `next` tells the host admin to restart that process, then rerun (it used to read `publication_overdue` or `no_progress`).' },{ since: 'TBD', text: 'The commit notifier counts a resumable sync that committed pages as progress even while `last_commit` has not moved yet (a long managed catch-up no longer reads `notifier_stalled`), and a source whose drain-lease holder has committed nothing for 5 minutes is no longer deferred silently: it counts as a failed attempt (`drain_holder_stalled`), so the retry tiers run and sync status and doctor show the sync-now fix.' },{ since: 'TBD', text: 'A sync pass\'s checkpoint that its pass can no longer publish (the pass ended, or another pass started) is now refused `sync_pass_superseded` instead of `revision_conflict`: it records no managed-sync failure, reads `superseded` in `gbrain sources writer failures` and does not count as an unresolved terminal failure, and a pass that stops with its checkpoint still pending reports `managedWrite.disposition: superseded` instead of "Re-run the same sync options to resume this request".' },+ { since: 'TBD', text: '`gbrain sync status` also reports `last_sync_at` (when the source last converged: every path of its target imported, deleted or held) and `last_committed_at` (when a managed sync write of the source last committed), and the human line says when the source is still importing since it last converged, so a long catch-up no longer reads as a day stale. Its `freshness` block adds `waiting_commits`, the commits on HEAD not synced yet; `unresolved_commits` still counts only synced commits that git cannot date on this host.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.tsindex 60f6532ca9..ea35a8f7fe 100644--- a/src/core/persistence/sync-freshness.ts+++ b/src/core/persistence/sync-freshness.ts@@ -38,8 +38,13 @@ export interface SourceFreshness {commit_to_embedded: LatencyStats & { pending: number };/** Distinct run targets dated from git. */commits: number;- /** Targets in the window git could not date here (no checkout on this host, or the commit is not in it); their pages are not sampled. */+ /**+ * Synced run targets in the window git could not date here (no checkout on this host, or the commit is not in it); their+ * pages are not sampled. Not the backlog: commits still waiting to sync are `waiting_commits` (`behind.commits`).+ */unresolved_commits: number;+ /** GBRA-133 (#7243): commits on this host's checkout HEAD the source has not synced yet (`behind.commits`), or null when git cannot say. */+ waiting_commits: number | null;/*** #7189: the current lag, which the latency samples above cannot show (they date only commits that already synced):* commits on this host's checkout HEAD after the source's last synced commit, and the committer age of the oldest@@ -108,7 +113,7 @@ export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?:const lag = b.root && b.last_commit ? await behindOf(b.root, b.last_commit).catch(() => null) : null;const behind = lag && { commits: lag.commits, oldest_seconds: lag.oldest === null ? null : Math.max(0, Math.round(Date.now() / 1000 - lag.oldest)) };const empty: SourceFreshness = { source_id: b.source_id, window_hours: FRESHNESS_WINDOW_HOURS, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },- commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, behind };+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, waiting_commits: behind ? behind.commits : null, behind };const targets = (await engine.executeRaw<{ target: string }>(`SELECT r.intent->>'target' AS target FROM persistence_requests r WHERE ${SAMPLE_WHERE}GROUP BY 1 ORDER BY max(r.completed_at) DESC LIMIT ${FRESHNESS_MAX_TARGETS}`, [b.worktree_id, b.source_incarnation, FRESHNESS_WINDOW_HOURS])).map(row => row.target).filter(target => typeof target === 'string' && SHA.test(target));diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 07c68112f7..40cd8f8582 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -120,6 +120,13 @@ export interface SyncStatus {source_id: string;/** #7243: the commit the source's sync applied through (`sources.last_commit`, stamped when a sync converges), or null before the first. */last_commit: string | null;+ /**+ * GBRA-133: when the source's sync last converged (`sources.last_sync_at`: every path of its target imported, deleted or+ * held), and when a managed sync write of the source last committed. A source still importing after its last convergence+ * reads `last_committed_at` newer than `last_sync_at`, so it does not read as stale while it is catching up.+ */+ last_sync_at: string | null;+ last_committed_at: string | null;/*** #7243: the job doing the work now: the holder of the source's drain lease (a serve pass, a sync job, a CLI sync, the* cycle), its heartbeat and progress, `job_id` when it is a Minions sync job, and `stalled` once it has made no commit@@ -302,9 +309,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst detail = opts.detail !== false;// #6712 PR 4b (design §9): the pass row and the withheld-delete record ride the source read (primary-key probes), so the plain status keeps its statement budget.const admissionSql = syncAdmissionSettingSql(4);- const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;+ const [source] = await engine.executeRaw<{ incarnation: string; last_commit: string | null; last_sync_at: Date | string | null; drain_lock: boolean; pass_value: PassRow['value'] | null; pass_updated_at: Date | string | null; withheld: DeletesWithheld | null;admission_stored: string | null; admission_row_value: string | null; admission_set_at: string | null; writeback_failed: string | null }>(- `SELECT s.incarnation::text AS incarnation, s.last_commit, EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$${4 + SYNC_ADMISSION_SETTING_PARAMS.length}) AS drain_lock,+ `SELECT s.incarnation::text AS incarnation, s.last_commit, s.last_sync_at, EXISTS (SELECT 1 FROM gbrain_cycle_locks l WHERE l.id=$${4 + SYNC_ADMISSION_SETTING_PARAMS.length}) AS drain_lock,p.completed_keys->0 AS pass_value, p.updated_at AS pass_updated_at, w.completed_keys->0 AS withheld, ${admissionSql.columns},(SELECT r.request_id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='git' AND e.state='failed'AND e.request_id IN (SELECT id::uuid FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.completed_keys->0->'obligations'->'converged'->'writeback')='array'@@ -318,8 +325,10 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst selected = await cursorHeader(engine, sourceId, source.incarnation, failures[0]?.cursor_key ?? null);const header = selected?.header ?? null;// #7010: the push-hold probe rides this statement, so a source with no held Git effect costs no extra round trip.- const [committed] = await engine.executeRaw<{ n: number | string; git_push_held: boolean }>(`SELECT count(*) AS n, EXISTS (SELECT 1 FROM persistence_effects e- WHERE e.source_id=$1 AND e.kind='git' AND e.state IN ('queued','running','failed') AND e.error_code IN ('targets_parked', ${GIT_PUSH_CODES.map(code => `'${code}'`).join(',')})) AS git_push_held+ const [committed] = await engine.executeRaw<{ n: number | string; git_push_held: boolean; last_committed_at: Date | string | null }>(`SELECT count(*) AS n, EXISTS (SELECT 1 FROM persistence_effects e+ WHERE e.source_id=$1 AND e.kind='git' AND e.state IN ('queued','running','failed') AND e.error_code IN ('targets_parked', ${GIT_PUSH_CODES.map(code => `'${code}'`).join(',')})) AS git_push_held,+ (SELECT max(r.completed_at) FROM persistence_source_bindings b JOIN persistence_requests r ON r.worktree_id=b.worktree_id AND r.source_incarnation=b.source_incarnation+ WHERE b.source_id=$1 AND r.state='committed' AND COALESCE(r.intent->>'kind','') LIKE 'managed_sync_%') AS last_committed_atFROM persistence_requests WHERE source_id=$1 AND state='committed'AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND completed_at > now() - interval '10 minutes'`, [sourceId]);const records = await observeDirtyEditors(engine, sourceId, source.incarnation,@@ -349,6 +358,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message, repeated: failure.repeats ? { path: failure.path, runs: failure.repeats } : null }) }: retired ? { code: 'cursor_incarnation_retired', category: 'sync_fault', public_category: 'superseded', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;+ const iso = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();if (failure && lastError) {const [seen] = await engine.executeRaw<{ failure_at: Date | string | null; committed_at: Date | string | null; admitted_at: Date | string | null; now_at: Date | string }>(`SELECT now() AS now_at,(SELECT f.updated_at FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=$2) AS failure_at,@@ -359,7 +369,6 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts// #7243: the newest pass (its row rides the source read) is evidence too: it pinned, and it read the level unless it stopped before.const pass = source.pass_value?.telemetry;const levelRead = pass && (pass.outcome === 'up_to_date' || Object.keys(pass.timings_ms ?? {}).length > 0) ? pass.started_at : null;- const iso = (value: Date | string | null | undefined) => value == null ? null : new Date(value).toISOString();const later = seen?.failure_at ? supersedingAttempt(failure.phase, iso(seen.failure_at)!, { commit: iso(seen.committed_at), admission: iso(seen.admitted_at), level_read: levelRead ?? null, pin: pass?.started_at ?? null }) : null;if (later) lastError.superseded = { ...later, age_seconds: Math.max(0, Math.round((Date.parse(iso(seen!.now_at)!) - Date.parse(iso(seen!.failure_at)!)) / 1000)) };}@@ -414,7 +423,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst admission = await syncAdmissionStatus(engine, sourceId, source.incarnation,{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at });const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed) : null;- return { source_id: sourceId, last_commit: source.last_commit, live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null, run_id: header?.runId ?? null,+ return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob ?? holderJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },diff --git a/test/sync-freshness-6858.test.ts b/test/sync-freshness-6858.test.tsindex b95473411e..ba60ed3756 100644--- a/test/sync-freshness-6858.test.ts+++ b/test/sync-freshness-6858.test.ts@@ -99,7 +99,7 @@ describe('sync freshness (#6858 ask 6)', () => {const f = await managedSource(engine, 60);const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });expect(fresh).toEqual({ source_id: f.id, window_hours: 24, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },- commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, behind: null });+ commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 }, commits: 0, unresolved_commits: 0, waiting_commits: null, behind: null });expect(formatSyncFreshness(fresh!)).toBe('no commit→searchable samples in the last 24 h');await engine.setConfig('sync.on_commit', 'true');expect(await doctor(engine)).toMatchObject({ name: 'managed_sync_latency', status: 'ok', message: expect.stringContaining('No commit→searchable samples') });@@ -122,7 +122,7 @@ describe('sync freshness (#6858 ask 6)', () => {await receipt(engine, f, 5, { intent: { kind: 'managed_sync_delete' } });const [fresh] = await readSyncFreshness(engine, { sourceIds: [f.id] });// searchable: [10, 20, 30, 400] -> p50 25, p95 30 + 0.85 * 370; embedded: [18, 22] (the page waiting on a chunk is pending).- expect(fresh, name).toEqual({ source_id: f.id, window_hours: 24, commits: 1, unresolved_commits: 0,+ expect(fresh, name).toEqual({ source_id: f.id, window_hours: 24, commits: 1, unresolved_commits: 0, waiting_commits: null,commit_to_searchable: { samples: 4, p50_seconds: 25, p95_seconds: 344.5 },commit_to_embedded: { samples: 2, p50_seconds: 20, p95_seconds: 21.8, pending: 1 }, behind: null });expect(formatSyncFreshness(fresh!)).toBe('commit→searchable p50 25s, p95 5.7m (4 page(s), last 24 h); commit→embedded p50 20s, p95 21.8s (2 page(s), 1 pending)');@@ -263,7 +263,7 @@ describe('sync freshness (#6858 ask 6)', () => {}), 120_000);test('gbrain status prints one freshness line per managed source with samples, and none for a source without', () => {- const sampled = { source_id: 'acme-example', window_hours: 24, commits: 2, unresolved_commits: 0,+ const sampled = { source_id: 'acme-example', window_hours: 24, commits: 2, unresolved_commits: 0, waiting_commits: null,commit_to_searchable: { samples: 3, p50_seconds: 8, p95_seconds: 14 }, commit_to_embedded: { samples: 3, p50_seconds: 15, p95_seconds: 31, pending: 0 } };const quiet = { ...sampled, source_id: 'alice-example', commits: 0, commit_to_searchable: { samples: 0, p50_seconds: null, p95_seconds: null },commit_to_embedded: { samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 } };diff --git a/test/sync-status-coherence-7189.test.ts b/test/sync-status-coherence-7189.test.tsindex c36ad76270..57f8a55994 100644--- a/test/sync-status-coherence-7189.test.ts+++ b/test/sync-status-coherence-7189.test.ts@@ -66,6 +66,8 @@ test('freshness reports the commits on HEAD that have not synced yet and the oldwriteFileSync(join(root, 'carol-example.md'), note('Carol.')); commit(root, 'three', now - 60);const [after] = await readSyncFreshness(engine, { sourceIds: [id] });expect(after!.behind!.commits).toBe(2);+ // GBRA-133 (#7243): the backlog is named beside unresolved_commits, which counts only synced commits git cannot date.+ expect(after!.waiting_commits).toBe(2);expect(after!.behind!.oldest_seconds).toBeGreaterThanOrEqual(3600);expect(after!.behind!.oldest_seconds).toBeLessThan(3600 + 300);expect(formatSyncFreshness(after!)).toMatch(/; 2 commit\(s\) not synced yet, oldest 6\d(\.\d)?m old$/);diff --git a/test/sync-status-truthful-7243.test.ts b/test/sync-status-truthful-7243.test.tsindex 330f248749..5fe491211e 100644--- a/test/sync-status-truthful-7243.test.ts+++ b/test/sync-status-truthful-7243.test.ts@@ -159,6 +159,26 @@ test('status names last_commit and a live block for the drain-lease holder, a se}}), 300_000);+test('GBRA-133: status reports when the source last converged and when a sync write last committed, so a catch-up never reads as stale', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const s = await syncedSource(engine);+ const synced = await readSyncStatus(engine, s.id, { detail: false });+ expect(synced.last_sync_at).not.toBeNull();+ expect(synced.last_committed_at).not.toBeNull();+ // A source that last converged a day ago and has committed sync writes since (a long catch-up blocked short of convergence).+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET last_sync_at=now() - interval '26 hours' WHERE id=$1", [s.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const catchingUp = await readSyncStatus(engine, s.id, { detail: false });+ expect(Date.parse(catchingUp.last_committed_at!) - Date.parse(catchingUp.last_sync_at!)).toBeGreaterThan(25 * 3600_000);+ const json = await statusJson(engine, ['--source', s.id, '--json']) as { last_sync_at?: string; last_committed_at?: string };+ expect(json.last_sync_at).toBe(catchingUp.last_sync_at!);+ expect(json.last_committed_at).toBe(catchingUp.last_committed_at!);+ expect(await printed(() => runSyncStatus(engine, ['--source', s.id]))).toContain(`last committed write: ${catchingUp.last_committed_at} (still importing since it last converged)`);+ }+}), 300_000);+test('a last error a later pass got past reads superseded with what passed it and its age; one it did not get past stays live', async () => withEnv(env, async () => {for (const engine of engines) {const s = await syncedSource(engine);