Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): lost_caller_writes reads set-based, walks replay attempts before supersession, reports compacted receipts; stillDrifted lets a deleted page fall through to supersession

garrytaned1d20b1ccae
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 61e6e8c1c6..354092b3b4 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -209,19 +209,20 @@ export async function lostCallerWritesCheck(engine: BrainEngine, sourceIds?: str
const docs = 'docs/guides/repair.md#failed-writes';
try {
const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
- const rows = await lostCallerWrites(engine, sources);
- const count = rows.reduce((sum, row) => sum + row.count, 0);
- const details = { count, writes: rows, repair: 'failed-writes', docs };
- if (!count) return { name: 'lost_caller_writes', status: 'ok', details, message: 'Every caller write with a retained receipt committed or was superseded.' };
+ const { lost, compacted } = await lostCallerWrites(engine, sources);
+ const count = lost.reduce((sum, row) => sum + row.count, 0);
+ const details = { count, writes: lost, compacted_unreplayable: compacted, repair: 'failed-writes', docs };
+ const compactedNote = compacted ? ` ${compacted} older refused receipt(s) were compacted (persistence.receipt_retention_days) and cannot be replayed.` : '';
+ if (!count) return { name: 'lost_caller_writes', status: 'ok', details, message: `Every caller write with a retained receipt committed or was superseded.${compactedNote}` };
const bySource = new Map<string, number>();
- for (const row of rows) bySource.set(row.source_id, (bySource.get(row.source_id) ?? 0) + row.count);
+ for (const row of lost) bySource.set(row.source_id, (bySource.get(row.source_id) ?? 0) + row.count);
const first = [...bySource.keys()][0]!;
- const drift = rows.filter(row => row.reason === 'file_database_drift').reduce((sum, row) => sum + row.count, 0);
- const memory = rows.filter(row => row.operation === 'remember').reduce((sum, row) => sum + row.count, 0);
+ const drift = lost.filter(row => row.reason === 'source_changed').reduce((sum, row) => sum + row.count, 0);
+ const memory = lost.filter(row => row.operation === 'remember').reduce((sum, row) => sum + row.count, 0);
return { name: 'lost_caller_writes', status: 'warn', details,
- message: `${count} caller write(s) never landed (${memory} remember; ${drift} refused source_changed because the page's file and database differed, `
- + `${count - drift} refused by the managed writer guard): ${[...bySource].map(([source, n]) => `${source}: ${n}`).join(', ')}. The callers saw an error and `
- + `the fact or page edit was dropped. Preview the replay on the brain host: gbrain repair failed-writes --source ${first} — then run the apply command it prints after the user agrees.`,
+ message: `${count} caller write(s) never landed (${memory} remember; ${drift} refused source_changed because the page's canonical file did not match its database copy `
+ + `or was missing, ${count - drift} refused by the managed writer guard): ${[...bySource].map(([source, n]) => `${source}: ${n}`).join(', ')}. The callers saw an error and `
+ + `the fact or page edit was dropped. Preview the replay on the brain host: gbrain repair failed-writes --source ${first} — then run the apply command it prints after the user agrees.${compactedNote}`,
fix: agentFix(['gbrain', 'repair', 'failed-writes', '--source', first],
'Read-only preview: lists each lost write with its disposition (replay, already_written, duplicate, superseded) and prints the apply command.', 'lost_caller_writes', { docs }) };
} catch (error) {
diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.ts
index 0918deee36..eecfe083be 100644
--- a/src/core/repair/failed-writes.ts
+++ b/src/core/repair/failed-writes.ts
@@ -110,26 +110,58 @@ async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: strin
/**
* #6429: the caller writes this command would still replay, counted per source, operation and refusal reason for
- * doctor's `lost_caller_writes`. Distinct intents, so a caller's retry counts its write once; a refused replay
- * attempt is the original write (its rows are dropped and its attempts walked as `disposition` does), a write whose
- * replay or retry committed or whose page was later deleted (for put_page: written again) is not lost. Owner-produced
- * writes are not counted: their producer runs them again. Reads no intents.
+ * doctor's `lost_caller_writes`, plus the refused receipts compaction already emptied (unreplayable). Distinct
+ * intents, so a caller's retry counts its write once; a refused replay attempt is the original write (its rows are
+ * dropped and its attempts walked as `disposition` does); a write whose replay or retry committed or whose page was
+ * later deleted (for put_page: written again) is not lost. Owner-produced writes are not counted: their producer
+ * runs them again. Reads no intents, and every read is one pass over the table, never one probe per candidate:
+ * doctor runs this on every call.
*/
export async function lostCallerWrites(engine: BrainEngine, sourceIds: string[]):
-Promise<{ source_id: string; operation: string; reason: 'file_database_drift' | 'writer_guard'; count: number }[]> {
- type Lost = { id: string; request_id: string; source_id: string; slug: string; operation: string; digest: string; reason: 'file_database_drift' | 'writer_guard' };
- const rows = await engine.executeRaw<Lost>(
- `SELECT r.id::text, r.request_id::text, r.source_id, r.slug, r.operation, r.digest, CASE WHEN r.state='conflict' THEN 'file_database_drift' ELSE 'writer_guard' END AS reason
- FROM persistence_requests r
- WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})
- AND r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind')
- AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE c.source_id=r.source_id AND c.slug=r.slug AND c.state='committed' AND c.sequence > r.sequence
- AND (c.digest=r.digest OR c.operation = ANY($3::text[]) OR r.operation='put_page'))
- ORDER BY r.sequence`, [sourceIds, REPLAYABLE, PAGE_REMOVALS]);
+Promise<{ lost: { source_id: string; operation: string; reason: 'source_changed' | 'writer_guard'; count: number }[]; compacted: number }> {
+ type Lost = { id: string; request_id: string; source_id: string; slug: string; operation: string; digest: string; sequence: string; reason: 'source_changed' | 'writer_guard' };
+ const caller = `r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind')`;
+ const refused = `(${GUARD_REFUSAL} OR ${DRIFT_REFUSAL})`;
+ const [rows, [compacted]] = await Promise.all([
+ engine.executeRaw<Lost>(
+ `SELECT r.id::text, r.request_id::text, r.source_id, r.slug, r.operation, r.digest, r.sequence::text,
+ CASE WHEN r.state='conflict' THEN 'source_changed' ELSE 'writer_guard' END AS reason
+ FROM persistence_requests r
+ WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND ${refused} AND ${caller}
+ ORDER BY r.sequence`, [sourceIds, REPLAYABLE]),
+ // A compacted receipt keeps no intent, so an owner-produced put_page cannot be told from a caller's; remember and
+ // add_timeline_entry are always caller writes.
+ engine.executeRaw<{ count: number }>(
+ `SELECT count(*)::int AS count FROM persistence_requests r
+ WHERE r.source_id = ANY($1::text[]) AND r.compacted AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL}) AND r.operation = ANY($2::text[])`,
+ [sourceIds, REPLAYABLE.filter(operation => operation !== 'put_page')]),
+ ]);
+ if (!rows.length) return { lost: [], compacted: Number(compacted?.count ?? 0) };
+ // Attempt rows this command submitted belong to their original (walked below), not to the listing.
const requestIds = new Set(rows.map(row => row.request_id));
const replays = new Set<string>();
for (const row of rows) for (let attempt = 0; requestIds.has(replayId(row.id, attempt)); attempt++) replays.add(replayId(row.id, attempt));
- let pending = rows.filter(row => !replays.has(row.request_id));
+ const originals = rows.filter(row => !replays.has(row.request_id));
+ // Supersession, set-based: per slug the newest committed removal and write, per (slug, digest) the newest committed same intent.
+ const slugs = [...new Set(originals.map(row => row.slug))];
+ const [bySlug, byDigest] = await Promise.all([
+ engine.executeRaw<{ source_id: string; slug: string; removal: string | null; write: string | null }>(
+ `SELECT c.source_id, c.slug, max(c.sequence) FILTER (WHERE c.operation = ANY($3::text[]))::text AS removal, max(c.sequence)::text AS write
+ FROM persistence_requests c WHERE c.source_id = ANY($1::text[]) AND c.slug = ANY($2::text[]) AND c.state='committed' GROUP BY c.source_id, c.slug`,
+ [sourceIds, slugs, PAGE_REMOVALS]),
+ engine.executeRaw<{ source_id: string; slug: string; digest: string; same: string }>(
+ `SELECT c.source_id, c.slug, c.digest, max(c.sequence)::text AS same FROM persistence_requests c
+ WHERE c.source_id = ANY($1::text[]) AND c.slug = ANY($2::text[]) AND c.digest = ANY($3::text[]) AND c.state='committed' GROUP BY c.source_id, c.slug, c.digest`,
+ [sourceIds, slugs, [...new Set(originals.map(row => row.digest))]]),
+ ]);
+ const later = (a: string | null | undefined, b: string) => a != null && BigInt(a) > BigInt(b);
+ const slugKey = (row: { source_id: string; slug: string }) => `${row.source_id}\0${row.slug}`;
+ const removalBy = new Map(bySlug.map(row => [slugKey(row), row.removal]));
+ const writeBy = new Map(bySlug.map(row => [slugKey(row), row.write]));
+ const sameBy = new Map(byDigest.map(row => [`${slugKey(row)}\0${row.digest}`, row.same]));
+ let pending = originals.filter(row => !later(sameBy.get(`${slugKey(row)}\0${row.digest}`), row.sequence)
+ && !later(removalBy.get(slugKey(row)), row.sequence) && !(row.operation === 'put_page' && later(writeBy.get(slugKey(row)), row.sequence)));
+ // Replay attempts whose row is not a refusal (committed, or still live): one read per attempt round, rounds are few.
const lost: Lost[] = [];
for (let attempt = 0; pending.length; attempt++) {
const states = new Map((await engine.executeRaw<{ request_id: string; state: string }>(
@@ -150,8 +182,8 @@ Promise<{ source_id: string; operation: string; reason: 'file_database_drift' |
group.digests.add(row.digest);
groups.set(key, group);
}
- return [...groups.values()].sort((a, b) => a.source_id.localeCompare(b.source_id) || a.operation.localeCompare(b.operation) || a.reason.localeCompare(b.reason))
- .map(group => ({ source_id: group.source_id, operation: group.operation, reason: group.reason, count: group.digests.size }));
+ const sorted = [...groups.values()].sort((a, b) => a.source_id.localeCompare(b.source_id) || a.operation.localeCompare(b.operation) || a.reason.localeCompare(b.reason));
+ return { lost: sorted.map(group => ({ source_id: group.source_id, operation: group.operation, reason: group.reason, count: group.digests.size })), compacted: Number(compacted?.count ?? 0) };
}
async function pageRevision(engine: BrainEngine, sourceId: string, slug: string): Promise<string | null> {
@@ -196,13 +228,14 @@ function driftDetail(sourceId: string, slug: string): string {
/**
* #6429: whether the page's canonical file still differs from its database copy, the same check the replay's
* preparation applies. A reconcile that rewrites only the file leaves the page row untouched, so the row's
- * `updated_at` alone cannot tell that the drift is gone. Without the page or its owner binding on this host the
- * drift is assumed to remain.
+ * `updated_at` alone cannot tell that the drift is gone. A page that no longer exists has no file to drift (the
+ * supersession rules below decide); without the owner binding on this host the drift is assumed to remain.
*/
async function stillDrifted(engine: BrainEngine, write: FailedWrite): Promise<boolean> {
const snapshot = await engine.readPageSnapshot(write.slug, { sourceId: write.source_id });
+ if (!snapshot) return false;
const binding = await getWorktreeBinding(engine, write.source_id);
- if (!snapshot || !binding) return true;
+ if (!binding) return true;
try {
await prepareFileTarget(engine, { source_id: write.source_id, worktree_id: binding.worktree_id, slug: write.slug }, snapshot, null);
return false;
diff --git a/test/doctor-lost-caller-writes.test.ts b/test/doctor-lost-caller-writes.test.ts
index 0a9f0d2770..30f762c406 100644
--- a/test/doctor-lost-caller-writes.test.ts
+++ b/test/doctor-lost-caller-writes.test.ts
@@ -20,7 +20,7 @@ afterAll(async () => { await engine.disconnect(); });
test('a brain with no refused caller writes is ok, and the check is wired to the explicit-only replay', async () => {
const check = await lostCallerWritesCheck(engine);
expect(check.status).toBe('ok');
- expect(check.details).toMatchObject({ count: 0, writes: [], repair: 'failed-writes' });
+ expect(check.details).toMatchObject({ count: 0, writes: [], compacted_unreplayable: 0, repair: 'failed-writes' });
expect(categorizeCheck('lost_caller_writes')).toBe('ops');
const spec = WAVE_CHECKS.find(spec => spec.id === 'lost_caller_writes');
expect(spec).toMatchObject({ resolution: 'repair', registration: 'wave' });
diff --git a/test/fixtures/goldens/doctor/content-pglite-human.json b/test/fixtures/goldens/doctor/content-pglite-human.json
index 9b011dac58..9fbe13dbee 100644
--- a/test/fixtures/goldens/doctor/content-pglite-human.json
+++ b/test/fixtures/goldens/doctor/content-pglite-human.json
@@ -88,6 +88,7 @@
" [OK] persistence_request_indexes: Managed sync request indexes are valid.",
" [OK] persistence_request_growth: 6 request row(s); no scope exhausts its lifetime request IDs within 90 days at its last-7-day rate.",
" [OK] persistence_write_stall: No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
+ " [OK] lost_caller_writes: Every caller write with a retained receipt committed or was superseded.",
" [OK] persistence_session_timeouts: PGLite has no session to time out.",
" [OK] connector_held_items: No connector items are held.",
" [OK] git_held_files: No Git source files are held.",
diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.json
index 94e5d98902..a8440c4d6d 100644
--- a/test/fixtures/goldens/doctor/content-pglite-json.json
+++ b/test/fixtures/goldens/doctor/content-pglite-json.json
@@ -884,6 +884,19 @@
"name": "persistence_write_stall",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "compacted_unreplayable": 0,
+ "count": 0,
+ "docs": "docs/guides/repair.md#failed-writes",
+ "repair": "failed-writes",
+ "writes": []
+ },
+ "message": "Every caller write with a retained receipt committed or was superseded.",
+ "name": "lost_caller_writes",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
index a862eafc74..7283975275 100644
--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json
@@ -915,6 +915,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
@@ -3921,6 +3922,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
index d3152906e5..f0f01c170a 100644
--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json
@@ -904,6 +904,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
@@ -3899,6 +3900,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 374fc9763d..6ac853f9ba 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -763,6 +763,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 1496441c98..a111adb680 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -846,6 +846,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index fc4cb1d179..0f55a1a67b 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -835,6 +835,7 @@
{
"category": "ops",
"details": {
+ "compacted_unreplayable": 0,
"count": 0,
"docs": "docs/guides/repair.md#failed-writes",
"repair": "failed-writes",
diff --git a/test/repair-failed-writes-conflict-6429.test.ts b/test/repair-failed-writes-conflict-6429.test.ts
index 8a4022d1b5..73efe21416 100644
--- a/test/repair-failed-writes-conflict-6429.test.ts
+++ b/test/repair-failed-writes-conflict-6429.test.ts
@@ -52,6 +52,51 @@ test('a remember refused as file/database drift is listed and replayed by repair
for (const engine of engines) await conflictCase(engine);
}, 240_000);
+test('a caller retry that commits clears the original and its refused replay attempt from the lost count', async () => {
+ for (const engine of engines) await retryCase(engine);
+}, 240_000);
+
+async function retryCase(engine: BrainEngine): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-6429r-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `r6429-${randomUUID().slice(0, 8)}`;
+ const slug = 'people/dana-example';
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: '---\ntitle: Dana Example\ntype: person\n---\nDana.', request_id: randomUUID() } });
+ const file = join(root, 'people', 'dana-example.md');
+ const published = readFileSync(file, 'utf8');
+ appendFileSync(file, '\nEdited in the file only.\n');
+ const params = { fact: 'Dana Example runs marathons', entity: slug, provenance: 'test', visibility: 'world' };
+ await submitRememberMutation(ctx, { ...params, request_id: randomUUID() }).catch(() => undefined);
+ const scope = await resolveRepairScope(engine, sourceId);
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });
+ // The replay attempt is refused too: two conflict rows (the original and its attempt, which carries a different digest).
+ await (await repairRunner(engine, { apply: true, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId, expect: preview.apply_command.split('--expect ')[1] });
+ const [conflicts] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND operation='remember' AND state='conflict'`, [sourceId]);
+ expect(conflicts.n).toBe(2);
+ expect((await lostCallerWritesCheck(engine, [sourceId])).details).toMatchObject({ count: 1 });
+
+ // The file is reconciled and the caller sends the same remember again (same intent, new request id): it commits.
+ writeFileSync(file, published);
+ await submitRememberMutation(ctx, { ...params, request_id: randomUUID() });
+ expect((await lostCallerWritesCheck(engine, [sourceId])).status).toBe('ok');
+ const again = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });
+ expect(again.affected).toBe(0);
+ expect(again.residuals).toEqual({ already_written: 1 });
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
async function conflictCase(engine: BrainEngine): Promise<void> {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-replay-6429-'));
const root = join(dir, 'brain'); mkdirSync(root);
@@ -79,8 +124,9 @@ async function conflictCase(engine: BrainEngine): Promise<void> {
const lost = await lostCallerWritesCheck(engine, [sourceId]);
expect(lost.status).toBe('warn');
expect(lost.message).toContain(`1 caller write(s) never landed (1 remember; 1 refused source_changed`);
+ expect(lost.message).not.toContain('compacted');
expect(lost.message).toContain(`gbrain repair failed-writes --source ${sourceId}`);
- expect(lost.details).toMatchObject({ count: 1, repair: 'failed-writes', writes: [{ source_id: sourceId, operation: 'remember', reason: 'file_database_drift', count: 1 }] });
+ expect(lost.details).toMatchObject({ count: 1, repair: 'failed-writes', writes: [{ source_id: sourceId, operation: 'remember', reason: 'source_changed', count: 1 }], compacted_unreplayable: 0 });
const scope = await resolveRepairScope(engine, sourceId);
const preview = await (await repairRunner(engine, { apply: false, logger })).run('failed-writes', scope, { explicit: true, sourceFlag: sourceId });