Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-130 PR 2: transient failures of recorded pages feed the outage breaker (F11); banked drain imports keep the isolated-infra streak across resumes (F12)
garrytan32b7e7d34b8d
diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex abed7ab501..c69e87b5b9 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -332,10 +332,11 @@ async function applyBookmarkGate(commit: pin,skipFailed: !company && opts.skipFailed === true,...(company ? { threshold: 0 } : {}),- // GBRA-130 A-18: files imported this run (an infra code on one file while- // others import goes chronic) and the import breaker's verdict (a run+ // GBRA-130 A-18: files of this drain imported this run or banked by an+ // earlier run of it (an infra code on one file while others import goes+ // chronic, also across resumes) and the import breaker's verdict (a run// where most files failed counts no attempt and auto-skips nothing).- imported: run.filesImported,+ imported: run.filesImported + run.bankedImports,systemic: run.itemRun.systemic() !== null,advance,});diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.tsindex 876915435e..165a4b21ae 100644--- a/src/commands/sync/imports.ts+++ b/src/commands/sync/imports.ts@@ -94,6 +94,9 @@ export async function runImportsPhase(// the breaker's successes, so a resumed run that re-attempts only the// failing files is not mistaken for a run where most files fail.for (let i = importsToDo.length; i < addsAndMods.length; i++) run.itemRun.succeed();+ // Their imports still prove other files of this drain import, so an infra+ // failure the resumed run re-attempts alone keeps its isolated streak.+ run.bankedImports = addsAndMods.filter(path => completed.has(path) && !holds?.existing.has(path)).length;const { effectiveConcurrency, runParallel } = await resolveImportConcurrency(engine, opts, importsToDo.length);diff --git a/src/commands/sync/sync-run.ts b/src/commands/sync/sync-run.tsindex b49ee2e84e..98785e9876 100644--- a/src/commands/sync/sync-run.ts+++ b/src/commands/sync/sync-run.ts@@ -120,6 +120,8 @@ export interface SyncRun {sinceYield: number;/** Add/modify files persisted this run (partial `filesImported`). */filesImported: number;+ /** GBRA-130 A-18: add/modify files of this drain an earlier run banked (held paths excluded); isolation evidence with `filesImported`. */+ bankedImports: number;/** Chunks written this run. */chunksCreated: number;/** The stall watchdog fired (partial reason `stall_timeout`). */@@ -178,6 +180,7 @@ export function createSyncRun(// this as `filesImported` so cron operators can see how much work the// aborted run completed before --timeout fired.filesImported: 0,+ bankedImports: 0,chunksCreated: 0,stallAborted: false,};diff --git a/src/core/cycle/propose-takes-failures.ts b/src/core/cycle/propose-takes-failures.tsindex ba28080835..04b443879e 100644--- a/src/core/cycle/propose-takes-failures.ts+++ b/src/core/cycle/propose-takes-failures.ts@@ -114,7 +114,7 @@ export class ProposeTakesFailures {private readonly itemRun = new ItemRun('propose_takes.pages');private readonly failures: RunFailure[] = [];private readonly succeeded: Array<{ sourceId: string; slug: string }> = [];- /** Failures of pages not recorded before; only these feed the breaker and the #3763 halt. */+ /** Failures that feed the breaker and the #3763 halt: every failure except a recorded page repeating its content-class code. */freshFailures = 0;private constructor(private readonly ledgers: Map<string, ProposeTakesFailureLedger>, private readonly promptVersion: string) {}@@ -137,17 +137,23 @@ export class ProposeTakesFailures {return [...pages.filter(page => !failing(page)), ...pages.filter(failing)];}- /** Records an extractor failure; a run-scoped error (abort, lost connection, failed transaction) is rethrown. */+ /**+ * Records an extractor failure; a run-scoped error (abort, lost connection, failed transaction) is rethrown.+ * Only a recorded page repeating its content-class code is the expected outcome and stays out of the+ * breaker and the #3763 halt; a transient or provider failure always counts, so an outage still halts.+ */fail(sourceId: string, slug: string, contentHash: string, err: unknown): void {- const known = this.known(sourceId, slug, contentHash) !== undefined;- const failure = known ? classifyItemFailure(err) : this.itemRun.record(slug, err).failure;- if (failure.scope === 'run') throw err;+ const classified = classifyItemFailure(err);+ if (classified.scope === 'run') throw err;+ const prior = this.known(sourceId, slug, contentHash);+ const repeat = prior?.class === 'content' && classified.class === 'content' && prior.code === classified.code;+ const failure = repeat ? classified : this.itemRun.record(slug, err).failure;this.failures.push({ sourceId, slug, contentHash, failure });- if (!known) this.freshFailures += 1;+ if (!repeat) this.freshFailures += 1;}succeed(sourceId: string, slug: string, contentHash: string): void {- if (this.known(sourceId, slug, contentHash) === undefined) this.itemRun.succeed();+ if (this.known(sourceId, slug, contentHash)?.class !== 'content') this.itemRun.succeed();this.succeeded.push({ sourceId, slug });}diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex f868cbebaf..c8e4e82858 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -1026,8 +1026,8 @@ class ProposeTakesPhase extends BaseCyclePhase {});} catch (err) {// GBRA-130: a run-scoped error (abort, lost connection, failed- // transaction) stops the phase and records nothing. Fresh pages feed- // the breaker; a page retried after an earlier failure does not.+ // transaction) stops the phase and records nothing. Every failure feeds+ // the breaker except a recorded page repeating its content-class code.failures.fail(sourceId, page.slug, ch, err);result.llm_calls_failed += 1;const msg = err instanceof Error ? err.message : String(err);@@ -1046,8 +1046,9 @@ class ProposeTakesPhase extends BaseCyclePhase {// Halt instead of spending an LLM call on every remaining page. A// single success anywhere in the run keeps llm_calls_succeeded > 0// and permanently disarms this halt (mixed runs are per-page noise).- // GBRA-130 A-25: only fresh pages count; pages that failed before are- // retried last and their failures are the expected outcome.+ // GBRA-130 A-25: a recorded page repeating its content-class code is the+ // expected outcome and does not count; a transient or provider failure+ // always does, so an outage halts even on pages that failed before.if (result.llm_calls_succeeded === 0 &&failures.freshFailures >= EXTRACTOR_FAILURE_HALT_STREAKdiff --git a/test/pathological/a18-ledger-path-text.test.ts b/test/pathological/a18-ledger-path-text.test.tsindex 6e47042ae7..63f557622b 100644--- a/test/pathological/a18-ledger-path-text.test.ts+++ b/test/pathological/a18-ledger-path-text.test.ts@@ -13,7 +13,8 @@* carries a structured code (errno -> PERMISSION_DENIED / FILE_UNREADABLE), the* text classifier never reads errno-led messages or path tokens as provider* errors, and an infra code on one file while other files import fine goes- * chronic as EMBEDDING_INFRA_ISOLATED. A run-scoped error during an import+ * chronic as EMBEDDING_INFRA_ISOLATED, also when resumed runs re-attempt it+ * alone (the files an earlier run of the drain banked count). A run-scoped error during an import* stops the sync and records nothing; a run where most files fail counts no* attempt and points at --skip-failed. (2) Reverting the classifier or the* structured code makes the item case red (4 blocked runs, new.md never@@ -120,12 +121,12 @@ describe('A-18 gate: an infra code on one file while the others import goes chro});});-/** The engine whose page reads inside a file's import (importOnePath) throw `error`. */-function failingImports(engine: BrainEngine, error: unknown): BrainEngine {+/** The engine whose page reads inside a file's import (importOnePath) throw `error`, for every slug or the ones `only` picks. */+function failingImports(engine: BrainEngine, error: unknown, only: (slug: unknown) => boolean = () => true): BrainEngine {return new Proxy(engine, { get(target, prop) {const value = Reflect.get(target, prop);if (prop === 'getPage' && typeof value === 'function') {- return (...args: unknown[]) => new Error().stack?.includes('importOnePath') ? Promise.reject(error) : (value as Function).apply(target, args);+ return (...args: unknown[]) => new Error().stack?.includes('importOnePath') && only(args[0]) ? Promise.reject(error) : (value as Function).apply(target, args);}return typeof value === 'function' ? value.bind(target) : value;} }) as BrainEngine;@@ -160,6 +161,26 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(loadSyncFailures().filter(f => f.source_id === r.sourceId).map(f => [f.path, f.state]).sort()).toEqual(locked.map(p => [p, 'auto_skipped']));}), 180_000);+ test('A-18 item: an embedding timeout on one file among six that import goes chronic on resumed runs (the banked imports count) and drains on run 3', () => legacyRepo(databaseUrl, async r => {+ const healthy = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(n => `ok/${n}.md`);+ r.commit(Object.fromEntries([...healthy.map(p => [p, md(p)]), ['img/huge.md', md('huge')]]), 'mixed');+ const timeout = new Error('[embed(openai:text-embedding-3-small)] The operation timed out.');+ const engine = failingImports(r.engine, timeout, slug => slug === 'img/huge');+ const runs = [];+ for (let i = 0; i < 3; i++) {+ const result = await expectUnitNotAborted(() => r.sync({ engine }));+ const failure = row(r.sourceId, 'img/huge.md');+ runs.push({ status: result.status, codes: result.failureCodes, isolated: failure?.state === 'open' ? failure.infra_isolated_runs : failure?.state });+ }+ const timedOut = [{ code: 'EMBEDDING_TIMEOUT', count: 1 }];+ expect(runs).toEqual([{ status: 'blocked_by_failures', codes: timedOut, isolated: 1 }, { status: 'blocked_by_failures', codes: timedOut, isolated: 2 },+ { status: 'synced', codes: undefined, isolated: 'auto_skipped' }]);+ expect({ state: row(r.sourceId, 'img/huge.md')?.state, code: row(r.sourceId, 'img/huge.md')?.code })+ .toEqual({ state: 'auto_skipped', code: 'EMBEDDING_INFRA_ISOLATED' });+ expect(await r.lastCommit()).toBe(git(r.root, 'rev-parse', 'HEAD'));+ for (const path of healthy) expect(await r.engine.getPage(path.slice(0, -3), { sourceId: r.sourceId })).not.toBeNull();+ }), 180_000);+test.skipIf(!perms)('A-18 recovery: once the file is readable and edited, the next sync imports it and clears its row', () => legacyRepo(databaseUrl, async r => {r.commit({ 'ok.md': md('ok'), 'billing/q3.md': md('q3') }, 'add');chmodSync(join(r.root, 'billing', 'q3.md'), 0o000);diff --git a/test/pathological/a25-propose-takes-poison-pages.test.ts b/test/pathological/a25-propose-takes-poison-pages.test.tsindex 3d6d5a055b..947ad680cd 100644--- a/test/pathological/a25-propose-takes-poison-pages.test.ts+++ b/test/pathological/a25-propose-takes-poison-pages.test.ts@@ -8,7 +8,9 @@** Authoring gate: (1) protects "a deterministically failing page stops being* billed and never blocks the rest": a page that failed before is retried- * after the fresh pages, the halt streak counts fresh pages only, and a page+ * after the fresh pages, the halt streak skips only a recorded page repeating+ * its content-class code (a transient or provider failure always counts, so a+ * 12-page outage halts systemic on every run), and a page* failing with the same content-class code in 3 counted runs at the same* content hash and prompt version gets a failure tombstone (distinct from a* successful empty extraction) that `gbrain takes propose --retry-failed`@@ -23,7 +25,7 @@import { describe, expect, test } from 'bun:test';import type { BrainEngine } from '../../src/core/engine.ts';import type { OperationContext } from '../../src/core/ops/contract.ts';-import { AIConfigError } from '../../src/core/ai/errors.ts';+import { AIConfigError, AITransientError } from '../../src/core/ai/errors.ts';import { runPhaseProposeTakes, type ProposeTakesExtractor } from '../../src/core/cycle/propose-takes.ts';import { retryFailedProposals } from '../../src/core/cycle/propose-takes-failures.ts';import { runTakes } from '../../src/commands/takes.ts';@@ -32,6 +34,7 @@ import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, patholoconst SOURCE = 'default';const PAGES = ['page-01', 'page-02', 'page-03', 'page-04', 'page-05', 'page-06'];+const OUTAGE_PAGES = Array.from({ length: 12 }, (_, i) => `page-${String(i + 1).padStart(2, '0')}`);const POISON = new Set(PAGES.slice(0, 5));const HEALTHY = 'page-06';const tooLong = () => Object.assign(new AIConfigError('[chat(anthropic:claude-example)] prompt is too long: 250000 tokens > 200000 maximum'), { status: 400 });@@ -172,5 +175,19 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(details.failed_pages!.filter(f => f.attempts !== 0 || f.held)).toEqual([]);}}), 120_000);++ test('A-25 breaker: an extractor outage over 12 pages halts systemic on every run, including pages that failed before', () => withBrain(databaseUrl, async engine => {+ const runs = [];+ const calls: string[][] = [];+ for (let i = 0; i < 4; i++) {+ const c: string[] = []; calls.push(c);+ runs.push(await run(engine, extractor(() => new AITransientError('[chat(anthropic:claude-example)] 503 Service Unavailable'), c)));+ }+ expect(await proposals(engine)).toEqual({});+ expect(runs.map(({ result, details }, i) => ({ run: i + 1, calls: calls[i]!.length, status: result.status, halted: details.halted,+ streak: details.aborted_failure_streak, systemic: (details.systemic as { code?: string } | undefined)?.code, succeeded: details.llm_calls_succeeded })))+ .toEqual([1, 2, 3, 4].map(run => ({ run, calls: 5, status: 'fail', halted: true, streak: true, systemic: 'item_failures_systemic', succeeded: 0 })));+ for (const { details } of runs) expect(details.failed_pages!.filter(f => f.attempts !== 0 || f.held)).toEqual([]);+ }, OUTAGE_PAGES), 120_000);});}