Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): bound the failed-writes supersession read by page history (#8707)
garrytanbe1d38443b10
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c5ef37cc8c..7b4c8995a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,11 +16,11 @@ identifiers and attribution are available in the pre-removal Git revision### Itemized changes-- `src/core/repair/failed-writes.ts`: recovered fact requests are read once for all refused writes instead of inside the candidate read; replay attempts are read for every refused write together (`request_id = ANY`); later requests of the same page and the file check are read per page, not per write. The listing, classes, residuals and preview hash are unchanged.+- `src/core/repair/failed-writes.ts`: recovered fact requests are read once for all refused writes instead of inside the candidate read; replay attempts are read for every refused write together (`request_id = ANY`); the later requests of each refused write's page are read for groups of writes sized by how long their pages' later history is, so one page with hundreds of refused writes and a long history cannot make one read outlast the statement timeout; the file check runs once per page. The listing, classes, residuals and preview hash are unchanged.- New refusal `repair_preview_timeout`. When the request indexes the preview reads are missing or INVALID, it names them and its fix is the read-only `gbrain repair request-indexes --json` preview, whose apply command builds them; when they are valid, it tells the brain host to run the same preview once with a longer statement timeout.- Schema migration v291 builds two request-table indexes online (`persistence_requests_replay_id` on the request id, `persistence_requests_slug_sequence` on source, slug and sequence). They join the indexes `gbrain repair request-indexes` and doctor's `persistence_request_indexes` check report. Without them the preview is still bounded, only slower. PGLite and repo-less brains get them unchanged.- The request-index states doctor and `gbrain repair request-indexes` print now come back in the order the indexes are declared on Postgres as well as PGLite.-- `test/repair-failed-writes-bounded-8707.test.ts` (PGLite and Postgres) seeds a journal with refused writes of every class and checks that the preview's request-table reads stay flat as refused writes grow, that each write gets its class, and that a read ended at the statement timeout refuses `repair_preview_timeout` and saves nothing.+- `test/repair-failed-writes-bounded-8707.test.ts` (PGLite and Postgres) seeds a journal with refused writes of every class and checks that the preview's request-table reads stay flat as refused writes grow, that each write gets its class, and that a read ended at the statement timeout refuses `repair_preview_timeout` and saves nothing, and (Postgres) that 500 refused writes on one page followed by 20,000 later commits preview inside a 1 s statement timeout.## [0.60.592.0] - 2026-11-06diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex fce9b1add1..089082c631 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -367,9 +367,34 @@ async function stillDrifted(engine: BrainEngine, write: FailedWrite): Promise<botype Verdict = { class: Disposition; detail?: string };+/** Later rows of the pages one supersession read may walk; a page's later rows bound each of its writes' walk. */+const SUPERSESSION_ROWS_PER_READ = 100_000;++/**+ * The open writes in groups whose supersession reads stay small: each write's read walks the later rows of its page, so+ * the groups are packed by that count (read once per page), and a write on a page longer than the bound is read alone.+ */+async function supersessionBatches(engine: BrainEngine, open: FailedWrite[]): Promise<string[][]> {+ if (!open.length) return [];+ const spans = new Map((await engine.executeRaw<{ source_id: string; slug: string; later: number }>(+ `SELECT p.source_id, p.slug, count(*)::int AS later FROM (SELECT source_id, slug, min(sequence) AS sequence FROM persistence_requests+ WHERE id = ANY($1::uuid[]) GROUP BY 1, 2) p JOIN persistence_requests c ON c.source_id=p.source_id AND c.slug=p.slug AND c.sequence>p.sequence GROUP BY 1, 2`,+ [open.map(write => write.id)])).map(row => [`${row.source_id}\0${row.slug}`, row.later]));+ const batches: string[][] = [];+ let rows = Infinity;+ for (const write of open) {+ const walk = 1 + (spans.get(`${write.source_id}\0${write.slug}`) ?? 0);+ if (rows + walk > SUPERSESSION_ROWS_PER_READ) { batches.push([]); rows = 0; }+ batches.at(-1)!.push(write.id);+ rows += walk;+ }+ return batches;+}+/*** Why each caller write must not be replayed now, or `replay`. #8707: the request-table reads (replay attempts, later- * requests of the page) are made once for all the writes, never once per write, and the file check runs once per page.+ * requests of the page) are made for all the writes together, never once per write (the later requests in groups bounded+ * by their pages' history, `supersessionBatches`), and the file check runs once per page.*/async function dispositions(engine: BrainEngine, writes: FailedWrite[]): Promise<Map<string, Verdict>> {const verdicts = new Map<string, Verdict>();@@ -389,9 +414,12 @@ async function dispositions(engine: BrainEngine, writes: FailedWrite[]): Promise}open.push(write);}- const later = new Map(open.length ? (await engine.executeRaw<{ id: string; state: string; operation: string; same_intent: boolean }>(- `SELECT DISTINCT ON (r.id) r.id::text, c.state, c.operation, c.digest=r.digest AS same_intent FROM persistence_requests r JOIN persistence_requests c ON ${supersessionSql('r', 'c')}- WHERE r.id = ANY($1::uuid[]) ORDER BY r.id, ${supersessionOrderSql('r', 'c')}`, [open.map(write => write.id)])).map(row => [row.id, row]) : []);+ const later = new Map<string, { state: string; operation: string; same_intent: boolean }>();+ for (const ids of await supersessionBatches(engine, open)) {+ for (const row of await engine.executeRaw<{ id: string; state: string; operation: string; same_intent: boolean }>(+ `SELECT r.id::text, c.state, c.operation, c.same_intent FROM persistence_requests r CROSS JOIN LATERAL (SELECT c.state, c.operation, c.digest=r.digest AS same_intent+ FROM persistence_requests c WHERE ${supersessionSql('r', 'c')} ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1) c WHERE r.id = ANY($1::uuid[])`, [ids])) later.set(row.id, row);+ }for (const write of open) {const row = later.get(write.id);const found = dispositionOf(row);diff --git a/test/repair-failed-writes-bounded-8707.test.ts b/test/repair-failed-writes-bounded-8707.test.tsindex f67fa61867..0f87ba6fd6 100644--- a/test/repair-failed-writes-bounded-8707.test.ts+++ b/test/repair-failed-writes-bounded-8707.test.ts@@ -173,4 +173,22 @@ for (const backend of testBackends()) describe(`[${backend}] #8707 the failed-wr}expect(await checkpoints()).toBe(before);}, 120_000);+ if (backend === 'postgres') test('one page with many refused writes and a long later history stays inside the statement timeout', async () => {+ const sourceId = `b8707-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,NULL)', [sourceId]);+ const insert = (state: string, n: number, tag: string) => engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,+ source_incarnation,slug,digest,intent,authority,state,intent_bytes,terminal_reservation,error_code,error_message)+ SELECT 'local_cli','cli',gen_random_uuid(),'put_page',s.id,s.incarnation,'people/alice-example',md5($2||i),jsonb_build_object('slug','people/alice-example','content',$2||i),+ '{}'::jsonb,$3,100,100,CASE WHEN $3='conflict' THEN 'source_changed' END,CASE WHEN $3='conflict' THEN 'refused' END+ FROM sources s, generate_series(1,$4::int) i WHERE s.id=$1`, [sourceId, tag, state, n]);+ await insert('conflict', 500, 'refused-');+ await insert('committed', 20_000, 'later-');+ await engine.executeRaw('ANALYZE persistence_requests');+ const timed = await withEnv({ GBRAIN_STATEMENT_TIMEOUT: '1s' }, async () => { const e = new PostgresEngine(); await e.connect({ database_url: databaseUrl!, poolSize: 1 }); return e; });+ try {+ const result = await preview(timed, sourceId);+ expect(result.residuals).toMatchObject({ superseded: 500 });+ expect((result.listing ?? []).filter(entry => entry.class === 'superseded')).toHaveLength(500);+ } finally { await timed.disconnect(); }+ }, 120_000);});