Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(GBRA-130 A-14): receipt compaction leaves each worktree's newest sync receipt out of its window, so 100+ of them never starve the rest
garrytan02b37446b0a7
diff --git a/src/commands/doctor/checks/persistence-compaction.ts b/src/commands/doctor/checks/persistence-compaction.tsindex e09e1c53f8..162e2ec833 100644--- a/src/commands/doctor/checks/persistence-compaction.ts+++ b/src/commands/doctor/checks/persistence-compaction.ts@@ -14,6 +14,11 @@ const DRIFT_DOCS = 'docs/guides/concurrent-writes.md#counter-drift';* (24) and no pass was recorded within that window; ok with no live consumer* (nothing is expected to compact) and on a fresh brain.*/+/** GBRA-130 A-14: a pass that compacted nothing names what it skipped (a fresh record is not proof bytes came back). */+const skippedNote = (last: { compacted: number; skipped_by_reason?: Record<string, number> }) => {+ const skipped = Object.entries(last.skipped_by_reason ?? {}).map(([reason, n]) => `${reason}: ${n}`);+ return last.compacted === 0 && skipped.length ? `; it skipped ${skipped.join(', ')}` : '';+};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,@@ -27,7 +32,7 @@ export async function checkPersistenceCompaction(engine: BrainEngine): Promise<Clast_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).`+ message: last ? `Receipt compaction last ran ${details.last_compaction_age_hours} hour(s) ago (compacted ${last.compacted}, freed ${last.freed_bytes} bytes${skippedNote(last)}).`: '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'}, `diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c76f28d2db..e42157a76a 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -1065,6 +1065,13 @@ const OPEN_SYNC_PASS_SQL = (r: string) => `${r}.intent ? 'passId' AND EXISTS (SEexport const OPEN_SYNC_CURSOR_EXCLUSION = (r: string) => `AND NOT (${r}.intent ? 'runId' AND EXISTS (SELECT 1 FROM op_checkpoints cWHERE c.op='managed-sync' AND c.completed_keys->0->>'runId'=${r}.intent->>'runId' AND COALESCE(c.completed_keys->0->>'done','false')<>'true'))AND NOT (${OPEN_SYNC_PASS_SQL(r)})`;+/**+ * GBRA-130 A-14: `newestSyncReceipt` as a selection filter, so a compaction pass's window is never filled by receipts+ * `compactReceipt` keeps (one per worktree, retired ones included); the per-row check still re-reads it under the lock.+ */+export const NEWEST_SYNC_RECEIPT_EXCLUSION = (r: string) => `AND NOT (${r}.state='committed' AND ${r}.worktree_id IS NOT NULL AND (${r}.intent ? 'runId' OR ${r}.intent ? 'passId')+ AND COALESCE(${r}.intent->>'kind','') LIKE 'managed_sync_%' AND ${r}.id=(SELECT n.id FROM persistence_requests n WHERE n.worktree_id=${r}.worktree_id+ AND n.state='committed' AND COALESCE(n.intent->>'kind','') LIKE 'managed_sync_%' ORDER BY n.completed_at DESC, n.sequence DESC LIMIT 1))`;export async function newestSyncReceipt(tx: SqlEngine, row: Pick<WriteRequest, 'id' | 'state' | 'intent' | 'worktree_id'>): Promise<boolean> {const intent = row.intent as { runId?: unknown; passId?: unknown; kind?: unknown } | null;if (row.state !== 'committed' || !row.worktree_id || (typeof intent?.runId !== 'string' && typeof intent?.passId !== 'string') || !String(intent?.kind ?? '').startsWith('managed_sync_')) return false;@@ -1087,6 +1094,7 @@ export async function compactWriteReceiptsDetailed(engine: BrainEngine, retentioAND completed_at < now()-($1::double precision*interval '1 day')AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state<>'committed')${OPEN_SYNC_CURSOR_EXCLUSION('r')}+ ${NEWEST_SYNC_RECEIPT_EXCLUSION('r')}ORDER BY sequence LIMIT 100`, [retentionDays]);const result: ReceiptCompactionResult = { compacted: 0, freed_bytes: 0, skipped_by_reason: {} };for (const row of rows) {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex fa26bb2a34..64ef39e785 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -263,6 +263,7 @@ test/purge-global-marker.test.tstest/purge-missing-cache-6911.test.tstest/purge-read-surfaces.test.tstest/recall-page-fill.test.ts+test/receipt-compaction-newest-sync-gbra130.test.tstest/remediation-manual-only.test.tstest/repair-apply-pending-6543.test.tstest/repair-embedding-effects.test.tsdiff --git a/test/receipt-compaction-newest-sync-gbra130.test.ts b/test/receipt-compaction-newest-sync-gbra130.test.tsnew file mode 100644index 0000000000..f6799868ec--- /dev/null+++ b/test/receipt-compaction-newest-sync-gbra130.test.ts@@ -0,0 +1,65 @@+/**+ * GBRA-130 A-14 (inventory E-6, #6712 PR 4b): the compaction pass selected the 100 oldest eligible receipts without+ * leaving out each worktree's newest committed managed-sync receipt (kept so a resumed run finds what it committed), and+ * `compactReceipt` then skipped every one of them. Once 100 or more worktrees (retired ones included) held such a receipt+ * past retention, every pass compacted 0 rows while still recording itself, so doctor read fresh and terminal_bytes grew+ * toward write_quota_exhausted.+ *+ * Protects (red before: the pass compacts 0 and the older put_page receipt stays): the exclusion is in the selection, so+ * 101 newest sync receipts on 101 worktrees, all past retention, leave the candidate window; the older put_page receipt+ * is compacted and the 101 stay. With nothing compacted, doctor's message names what the pass skipped.+ * Runs on PGLite and, with DATABASE_URL, on Postgres.+ */+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 type { BrainEngine } from '../src/core/engine.ts';+import { compactWriteReceiptsDetailed } from '../src/core/persistence/journal.ts';+import { LAST_COMPACTION_KEY } from '../src/core/persistence/compaction-pass.ts';+import { checkPersistenceCompaction } from '../src/commands/doctor/checks/persistence-compaction.ts';+import { editRequest, freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const WORKTREES = 101;++for (const kind of testBackends()) describe(`[${kind}] GBRA-130 A-14: the compaction window past each worktree's newest sync receipt`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-a14-'));+ factory = await freshBrainFactory(kind, process.env.DATABASE_URL);+ }, 120_000);+ afterAll(async () => { await factory?.dispose(); if (scratch) rmSync(scratch, { recursive: true, force: true }); });++ test(`${WORKTREES} worktrees' newest sync receipts past retention do not starve an older put_page receipt`, () => withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const engine: BrainEngine = await factory.fresh();+ const requests = await requestFixture(engine);+ // 101 worktrees (retired or not), each with its newest committed managed-sync receipt, all past retention; admitted first,+ // so they lead the selection's sequence order.+ const sync = (await engine.executeRaw<{ id: string }>(`WITH w AS (INSERT INTO persistence_worktrees(state) SELECT 'active' FROM generate_series(1, ${WORKTREES}) RETURNING id)+ INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,intent,authority,+ intent_bytes,terminal_reservation,state,completed_at,published_at)+ SELECT 'local_cli','sync-example',gen_random_uuid(),'submit_job',$1,$2::uuid,'s-'||w.id,w.id,'d',jsonb_build_object('kind','managed_sync_import','runId','run-'||w.id),+ '{}'::jsonb,1,16384,'committed',now()-interval '150 days',now()-interval '150 days' FROM w RETURNING id::text AS id`, [requests.sourceId, requests.incarnation])).map(row => row.id);+ expect(sync).toHaveLength(WORKTREES);+ // The put_page receipt completed earlier than all of them but was admitted after them.+ const admitted = await requests.admit('put-page');+ await editRequest(engine, admitted.id, `state='committed',completed_at=now()-interval '200 days',published_at=now(),claim_expires_at=NULL`);+ await engine.executeRaw('DELETE FROM persistence_effects WHERE request_id=$1::uuid', [admitted.id]);+ const putPage = admitted.id;+ await engine.setConfig('persistence.receipt_retention_days', '90');++ const result = await compactWriteReceiptsDetailed(engine);+ const compacted = new Set((await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE compacted')).map(row => row.id));+ expect(compacted.has(putPage)).toBe(true);+ expect(sync.filter(id => compacted.has(id))).toEqual([]);+ expect(result.compacted).toBe(1);+ expect(result.skipped_by_reason.newest_sync_receipt ?? 0).toBe(0);++ // A pass that compacted nothing names what it skipped.+ await engine.setConfig(LAST_COMPACTION_KEY, JSON.stringify({ at: new Date().toISOString(), host_id: 'host-example', compacted: 0, freed_bytes: 0, skipped_by_reason: { lock_timeout: 3 } }));+ expect((await checkPersistenceCompaction(engine)).message).toContain('lock_timeout: 3');+ }), 180_000);+});