Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): counter drift names its direction and the receipts behind it (#6759)
garrytanee178b01b901
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 9b0345cef4..2cc00409aa 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -955,8 +955,15 @@ Two read-only doctor checks watch the receipt-bytes accounting:(brain and every principal) with what the receipts hold(`terminal_reservation` per request plus lifecycle receipts) in onestatement, and reports `persistence.true_up.clamped`, the number of- settle-time decrements that were clamped at zero. A positive delta charges- capacity no receipt holds; a negative one under-counts. It changes nothing.+ settle-time decrements that were clamped at zero. Each drifting scope in+ `details.drift` names its `direction`: `overcharge` (a positive delta) is a+ bounded charge against write capacity that no receipt holds, so writes are+ refused a little early and no data is lost; `undercount` (a negative delta)+ lets writes use capacity the receipts already reserve. `receipts_by_kind`+ splits the receipt side into `requests` and `topology_changes` (rows and+ bytes), and `details.incident` is `current` because the comparison is+ live. It changes nothing, and there is no reconcile repair yet: report a+ persistent drift with `gbrain doctor --only persistence_counter_drift --json`.- `persistence_compaction` reads `persistence.maintenance.last_compaction`,the record each resident consumer's compaction pass writes (`at`,`host_id`, `compacted`, `freed_bytes`, `skipped_by_reason`), and warns whendiff --git a/src/commands/doctor/checks/persistence-compaction.ts b/src/commands/doctor/checks/persistence-compaction.tsindex 4aa40bd646..e09e1c53f8 100644--- a/src/commands/doctor/checks/persistence-compaction.ts+++ b/src/commands/doctor/checks/persistence-compaction.ts@@ -45,26 +45,39 @@ export async function checkPersistenceCompaction(engine: BrainEngine): Promise<C* (`terminal_reservation` per request, plus lifecycle receipts) per principal* and brain-wide. Read-only, one statement (one snapshot); also reports how* many true-up decrements were clamped at zero (`persistence.true_up.clamped`).+ * #6759: each drifting scope names its direction (a positive delta is a+ * bounded overcharge of write capacity, a negative one under-counts) and the+ * receipts behind it by kind; the comparison is live, so a warn's incident is+ * current.*/export async function checkPersistenceCounterDrift(engine: BrainEngine): Promise<Check> {try {- const rows = await engine.executeRaw<{ key: string; counter: string; receipts: string | null; clamped: string | null }>(`WITH s AS (- SELECT key,SUM(bytes) AS bytes FROM (- SELECT 'principal:'||principal_kind||':'||principal_id AS key,terminal_reservation AS bytes FROM persistence_requests- UNION ALL SELECT 'principal:local_cli:'||principal_id::text,terminal_bytes FROM persistence_topology_changes) u GROUP BY key),- every AS (SELECT key,bytes FROM s UNION ALL SELECT 'brain',SUM(bytes) FROM s)- SELECT c.key,c.terminal_bytes::text AS counter,COALESCE(e.bytes,0)::text AS receipts,(SELECT value FROM config WHERE key=$1) AS clamped+ const rows = await engine.executeRaw<{ key: string; counter: string; req_rows: string; req_bytes: string; topo_rows: string; topo_bytes: string; clamped: string | null }>(`WITH u AS (+ SELECT 'principal:'||principal_kind||':'||principal_id AS key,'requests' AS kind,terminal_reservation AS bytes FROM persistence_requests+ UNION ALL SELECT 'principal:local_cli:'||principal_id::text,'topology_changes',terminal_bytes FROM persistence_topology_changes),+ s AS (SELECT key,count(*) FILTER (WHERE kind='requests') AS req_rows,COALESCE(SUM(bytes) FILTER (WHERE kind='requests'),0) AS req_bytes,+ count(*) FILTER (WHERE kind='topology_changes') AS topo_rows,COALESCE(SUM(bytes) FILTER (WHERE kind='topology_changes'),0) AS topo_bytes FROM u GROUP BY key),+ every AS (SELECT * FROM s UNION ALL SELECT 'brain',COALESCE(SUM(req_rows),0),COALESCE(SUM(req_bytes),0),COALESCE(SUM(topo_rows),0),COALESCE(SUM(topo_bytes),0) FROM s)+ SELECT c.key,c.terminal_bytes::text AS counter,COALESCE(e.req_rows,0)::text AS req_rows,COALESCE(e.req_bytes,0)::text AS req_bytes,+ COALESCE(e.topo_rows,0)::text AS topo_rows,COALESCE(e.topo_bytes,0)::text AS topo_bytes,(SELECT value FROM config WHERE key=$1) AS clampedFROM persistence_counters c LEFT JOIN every e ON e.key=c.key WHERE c.key='brain' OR c.key LIKE 'principal:%' ORDER BY c.key`, [TRUE_UP_CLAMPED_KEY]);const clamped = Number(rows[0]?.clamped ?? 0) || 0;- const drift = rows.map(row => ({ scope: row.key, counter: Number(row.counter), receipts: Number(row.receipts), delta: Number(row.counter) - Number(row.receipts) }))- .filter(row => row.delta !== 0);+ const drift = rows.map(row => {+ const receipts = Number(row.req_bytes) + Number(row.topo_bytes);+ const delta = Number(row.counter) - receipts;+ return { scope: row.key, counter: Number(row.counter), receipts, delta, direction: delta > 0 ? 'overcharge' : 'undercount',+ receipts_by_kind: { requests: { rows: Number(row.req_rows), bytes: Number(row.req_bytes) }, topology_changes: { rows: Number(row.topo_rows), bytes: Number(row.topo_bytes) } } };+ }).filter(row => row.delta !== 0);const details = { inspected: rows.length, drift, true_up_clamped: clamped, docs: DRIFT_DOCS };if (!drift.length) return { name: 'persistence_counter_drift', status: 'ok', details,message: `Receipt-bytes counters match the receipts they account for (${rows.length} scope(s))${clamped ? `; ${clamped} true-up decrement(s) were clamped at zero earlier` : ''}.` };- return { name: 'persistence_counter_drift', status: 'warn', details,- message: `Receipt-bytes counters differ from the receipts they account for: ${drift.map(row => `${row.scope} counter ${row.counter} vs receipts ${row.receipts} (${row.delta > 0 ? '+' : ''}${row.delta})`).join('; ')}. `- + `A positive delta charges capacity no receipt holds; a negative one under-counts.${clamped ? ` ${clamped} true-up decrement(s) were clamped at zero.` : ''} `- + 'Nothing is changed by this check; report it with gbrain doctor --only persistence_counter_drift --json.' };+ return { name: 'persistence_counter_drift', status: 'warn', details: { ...details, incident: { scope: 'current', since: null } },+ message: `Receipt-bytes counters differ from the receipts they account for: ${drift.map(row => `${row.scope} counter ${row.counter} vs receipts ${row.receipts} (${row.delta > 0 ? '+' : ''}${row.delta}): `+ + (row.delta > 0 ? `a bounded overcharge of ${row.delta} bytes` : `under-counts by ${-row.delta} bytes`)).join('; ')}. `+ + (drift.some(row => row.delta > 0) ? 'An overcharge holds back write capacity no receipt uses; no data is lost. ' : '')+ + (drift.some(row => row.delta < 0) ? 'An under-count lets writes use capacity the receipts already reserve. ' : '')+ + `${clamped ? `${clamped} true-up decrement(s) were clamped at zero. ` : ''}`+ + 'Nothing is changed by this check; details.drift lists the receipts behind each scope by kind. Report it with gbrain doctor --only persistence_counter_drift --json.' };} catch (error) {return { name: 'persistence_counter_drift', status: 'warn', message: `Receipt-bytes counters could not be compared: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,details: { health: 'unknown' } };diff --git a/test/doctor-persistence-compaction.test.ts b/test/doctor-persistence-compaction.test.tsindex 1edeb99984..77e061a4dd 100644--- a/test/doctor-persistence-compaction.test.ts+++ b/test/doctor-persistence-compaction.test.ts@@ -46,6 +46,28 @@ describe('persistence counter drift and compaction health', () => {expect(drift.message).toContain('(+5000)');}), 60_000);+ test('#6759: a positive delta is a bounded overcharge with a per-scope receipt breakdown; a negative one under-counts', run(async engine => {+ const requests = await requestFixture(engine);+ await requests.admit('one'); await requests.admit('two');+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_counters SET terminal_bytes=terminal_bytes+983040 WHERE key='brain'");+ await tx.executeRaw("UPDATE persistence_counters SET terminal_bytes=terminal_bytes-100 WHERE key LIKE 'principal:%'");+ });+ const drift = await checkPersistenceCounterDrift(engine);+ expect(drift.status).toBe('warn');+ const details = drift.details as { drift: Array<Record<string, unknown>>; incident: unknown };+ expect(details.incident).toEqual({ scope: 'current', since: null });+ const brain = details.drift.find(d => d.scope === 'brain')!;+ const principal = details.drift.find(d => String(d.scope).startsWith('principal:'))!;+ expect(brain).toMatchObject({ direction: 'overcharge', receipts_by_kind: { requests: { rows: 2 }, topology_changes: { rows: 0, bytes: 0 } } });+ expect((brain.receipts_by_kind as { requests: { bytes: number } }).requests.bytes).toBe(brain.receipts as number);+ expect(principal).toMatchObject({ direction: 'undercount', delta: -100, receipts_by_kind: { requests: { rows: 2 } } });+ expect(drift.message).toContain('bounded overcharge of 983040 bytes');+ expect(drift.message).toContain('no data is lost');+ expect(drift.message).toContain('under-counts by 100 bytes');+ }), 60_000);+test('a consumer up past the window with no pass warns; a pass records what it freed and clears it; a stale record warns again', run(async engine => {const requests = await requestFixture(engine);const old = await requests.admit('old');