Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): compaction visibility and counter drift (#6696 A10, A11)
garrytanefdc4013f58e
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 52934e7ea4..23611d5570 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -927,6 +927,24 @@ gbrain doctor --only persistence_capacity,persistence_request_growth --json**Say to your agent:** *"How many days of write capacity does my brain have left?"*+<a id="counter-drift"></a>+### Counter drift and compaction health++Two read-only doctor checks watch the receipt-bytes accounting:++- `persistence_counter_drift` compares each `persistence_counters` row+ (brain and every principal) with what the receipts hold+ (`terminal_reservation` per request plus lifecycle receipts) in one+ statement, 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.+- `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 when+ a full consumer has run longer than+ `persistence.maintenance.compaction_stale_hours` (default 24) without a+ pass. Its fix previews `gbrain repair receipt-compaction --json`.+<a id="quota-near-exhaustion"></a>### Quota near exhaustiondiff --git a/src/commands/doctor/checks/persistence-compaction.ts b/src/commands/doctor/checks/persistence-compaction.tsnew file mode 100644index 0000000000..4aa40bd646--- /dev/null+++ b/src/commands/doctor/checks/persistence-compaction.ts@@ -0,0 +1,72 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { doctorVerify } from '../check-fix.ts';+import { COMPACTION_STALE_HOURS_KEY, DEFAULT_COMPACTION_STALE_HOURS, readLastCompaction } from '../../../core/persistence/compaction-pass.ts';+import { TRUE_UP_CLAMPED_KEY } from '../../../core/persistence/receipt-bytes.ts';++const COMPACTION_DOCS = 'docs/guides/repair.md#receipt-compaction';+const DRIFT_DOCS = 'docs/guides/concurrent-writes.md#counter-drift';++/**+ * #6696 (A11): receipt compaction is how receipt bytes come back, and it runs+ * on a resident consumer's idle and volume ticks. Warns when a full consumer+ * has been up longer than `persistence.maintenance.compaction_stale_hours`+ * (24) and no pass was recorded within that window; ok with no live consumer+ * (nothing is expected to compact) and on a fresh brain.+ */+export async function checkPersistenceCompaction(engine: BrainEngine): Promise<Check> {+ try {+ const [consumers] = await engine.executeRaw<{ live: string; oldest_hours: number | null }>(`SELECT count(DISTINCT host_id)::text AS live,+ (EXTRACT(EPOCH FROM now()-min(started_at))/3600)::float8 AS oldest_hours+ FROM persistence_consumers WHERE mode IN ('full','promoted') AND renewed_at > now()-interval '5 minutes'`);+ const staleRaw = Number(await engine.getConfig(COMPACTION_STALE_HOURS_KEY));+ const staleHours = Number.isFinite(staleRaw) && staleRaw > 0 ? staleRaw : DEFAULT_COMPACTION_STALE_HOURS;+ const last = await readLastCompaction(engine);+ const ageHours = last ? (Date.now() - Date.parse(last.at)) / 3_600_000 : null;+ const details = { live_consumers: Number(consumers?.live ?? 0), stale_hours: staleHours, last_compaction: last,+ last_compaction_age_hours: ageHours === null ? null : Math.floor(ageHours), docs: COMPACTION_DOCS };+ const overdue = details.live_consumers > 0 && Number(consumers?.oldest_hours ?? 0) > staleHours && (ageHours === null || ageHours > staleHours);+ if (!overdue) return { name: 'persistence_compaction', status: 'ok', details,+ message: last ? `Receipt compaction last ran ${details.last_compaction_age_hours} hour(s) ago (compacted ${last.compacted}, freed ${last.freed_bytes} bytes).`+ : 'No receipt compaction recorded yet; a resident consumer compacts receipts past the retention window on its idle ticks.' };+ return { name: 'persistence_compaction', status: 'warn', details,+ message: `A resident consumer has run for over ${staleHours} hours but ${last ? `the last receipt compaction was ${details.last_compaction_age_hours} hours ago` : 'no receipt compaction was recorded'}, `+ + 'so receipt bytes are not coming back. Check the consumer (gbrain sources writer status --json), and preview an on-demand pass with gbrain repair receipt-compaction --json.',+ fix: { argv: ['gbrain', 'repair', 'receipt-compaction', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify: doctorVerify('persistence_compaction'),+ docs: COMPACTION_DOCS, why: 'Previews compacting the receipts past the retention window; it writes nothing.' } };+ } catch (error) {+ return { name: 'persistence_compaction', status: 'warn', message: `Receipt compaction state could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { health: 'unknown' } };+ }+}++/**+ * #6696 (A10): the receipt-bytes counters must equal what the receipts reserve+ * (`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`).+ */+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+ FROM 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 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.' };+ } 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/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.tsindex fc710cf1bc..7e46a02e50 100644--- a/src/commands/doctor/checks/schema-health.ts+++ b/src/commands/doctor/checks/schema-health.ts@@ -19,6 +19,7 @@ import { checkParkedEffects } from './parked-effects.ts';import { checkManagedGuardSchemaDrift, checkPublicationRefusals } from './managed-guard.ts';import { checkWorktreeRefreshStuck } from './worktree-refresh.ts';import { checkPersistenceCapacity } from './persistence-capacity.ts';+import { checkPersistenceCompaction, checkPersistenceCounterDrift } from './persistence-compaction.ts';import { checkPostgresCancellationDriver } from './postgres-cancellation.ts';import { checkProjectionReadiness } from './projection-readiness.ts';import type { Check } from '../../doctor.ts';@@ -47,7 +48,8 @@ async function runPgvector(ctx: DoctorContext): Promise<Check[]> {// 4a-bis. Managed write capacity (#5470) and parked postcommit effects (#5612).progress.heartbeat('persistence_capacity');- checks.push(await checkPersistenceCapacity(engine), await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));+ checks.push(await checkPersistenceCapacity(engine), await checkPersistenceCompaction(engine), await checkPersistenceCounterDrift(engine),+ await checkParkedEffects(engine), await checkWorktreeRefreshStuck(engine));// #5983/#5974: schema drift on guarded tables and writes the database refused.checks.push(await checkManagedGuardSchemaDrift(engine), await checkPublicationRefusals(engine));@@ -75,6 +77,8 @@ export const pgvectorEntry: DoctorEntry = {'pages_upsert_arbiter','text_projection_readiness','persistence_capacity',+ 'persistence_compaction',+ 'persistence_counter_drift','parked_effects','worktree_refresh_stuck','managed_guard_schema_drift',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 5f3fb98179..355b0386e4 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -208,6 +208,20 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [instruction: 'Raise the named journal limit with the `gbrain config set` command doctor prints, on the brain host.',run: async engine => (await import('./checks/persistence-capacity.ts')).checkPersistenceCapacity(engine),},+ {+ id: 'persistence_compaction', resolution: 'operator', registration: 'doctor.ts',+ count: d => (d.live_consumers ?? 0) > 0 ? 1 : 0,+ impact: 'A resident consumer has not compacted write receipts within its staleness window, so receipt bytes are not coming back',+ instruction: 'Check the consumer with `gbrain sources writer status --json`; preview an on-demand pass with `gbrain repair receipt-compaction --json` and apply it after the user agrees.',+ run: async engine => (await import('./checks/persistence-compaction.ts')).checkPersistenceCompaction(engine),+ },+ {+ id: 'persistence_counter_drift', resolution: 'operator', registration: 'doctor.ts',+ count: d => (d.drift ?? []).length,+ impact: 'Receipt-bytes counters differ from the receipts they account for',+ instruction: 'Report the drift with `gbrain doctor --only persistence_counter_drift --json`; the check changes nothing.',+ run: async engine => (await import('./checks/persistence-compaction.ts')).checkPersistenceCounterDrift(engine),+ },{id: 'parked_effects', resolution: 'operator', registration: 'doctor.ts',count: d => Number(d.parked_effects ?? 0),diff --git a/src/core/config.ts b/src/core/config.tsindex 0cffff542a..0a61451a11 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1773,6 +1773,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts'persistence.publication_ceiling_ms', 'persistence.terminal_failures.window_days', 'persistence.terminal_failures.spike_factor', 'persistence.terminal_failures.spike_min', // #6405: persistence/sync-drain.ts (in-pass publication ceiling); #6650: persistence/terminal-failures.ts'persistence.capacity.warn_days', 'persistence.capacity.fail_days', 'persistence.capacity.background_pause_pct', // #6696: persistence/capacity-forecast.ts, admission-origin.ts+ 'persistence.maintenance.compaction_stale_hours', // #6696 (A11): persistence/compaction-pass.ts, doctor persistence_compaction'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 9ea609ad42..46440fa881 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -257,6 +257,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['oauth_confidential_client_health','orphan_clones','persistence_capacity',+ 'persistence_compaction',+ 'persistence_counter_drift','worktree_refresh_stuck','managed_guard_schema_drift','publication_refusals',diff --git a/src/core/persistence/compaction-pass.ts b/src/core/persistence/compaction-pass.tsnew file mode 100644index 0000000000..883590a768--- /dev/null+++ b/src/core/persistence/compaction-pass.ts@@ -0,0 +1,50 @@+/**+ * #6696 (A11): the resident consumer's compaction pass, made visible. One pass+ * compacts what `compactWriteReceiptsDetailed` finds eligible, runs one bounded+ * step of the one-shot sweep of receipts compacted before reservations were+ * trued up, and records `{at, host_id, compacted, freed_bytes,+ * skipped_by_reason}` in `persistence.maintenance.last_compaction` (when it+ * compacted something, else at most once an hour per process). Doctor reads+ * the record (`persistence_compaction`) and warns when a live consumer has not+ * recorded a pass within `persistence.maintenance.compaction_stale_hours`+ * (default 24). A pass that frees bytes writes one `[persistence]+ * phase=compaction` line on stderr when the owner is `serve`.+ */+import type { BrainEngine } from '../engine.ts';+import { compactWriteReceiptsDetailed, type ReceiptCompactionResult } from './journal.ts';+import { sweepCompactedReservations } from './receipt-true-up.ts';++export const LAST_COMPACTION_KEY = 'persistence.maintenance.last_compaction';+export const COMPACTION_STALE_HOURS_KEY = 'persistence.maintenance.compaction_stale_hours';+export const DEFAULT_COMPACTION_STALE_HOURS = 24;+const RECORD_EVERY_MS = 60 * 60_000;++export interface CompactionRecord extends ReceiptCompactionResult { at: string; host_id: string }+const recordedAt = new WeakMap<object, number>();++export async function runCompactionPass(engine: BrainEngine, opts: { hostId: string; notice?: boolean; now?: number }): Promise<CompactionRecord> {+ const result = await compactWriteReceiptsDetailed(engine);+ const swept = await sweepCompactedReservations(engine);+ const now = opts.now ?? Date.now();+ const record: CompactionRecord = { at: new Date(now).toISOString(), host_id: opts.hostId, compacted: result.compacted,+ freed_bytes: result.freed_bytes + swept.freed_bytes, skipped_by_reason: result.skipped_by_reason };+ if (record.compacted > 0 || record.freed_bytes > 0 || now - (recordedAt.get(engine) ?? -Infinity) >= RECORD_EVERY_MS) {+ // The record is a report: a refused config write (a read-only or fenced brain) never fails the maintenance tick.+ if (await engine.setConfig(LAST_COMPACTION_KEY, JSON.stringify(record)).then(() => true, () => false)) recordedAt.set(engine, now);+ }+ if (opts.notice && record.freed_bytes > 0) {+ const skipped = Object.entries(record.skipped_by_reason).map(([reason, n]) => `${reason}:${n}`).join(',');+ process.stderr.write(`[persistence] phase=compaction compacted=${record.compacted} freed_bytes=${record.freed_bytes}${skipped ? ` skipped=${skipped}` : ''}\n`);+ }+ return record;+}++/** The last recorded pass, or null when none was recorded (or the record does not parse). */+export async function readLastCompaction(engine: Pick<BrainEngine, 'getConfig'>): Promise<CompactionRecord | null> {+ const raw = await engine.getConfig(LAST_COMPACTION_KEY);+ if (!raw) return null;+ try {+ const parsed = JSON.parse(raw) as CompactionRecord;+ return typeof parsed?.at === 'string' && Number.isFinite(Date.parse(parsed.at)) ? parsed : null;+ } catch { return null; }+}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex cc92d640ea..27c24dd39b 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,6 +1,6 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, compactWriteReceipts, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';@@ -17,6 +17,7 @@ import { claimedHeadOrder } from './sync-window.ts';import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';import { runPersistenceEffects } from './effects.ts';import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';+import { runCompactionPass } from './compaction-pass.ts';import { currentEmbeddingSignature } from '../embedding.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -490,7 +491,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));// F4b: idle maintenance also refreshes stale PGLite planner statistics (a no-op on Postgres).- this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => maybeRefreshPlannerStats(this.engine, 'idle')).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}return;@@ -526,7 +527,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (!this.maintenanceWorker && (Date.now() >= this.nextMaintenance || this.publishedSinceMaintenance >= this.maintenanceVolume)) {this.nextMaintenance = Date.now() + 60_000;this.publishedSinceMaintenance = 0;- this.maintenanceWorker = compactWriteReceipts(this.engine).then(() => vacuumPersistenceQueues(this.engine))+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => vacuumPersistenceQueues(this.engine)).then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}diff --git a/test/doctor-persistence-compaction.test.ts b/test/doctor-persistence-compaction.test.tsnew file mode 100644index 0000000000..1edeb99984--- /dev/null+++ b/test/doctor-persistence-compaction.test.ts@@ -0,0 +1,70 @@+/**+ * #6696 (A10, A11): `persistence_counter_drift` compares the receipt-bytes+ * counters with what the receipts reserve in one statement;+ * `persistence_compaction` warns when a resident consumer has run past the+ * staleness window without recording a compaction pass. Both are ok on a+ * fresh brain. PGLite in-memory ($0).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { checkPersistenceCompaction, checkPersistenceCounterDrift } from '../src/commands/doctor/checks/persistence-compaction.ts';+import { LAST_COMPACTION_KEY, readLastCompaction, runCompactionPass } from '../src/core/persistence/compaction-pass.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { editRequest, freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++describe('persistence counter drift and compaction health', () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => { scratch = mkdtempSync(join(tmpdir(), 'gbrain-doctor-compaction-')); factory = await freshBrainFactory('pglite'); }, 120_000);+ afterAll(async () => { await factory?.dispose(); rmSync(scratch, { recursive: true, force: true }); });+ const run = (fn: (engine: BrainEngine) => Promise<void>) => () => withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },+ async () => fn(await factory.fresh()));++ test('both are categorized and ok on a fresh brain', run(async engine => {+ for (const name of ['persistence_compaction', 'persistence_counter_drift']) expect(categorizeCheck(name)).toBeTruthy();+ expect(await checkPersistenceCounterDrift(engine)).toMatchObject({ status: 'ok' });+ expect(await checkPersistenceCompaction(engine)).toMatchObject({ status: 'ok', details: { live_consumers: 0, last_compaction: null } });+ }), 60_000);++ test('counters that match the receipts are ok; a counter charged past them warns with the delta and the clamp count', run(async engine => {+ const requests = await requestFixture(engine);+ await requests.admit('one'); await requests.admit('two');+ expect(await checkPersistenceCounterDrift(engine)).toMatchObject({ status: 'ok', details: { drift: [] } });+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_counters SET terminal_bytes=terminal_bytes+5000 WHERE key='brain'");+ });+ await engine.setConfig('persistence.true_up.clamped', '2');+ const drift = await checkPersistenceCounterDrift(engine);+ expect(drift).toMatchObject({ status: 'warn', details: { drift: [{ scope: 'brain', delta: 5000 }], true_up_clamped: 2 } });+ expect(drift.message).toContain('(+5000)');+ }), 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');+ await editRequest(engine, old.id, "state='committed',completed_at=now()-interval '60 days',published_at=now(),claim_expires_at=NULL");+ await engine.executeRaw('DELETE FROM persistence_effects WHERE request_id=$1::uuid', [old.id]);+ const host = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_consumers(host_id,pid,nonce,kind,mode,started_at,renewed_at,host_json_path,persistence_home,version)+ VALUES($1::uuid,1,'n','serve','full',now()-interval '30 hours',now(),'/tmp/example-host.json','/tmp/example-home','0.0.0')`, [host]);+ const overdue = await checkPersistenceCompaction(engine);+ expect(overdue).toMatchObject({ status: 'warn', fix: { argv: ['gbrain', 'repair', 'receipt-compaction', '--json'] } });+ const record = await runCompactionPass(engine, { hostId: host });+ expect(record).toMatchObject({ compacted: 1, host_id: host });+ expect(record.freed_bytes).toBeGreaterThan(0);+ expect(await readLastCompaction(engine)).toMatchObject({ compacted: 1, freed_bytes: record.freed_bytes });+ expect(await checkPersistenceCompaction(engine)).toMatchObject({ status: 'ok' });+ expect(await checkPersistenceCounterDrift(engine)).toMatchObject({ status: 'ok' });+ await engine.setConfig(LAST_COMPACTION_KEY, JSON.stringify({ ...record, at: new Date(Date.now() - 30 * 3_600_000).toISOString() }));+ expect(await checkPersistenceCompaction(engine)).toMatchObject({ status: 'warn' });+ await engine.setConfig('persistence.maintenance.compaction_stale_hours', '48');+ expect(await checkPersistenceCompaction(engine)).toMatchObject({ status: 'ok', details: { stale_hours: 48 } });+ }), 60_000);+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 9178d71e98..58f5aee1e9 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -453,16 +453,138 @@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ }+ ],+ "table_bytes": 262144,+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24+ },+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@ -810,7 +932,7 @@"days_to_exhaustion": null,"exhaustion_date": null,"lifetime_ids": 1,- "limit": 1000000,+ "limit": 8000000,"per_day": 0,"scope": "brain","window_days": 7@@ -821,7 +943,7 @@"days_to_exhaustion": null,"exhaustion_date": null,"lifetime_ids": 1,- "limit": 250000,+ "limit": 2000000,"per_day": 0,"scope": "principal:local_cli:<uuid>","window_days": 7@@ -830,7 +952,7 @@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},- "message": "1 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "1 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 934b02ace6..6b432b099d 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -456,16 +456,138 @@{"category": "ops","details": {+ "background_pause_pct": 80,"commands": [],+ "docs": "docs/guides/concurrent-writes.md#quota-near-exhaustion","exact": true,+ "forecast": {+ "retention_days": 30,+ "rows": [+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.brain_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 8000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 16000000,+ "resource": "lifetime_ids",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.brain_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 68719476736,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 137438953472,+ "resource": "terminal_bytes",+ "scope": "brain",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history",+ "config_key": "persistence.limits.principal_lifetime_ids",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 2000000,+ "max_day_7d": 1,+ "pct": 0,+ "per_day_7d": 1,+ "recommended_limit": 4000000,+ "resource": "lifetime_ids",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "used": 1,+ "window_days": 1+ },+ {+ "basis": "aggregate_1d_short_history:gross_then_net",+ "config_key": "persistence.limits.principal_terminal_bytes",+ "days_to_exhaustion": null,+ "exhaustion_date": null,+ "limit": 17179869184,+ "max_day_7d": 19163,+ "net_per_day_7d": 2845,+ "pct": 0,+ "per_day_7d": 19163,+ "reclaimable_bytes": 16318,+ "recommended_limit": 34359738368,+ "resource": "terminal_bytes",+ "scope": "principal:local_cli:<uuid>",+ "spike_day": null,+ "status": "ok",+ "under_reserved_receipts": 0,+ "used": 19163,+ "window_days": 1+ }+ ],+ "table_bytes": 262144,+ "thresholds": {+ "fail_days": 7,+ "fail_pct": 95,+ "warn_days": 30,+ "warn_pct": 80+ },+ "window_days": 1+ },"inspected": 2,+ "paused_producers": [],"resources": [],- "truncated": false+ "truncated": false,+ "verify": "gbrain doctor --only persistence_capacity --json"},- "message": "Managed write capacity is below 80% of every cumulative limit.",+ "message": "Managed write capacity is below 80% of every cumulative limit and none runs out within 30 days at its 7-day rate.","name": "persistence_capacity","status": "ok"},+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/repair.md#receipt-compaction",+ "last_compaction": {+ "at": "<ts>",+ "compacted": 0,+ "freed_bytes": 0,+ "host_id": "<uuid>",+ "skipped_by_reason": {}+ },+ "last_compaction_age_hours": 0,+ "live_consumers": 0,+ "stale_hours": 24+ },+ "message": "Receipt compaction last ran 0 hour(s) ago (compacted 0, freed 0 bytes).",+ "name": "persistence_compaction",+ "status": "ok"+ },+ {+ "category": "ops",+ "details": {+ "docs": "docs/guides/concurrent-writes.md#counter-drift",+ "drift": [],+ "inspected": 2,+ "true_up_clamped": 0+ },+ "message": "Receipt-bytes counters match the receipts they account for (2 scope(s)).",+ "name": "persistence_counter_drift",+ "status": "ok"+ },{"category": "brain","details": {@@ -829,7 +951,7 @@"days_to_exhaustion": null,"exhaustion_date": null,"lifetime_ids": 1,- "limit": 1000000,+ "limit": 8000000,"per_day": 0,"scope": "brain","window_days": 7@@ -840,7 +962,7 @@"days_to_exhaustion": null,"exhaustion_date": null,"lifetime_ids": 1,- "limit": 250000,+ "limit": 2000000,"per_day": 0,"scope": "principal:local_cli:<uuid>","window_days": 7@@ -849,7 +971,7 @@"verify": "gbrain doctor --json (check persistence_request_growth)","window_days": 7},- "message": "1 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",+ "message": "1 request row(s); no scope exhausts its lifetime request IDs within 30 days at its last-7-day rate.","name": "persistence_request_growth","status": "ok"},diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex a042813fdc..b8e161a2ce 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -265,6 +265,14 @@"category": "ops","name": "persistence_capacity"},+ {+ "category": "ops",+ "name": "persistence_compaction"+ },+ {+ "category": "ops",+ "name": "persistence_counter_drift"+ },{"category": "brain","name": "parked_effects"diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.jsonindex 80ef4cd79a..e13574d77e 100644--- a/test/fixtures/goldens/doctor/registry-report-remote.json+++ b/test/fixtures/goldens/doctor/registry-report-remote.json@@ -233,6 +233,14 @@"category": "ops","name": "persistence_capacity"},+ {+ "category": "ops",+ "name": "persistence_compaction"+ },+ {+ "category": "ops",+ "name": "persistence_counter_drift"+ },{"category": "brain","name": "parked_effects"diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsindex e5335d51c4..65999cbf91 100644--- a/test/repair-explicit-only.test.ts+++ b/test/repair-explicit-only.test.ts@@ -24,7 +24,7 @@ import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';-const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery'];+const EXPLICIT: RepairKind[] = ['google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery', 'receipt-compaction'];let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));