Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(item-failure): shared item-vs-run classifier, per-run breaker and the pathological suite skeleton (GBRA-130)

garrytan5e26b29b0ba3
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 77387eba59..4505c2e33a 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1998,6 +1998,14 @@ More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guid
More: [docs/guides/troubleshooting.md#ipc-path-too-long](../../docs/guides/troubleshooting.md#ipc-path-too-long)
+### item_failures_systemic
+
+<a id="item_failures_systemic"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Most items of one per-item loop failed (or many failed with one code, or none succeeded), so the failure is systemic and no item was held; the unit stopped instead of skipping every item. | A per-item loop holds a bad item and continues (GBRA-130), but a run where most items fail points at a shared cause, and holding every item would hide it. | Fix the shared cause the first failures name, then rerun the same command; run gbrain doctor --json if the cause is unclear. Run: gbrain doctor --json | agent | `gbrain doctor --json` | 1 | no |
+
### keyword_candidates_incomplete
<a id="keyword_candidates_incomplete"></a>
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index f7a58783a9..56524e685b 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -102,6 +102,10 @@ export const CODES = {
coverage_from: { class: 'caller', summary: "The belief ledger does not cover that time for this page or source: it starts at the page's baseline cut or the source's watermark.", why: "Recorded history exists only from a page's baseline (or creation) after the ledger was enabled; earlier times are unknown, not empty. A best-effort backfill from retained versions carries source times only, so it never answers a recorded-time read.", reasons: ['not_recorded', 'backfill_only', 'backfill_incomplete'], docs: 'docs/guides/repair.md#coverage-from', suggestion: 'Ask about a time at or after the time the message names; `gbrain beliefs status --source <id>` lists the coverage intervals.' },
coverage_gap: { class: 'caller', summary: "The belief ledger was not recording at that time: coverage was stopped, or a backup restore left a gap between the archive's time and the restore.", why: 'Nothing proves what happened to the page inside the gap, so the read refuses instead of answering from either side.', reasons: ['not_covered', 'restore'], docs: 'docs/guides/repair.md#coverage-gap', suggestion: 'Ask about a time outside the gap; `gbrain beliefs status --source <id>` lists the intervals and gaps.' },
clock_mismatch: { class: 'caller', summary: 'A time parameter got a value on the wrong clock: `known_as_of` (recorded time) needs an instant with a zone, not a calendar date.', why: 'Recorded time (`known_as_of`) is when the brain had recorded something; valid time (`as_of`) is when a fact held in the world, as a date. A bare date is ambiguous as a recorded-time instant, so it is refused instead of guessed.', reasons: ['date_for_instant'], docs: 'docs/guides/repair.md#clock-mismatch', suggestion: 'Pass a full instant such as 2026-10-01T12:00:00Z to known_as_of, or use as_of where the tool takes a valid-time date.' },
+ item_failures_systemic: { class: 'server', summary: "Most items of one per-item loop failed (or many failed with one code, or none succeeded), so the failure is systemic and no item was held; the unit stopped instead of skipping every item.",
+ why: 'A per-item loop holds a bad item and continues (GBRA-130), but a run where most items fail points at a shared cause, and holding every item would hide it.',
+ suggestion: 'Fix the shared cause the first failures name, then rerun the same command; run gbrain doctor --json if the cause is unclear.',
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Reports brain health and names failing checks; changes nothing.' } },
known_as_of_unproven: { class: 'caller', summary: 'A change to the page was recorded before the requested instant but was not yet proven committed at it, so the page at that instant cannot be stated.', why: "A write's recorded time is a lower bound on when it became visible; until its commit mark (or a later write to the same page) proves it committed by the instant, the page then may or may not have included it.", docs: 'docs/guides/repair.md#known-as-of-unproven', suggestion: 'Ask about an instant before the write was recorded, or after it was observed committed (the message names both).' },
cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
calendar_unreadable: { class: 'caller', summary: "A Google source's configured calendar returned HTTP 403 or 404 to its account, so its sync imports no events.", why: "Without the typed result an unreadable calendar looks exactly like an empty one. The calendar sweep records it in the source's connector state (the run is not failed); `gbrain doctor` (google_calendar_readable) reads it with no network call and `gbrain google status` probes it live.", docs: 'docs/guides/google-connect.md#unreadable-calendar', suggestion: 'List the calendars the account can read with `gbrain google calendars --account <email>`, then point the source at one with `gbrain sources set-calendar <source> <calendar-id>` and run `gbrain sync --source <source>`.', fix: { argv: ['gbrain', 'google', 'calendars', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the calendar ids the connected account can read.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'google_calendar_readable', '--json'] } } },
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
new file mode 100644
index 0000000000..d6c6afddac
--- /dev/null
+++ b/src/core/item-failure.ts
@@ -0,0 +1,177 @@
+/**
+ * One bad item never stops the unit (GBRA-130, the class after #6948).
+ *
+ * A per-item loop (a page in a maintenance phase, a file in an import, a row
+ * in a backfill, an item in a repair kind) classifies each failure with
+ * `classifyItemFailure`: run-scoped failures stop the unit, item-scoped ones are
+ * recorded for that item and the loop continues, and an accepted, still
+ * pending write is progress, never a failure. `ItemRun` adds the circuit
+ * breaker every adopting loop needs: when most attempted items fail, or many
+ * fail with one code, or none succeeds, the failure is systemic and the run
+ * stops with `item_failures_systemic` instead of holding every item.
+ *
+ * The classification order is fixed: abort, run-level error classes, an
+ * accepted pending receipt, the operation code (with its write error), the
+ * SQLSTATE, the errno, the `cause` chain, and then the default. Unknown
+ * failures are item-scoped and transient, so they never hold an item on their
+ * own and always count toward the breaker. The connector holds
+ * (connectors/item-holds.ts) keep their own source/rate-limit vocabulary.
+ *
+ * Every loop that adopts this names its site in `ISOLATE_SITES`; the
+ * pathological suite (test/pathological/) must cover each site, which
+ * test/pathological/sites.test.ts checks.
+ */
+import { OperationError, opError } from './ops/contract.ts';
+import { CODES } from './error-registry.ts';
+import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
+
+/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
+export const ISOLATE_SITES = {
+} as const satisfies Record<string, string>;
+
+export type IsolateSite = keyof typeof ISOLATE_SITES;
+export type ItemFailureScope = 'run' | 'item' | 'pending';
+export type ItemFailureClass = 'content' | 'transient';
+
+export interface ClassifiedItemFailure {
+ code: string;
+ scope: ItemFailureScope;
+ /** Content: the item itself is refused and will fail the same way until it changes. Transient: it may pass on a later run. */
+ class: ItemFailureClass;
+ message: string;
+ /** An accepted write's request id (scope `pending`), or the failed receipt's. */
+ requestId: string | null;
+}
+
+/** Codes that mean the writer, the database, the budget or the run itself is unavailable: never one item's fault. */
+export const RUN_SCOPED_CODES: ReadonlySet<string> = new Set([
+ 'aborted', 'lock_stolen', 'budget_exhausted', 'item_failures_systemic', 'schema_behind',
+ 'writer_coordinator_required', 'owner_unavailable', 'writer_lock_unavailable', 'writer_busy', 'writer_pool_capacity',
+ 'queue_capacity', 'write_quota_exhausted', 'write_capacity_backpressure', 'maintenance_backpressure', 'database_contention',
+ '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', 'scope_denied', 'config', 'auth', 'connector_holds_exhausted', 'transfer_in_progress', 'disk_full',
+]);
+
+/** Item codes that fail the same way until the item changes. Every other item code is transient. */
+export const CONTENT_ITEM_CODES: ReadonlySet<string> = new Set([
+ 'invalid_params', 'invalid_fence', 'invalid_frontmatter', 'invalid_connector_text', 'request_too_large', 'payload_too_large',
+ 'page_identity_changed', 'page_not_found', 'page_body_segmented', 'take_row_collision', 'content_rejected', 'purged_content',
+ 'fact_withdrawn', 'skill_bundle_required', 'source_changed', 'malformed', 'invalid_data', 'unreadable_item',
+]);
+
+/** SQLSTATE classes: a failed transaction, a lost or overloaded connection, a missing relation stop the run; data and constraint errors are the row's. */
+function sqlstateFailure(state: string): { code: string; scope: 'run' | 'item'; class: ItemFailureClass } | null {
+ 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 === '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' };
+ return null;
+}
+
+const RUN_ERRNOS = new Set(['ENOSPC', 'EMFILE', 'ENFILE', 'EROFS', 'EDQUOT']);
+const ITEM_ERRNOS = new Set(['EACCES', 'EPERM', 'ENOENT', 'ELOOP', 'EISDIR', 'ENOTDIR', 'ENAMETOOLONG', 'EILSEQ']);
+const RUN_ERROR_NAMES: Record<string, string> = { AbortError: 'aborted', LockStolenError: 'lock_stolen', BudgetExhausted: 'budget_exhausted' };
+
+function classifyOne(error: unknown): ClassifiedItemFailure | null {
+ const message = error instanceof Error ? error.message : String(error);
+ const name = (error as { name?: unknown } | null)?.name;
+ if (typeof name === 'string' && RUN_ERROR_NAMES[name]) return { code: RUN_ERROR_NAMES[name]!, scope: 'run', class: 'transient', message, requestId: null };
+ const pending = acceptedPendingReceipt(error);
+ if (pending) return { code: 'write_pending', scope: 'pending', class: 'transient', message, requestId: pending.request_id };
+ if (error instanceof OperationError) {
+ const code = String(error.code === 'storage_error' && error.writeError ? error.writeError : error.canonicalCode);
+ const requestId = error.writeRequest?.request_id ?? null;
+ if (RUN_SCOPED_CODES.has(code) || (code === 'storage_error' && error.detail === 'database_contention')) {
+ return { code, scope: 'run', class: 'transient', message, requestId };
+ }
+ const registryClass = (CODES as Record<string, { class: string }>)[code]?.class;
+ return { code, scope: 'item', class: CONTENT_ITEM_CODES.has(code) || registryClass === 'caller' ? 'content' : 'transient', message, requestId };
+ }
+ const raw = (error as { code?: unknown } | null)?.code;
+ if (typeof raw === 'string' && /^[0-9A-Z]{5}$/.test(raw)) {
+ const sql = sqlstateFailure(raw);
+ if (sql) return { ...sql, message, requestId: null };
+ }
+ if (typeof raw === 'string' && RUN_ERRNOS.has(raw)) return { code: 'disk_full', scope: 'run', class: 'transient', message, requestId: null };
+ if (typeof raw === 'string' && ITEM_ERRNOS.has(raw)) return { code: 'unreadable_item', scope: 'item', class: 'content', message, requestId: null };
+ if (/ECONNRESET|ECONNREFUSED|connection (terminated|ended|closed)|Connection terminated|socket hang up/i.test(message)) {
+ return { code: 'connection_lost', scope: 'run', class: 'transient', message, requestId: null };
+ }
+ return 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.
+ */
+export function classifyItemFailure(error: unknown): ClassifiedItemFailure {
+ 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) };
+ current = (current as { cause?: unknown }).cause;
+ }
+ return { code: 'internal', scope: 'item', class: 'transient', message: error instanceof Error ? error.message : String(error), requestId: null };
+}
+
+export interface ItemFailure extends ClassifiedItemFailure { key: string }
+
+/** The breaker's floor: no verdict before this many items were attempted. Matches the connector outage breaker. */
+export const ITEM_BREAKER_MIN_ITEMS = 5;
+
+/**
+ * One run of a per-item loop. `fail` classifies the error: a run-scoped error is
+ * rethrown as is; otherwise the failure is recorded, and when the breaker trips
+ * `fail` throws `item_failures_systemic` so the caller stops without holding
+ * items from a run that looks systemic.
+ */
+export class ItemRun {
+ private attempted = 0;
+ private successes = 0;
+ private readonly failed: ItemFailure[] = [];
+ private readonly pendingItems: ItemFailure[] = [];
+
+ constructor(readonly site: IsolateSite, private readonly opts: { minItems?: number } = {}) {}
+
+ succeed(): void { this.attempted++; this.successes++; }
+
+ /** Records one item's failure and returns it; rethrows run-scoped errors; throws `item_failures_systemic` when the breaker trips. */
+ fail(key: string, error: unknown): ItemFailure {
+ const classified = classifyItemFailure(error);
+ if (classified.scope === 'run') throw error;
+ const failure: ItemFailure = { ...classified, key, message: classified.message.slice(0, 500) };
+ if (classified.scope === 'pending') { this.pendingItems.push(failure); return failure; }
+ this.attempted++;
+ this.failed.push(failure);
+ const systemic = this.systemic();
+ if (systemic) throw systemic;
+ return failure;
+ }
+
+ /** Item failures recorded so far (pending writes excluded). */
+ get failures(): readonly ItemFailure[] { return this.failed; }
+ /** Accepted writes still publishing. */
+ get pending(): readonly ItemFailure[] { return this.pendingItems; }
+ get succeeded(): number { return this.successes; }
+
+ /** Holds are recorded only for runs whose failures look like the items' own: call before persisting any hold. */
+ systemic(): OperationError | null {
+ const min = this.opts.minItems ?? ITEM_BREAKER_MIN_ITEMS;
+ if (this.attempted < min || this.failed.length === 0) return null;
+ const transient = this.failed.filter(f => f.class === 'transient').length;
+ const byCode = new Map<string, number>();
+ for (const f of this.failed) byCode.set(f.code, (byCode.get(f.code) ?? 0) + 1);
+ const [topCode, sameCode] = [...byCode.entries()].sort((a, b) => b[1] - a[1])[0]!;
+ const tripped = this.successes === 0 || transient * 2 >= this.attempted || (sameCode >= min && sameCode * 2 >= this.attempted);
+ if (!tripped) return null;
+ const sample = this.failed.slice(0, 3).map(f => `${f.key} (${f.code})`).join(', ');
+ const error = opError('item_failures_systemic',
+ `${this.failed.length} of ${this.attempted} items failed at ${this.site} (most often ${topCode}: ${sameCode}); this looks systemic, so no item was held. First failures: ${sample}.`,
+ 'Fix the shared cause the first failures name, then rerun; run `gbrain doctor --json` if the cause is unclear.',
+ { detail: this.site, reason: topCode });
+ return error;
+ }
+}
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
new file mode 100644
index 0000000000..038e54eda2
--- /dev/null
+++ b/test/pathological/catalogue.ts
@@ -0,0 +1,21 @@
+/**
+ * The pathological catalogue (GBRA-130): for every per-item site in
+ * src/core/item-failure.ts ISOLATE_SITES, the test file and the titles of its
+ * item case (the bad item is held and the unit continues) and its run case (a
+ * run-scoped failure at the same site still stops the unit and holds nothing).
+ * The `Record<IsolateSite, …>` type makes a site without cases a compile error;
+ * ./sites.test.ts checks that each named file holds each named title.
+ */
+import type { IsolateSite } from '../../src/core/item-failure.ts';
+
+export interface SiteCases {
+ /** Repo-relative test file. */
+ file: string;
+ /** Title (substring) of the case where one bad item is held and the rest continue. */
+ item: string;
+ /** Title (substring) of the case where a run-scoped failure stops the unit. */
+ run: string;
+}
+
+export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+};
diff --git a/test/pathological/harness.ts b/test/pathological/harness.ts
new file mode 100644
index 0000000000..26a18827ee
--- /dev/null
+++ b/test/pathological/harness.ts
@@ -0,0 +1,98 @@
+/**
+ * Shared pathological-state harness (GBRA-130). Each case builds one bad state
+ * directly (PGLite always, Postgres when DATABASE_URL is set), runs it through
+ * the unit it used to wedge, and asserts three things:
+ * 1. the unit was not aborted (`expectUnitNotAborted`);
+ * 2. the bad item is held or reported with a typed code and fix (`expectItemFailure`);
+ * 3. no other item was lost or changed (`snapshotItems` before, `expectOthersUnchanged` after),
+ * and, for the same site, that a run-scoped failure still stops the unit and holds nothing.
+ *
+ * Builders for other lanes' states live with those lanes; import this module
+ * and add a builder next to your case. Register a new per-item site in
+ * src/core/item-failure.ts ISOLATE_SITES and its cases in ./catalogue.ts.
+ */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { classifyItemFailure, type ClassifiedItemFailure } from '../../src/core/item-failure.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { requirePostgresTestDatabase, testBackends, type TestBackend } from '../helpers/test-backends.ts';
+
+export { managedBrain } from '../helpers/managed-brain.ts';
+
+/** The engine arms a pathological case runs on: PGLite, plus Postgres when the lane provides DATABASE_URL. */
+export function pathologicalArms(): Array<{ backend: TestBackend; databaseUrl: string | undefined }> {
+ return testBackends().map(backend => ({ backend, databaseUrl: backend === 'pglite' ? undefined : requirePostgresTestDatabase() }));
+}
+
+export interface ItemSnapshotRow {
+ slug: string;
+ content_hash: string | null;
+ updated_at: string;
+ deleted_at: string | null;
+ links: number;
+ chunks: number;
+}
+
+/** Every page of a source with what a wedge could lose or change: content, liveness, outgoing links and chunks. */
+export async function snapshotItems(engine: BrainEngine, sourceId: string): Promise<Map<string, ItemSnapshotRow>> {
+ const rows = await engine.executeRaw<ItemSnapshotRow>(
+ `SELECT p.slug, p.content_hash, p.updated_at::text AS updated_at, p.deleted_at::text AS deleted_at,
+ (SELECT count(*)::int FROM links l WHERE l.from_page_id = p.id) AS links,
+ (SELECT count(*)::int FROM content_chunks c WHERE c.page_id = p.id) AS chunks
+ FROM pages p WHERE p.source_id = $1 ORDER BY p.slug`, [sourceId]);
+ return new Map(rows.map(row => [row.slug, row]));
+}
+
+/**
+ * Every page outside `changed` is byte-for-byte what it was. `expectProgress`
+ * lists pages the run had to change (the healthy siblings): each must differ
+ * from `before` in at least one of the listed fields, so "nothing happened"
+ * can't pass as "nothing was lost".
+ */
+export function expectOthersUnchanged(before: Map<string, ItemSnapshotRow>, after: Map<string, ItemSnapshotRow>,
+ opts: { changed?: Iterable<string>; expectProgress?: Iterable<string>; progressFields?: Array<keyof ItemSnapshotRow> } = {}): void {
+ const changed = new Set([...(opts.changed ?? []), ...(opts.expectProgress ?? [])]);
+ for (const [slug, row] of before) {
+ if (changed.has(slug)) continue;
+ expect({ slug, row: after.get(slug) }).toEqual({ slug, row });
+ }
+ for (const slug of opts.expectProgress ?? []) {
+ const fields = opts.progressFields ?? ['content_hash', 'updated_at', 'links', 'chunks'];
+ const was = before.get(slug);
+ const now = after.get(slug);
+ expect(now).toBeDefined();
+ expect({ slug, moved: fields.some(f => was?.[f] !== now?.[f]) }).toEqual({ slug, moved: true });
+ }
+}
+
+/** The run returned (it did not throw) and reports a result: a wedge is a throw or a never-advancing cursor, never a quiet ok. */
+export async function expectUnitNotAborted<T>(run: () => Promise<T>): Promise<T> {
+ let thrown: unknown;
+ let result: T | undefined;
+ try { result = await run(); } catch (error) { thrown = error; }
+ expect({ aborted: thrown === undefined ? null : (thrown instanceof Error ? `${thrown.name}: ${thrown.message}` : String(thrown)) }).toEqual({ aborted: null });
+ return result as T;
+}
+
+/** A recorded item failure names its item and a typed code; `fix` (when given) is a command an agent can run. */
+export function expectItemFailure(failure: { key?: string; slug?: string; item?: string; code?: string; reason?: string; fix?: unknown } | undefined,
+ want: { key: string; code: string; fix?: RegExp }): void {
+ expect(failure).toBeDefined();
+ const key = failure!.key ?? failure!.item ?? failure!.slug;
+ const code = failure!.code ?? failure!.reason;
+ expect({ key, code }).toEqual({ key: want.key, code: want.code });
+ if (want.fix) expect(String(typeof failure!.fix === 'string' ? failure!.fix : JSON.stringify(failure!.fix))).toMatch(want.fix);
+}
+
+/** Errors a run-scoped probe injects at a site: each must stop the unit and record no hold. */
+export function runScopedErrors(): Array<{ name: string; error: () => unknown }> {
+ const lost = () => Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' });
+ const aborted = () => Object.assign(new Error('The operation was aborted'), { name: 'AbortError' });
+ const failedTx = () => Object.assign(new Error('current transaction is aborted, commands ignored until end of transaction block'), { code: '25P02' });
+ const owner = () => new OperationError('owner_unavailable', 'The canonical writer for this source is unavailable.');
+ return [{ name: 'connection lost', error: lost }, { name: 'abort', error: aborted }, { name: 'failed transaction (25P02)', error: failedTx },
+ { name: 'owner_unavailable', error: owner }];
+}
+
+/** Sanity: every injected run-scoped error classifies as run-scoped. */
+export function classifyInjected(error: unknown): ClassifiedItemFailure { return classifyItemFailure(error); }
diff --git a/test/pathological/item-failure.test.ts b/test/pathological/item-failure.test.ts
new file mode 100644
index 0000000000..d72ed92e47
--- /dev/null
+++ b/test/pathological/item-failure.test.ts
@@ -0,0 +1,99 @@
+/**
+ * GBRA-130: the item-vs-run classifier and the per-run breaker every
+ * per-item loop uses (src/core/item-failure.ts).
+ */
+import { describe, expect, test } from 'bun:test';
+import { CODES } from '../../src/core/error-registry.ts';
+import { classifyItemFailure, CONTENT_ITEM_CODES, ItemRun, RUN_SCOPED_CODES } from '../../src/core/item-failure.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+import { runScopedErrors } from './harness.ts';
+
+const op = (code: string, extra: Partial<OperationError> = {}) => Object.assign(new OperationError(code as never, `refused: ${code}`), extra);
+const sql = (code: string) => Object.assign(new Error(`sql ${code}`), { code });
+
+describe('classifyItemFailure', () => {
+ test('run-scoped errors stop the unit', () => {
+ for (const { name, error } of runScopedErrors()) expect({ name, scope: classifyItemFailure(error()).scope }).toEqual({ name, scope: 'run' });
+ expect(classifyItemFailure(Object.assign(new Error('stolen'), { name: 'LockStolenError' })).code).toBe('lock_stolen');
+ expect(classifyItemFailure(Object.assign(new Error('budget'), { name: 'BudgetExhausted' })).code).toBe('budget_exhausted');
+ expect(classifyItemFailure(sql('42P01'))).toMatchObject({ scope: 'run', code: 'schema_behind' });
+ expect(classifyItemFailure(Object.assign(new Error('no space'), { code: 'ENOSPC' }))).toMatchObject({ scope: 'run', code: 'disk_full' });
+ expect(classifyItemFailure(op('storage_error', { detail: 'database_contention' })).scope).toBe('run');
+ });
+
+ test('an item refusal is the item\'s: content codes are content, the rest transient', () => {
+ expect(classifyItemFailure(op('invalid_fence'))).toMatchObject({ scope: 'item', class: 'content', code: 'invalid_fence' });
+ expect(classifyItemFailure(op('storage_error', { writeError: 'request_too_large' as never }))).toMatchObject({ scope: 'item', code: 'request_too_large', class: 'content' });
+ expect(classifyItemFailure(sql('57014'))).toMatchObject({ scope: 'item', class: 'transient', code: 'statement_timeout' });
+ expect(classifyItemFailure(sql('22P05'))).toMatchObject({ scope: 'item', class: 'content', code: 'invalid_data' });
+ expect(classifyItemFailure(sql('23505'))).toMatchObject({ scope: 'item', class: 'content' });
+ expect(classifyItemFailure(Object.assign(new Error('denied'), { code: 'EACCES' }))).toMatchObject({ scope: 'item', class: 'content', code: 'unreadable_item' });
+ });
+
+ test('an unknown error is an item failure that never counts as content', () => {
+ expect(classifyItemFailure(new TypeError('x is undefined'))).toMatchObject({ scope: 'item', class: 'transient', code: 'internal' });
+ });
+
+ test('the cause chain is walked', () => {
+ const wrapped = new Error('wrapper', { cause: sql('25P02') });
+ expect(classifyItemFailure(wrapped)).toMatchObject({ scope: 'run', code: 'database_contention', message: 'wrapper' });
+ });
+
+ 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' });
+ const terminal = op('write_pending', { writeRequest: { request_id: 'req-2', state: 'failed' } as never });
+ expect(classifyItemFailure(terminal).scope).toBe('item');
+ });
+
+ test('every run-scoped and content code is a registry code or one of the classifier\'s own codes (no typos)', () => {
+ const own = new Set(['aborted', 'lock_stolen', 'budget_exhausted', 'schema_behind', 'database_contention', 'disk_full', 'connection_lost',
+ 'writer_busy', 'config', 'auth', 'malformed', 'invalid_data', 'unreadable_item', 'maintenance_backpressure', 'transfer_in_progress']);
+ const unknown = [...RUN_SCOPED_CODES, ...CONTENT_ITEM_CODES].filter(code => !(code in CODES) && !own.has(code));
+ expect(unknown).toEqual([]);
+ });
+});
+
+describe('ItemRun breaker', () => {
+ test('a few bad items among good ones are recorded and the run continues', () => {
+ const run = new ItemRun('links.extract_stale' as never);
+ for (let i = 0; i < 8; i++) run.succeed();
+ run.fail('a', op('invalid_fence'));
+ run.fail('b', op('invalid_fence'));
+ expect(run.failures.map(f => f.key)).toEqual(['a', 'b']);
+ expect(run.systemic()).toBeNull();
+ });
+
+ test('a run where nothing succeeds trips at the floor and names the site', () => {
+ const run = new ItemRun('links.extract_stale' as never);
+ for (let i = 0; i < 4; i++) run.fail(`p${i}`, op('invalid_fence'));
+ expect(() => run.fail('p4', op('invalid_fence'))).toThrow(/items failed at links\.extract_stale/);
+ });
+
+ test('half the attempts failing transiently trips', () => {
+ const run = new ItemRun('links.extract_stale' as never);
+ for (let i = 0; i < 3; i++) run.succeed();
+ run.fail('x', new TypeError('boom'));
+ run.fail('y', new TypeError('boom'));
+ expect(() => run.fail('z', new TypeError('boom'))).toThrow(OperationError);
+ });
+
+ test('a run-scoped error is rethrown untouched and records nothing', () => {
+ const run = new ItemRun('links.extract_stale' as never);
+ const lost = runScopedErrors()[0]!.error();
+ expect(() => run.fail('p', lost)).toThrow(lost as Error);
+ expect(run.failures).toEqual([]);
+ });
+
+ test('pending writes are kept apart and never trip the breaker', () => {
+ const run = new ItemRun('links.extract_stale' as never);
+ for (let i = 0; i < 10; i++) run.fail(`p${i}`, op('write_pending', { writeRequest: { request_id: `r${i}`, state: 'queued' } as never }));
+ expect(run.pending.length).toBe(10);
+ expect(run.failures).toEqual([]);
+ expect(run.systemic()).toBeNull();
+ });
+});
+
+test('RUN_SCOPED_CODES holds item_failures_systemic so a tripped inner loop stops its outer loop', () => {
+ expect(RUN_SCOPED_CODES.has('item_failures_systemic')).toBe(true);
+});
diff --git a/test/pathological/sites.test.ts b/test/pathological/sites.test.ts
new file mode 100644
index 0000000000..68060c2c84
--- /dev/null
+++ b/test/pathological/sites.test.ts
@@ -0,0 +1,32 @@
+/**
+ * GBRA-130 ratchet: every per-item site registered in ISOLATE_SITES has a
+ * pathological item case and a run-scoped case in the file the catalogue names,
+ * and every site names an inventory row.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { ISOLATE_SITES } from '../../src/core/item-failure.ts';
+import { CATALOGUE, type SiteCases } from './catalogue.ts';
+
+const ROOT = join(import.meta.dir, '..', '..');
+
+describe('pathological catalogue covers every isolate site', () => {
+ for (const [site, row] of Object.entries(ISOLATE_SITES)) {
+ test(`${site} (${row})`, () => {
+ expect(row).toMatch(/^[ABC]-\d+$/);
+ const cases = (CATALOGUE as Record<string, SiteCases | undefined>)[site]!;
+ expect(cases).toBeDefined();
+ const path = join(ROOT, cases.file);
+ expect({ file: cases.file, exists: existsSync(path) }).toEqual({ file: cases.file, exists: true });
+ const text = readFileSync(path, 'utf8');
+ expect({ site, item: text.includes(cases.item) }).toEqual({ site, item: true });
+ expect({ site, run: text.includes(cases.run) }).toEqual({ site, run: true });
+ expect(cases.item).not.toBe(cases.run);
+ });
+ }
+
+ test('isolateItem call sites use a registered literal site', () => {
+ expect(Object.keys(CATALOGUE).sort()).toEqual(Object.keys(ISOLATE_SITES).sort());
+ });
+});