Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
projections: name the changed field in PageProjectionConflictError, bounded re-read retry, page_projection_conflict envelope
garrytanb7c983b24739
diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 88acd6d193..35a67576c2 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -605,6 +605,18 @@ const ROWS: Row[] = [};},},+ {+ // Before any PageRevisionConflictError handling: same canonical revision, a newer projection installed by another worker.+ match: named('PageProjectionConflictError'),+ map: (e: Error & { changed: readonly string[]; slug: string; sourceId: string }, ctx) => ({+ error: 'page_projection_conflict', code: 'page_projection_conflict', message: e.message,+ detail: `changed: ${e.changed.join(', ')}`,+ why: `Another worker (the persistence owner's projection rebuild, an embed or an import) installed a newer search projection of ${e.slug} while this command prepared its own; the guard keeps that newer installation instead of overwriting it.`,+ suggestion: `Re-run ${ctx.command ? `gbrain ${ctx.command}` : 'the same command'}; it re-reads the current projection. If it conflicts again, another worker is still installing: wait for it to finish, then re-run.`,+ fix: { argv: ['gbrain', 'get', '--source', e.sourceId, '--', e.slug], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Reads the page as stored now (read-only) before the command is re-run.' },+ }),+ },{match: named('EmbeddingDisabledError'),map: (e: Error & { fix?: Action }) => ({diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 8a9dc9d0db..6a6b44717e 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -42,12 +42,29 @@ export interface ProjectionSnapshot {pageKind: PageKind;}+export type ProjectionConflictField = 'text_projection_revision' | 'chunk_digest' | 'indexing_context';+/** Canonical state can stay unchanged while another worker replaces its projection. */export class PageProjectionConflictError extends PageRevisionConflictError {- constructor(expected: string, current: string) {+ constructor(expected: string, current: string, readonly changed: readonly ProjectionConflictField[], readonly slug: string, readonly sourceId: string) {super(expected, current);this.name = 'PageProjectionConflictError';- this.message = 'The page projection changed during preparation. Read its current snapshot before retrying.';+ this.message = `The search projection of ${slug} (source ${sourceId}) changed during preparation (${changed.join(', ')}) at the same page revision; nothing was installed. Re-read its current snapshot before retrying.`;+ }+}++/**+ * The loser of a concurrent projection installation re-reads and prepares+ * again: `attempt` must capture a fresh snapshot on every call. At most three+ * retries with jitter, so two reinstalling writers cannot livelock; the last+ * conflict is rethrown (`page_projection_conflict` on the wire).+ */+export async function retryProjectionConflict<T>(attempt: () => Promise<T>, random: () => number = Math.random): Promise<T> {+ for (let retry = 0; ; retry++) {+ try { return await attempt(); } catch (error) {+ if (!(error instanceof PageProjectionConflictError) || retry === 3) throw error;+ await new Promise(resolve => setTimeout(resolve, Math.floor(random() * 20 * (retry + 1))));+ }}}@@ -140,11 +157,12 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje// getChunks omits vector payloads but includes identity, text/source, metadata// and embedding completion state. A newer installation must not be deleted,// even when its canonical revision stayed the same.- if (current!.page.text_projection_revision !== snapshot.page.text_projection_revision- || digest(stored) !== digest(prepared.chunks)- || context.key !== prepared.indexingContext) {- throw new PageProjectionConflictError(snapshot.revision, current!.revision);- }+ const changed: ProjectionConflictField[] = [+ ...(current!.page.text_projection_revision !== snapshot.page.text_projection_revision ? ['text_projection_revision' as const] : []),+ ...(digest(stored) !== digest(prepared.chunks) ? ['chunk_digest' as const] : []),+ ...(context.key !== prepared.indexingContext ? ['indexing_context' as const] : []),+ ];+ if (changed.length) throw new PageProjectionConflictError(snapshot.revision, current!.revision, changed, slug, sourceId);if (opts.seal && opts.preserveEmbeddings) {const byIndex = new Map(chunks.map(chunk => [chunk.chunk_index, chunk]));const identity = (chunk: ChunkInput | Chunk) => [chunk.chunk_text, chunk.chunk_source,diff --git a/test/helpers/page-projection.ts b/test/helpers/page-projection.tsindex 3c8e4122c8..e828666425 100644--- a/test/helpers/page-projection.ts+++ b/test/helpers/page-projection.ts@@ -1,10 +1,16 @@import type { BrainEngine } from '../../src/core/engine.ts';import type { ChunkInput } from '../../src/core/types.ts';-import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';+import { installPageProjection, readProjectionSnapshot, retryProjectionConflict } from '../../src/core/page-state/projections.ts';-/** Install an explicitly authored synthetic fixture as a complete, revision-bound projection. */+/**+ * Install an explicitly authored synthetic fixture as a complete, revision-bound projection.+ * A live persistence owner's resident rebuild may seal the same revision between the read+ * and the install; the fixture then re-reads and installs over it, as product callers do.+ */export async function installFixtureChunks(engine: BrainEngine, slug: string, chunks: ChunkInput[], opts?: { sourceId?: string }) {- const snapshot = await readProjectionSnapshot(engine, slug, opts?.sourceId ?? 'default', { allowUnsealed: true });- if (!snapshot) throw new Error(`Missing fixture page: ${slug}`);- await installPageProjection(engine, snapshot, chunks, { seal: true });+ await retryProjectionConflict(async () => {+ const snapshot = await readProjectionSnapshot(engine, slug, opts?.sourceId ?? 'default', { allowUnsealed: true });+ if (!snapshot) throw new Error(`Missing fixture page: ${slug}`);+ await installPageProjection(engine, snapshot, chunks, { seal: true });+ });}diff --git a/test/page-projection-origin.test.ts b/test/page-projection-origin.test.tsindex f0b80dc6c0..0611ef3140 100644--- a/test/page-projection-origin.test.ts+++ b/test/page-projection-origin.test.ts@@ -3,7 +3,8 @@ import type { BrainEngine } from '../src/core/engine.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { healOversizedPageChunks } from '../src/core/embed-oversize-heal.ts';import { installPageEmbeddings, installPageProjection, PageProjectionConflictError,- readProjectionSnapshot, rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';+ readProjectionSnapshot, rebuildPendingPageProjections, retryProjectionConflict } from '../src/core/page-state/projections.ts';+import { renderCliError } from '../src/core/agent-output.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { installFixtureChunks } from './helpers/page-projection.ts';import { withEnv } from './helpers/with-env.ts';@@ -379,3 +380,86 @@ def protected_example():expect(after.withdrawals).toEqual(before.withdrawals);}});++// Master red (pack-relation-direction-engine): a test's fixture install read the page, the live persistence+// owner's resident rebuild sealed the same revision, and the install threw at an unchanged revision.+test('the resident rebuild sealing between a read and an install is a named projection conflict; the fixture re-reads and wins', async () => {+ for (const engine of engines) {+ const slug = 'resident-race';+ await seed(engine, slug, false);+ const read = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ expect((await rebuildPendingPageProjections(engine, 100, { pages: { sourceId, slugs: [slug] } })).rebuilt).toBe(1);+ const conflict = await installPageProjection(engine, read, [chunk('fixture text')], { seal: true }).catch(e => e);+ expect(conflict).toBeInstanceOf(PageProjectionConflictError);+ expect(conflict.expectedRevision).toBe(conflict.currentRevision);+ expect(conflict.changed).toEqual(['text_projection_revision', 'chunk_digest', 'indexing_context']);+ expect(conflict.message).toContain(`The search projection of ${slug} (source ${sourceId}) changed during preparation (text_projection_revision, chunk_digest, indexing_context)`);+ let reads = 0;+ const raced = afterCapture(engine, async () => { await rebuildPendingPageProjections(engine, 100, { pages: { sourceId, slugs: [slug] } }); });+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason) SELECT s.incarnation,p.slug,p.knowledge_revision,'canonical_change'+ FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id=$1 AND p.slug=$2 ON CONFLICT(source_incarnation,slug) DO NOTHING`, [sourceId, slug]);+ await retryProjectionConflict(async () => {+ const prepared = (await readProjectionSnapshot(reads++ === 0 ? raced : engine, slug, sourceId, { allowUnsealed: true }))!;+ await installPageProjection(engine, prepared, [chunk('fixture text')], { seal: true });+ });+ expect(reads).toBe(2);+ expect((await engine.getChunks(slug, { sourceId })).map(c => c.chunk_text)).toEqual(['fixture text']);+ }+});++test('two writers reinstalling one page 10 times each make progress: every lost attempt is matched by the other writer\'s install', async () => {+ for (const engine of engines) {+ const slug = 'two-writers';+ await seed(engine, slug);+ const installs = { a: 0, b: 0 };+ const conflicts = { a: 0, b: 0 };+ const writer = async (name: 'a' | 'b') => {+ for (let round = 0; round < 10; round++) {+ await retryProjectionConflict(async () => {+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ try { await installPageProjection(engine, prepared, [chunk(`${name} ${round} ${body}`)], { seal: true }); }+ catch (error) { if (error instanceof PageProjectionConflictError) conflicts[name]++; throw error; }+ installs[name]++;+ }).catch(error => { expect(error).toBeInstanceOf(PageProjectionConflictError); });+ }+ };+ await Promise.all([writer('a'), writer('b')]);+ // A writer has one attempt in flight, so each of its conflicts needs a distinct install by the other writer.+ expect(conflicts.a).toBeLessThanOrEqual(installs.b);+ expect(conflicts.b).toBeLessThanOrEqual(installs.a);+ expect(installs.a + installs.b).toBeGreaterThanOrEqual(10);+ const [installed] = await engine.getChunks(slug, { sourceId });+ expect(installed.chunk_text).toMatch(/^[ab] \d /);+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.text_projection_revision).toBe((await engine.readPageSnapshot(slug, { sourceId }))!.revision);+ }+});++test('an exhausted projection retry reports page_projection_conflict with the changed field and the next step', async () => {+ for (const engine of engines) {+ const slug = 'exhausted-retry';+ await seed(engine, slug);+ let attempts = 0;+ const error = await retryProjectionConflict(async () => {+ attempts++;+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;+ await installFixtureChunks(engine, slug, [chunk(`competing install ${attempts}`)], { sourceId });+ await installPageProjection(engine, prepared, [chunk(body)], { seal: true });+ }, () => 0).catch(e => e);+ expect(attempts).toBe(4);+ expect(error).toBeInstanceOf(PageProjectionConflictError);+ expect(error.changed).toEqual(['chunk_digest']);+ const json = JSON.parse(renderCliError(error, { json: true, command: 'reindex-code', tty: false }).stdout!);+ expect(json).toMatchObject({+ code: 'page_projection_conflict', error: 'page_projection_conflict', class: 'retryable', retryable: true,+ message: `The search projection of ${slug} (source ${sourceId}) changed during preparation (chunk_digest) at the same page revision; nothing was installed. Re-read its current snapshot before retrying.`,+ detail: 'changed: chunk_digest',+ suggestion: `Re-run gbrain reindex-code; it re-reads the current projection. If it conflicts again, another worker is still installing: wait for it to finish, then re-run. Next: gbrain get --source ${sourceId} -- ${slug}`,+ fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], command: `gbrain get --source ${sourceId} -- ${slug}`, actor: 'agent' },+ });+ expect(json.why).toContain(`installed a newer search projection of ${slug}`);+ const text = renderCliError(error, { json: false, command: 'reindex-code', tty: false });+ expect(text.stderr).toBe(`Error [page_projection_conflict]: ${json.message}\nFix: gbrain get --source ${sourceId} -- ${slug}\nWhy: ${json.why}\nDocs: ${json.docs}\n`);+ expect(json.docs).toContain('docs/guides/repair.md#page-projection-conflict');+ }+});