Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(item-failure): authorization and wrapped stops are run-scoped; a failed backfill ledger read stops the run; held safe-chunks failures count toward the breaker (GBRA-130 review)
garrytana9149aff5306
diff --git a/src/core/backfill-base.ts b/src/core/backfill-base.tsindex 6085b057a6..82cc6afd3c 100644--- a/src/core/backfill-base.ts+++ b/src/core/backfill-base.ts@@ -271,7 +271,7 @@ export async function runBackfill<TRow = Record<string, unknown>>(let updated = 0;let errors = 0;let batchNum = 0;- const startLedger = opts.dryRun ? null : await readSkipLedgerRaw(engine, spec.name).catch(() => null);+ const startLedger = opts.dryRun ? null : await readSkipLedgerRaw(engine, spec.name);const ledger = parseSkipLedger(opts.fresh === true ? null : startLedger);const items = new ItemRun('backfill.rows');const { VERSION: producer } = await import('../version.ts');diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex 31f954e906..1be9608feb 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -70,6 +70,8 @@ export const RUN_SCOPED_CODES: ReadonlySet<string> = new Set(['writer_registration_required', 'writer_identity_invalid', 'writer_not_initialized', 'writer_upgrade_required','writer_not_quiesced', 'writer_admin_locked', 'unsupported_mutation_protocol', 'write_claim_lost', 'connection_lost','permission_denied', 'schema_owner_required', 'scope_denied', 'config', 'auth', 'connector_holds_exhausted', 'transfer_in_progress', 'disk_full',+ 'invalid_token', 'insufficient_scope', 'trusted_local_only', 'requires_local_engine', 'not_owner_host', 'host_identity_mismatch',+ 'recovery_required', 'cancelled', 'persistence_restart_required', 'writer_regrant_required', 'writer_manifest_rescope_required',]);/** Item codes that fail the same way until the item changes. Every other item code is transient. */@@ -84,6 +86,8 @@ function sqlstateFailure(state: string): { code: string; scope: 'run' | 'item';if (state === '25P02' || state === '40001' || state === '40P01' || state.startsWith('08') || state.startsWith('53') || state.startsWith('57P')|| state.startsWith('58') || state.startsWith('XX')) return { code: 'database_contention', scope: 'run', class: 'transient' };if (state === '42P01' || state === '42703' || state === '42883') return { code: 'schema_behind', scope: 'run', class: 'transient' };+ if (state === '42501') return { code: 'permission_denied', scope: 'run', class: 'transient' };+ if (state.startsWith('28')) return { code: 'auth', scope: 'run', class: 'transient' };if (state === '57014') return { code: 'statement_timeout', scope: 'item', class: 'transient' };if (state === '55P03') return { code: 'lock_timeout', scope: 'item', class: 'transient' };if (state.startsWith('22') || state.startsWith('23') || state === '54000') return { code: 'invalid_data', scope: 'item', class: 'content' };@@ -127,16 +131,21 @@ function classifyOne(error: unknown): ClassifiedItemFailure | null {/*** Classifies one failure raised while processing a single item. The `cause`- * chain is walked (at most 5 deep) when the error itself is not recognized.+ * chain is walked (at most 5 deep): a run-scoped stop anywhere in it wins, so a+ * wrapped abort or authorization failure is never one item's; otherwise the+ * outermost recognized error decides.*/export function classifyItemFailure(error: unknown): ClassifiedItemFailure {+ const message = error instanceof Error ? error.message : String(error);+ let first: ClassifiedItemFailure | null = null;let current: unknown = error;for (let depth = 0; depth < 5 && current != null; depth++) {const classified = classifyOne(current);- if (classified) return depth === 0 ? classified : { ...classified, message: error instanceof Error ? error.message : String(error) };+ if (classified?.scope === 'run') return depth === 0 ? classified : { ...classified, message };+ if (classified && !first) first = depth === 0 ? classified : { ...classified, message };current = (current as { cause?: unknown }).cause;}- return { code: 'internal', scope: 'item', class: 'transient', message: error instanceof Error ? error.message : String(error), requestId: null };+ return first ?? { code: 'internal', scope: 'item', class: 'transient', message, requestId: null };}export interface ItemFailure extends ClassifiedItemFailure { key: string }diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex f9e95bfdcb..de420d3471 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -151,7 +151,9 @@ export interface RepairHandler {* with the reason, message and fix the result reports.*/export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number;- stop?: { reason: string; message: string; fix?: Action } }+ stop?: { reason: string; message: string; fix?: Action };+ /** The item-scoped error behind a held outcome: counted by the run's breaker like a thrown item failure. */+ failure?: unknown }/*** Refusal codes a kind may treat as one item's verdict inside its own apply (ghost-pages extends them). The core records@@ -448,13 +450,20 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc...(applied.detail ? { detail: applied.detail } : {}), ...(applied.llm_usd ? { llm_usd: applied.llm_usd } : {}) });}}- items.succeed();+ if (typeof applied === 'object' && applied.failure !== undefined) {+ const { systemic: heldStop } = items.record(`${item.source_id}:${item.slug}`, applied.failure);+ if (heldStop) {+ return stopAfterSettle({ reason: heldStop.code, message: redactConnectionInfo(`${heldStop.message} Fix the shared cause, then rerun \`${result.apply_command}\` to resume.`),+ fix: readFix(`Previews ${handler.kind} again (read-only) to show whether the shared cause is gone.`, { argv: ['gbrain', 'repair', handler.kind, ...(opts.sourceFlag ? ['--source', opts.sourceFlag] : []), '--json'] }) });+ }+ } else items.succeed();if (typeof applied === 'object' ? applied.applied : applied) result.applied++;else result.skipped++;if (typeof applied === 'object' && applied.stop) {await advance(item.cursor);return stopAfterSettle(applied.stop);}+ if (typeof applied === 'object' && applied.failure !== undefined) continue;} catch (error) {// A page edited since planning is left for the next full scan.if (error instanceof OperationError && error.code === 'revision_conflict') { result.skipped++; continue; }diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.tsindex bab05e8f14..a5a504721f 100644--- a/src/core/repair/safe-chunks.ts+++ b/src/core/repair/safe-chunks.ts@@ -62,7 +62,7 @@ export const safeChunksRepair: RepairHandler = {// 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),+ return { applied: false, outcome: 'held', reason: 'projection_unbuildable', failure: error, detail: { code: failure.code, message: redactConnectionInfo(failure.message).slice(0, 500),fix: { argv: ['gbrain', 'repair', 'safe-chunks', '--source', item.source_id], consent: [], actor: 'agent', requires_exclusive: false,why: 'Previews safe-chunks for this source (read-only); it lists the held page with its current state, and its printed apply command re-seals it once the cause is fixed.' } } };}diff --git a/test/pathological/a26-safe-chunks-reseal.test.ts b/test/pathological/a26-safe-chunks-reseal.test.tsindex 194dc5f8c3..6ae8df6f43 100644--- a/test/pathological/a26-safe-chunks-reseal.test.ts+++ b/test/pathological/a26-safe-chunks-reseal.test.ts@@ -97,6 +97,26 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), { expectProgress: [POISON], progressFields: ['chunks'] });});+ test('breaker case: when every page is unbuildable the held outcomes trip item_failures_systemic and the run is not complete', async () => {+ for (let i = 5; i <= 8; i++) {+ await importFromContent(engine, 'notes/a' + i, '---\ntitle: notes/a' + i + '\ntype: note\n---\n\nBody of notes/a' + i + ' 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]);+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION pathological_refuse_chunk() RETURNS trigger LANGUAGE plpgsql AS $fn$+ BEGIN RAISE EXCEPTION 'pathological: chunk refused for every page' USING ERRCODE = 'check_violation'; 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()');+ const before = await snapshotItems(engine, SOURCE);+ const result = await run();+ expect(result.stopped?.reason).toBe('item_failures_systemic');+ expect(result.complete).toBe(false);+ expect(result.applied).toBe(0);+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE));+ const again = await run();+ expect(again.stopped?.reason).toBe('item_failures_systemic');+ });+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');diff --git a/test/pathological/a47-backfill-poison-row.test.ts b/test/pathological/a47-backfill-poison-row.test.tsindex 1017d68489..77de1c9e9e 100644--- a/test/pathological/a47-backfill-poison-row.test.ts+++ b/test/pathological/a47-backfill-poison-row.test.ts@@ -179,6 +179,68 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(await skipLedger(engine, spec.name)).toEqual({ version: 1, items: {} });});+ test('ledger: a failed skip-ledger read stops the run before any row, so older retry records are never overwritten', async () => {+ const { sourceId, rows } = await seed(engine, titles([1, 6]));+ const spec = probeSpec(sourceId);+ await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 4 }));+ const ledgerBefore = await skipLedger(engine, spec.name);+ expect(Object.keys(ledgerBefore!.items)).toEqual([String(rows[1]!.id), String(rows[6]!.id)]);+ const checkpointBefore = await checkpoint(engine, spec.name);+ const before = await snapshotItems(engine, sourceId);+ const readFailure = sqlError('57014', 'canceling statement due to statement timeout');+ const flaky = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') {+ return (sql: string, params?: unknown[]) => String(params?.[0] ?? '').endsWith('.skipped') && sql.includes('SELECT value FROM config')+ ? Promise.reject(readFailure) : target.executeRaw(sql, params as never);+ }+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ expect(await runBackfill(flaky, spec, { batchSize: 4, fresh: true }).catch(e => e)).toBe(readFailure);+ expect(await skipLedger(engine, spec.name)).toEqual(ledgerBefore);+ expect(await checkpoint(engine, spec.name)).toBe(checkpointBefore);+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ });++ test('run: a role without UPDATE privilege (a real 42501) stops the backfill at its first write and records nothing', async () => {+ const { sourceId } = await seed(engine, titles([]));+ const spec = probeSpec(sourceId);+ const role = `gbra130_ro_${randomUUID().slice(0, 8)}`;+ await engine.executeRaw(`CREATE ROLE ${role}`);+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${role}`);+ await engine.executeRaw(`GRANT SELECT ON pages TO ${role}`);+ try {+ const readOnly = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'withReservedConnection') {+ const reserve = target.withReservedConnection.bind(target) as unknown as (fn: (conn: RawConn) => Promise<unknown>, opts?: unknown) => Promise<unknown>;+ return (fn: (conn: RawConn) => Promise<unknown>, opts?: unknown) => reserve(conn => fn({+ executeRaw: async (sql, params) => {+ const out = await conn.executeRaw(sql, params);+ if (/^\s*BEGIN/i.test(sql)) await conn.executeRaw(`SET LOCAL ROLE ${role}`);+ return out;+ },+ }), opts);+ }+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ const before = await snapshotItems(engine, sourceId);+ const thrown = await runBackfill(readOnly, spec, { batchSize: 100 }).catch(e => e);+ expect(String((thrown as { code?: unknown })?.code)).toBe('42501');+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ } finally {+ await engine.executeRaw(`REVOKE ALL ON pages FROM ${role}`);+ await engine.executeRaw(`REVOKE ALL ON SCHEMA public FROM ${role}`);+ await engine.executeRaw(`DROP ROLE ${role}`);+ }+ });+test('breaker: when most rows fail the run stops item_failures_systemic and records no skip', async () => {const { sourceId } = await seed(engine, titles([0, 1, 2, 3, 4, 5, 6, 7]));const spec = probeSpec(sourceId);diff --git a/test/pathological/item-failure.test.ts b/test/pathological/item-failure.test.tsindex 642603552f..46b8a6d968 100644--- a/test/pathological/item-failure.test.ts+++ b/test/pathological/item-failure.test.ts@@ -45,6 +45,23 @@ describe('classifyItemFailure', () => {expect(classifyItemFailure(wrapped)).toMatchObject({ scope: 'run', code: 'database_contention', message: 'wrapper' });});+ test('authorization and security refusals stop the unit, from SQL or as canonical codes', () => {+ expect(classifyItemFailure(sql('42501'))).toMatchObject({ scope: 'run', code: 'permission_denied' });+ expect(classifyItemFailure(sql('28P01'))).toMatchObject({ scope: 'run', code: 'auth' });+ expect(classifyItemFailure(sql('28000'))).toMatchObject({ scope: 'run', code: 'auth' });+ for (const code of ['invalid_token', 'insufficient_scope', 'trusted_local_only', 'recovery_required', 'cancelled']) {+ expect({ code, scope: classifyItemFailure(op(code)).scope }).toEqual({ code, scope: 'run' });+ }+ });++ test('a run-scoped stop wrapped under a recognized item error still stops the unit', () => {+ const abort = Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });+ const wrapped = Object.assign(op('invalid_params'), { cause: abort });+ expect(classifyItemFailure(wrapped)).toMatchObject({ scope: 'run', code: 'aborted', message: 'refused: invalid_params' });+ expect(classifyItemFailure(new Error('outer', { cause: Object.assign(op('invalid_fence'), { cause: sql('42501') }) }))).toMatchObject({ scope: 'run', code: 'permission_denied' });+ expect(classifyItemFailure(Object.assign(op('invalid_fence'), { cause: sql('23505') }))).toMatchObject({ scope: 'item', code: 'invalid_fence', class: 'content' });+ });+test('an accepted pending write is progress, not a failure', () => {const pending = op('write_pending', { writeRequest: { request_id: 'req-1', state: 'queued' } as never });expect(classifyItemFailure(pending)).toMatchObject({ scope: 'pending', requestId: 'req-1' });