Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): safe-chunks holds an unbuildable page instead of aborting (GBRA-130 A-26)
garrytan0a2e49bb3c82
diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex 340170334a..15f0b6ec67 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -601,24 +601,30 @@ async function reindexManaged(engine: BrainEngine, opts: ReindexOpts, type: strilogger: { info: (msg: string) => process.stderr.write(`${msg}\n`), warn: (msg: string) => process.stderr.write(`${msg}\n`), error: (msg: string) => process.stderr.write(`${msg}\n`) } };const scope = await resolveRepairScope(engine);const stopped: string[] = [];+ const failures: string[] = [];let unsupported = 0;for (const handler of opts.noEmbed ? [safeChunksRepair] : [safeChunksRepair, contextualModeRepair]) {const run = await runRepair(ctx as Parameters<typeof runRepair>[0], handler, scope, { apply: true, limit: opts.limit, embed: !opts.noEmbed });if (run.stopped) stopped.push(run.stopped.message);unsupported += Object.values(run.residuals).reduce((sum, count) => sum + count, 0);+ // GBRA-130 A-26: pages the repair held (projection_unbuildable) or failed per item are counted, not thrown.+ failures.push(...run.failed.map(f => `${f.item} (${f.reason}): ${f.message}`),+ ...(run.outcome_items ?? []).filter(o => o.outcome === 'held').map(o => `${o.item} (${o.reason}): ${String(o.detail?.message ?? '')}`));}+ const failed = failures.length;if (pending > 0) await refreshProjectionStatistics(engine, pending);const pendingAfter = await countPending(engine, type, !!opts.noEmbed);const reindexed = Math.max(0, pending - pendingAfter);- if (stopped.length) setCliExitVerdict(1);+ if (stopped.length || failed) setCliExitVerdict(1);if (opts.json) {- process.stdout.write(JSON.stringify({ pending, pending_after: pendingAfter, reindexed, skipped: 0, failed: 0, chunker_version: MARKDOWN_CHUNKER_VERSION, type,- delegated_to: repairs, ...(unsupported ? { unsupported_pages: unsupported } : {}), ...(stopped.length ? { stopped } : {}) }) + '\n');+ process.stdout.write(JSON.stringify({ pending, pending_after: pendingAfter, reindexed, skipped: 0, failed, chunker_version: MARKDOWN_CHUNKER_VERSION, type,+ delegated_to: repairs, ...(unsupported ? { unsupported_pages: unsupported } : {}), ...(stopped.length ? { stopped } : {}), ...(failed ? { failures } : {}) }) + '\n');} else {process.stderr.write(`[reindex] Managed brain: re-chunked through ${repairs.map(kind => `gbrain repair ${kind}`).join(' and ')} (no page writes). `+ `reindexed=${reindexed} pending_before=${pending} pending_after=${pendingAfter}\n`);if (unsupported) process.stderr.write(`[reindex] ${unsupported} page(s) the projection repairs cannot rebuild (code without a source path, or another page kind) are left for their importer.\n`);for (const message of stopped) process.stderr.write(`[reindex] ${message}\n`);+ for (const failure of failures) process.stderr.write(`[reindex] not re-chunked, its chunks stay withheld: ${failure}. Retry with: gbrain repair safe-chunks --apply\n`);}- return { ...base, pendingAfter, reindexed, skipped: 0, failed: 0 };+ return { ...base, pendingAfter, reindexed, skipped: 0, failed };}diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.tsindex 1e0a096d64..8598b0441a 100644--- a/src/core/repair/safe-chunks.ts+++ b/src/core/repair/safe-chunks.ts@@ -13,6 +13,12 @@* Code pages need their recorded source path to re-chunk; pages without one,* and page kinds the projection installer cannot rebuild (images), are counted* as residuals and left for their importer.+ *+ * A page whose re-seal throws item-scoped (its chunker refuses the body, the+ * chunk install fails a constraint) is a `held` outcome with reason+ * `projection_unbuildable`, the classified code and message: its old chunks+ * stay withheld and the next run retries it. A run-scoped failure (a lost+ * connection, a failed transaction, a held writer) stops the run.*/import type { BrainEngine } from '../engine.ts';import { resealSafeChunks } from '../page-state/projections.ts';@@ -21,6 +27,8 @@ import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';import { embedStalePages } from '../embed-stale.ts';import { CREDENTIAL_RESEAL_HELD } from '../page-state/credential-reseal.ts';import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';+import { classifyItemFailure } from '../item-failure.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; chars: number }@@ -51,7 +59,11 @@ export const safeChunksRepair: RepairHandler = {} catch (error) {// A page edited since planning is re-sealed by its own write.if (error instanceof PageRevisionConflictError) return false;- throw error;+ // GBRA-130 A-26: a page whose projection cannot be built is held (its chunks stay withheld) and the kind goes on; a run-scoped failure stops it.+ const failure = classifyItemFailure(error);+ if (failure.scope !== 'item') throw error;+ return { applied: false, outcome: 'held', reason: 'projection_unbuildable', detail: { code: failure.code, message: redactConnectionInfo(failure.message).slice(0, 500),+ fix: `gbrain repair safe-chunks --source ${item.source_id} --apply` } };}if (!resealed) return false;if (opts?.embed && resealed.pendingChunks > 0) {diff --git a/test/pathological/a26-safe-chunks-reseal.test.ts b/test/pathological/a26-safe-chunks-reseal.test.tsnew file mode 100644index 0000000000..c7b95acb46--- /dev/null+++ b/test/pathological/a26-safe-chunks-reseal.test.ts@@ -0,0 +1,130 @@+/**+ * GBRA-130 A-26: \`gbrain repair safe-chunks\` re-seals pages chunked before the+ * safe-chunk fence (src/core/repair/safe-chunks.ts), and a managed+ * \`gbrain reindex\` delegates to it (src/commands/reindex.ts).+ *+ * Protects: a page whose re-seal throws (here a projection constraint error+ * from the chunk install) is reported as a held outcome+ * \`projection_unbuildable\` with the classified code and message, its chunks+ * stay as they were (withheld, the safe default), every later page is+ * re-sealed, and a rerun does not throw; a managed reindex counts it as failed+ * instead of failing the command. A run-scoped failure (connection lost, 25P02,+ * abort, a held writer) still stops the run.+ * Fails when: the apply rethrows anything but a revision conflict again (the+ * kind aborts at the same page id on every rerun and the managed reindex+ * never reaches contextual-mode).+ * Why new: test/safe-chunk-reseal.test.ts covers healthy re-seals only.+ * Seams: a test-only trigger on content_chunks builds the unbuildable page+ * directly; run-scoped errors are injected at the engine's transaction.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { resolveRepairScope, runRepair } from '../../src/core/repair/core.ts';+import { safeChunksRepair } from '../../src/core/repair/safe-chunks.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runReindex } from '../../src/commands/reindex.ts';+import { _resetCliExitVerdictForTests } from '../../src/core/cli-force-exit.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const SOURCE = 'default';+const SLUGS = ['notes/a1', 'notes/a2', 'notes/a3', 'notes/a4'];+const POISON = 'notes/a2';+const quiet = { info() {}, warn() {}, error() {} };++/** Builds the bad state directly: every chunk insert for the poison page fails a constraint, as a projection that cannot be installed does. */+async function refuseChunksOf(engine: BrainEngine, slug: string) {+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION pathological_refuse_chunk() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN IF NEW.page_id = ${Number(page!.id)} THEN RAISE EXCEPTION 'pathological: chunk refused for this page' USING ERRCODE = 'check_violation'; END IF; RETURN NEW; END $fn$`);+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');+ await engine.executeRaw('CREATE TRIGGER pathological_refuse_chunk BEFORE INSERT OR UPDATE ON content_chunks FOR EACH ROW EXECUTE FUNCTION pathological_refuse_chunk()');+}++async function quietIo<T>(fn: () => Promise<T>): Promise<{ result: T; stdout: string }> {+ const out = process.stdout.write.bind(process.stdout), err = process.stderr.write.bind(process.stderr);+ let stdout = '';+ (process.stdout.write as unknown as (chunk: unknown) => boolean) = (chunk: unknown) => { stdout += String(chunk); return true; };+ (process.stderr.write as unknown as (chunk: unknown) => boolean) = () => true;+ try { return { result: await fn(), stdout }; } finally { process.stdout.write = out; process.stderr.write = err; }+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe('A-26 safe-chunks: one unbuildable page never stops the re-seal (' + backend + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); await close(); });+ beforeEach(async () => {+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [SOURCE]);+ for (const slug of SLUGS) {+ await importFromContent(engine, slug, '---\ntitle: ' + slug + '\ntype: note\n---\n\nBody of ' + slug + ' for the safe-chunk fixture, long enough to chunk.\n', { noEmbed: true, sourceId: SOURCE });+ }+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1', [SOURCE]);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [SOURCE]);+ });+ const ctxOf = (e: BrainEngine = engine) => ({ engine: e, sourceId: SOURCE, remote: false as const, config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: quiet }) as never;+ const run = async (e?: BrainEngine) => runRepair(ctxOf(e), safeChunksRepair, await resolveRepairScope(engine), { apply: true, embed: false });++ test('item case: an unbuildable page is held projection_unbuildable and every other page is re-sealed', async () => {+ await refuseChunksOf(engine, POISON);+ const before = await snapshotItems(engine, SOURCE);+ const result = await expectUnitNotAborted(() => run());+ expect(result).toMatchObject({ applied: 3, complete: true, failed: [] });+ expect(result.outcomes).toMatchObject({ held: 1 });+ const held = result.outcome_items?.find(o => o.outcome === 'held');+ expectItemFailure({ key: held?.item, code: held?.reason, fix: held?.detail }, { key: SOURCE + ':' + POISON, code: 'projection_unbuildable', fix: /gbrain repair safe-chunks --source default/ });+ expect(held?.detail).toMatchObject({ code: 'invalid_data', message: expect.stringContaining('chunk refused') });+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: SLUGS.filter(s => s !== POISON), progressFields: ['chunks'] });+ const [poison] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, POISON]);+ expect(Number(poison!.chunker_version)).toBe(1);+ const rerun = await expectUnitNotAborted(() => run());+ expect(rerun.outcomes).toMatchObject({ held: 1 });+ });++ test('recovery case: once the page can be built again, the next run re-seals it', async () => {+ await refuseChunksOf(engine, POISON);+ await expectUnitNotAborted(() => run());+ await engine.executeRaw('DROP TRIGGER IF EXISTS pathological_refuse_chunk ON content_chunks');+ const before = await snapshotItems(engine, SOURCE);+ const result = await expectUnitNotAborted(() => run());+ expect(result).toMatchObject({ applied: 1, complete: true });+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: [POISON], progressFields: ['chunks'] });+ });++ test('a managed reindex counts the held page as failed instead of failing the command', async () => {+ await refuseChunksOf(engine, POISON);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ _resetCliExitVerdictForTests();+ const { result, stdout } = await expectUnitNotAborted(() => quietIo(() => runReindex(engine, ['--markdown', '--no-embed', '--json'])));+ expect(result.failed).toBe(1);+ expect(result.reindexed).toBe(3);+ expect(JSON.parse(stdout.trim().split('\n').pop()!)).toMatchObject({ failed: 1, reindexed: 3 });+ });++ for (const { name, error } of runScopedErrors()) {+ test('run case: a run-scoped ' + name + ' during a re-seal stops the run and holds nothing', async () => {+ const injected = error();+ const faulty = new Proxy(engine, { get(target, prop) {+ const value = Reflect.get(target, prop);+ if (prop === 'transaction' && typeof value === 'function') {+ return (...args: unknown[]) => new Error().stack?.includes('resealSafeChunks') ? Promise.reject(injected) : (value as Function).apply(target, args);+ }+ return typeof value === 'function' ? value.bind(target) : value;+ } }) as BrainEngine;+ const before = await snapshotItems(engine, SOURCE);+ let thrown: unknown;+ const result = await run(faulty).catch(err => { thrown = err; return null; });+ if (result) {+ expect(result.stopped?.reason).toBe('owner_unavailable');+ expect(result.outcomes?.held ?? 0).toBe(0);+ } else expect(thrown).toBe(injected);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));+ });+ }+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 41e6d74f07..18c712560f 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -218,6 +218,7 @@ test/page-prepare-shared-origin-6517.test.tstest/page-purge-batch-sweep-6884.test.tstest/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.ts+test/pathological/a26-safe-chunks-reseal.test.tstest/pathological/a27-credential-reseal.test.tstest/pathological/a45-repair-all-kinds.test.tstest/pathological/a46-content-lane-kinds.test.ts