Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): receipt health judges a claimed write only against earlier started writes (#5984 Phase 4.5 audit)

garrytan36c93195c5af
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index c8b7b962bc..3e8025a609 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -717,6 +717,12 @@ export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Da
}
const healthQueries = new WeakMap<BrainEngine, Promise<unknown>>();
+/**
+ * Receipt health facts per root. #5984: a queued request waits on any earlier unfinished request of its root;
+ * a claimed one (a lane, a group follower, or a foreground write claimed ahead of queued sync rows) waits only
+ * on an earlier one already publishing or recovering, so the queued rows it overtook never make it report
+ * `waiting_on_earlier_write`.
+ */
export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]): Promise<Map<string, WriteHealthFacts>> {
if (rows.length > 100) throw new RangeError('Receipt health pages are limited to 100 rows.');
const pending = rows.filter(row => !isTerminal(row));
@@ -725,20 +731,24 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
const roots = [...new Set(pending.map(row => row.worktree_id ?? `db:${row.source_incarnation}`))];
const abort = new AbortController();
const observed_at = new Date().toISOString();
- const query = engine.executeRaw<{ root: string; sequence: string | null; recovery_required: boolean; owner_unavailable: boolean; inspect_owner: boolean }>(`
+ const query = engine.executeRaw<{ root: string; sequence: string | null; started_sequence: string | null; recovery_required: boolean; owner_unavailable: boolean; inspect_owner: boolean }>(`
WITH roots AS (SELECT unnest($1::text[]) AS root)
- SELECT roots.root,head.sequence::text,COALESCE(head.inspect_owner,false) AS inspect_owner,
+ SELECT roots.root,head.sequence::text,head.started_sequence::text,COALESCE(head.inspect_owner,false) AS inspect_owner,
COALESCE(head.recovering,false) OR EXISTS (SELECT 1 FROM persistence_effects e
WHERE e.worktree_id=w.id AND e.recovery IS NOT NULL) AS recovery_required,
w.id IS NOT NULL AND (w.state<>'active' OR w.owner_host_id IS NULL) AS owner_unavailable
FROM roots LEFT JOIN persistence_worktrees w ON w.id::text=roots.root
LEFT JOIN LATERAL (
- (SELECT r.sequence,r.recovery IS NOT NULL AS recovering,
+ (SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id=w.id
+ AND (s.state IN ('running','recovering') OR s.recovery IS NOT NULL) ORDER BY s.sequence LIMIT 1) AS started_sequence,
+ r.recovery IS NOT NULL AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id=w.id AND (r.state IN ('queued','running','recovering') OR r.recovery IS NOT NULL)
ORDER BY r.sequence LIMIT 1)
UNION ALL
- (SELECT r.sequence,r.recovery IS NOT NULL AS recovering,
+ (SELECT r.sequence,(SELECT s.sequence FROM persistence_requests s WHERE s.worktree_id IS NULL AND s.source_incarnation=r.source_incarnation
+ AND s.state IN ('running','recovering') ORDER BY s.sequence LIMIT 1) AS started_sequence,
+ r.recovery IS NOT NULL AS recovering,
r.blocked_reason IN ('unexpected_file_bytes','unexpected_staging_bytes') AS inspect_owner FROM persistence_requests r
WHERE r.worktree_id IS NULL AND r.source_incarnation=CASE WHEN roots.root LIKE 'db:%' THEN substring(roots.root FROM 4)::uuid END
AND r.state IN ('queued','running','recovering') ORDER BY r.sequence LIMIT 1)
@@ -753,10 +763,12 @@ export async function writeHealthFacts(engine: BrainEngine, rows: WriteRequest[]
const byRoot = new Map(facts.map(fact => [fact.root, fact]));
for (const row of pending) {
const fact = byRoot.get(row.worktree_id ?? `db:${row.source_incarnation}`);
- if (fact) result.set(row.id, { observed_at, recovery_required: fact.recovery_required,
+ if (!fact) continue;
+ const head = row.state === 'queued' ? fact.sequence : fact.started_sequence;
+ result.set(row.id, { observed_at, recovery_required: fact.recovery_required,
owner_unavailable: fact.owner_unavailable,
inspect_owner: fact.inspect_owner,
- earlier_write: fact.sequence != null && BigInt(fact.sequence) < BigInt(row.sequence) });
+ earlier_write: head != null && BigInt(head) < BigInt(row.sequence) });
}
return result;
}
diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.ts
index 02c573b018..9898690141 100644
--- a/test/persistence-diagnostics.test.ts
+++ b/test/persistence-diagnostics.test.ts
@@ -4,7 +4,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
-import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { initializeLocalPersistence, submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { submissionAuthority } from '../src/core/persistence/authority.ts';
import { admitWrite, writeHealthFacts } from '../src/core/persistence/journal.ts';
import type { WriteRequest } from '../src/core/persistence/model.ts';
@@ -141,3 +141,43 @@ test('writer status labels the answering process consumer instead of reporting i
expect(diagnostics.local_process_ingress.scope).toContain('another process may own');
}
});
+
+test('#5984 4.5: health never reports an overtaking claimed write as waiting, nor skips the overtaken sync row', async () => {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, sourceId: 'default',
+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await initializeLocalPersistence(ctx);
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'persistence.limits.%'");
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const admit = async (slug: string, intent: Record<string, unknown>) => {
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, slug);
+ return admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug, requestId: randomUUID(), callerIntent: {}, intent });
+ };
+ const sync = await admit('inbox/overtaken-sync', { kind: 'managed_sync_import', content: 'a' });
+ const laterSync = await admit('inbox/later-sync', { kind: 'managed_sync_import', content: 'b' });
+ const foreground = await admit('inbox/overtaking-foreground', { content: 'c' });
+ const worktree = randomUUID();
+ await engine.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,state) VALUES($1,$2,'active')", [worktree, randomUUID()]);
+ await engine.executeRaw('UPDATE persistence_requests SET worktree_id=$2 WHERE id=ANY($1::uuid[])', [[sync.id, laterSync.id, foreground.id], worktree]);
+ const read = async () => engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [[sync.id, laterSync.id, foreground.id]]);
+ const earlier = async () => {
+ const rows = await read();
+ const facts = await writeHealthFacts(engine, rows);
+ return Object.fromEntries(rows.filter(row => facts.has(row.id)).map(row => [row.slug, facts.get(row.id)!.earlier_write]));
+ };
+ // The later-sequence foreground write is claimed ahead of the queued sync rows that do not name its page.
+ await engine.executeRaw("UPDATE persistence_requests SET state='running',execution_token=$2::uuid WHERE id=$1::uuid", [foreground.id, randomUUID()]);
+ expect(await earlier()).toEqual({ 'inbox/overtaken-sync': false, 'inbox/later-sync': true, 'inbox/overtaking-foreground': false });
+ // It commits first: the overtaken sync row is still the head and still reported pending, never skipped.
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed',execution_token=NULL,completed_at=now() WHERE id=$1::uuid", [foreground.id]);
+ expect(await earlier()).toEqual({ 'inbox/overtaken-sync': false, 'inbox/later-sync': true });
+ // The overtaken row is then claimed and publishes; the later sync row still waits on it while it runs.
+ await engine.executeRaw("UPDATE persistence_requests SET state='running',execution_token=$2::uuid WHERE id=$1::uuid", [sync.id, randomUUID()]);
+ expect(await earlier()).toEqual({ 'inbox/overtaken-sync': false, 'inbox/later-sync': true });
+ await engine.executeRaw("UPDATE persistence_requests SET state='committed',execution_token=NULL,completed_at=now() WHERE id=$1::uuid", [sync.id]);
+ expect(await earlier()).toEqual({ 'inbox/later-sync': false });
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',completed_at=now() WHERE id=$1::uuid", [laterSync.id]);
+ }
+});