Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): each repair item gets its own request id, so two items on one page never collide as idempotency_conflict (#7436)
garrytan02d8abc89d39
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2a5325aca3..bdfbdab9ef 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1177,6 +1177,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.401.0', text: '`gbrain sources reconcile --apply` that commits and leaves the page and its canonical file agreeing now clears that file\'s `preparation_stalled` or `write_interrupted` sync hold (the write owner stalled, not the file), and its result names the cleared row (`cleared_hold`); a file that still differs keeps its hold. A page write refused for a held file now names the hold row it read in its message (`Hold row: source <id>, incarnation <uuid>.`), and `gbrain sources retry-held --json` reports the rows it read (`hold_rows`) and each held file\'s `fingerprint`, so a refusal naming a row the listing does not show can be told apart (#7364).' },// #7341 (GBRA-133 wave 3). `since` is restamped at the merge slot.{ since: '0.60.401.0', text: 'A nested folder-scaffolding file (`index.md`, `README.md`, `log.md`, `schema.md`, `RESOLVER.md`) whose frontmatter `slug:` names another page, for example `slug: projects/acme-example` or just `slug: acme-example` in `projects/acme-example/index.md`, is skipped by sync again, as before 0.60.337.0, even when it has `type:` or `title:`. Since then it was imported only to be held `frontmatter_slug_conflict`, so a folder of such hubs became one hold per file. The next sync releases those holds. One whose `slug:` is its own path slug, or that has none, is still a page; remove the `slug:` line to make a skipped one a page.' },+ // #7436 (GBRA-151). `since` is restamped at the merge slot.+ { since: 'TBD', text: '`gbrain repair <kind> --apply` no longer stops with `idempotency_conflict` when two of its items write the same page (two facts of one page in `repair visibility`, two duplicate groups or two takes on one page) while the first write is still pending: each item now has its own request id, where before both used the page and revision. A rerun of the same approved set still replays its own pending writes; an item whose page an earlier item changed is skipped for the next full scan, as before (#7436).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 9a2137991c..cc16c7dc6e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -292,12 +292,17 @@ function embeddingUsd(chars: number, model: string | undefined): number | null {* Deterministic per-item request id: a rerun after a crash replays the same* admission (and waits for it if still pending). An attempt that ended in a* terminal failure is not replayed forever; the next attempt gets a new id.+ * An item's cursor is part of the id, so two items that write the same page at+ * the same revision (two facts of one page) never share one: the second item+ * of a run is admitted while the first is still pending, and reusing the+ * first's id for a different write is refused as idempotency_conflict.*/-export async function repairRequestId(ctx: OperationContext, kind: RepairKind, item: Pick<RepairItem, 'source_id' | 'slug'>, revision: string): Promise<string> {+export async function repairRequestId(ctx: OperationContext, kind: RepairKind, item: Pick<RepairItem, 'source_id' | 'slug'> & { cursor?: RepairCursor }, revision: string): Promise<string> {await initializeLocalPersistence(ctx);const principal = await requestPrincipalForContext(ctx);for (let attempt = 0; ; attempt++) {- const h = digest(['repair-request-v1', kind, item.source_id, item.slug, revision, attempt]);+ const h = digest(item.cursor ? ['repair-request-v2', kind, item.source_id, item.slug, revision, item.cursor.phase, item.cursor.id, attempt]+ : ['repair-request-v1', kind, item.source_id, item.slug, revision, attempt]);const id = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;const prior = await getWriteRequest(ctx.engine, principal, id);if (!prior || !isTerminal(prior) || prior.state === 'committed') return id;diff --git a/test/repair-request-id-per-item-7436.test.ts b/test/repair-request-id-per-item-7436.test.tsnew file mode 100644index 0000000000..51c04d945b--- /dev/null+++ b/test/repair-request-id-per-item-7436.test.ts@@ -0,0 +1,66 @@+/**+ * A repair item's request id named its page and revision, not the item. Two items of one run that write the same page+ * (two facts of one fence) at the same revision got one id: while the first write was still pending, the second item+ * reused its id for a different write, and admission refused it as idempotency_conflict, which an approved apply+ * (--expect) does not continue past (#7436). Each item now gets its own id.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { repairRequestId, resolveRepairScope, runRepair, type RepairHandler, type RepairItem } from '../src/core/repair/core.ts';+import { repairSpec } from '../src/core/repair/registry.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-repair-per-item-'));+const quiet = { info() {}, warn() {}, error() {} };++beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(dataDir, { recursive: true, force: true }); });++const ctxFor = (sourceId: string, writeWaitMs?: number) => ({ engine, sourceId, remote: false as const, config: { engine: 'pglite', embedding_disabled: true },+ dryRun: false, logger: quiet, ...(writeWaitMs === undefined ? {} : { writeWaitMs }) }) as never;+const page = (body: string) => `---\ntype: note\ntitle: Example\n---\n${body}\n`;++describe('repair request ids are per item', () => {+ test('a second item writing the same page while the first is pending is admitted under its own id, not refused as idempotency_conflict', async () => {+ const dir = mkdtempSync(join(dataDir, 'case-'));+ const source = `repair-${randomUUID().slice(0, 8)}`;+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ try {+ const root = join(dir, source); mkdirSync(root);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [source, root]);+ await claimWorktree(engine, source, root);+ await submitPageMutation(ctxFor(source), { operation: 'put_page', params: { slug: 'notes/a', content: page('Fact one. Fact two.'), request_id: randomUUID() } });+ const ids: string[] = [];+ const item = (id: number): RepairItem => ({ cursor: { phase: 0, id }, source_id: source, slug: 'notes/a', chars: 1, action: `mark fact ${id}` });+ const handler: RepairHandler = { kind: 'visibility', embeds: false,+ async plan(_engine, _scope, after) { return { items: [0, 1, 2].map(item).filter(i => !after || i.cursor.id > after.id), residuals: {}, preview_hash: 'h' }; },+ async apply(ctx, it) {+ const snapshot = (await engine.readPageSnapshot('notes/a', { sourceId: source }))!;+ const request_id = await repairRequestId(ctx, 'visibility', it, snapshot.revision);+ ids.push(request_id);+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/a', source_id: source, expected_revision: snapshot.revision,+ content: page(`Fact one. Fact two. Marked ${it.cursor.id}.`), request_id } });+ return true;+ } };+ let held = true;+ installFaultHook(async point => { if (point === 'consumer:prepared' && held) { held = false; await new Promise(resolve => setTimeout(resolve, 1_500)); } });+ const scope = await resolveRepairScope(engine);+ const result = await runRepair(ctxFor(source, 1_000), handler, scope, { apply: true, spec: repairSpec('visibility'), embed: false, expect: 'h',+ publicationOwner: async () => ({ alive: true, owner: 'this process' }) });+ expect(new Set(ids).size).toBe(3);+ expect(result.failed).toEqual([]);+ expect(result.stopped).toBeUndefined();+ expect(result.applied + result.skipped).toBe(3);+ } finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); }+ });+ }, 120_000);+});