Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backfill): isolate a poison row by bisecting its batch; record, skip and retry it (GBRA-130 A-47)
garrytan1424d9c2adc4
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 54d92975ae..570f3ef369 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -999,6 +999,25 @@ checkpoint did not advance. The message names both errors (redacted, at most200 characters each). Fix the cause they name, then run`gbrain backfill <kind> --resume`.+<a id="backfill-commit-indeterminate"></a>**`backfill_commit_indeterminate`** (error).+A `gbrain backfill` batch sent its `COMMIT` and got no verdict from the+server (for example the connection dropped), so the batch may or may not have+committed. The run stops without bisecting or skipping anything, and the+checkpoint stays before the batch. Run `gbrain backfill <kind> --resume`:+rows that did commit no longer match the backfill and are not redone.++<a id="backfill-skipped-rows"></a>**Skipped backfill rows.** A row whose compute+or UPDATE fails on its own (a CHECK or type violation, a compute error) is+isolated by splitting its batch, each part in its own transaction, and recorded+in the config key `backfill.<kind>.skipped`; the checkpoint moves past it and+the other rows land. `gbrain backfill <kind>` prints each recorded row with+its code and the retry command, and every later run retries it first. A row+that fails with the same content error on 3 consecutive runs (same row, same+gbrain version) is held: it is reported but not retried until the row or the+gbrain version changes; `gbrain backfill <kind> --fresh` retries it now. When+most rows of a run fail, the run stops with `item_failures_systemic` and keeps+the skip record and checkpoint it began with.+<a id="persistence-consumer-log"></a>**`[persistence] phase=<phase> reason=<code>`**(stderr). The resident write consumer could not finish a phase. `reason` isthe SQLSTATE (for example `53300` when a pooler's client limit is reached),diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 55f46e121c..97c21b84db 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -9,6 +9,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/backfill-registry.ts` — registry of idempotent data backfills. The `modality` backfill flips `modality` to `'image'` on image-asset chunks the ingest path missed; its SQL filter requires `chunk_source='image_asset'` AND `embedding_image IS NOT NULL` AND `(modality IS NULL OR modality != 'image')` — the `chunk_source` guard ensures a non-image chunk that happens to have `embedding_image` populated is never flagged. A second run finds zero rows.+- `src/core/backfill-base.ts` + `src/core/backfill-skips.ts` — `runBackfill` (`gbrain backfill <kind>`). A batch failing on its own rows is bisected to single rows (own transaction per part); a failing row is recorded in `backfill.<name>.skipped` before the checkpoint passes it, listed in result `skipped`, retried first by later runs, and held after 3 content failures at the same row revision and gbrain version (`--fresh` retries). A failed ROLLBACK, an undecided COMMIT or a run-scoped error stops the run; a systemic run restores both. Docs: `docs/ENGINES.md#backfill-skipped-rows`. Tests: `test/backfill-base.test.ts`, `test/pathological/a47-backfill-poison-row.test.ts`.+- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).- `src/core/bun-floor.ts` — the Bun floor of an upgrade target (#5855): `readBunLinkTarget` (`git fetch`, the fetched upstream SHA, `package.json` at that SHA; the swap fast-forwards to that SHA), `readPackageTarget` (`package.json` at the ref a global install's `github:` spec names, default branch when unpinned; ClawHub reads the canonical default branch), `parseReleasePackage` (only a `>=X.Y.Z` `engines.bun` is a floor; any other shape is unreadable), `readHostBun` (the lower of the `bun` on PATH and the Bun at `process.execPath`) and `evaluateBunFloor` (the refusal text with path, and a path-free copy for the self-upgrade audit). `BUN_FLOOR_EXIT_CODE` (78) marks a `gbrain upgrade` refused for the floor, which the autopilot channel treats as a hold. Tests: `bun-floor.test.ts`, `autopilot-bun-floor.test.ts`, `upgrade-bun-link-arc.serial.test.ts`.diff --git a/src/commands/backfill.ts b/src/commands/backfill.tsindex b13b73e68c..99e08ebe3c 100644--- a/src/commands/backfill.ts+++ b/src/commands/backfill.ts@@ -91,7 +91,7 @@ Flags:(default 3 - 1 = 2). Always reserves 1 conn for HNSW +heartbeat + doctor probes.--resume Pick up from last checkpoint (auto-detected; default on).- --fresh Restart from id=0, ignoring checkpoint.+ --fresh Restart from id=0, ignoring checkpoint; retries held rows.--dry-run Report what WOULD happen; no writes.--keep-index Skip HNSW drop-rebuild for embedding backfills.--max-errors N Bail after N total errors (default 200).@@ -186,6 +186,12 @@ export async function runBackfillCommand(engine: BrainEngine, args: string[]): Pconsole.log(` errors: ${result.errors}`);console.log(` lastId: ${result.lastId}`);console.log(` duration: ${result.durationSec.toFixed(2)}s`);+ if (result.skipped.length > 0) {+ const held = result.skipped.filter(s => s.state === 'held').length;+ console.log(` skipped: ${result.skipped.length} row(s) recorded in backfill.${reg.spec.name}.skipped (${held} held); each later run retries them`);+ for (const s of result.skipped.slice(0, 20)) console.log(` id ${s.id}: ${s.code} (${s.state} after ${s.attempts} run(s)); retry: ${s.fix}`);+ if (result.skipped.length > 20) console.log(` ... ${result.skipped.length - 20} more`);+ }if (result.cappedByMaxRows) console.log(` ⚠️ Capped by --max-rows; more remain.`);if (result.cappedByErrors) console.log(` ⚠️ Capped by --max-errors at ${result.errors}.`);diff --git a/src/core/backfill-base.ts b/src/core/backfill-base.tsindex 2d6316cd44..ee49131025 100644--- a/src/core/backfill-base.ts+++ b/src/core/backfill-base.ts@@ -25,6 +25,9 @@ import { isStatementTimeoutError, isRetryableConnError } from './retry-matcher.timport { abortableSleep } from './retry.ts';import { GBrainError } from './types.ts';import { redactConnectionInfo } from './audit/redact-connection-info.ts';+import { classifyItemFailure, ItemRun } from './item-failure.ts';+import { OperationError } from './ops/contract.ts';+import { heldUnchanged, noteSkip, parseSkipLedger, readSkipLedgerRaw, reportSkips, restoreSkipLedger, rowRevision, type BackfillSkip } from './backfill-skips.ts';function brief(err: unknown): string {const code = (err as { code?: unknown } | null)?.code;@@ -51,6 +54,26 @@ export class BackfillRollbackError extends GBrainError {}}+/**+ * GBRA-130 A-47: the COMMIT of a batch was sent and failed without a server+ * verdict (a lost connection, no SQLSTATE of the row's own), so the batch may+ * or may not have committed. The run stops: it never bisects or skips an+ * undecided batch, and the checkpoint stays before it. A resumed run re-selects+ * the batch; rows that did commit no longer match and are not redone.+ */+export class BackfillCommitIndeterminateError extends GBrainError {+ readonly code = 'backfill_commit_indeterminate';+ constructor(name: string, commitError: unknown) {+ super(+ `Backfill ${name} stopped: a batch COMMIT was sent but its outcome is unknown`,+ `commit error: ${brief(commitError)}; the checkpoint stays before the batch`,+ `gbrain backfill ${name} --resume`,+ 'docs/ENGINES.md#backfill-commit-indeterminate',+ );+ this.name = 'BackfillCommitIndeterminateError';+ }+}+export interface BackfillSpec<TRow = Record<string, unknown>> {/** Stable identifier — used in checkpoint key + CLI dispatch. */name: string;@@ -125,6 +148,11 @@ export interface BackfillResult {cappedByMaxRows: boolean;/** True iff `maxErrors` bailed the run. */cappedByErrors: boolean;+ /**+ * GBRA-130 A-47: every row recorded in `backfill.<name>.skipped` after this run (failing or held), with its code+ * and the command that retries it. A recorded row is behind the checkpoint and is retried by every later run.+ */+ skipped: BackfillSkip[];}const DEFAULT_BATCH_SIZE = 1000;@@ -190,9 +218,34 @@ export async function ensureBackfillIndex<TRow>(}}+/** A COMMIT failure the server decided (a row's own SQLSTATE error): the batch rolled back, so it may be bisected. */+function decidedCommitFailure(err: unknown): boolean {+ const code = (err as { code?: unknown } | null)?.code;+ return typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code) && classifyItemFailure(err).scope === 'item';+}++/** Failures of a batch transaction's BEGIN or SET LOCAL: never the rows' fault. */+const SETUP_FAILURES = new WeakSet<object>();++/** A failure of the batch's own rows (not a setup failure, a timeout, a dropped connection, a failed ROLLBACK or an undecided COMMIT): bisect it. */+function isolatable(err: unknown): boolean {+ if (err instanceof BackfillRollbackError || err instanceof BackfillCommitIndeterminateError) return false;+ if (typeof err === 'object' && err !== null && SETUP_FAILURES.has(err)) return false;+ if (isStatementTimeoutError(err) || isRetryableConnError(err)) return false;+ return classifyItemFailure(err).scope === 'item';+}+/*** Run a backfill end-to-end. Honors the checkpoint, halves on timeout,* reconnects on conn drop, bails on max errors.+ *+ * GBRA-130 A-47: a batch whose compute or write fails with an item-scoped+ * error is bisected down to single rows, each part computed and written in its+ * own transaction; a single failing row is recorded (backfill-skips.ts) and the+ * checkpoint moves past it. Recorded rows are retried first on every later run.+ * Inside a bisection any other failure stops the run with the checkpoint before+ * the batch. When most attempted rows fail (ItemRun's breaker), the run stops+ * `item_failures_systemic` and restores the skip record and checkpoint it began with.*/export async function runBackfill<TRow = Record<string, unknown>>(engine: BrainEngine,@@ -204,6 +257,7 @@ export async function runBackfill<TRow = Record<string, unknown>>(const cols = [idCol, ...spec.selectColumns.filter(c => c !== idCol)];const maxErrors = opts.maxErrors ?? DEFAULT_MAX_ERRORS;const perBatchTimeoutSec = opts.perBatchTimeoutSec ?? DEFAULT_PER_BATCH_TIMEOUT_SEC;+ const idOf = (row: TRow) => Number((row as Record<string, unknown>)[idCol]);// X4 / P2: verify/create the partial index up-front when declared.if (spec.requiredIndex) {@@ -211,152 +265,223 @@ export async function runBackfill<TRow = Record<string, unknown>>(}let batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;- let lastId = await getCheckpoint(engine, spec.name, opts.fresh === true);+ const startCheckpoint = await getCheckpoint(engine, spec.name, false);+ let lastId = opts.fresh === true ? 0 : startCheckpoint;let examined = 0;let updated = 0;let errors = 0;let batchNum = 0;+ const startLedger = opts.dryRun ? null : await readSkipLedgerRaw(engine, spec.name).catch(() => null);+ const ledger = parseSkipLedger(opts.fresh === true ? null : startLedger);+ const items = new ItemRun('backfill.rows');- while (true) {- const remaining = opts.maxRows ? Math.max(0, opts.maxRows - examined) : Number.POSITIVE_INFINITY;- if (remaining <= 0) {- return {- examined, updated, errors, lastId,- durationSec: (Date.now() - t0) / 1000,- cappedByMaxRows: true, cappedByErrors: false,- };- }- const effective = Math.min(batchSize, remaining);-- let rows: TRow[];- try {- rows = await engine.executeRaw<TRow>(- `SELECT ${cols.join(', ')} FROM ${spec.table}- WHERE ${idCol} > $1 AND (${spec.needsBackfill})- ORDER BY ${idCol}- LIMIT $2`,- [lastId, effective],- );- } catch (err) {- errors++;- if (errors >= maxErrors) {- return {- examined, updated, errors, lastId,- durationSec: (Date.now() - t0) / 1000,- cappedByMaxRows: false, cappedByErrors: true,- };+ const saveLedger = async () => {+ const raw = JSON.stringify(ledger);+ if (!opts.dryRun && raw !== startLedger && (startLedger !== null || Object.keys(ledger.items).length > 0)) await engine.setConfig(`backfill.${spec.name}.skipped`, raw);+ };+ const finish = async (flags: { cappedByMaxRows: boolean; cappedByErrors: boolean }): Promise<BackfillResult> => {+ if (items.systemic()) throw items.systemic();+ await saveLedger();+ return { examined, updated, errors, lastId, durationSec: (Date.now() - t0) / 1000, ...flags, skipped: reportSkips(ledger, spec.name) };+ };++ // T3 fix: writes go through withReservedConnection so BEGIN / SET LOCAL+ // / UPDATE / COMMIT all happen on the same backend. Without this,+ // pooled executeRaw can land BEGIN on backend-A and UPDATE on backend-B+ // and SET LOCAL evaporates.+ const writeBatch = async (computedUpdates: Array<{ id: number; updates: Record<string, unknown> }>): Promise<number> => {+ if (opts.dryRun || computedUpdates.length === 0) return 0;+ return engine.withReservedConnection(async conn => {+ await conn.executeRaw(`BEGIN`);+ let batchUpdated = 0;+ let stage: 'setup' | 'update' | 'commit' = 'setup';+ try {+ if (engine.kind === 'postgres') {+ await conn.executeRaw(`SET LOCAL statement_timeout = '${perBatchTimeoutSec}s'`);+ }+ stage = 'update';+ for (const { id, updates } of computedUpdates) {+ const setClauses: string[] = [];+ const params: unknown[] = [id];+ let paramIdx = 2;+ for (const [col, val] of Object.entries(updates)) {+ setClauses.push(`${col} = $${paramIdx}`);+ params.push(val);+ paramIdx++;+ }+ if (setClauses.length === 0) continue;+ await conn.executeRaw(+ `UPDATE ${spec.table} SET ${setClauses.join(', ')} WHERE ${idCol} = $1`,+ params,+ );+ batchUpdated++;+ }+ stage = 'commit';+ await conn.executeRaw(`COMMIT`);+ return batchUpdated;+ } catch (err) {+ if (stage === 'setup' && typeof err === 'object' && err !== null) SETUP_FAILURES.add(err);+ if (stage === 'commit' && !decidedCommitFailure(err)) {+ await conn.executeRaw(`ROLLBACK`).catch(() => undefined);+ throw new BackfillCommitIndeterminateError(spec.name, err);+ }+ try {+ await conn.executeRaw(`ROLLBACK`);+ } catch (rollbackErr) {+ throw new BackfillRollbackError(spec.name, err, rollbackErr);+ }+ throw err;}- // Connection drop: brief sleep + retry the same window.- if (isRetryableConnError(err)) {- await abortableSleep(1000);- continue;+ }, { selfContained: true });+ };++ const now = () => new Date().toISOString();+ const attempt = async (rows: TRow[]): Promise<void> => {+ updated += await writeBatch(await spec.compute(rows, engine));+ for (const row of rows) { items.succeed(); delete ledger.items[String(idOf(row))]; }+ };+ /** Bisects rows that failed together with `first` down to single rows; returns how many rows it recorded as skipped. */+ const isolate = async (rows: TRow[], first: unknown): Promise<number> => {+ let skipped = 0;+ const visit = async (part: TRow[], error?: unknown): Promise<void> => {+ if (error === undefined) {+ try { await attempt(part); return; } catch (err) {+ if (!isolatable(err)) throw err;+ error = err;+ }}- throw err;- }+ if (part.length === 1) {+ noteSkip(ledger, idOf(part[0]), rowRevision(part[0]), items.fail(String(idOf(part[0])), error), now());+ skipped++;+ return;+ }+ const mid = Math.ceil(part.length / 2);+ await visit(part.slice(0, mid));+ await visit(part.slice(mid));+ };+ await visit(rows, first);+ return skipped;+ };- if (rows.length === 0) {- // No more rows match the predicate. Done.- return {- examined, updated, errors, lastId,- durationSec: (Date.now() - t0) / 1000,- cappedByMaxRows: false, cappedByErrors: false,- };- }- examined += rows.length;- batchNum++;-- let computedUpdates: Array<{ id: number; updates: Record<string, unknown> }>;- try {- computedUpdates = await spec.compute(rows, engine);- } catch (err) {- errors++;- if (errors >= maxErrors) break;- if (isStatementTimeoutError(err)) {- batchSize = Math.max(MIN_BATCH_SIZE, Math.floor(batchSize / 2));- process.stderr.write(`[backfill:${spec.name}] compute timeout; halving batch to ${batchSize}\n`);- continue;+ try {+ // Rows recorded by earlier runs that still need the backfill are retried one at a time first;+ // a held row is retried only once it or the gbrain version changed. Records of rows that landed or went away are dropped.+ const recorded = opts.dryRun ? [] : Object.keys(ledger.items).map(Number).filter(id => id <= lastId);+ for (let i = 0; i < recorded.length; i += 500) {+ const ids = recorded.slice(i, i + 500);+ const pending = await engine.executeRaw<TRow>(+ `SELECT ${cols.join(', ')} FROM ${spec.table} WHERE ${idCol} IN (${ids.map((_, n) => `$${n + 1}`).join(', ')}) AND (${spec.needsBackfill}) ORDER BY ${idCol}`, ids);+ const present = new Set(pending.map(idOf));+ for (const id of ids) if (!present.has(id)) delete ledger.items[String(id)];+ for (const row of pending) {+ if (heldUnchanged(ledger.items[String(idOf(row))], rowRevision(row))) continue;+ examined++;+ try { await attempt([row]); } catch (err) {+ if (!isolatable(err)) throw err;+ errors += await isolate([row], err);+ }}- throw err;}- // T3 fix: writes go through withReservedConnection so BEGIN / SET LOCAL- // / UPDATE / COMMIT all happen on the same backend. Without this,- // pooled executeRaw can land BEGIN on backend-A and UPDATE on backend-B- // and SET LOCAL evaporates.- if (!opts.dryRun && computedUpdates.length > 0) {+ while (true) {+ const remaining = opts.maxRows ? Math.max(0, opts.maxRows - examined) : Number.POSITIVE_INFINITY;+ if (remaining <= 0) return await finish({ cappedByMaxRows: true, cappedByErrors: false });+ const effective = Math.min(batchSize, remaining);++ let rows: TRow[];try {- await engine.withReservedConnection(async conn => {- await conn.executeRaw(`BEGIN`);- let batchUpdated = 0;- try {- if (engine.kind === 'postgres') {- await conn.executeRaw(`SET LOCAL statement_timeout = '${perBatchTimeoutSec}s'`);- }- for (const { id, updates } of computedUpdates) {- const setClauses: string[] = [];- const params: unknown[] = [id];- let paramIdx = 2;- for (const [col, val] of Object.entries(updates)) {- setClauses.push(`${col} = $${paramIdx}`);- params.push(val);- paramIdx++;- }- if (setClauses.length === 0) continue;- await conn.executeRaw(- `UPDATE ${spec.table} SET ${setClauses.join(', ')} WHERE ${idCol} = $1`,- params,- );- batchUpdated++;- }- await conn.executeRaw(`COMMIT`);- updated += batchUpdated;- } catch (err) {- try {- await conn.executeRaw(`ROLLBACK`);- } catch (rollbackErr) {- throw new BackfillRollbackError(spec.name, err, rollbackErr);- }- throw err;- }- }, { selfContained: true });+ rows = await engine.executeRaw<TRow>(+ `SELECT ${cols.join(', ')} FROM ${spec.table}+ WHERE ${idCol} > $1 AND (${spec.needsBackfill})+ ORDER BY ${idCol}+ LIMIT $2`,+ [lastId, effective],+ );+ } catch (err) {+ errors++;+ if (errors >= maxErrors) return await finish({ cappedByMaxRows: false, cappedByErrors: true });+ // Connection drop: brief sleep + retry the same window.+ if (isRetryableConnError(err)) {+ await abortableSleep(1000);+ continue;+ }+ throw err;+ }++ // No more rows match the predicate. Done.+ if (rows.length === 0) return await finish({ cappedByMaxRows: false, cappedByErrors: false });+ examined += rows.length;+ batchNum++;++ let computedUpdates: Array<{ id: number; updates: Record<string, unknown> }> | null = null;+ let skippedRows: number | null = null;+ try {+ computedUpdates = await spec.compute(rows, engine);} catch (err) {- if (err instanceof BackfillRollbackError) throw err;errors++;if (errors >= maxErrors) break;if (isStatementTimeoutError(err)) {batchSize = Math.max(MIN_BATCH_SIZE, Math.floor(batchSize / 2));- process.stderr.write(`[backfill:${spec.name}] write timeout; halving batch to ${batchSize}\n`);+ process.stderr.write(`[backfill:${spec.name}] compute timeout; halving batch to ${batchSize}\n`);continue;}- if (isRetryableConnError(err)) {- await abortableSleep(1000);- continue;+ if (!isolatable(err)) throw err;+ skippedRows = await isolate(rows, err);+ }++ if (computedUpdates) {+ try {+ updated += await writeBatch(computedUpdates);+ } catch (err) {+ if (err instanceof BackfillRollbackError || err instanceof BackfillCommitIndeterminateError) throw err;+ errors++;+ if (errors >= maxErrors) break;+ if (isStatementTimeoutError(err)) {+ batchSize = Math.max(MIN_BATCH_SIZE, Math.floor(batchSize / 2));+ process.stderr.write(`[backfill:${spec.name}] write timeout; halving batch to ${batchSize}\n`);+ continue;+ }+ if (isRetryableConnError(err)) {+ await abortableSleep(1000);+ continue;+ }+ if (!isolatable(err)) throw err;+ skippedRows = await isolate(rows, err);}- throw err;}+ if (skippedRows === null) for (const _ of rows) items.succeed();+ else {+ errors += skippedRows;+ // The skipped rows are recorded before the checkpoint moves past them.+ await saveLedger();+ }++ // Advance the checkpoint to the highest id we examined this batch.+ const lastBatchId = (rows[rows.length - 1] as Record<string, unknown>)[idCol];+ if (typeof lastBatchId === 'number') lastId = lastBatchId;+ if (!opts.dryRun) await setCheckpoint(engine, spec.name, lastId);++ opts.onBatch?.({+ batch: batchNum,+ rowsThisBatch: rows.length,+ cumulative: examined,+ lastId,+ errorsSeen: errors,+ effectiveBatchSize: effective,+ });+ if (errors >= maxErrors) break;}- // Advance the checkpoint to the highest id we examined this batch.- const idAccessor = idCol;- const lastBatchId = (rows[rows.length - 1] as Record<string, unknown>)[idAccessor];- if (typeof lastBatchId === 'number') lastId = lastBatchId;- if (!opts.dryRun) await setCheckpoint(engine, spec.name, lastId);-- opts.onBatch?.({- batch: batchNum,- rowsThisBatch: rows.length,- cumulative: examined,- lastId,- errorsSeen: errors,- effectiveBatchSize: effective,- });+ return await finish({ cappedByMaxRows: false, cappedByErrors: errors >= maxErrors });+ } catch (err) {+ // A systemic run records nothing: the skip record and the checkpoint go back to what the run began with.+ if (!opts.dryRun && err instanceof OperationError && err.code === 'item_failures_systemic') {+ await restoreSkipLedger(engine, spec.name, startLedger);+ if (startCheckpoint > 0) await setCheckpoint(engine, spec.name, startCheckpoint);+ else await clearBackfillCheckpoint(engine, spec.name);+ }+ throw err;}-- return {- examined, updated, errors, lastId,- durationSec: (Date.now() - t0) / 1000,- cappedByMaxRows: false, cappedByErrors: errors >= maxErrors,- };}/**diff --git a/src/core/backfill-skips.ts b/src/core/backfill-skips.tsnew file mode 100644index 0000000000..e25274a9ee--- /dev/null+++ b/src/core/backfill-skips.ts@@ -0,0 +1,101 @@+/**+ * Skipped backfill rows (GBRA-130 A-47): the durable record of rows a+ * `runBackfill` could not write, in config key `backfill.<name>.skipped`.+ *+ * A row whose compute or UPDATE fails with an item-scoped error is recorded+ * here before the checkpoint moves past it, so it is never skipped silently:+ * every later run retries each recorded row that still needs the backfill and+ * drops the record once the row lands or no longer matches. A content failure+ * (classifyItemFailure class `content`, such as a CHECK violation) on 3+ * consecutive runs at the same row revision (a hash of the selected columns)+ * and the same gbrain version is held: later runs report it without retrying+ * it until the row or the version changes, or `gbrain backfill <name> --fresh`+ * walks every pending row again. A transient failure is never held.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from './engine.ts';+import type { ItemFailure } from './item-failure.ts';+import { VERSION } from '../version.ts';++export const BACKFILL_HOLD_RUNS = 3;++export interface BackfillSkipRecord {+ id: number;+ code: string;+ class: 'content' | 'transient';+ message: string;+ /** Hash of the row's selected columns when it last failed. */+ revision: string;+ /** The gbrain version that last attempted it. */+ producer: string;+ /** Consecutive runs that failed it at this revision, version and class. */+ attempts: number;+ state: 'failing' | 'held';+ first_failed_at: string;+ last_failed_at: string;+}++export interface BackfillSkipLedger { version: 1; items: Record<string, BackfillSkipRecord> }++/** One recorded row as a backfill result reports it; `fix` is the command that retries it. */+export interface BackfillSkip {+ key: string;+ id: number;+ code: string;+ class: 'content' | 'transient';+ state: 'failing' | 'held';+ attempts: number;+ message: string;+ fix: string;+}++export function skipLedgerKey(name: string): string {+ return `backfill.${name}.skipped`;+}++/** The stored ledger as text (null when absent): runBackfill restores it exactly when a run stops systemic. */+export async function readSkipLedgerRaw(engine: BrainEngine, name: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1 LIMIT 1', [skipLedgerKey(name)]);+ return rows[0]?.value ?? null;+}++export function parseSkipLedger(raw: string | null): BackfillSkipLedger {+ try {+ const parsed = raw ? JSON.parse(raw) as Partial<BackfillSkipLedger> : null;+ if (parsed?.version === 1 && parsed.items && typeof parsed.items === 'object') return { version: 1, items: parsed.items };+ } catch { /* an unreadable ledger is treated as empty; the next write replaces it */ }+ return { version: 1, items: {} };+}++export async function restoreSkipLedger(engine: BrainEngine, name: string, raw: string | null): Promise<void> {+ if (raw === null) await engine.executeRaw('DELETE FROM config WHERE key = $1', [skipLedgerKey(name)]);+ else await engine.setConfig(skipLedgerKey(name), raw);+}++export function rowRevision(row: unknown): string {+ return createHash('sha256').update(JSON.stringify(row)).digest('hex').slice(0, 16);+}++/** A held record whose row and gbrain version are unchanged: reported, not retried. */+export function heldUnchanged(record: BackfillSkipRecord | undefined, revision: string): boolean {+ return record?.state === 'held' && record.revision === revision && record.producer === VERSION;+}++/** Counts one run's failure of a row: consecutive at the same revision, version and class; held at BACKFILL_HOLD_RUNS content failures. */+export function noteSkip(ledger: BackfillSkipLedger, id: number, revision: string, failure: ItemFailure, now: string): void {+ const prev = ledger.items[String(id)];+ const consecutive = prev && prev.revision === revision && prev.producer === VERSION && prev.class === failure.class;+ const attempts = consecutive ? prev.attempts + 1 : 1;+ ledger.items[String(id)] = {+ id, code: failure.code, class: failure.class, message: failure.message.slice(0, 300), revision, producer: VERSION, attempts,+ state: failure.class === 'content' && attempts >= BACKFILL_HOLD_RUNS ? 'held' : 'failing',+ first_failed_at: consecutive ? prev.first_failed_at : now, last_failed_at: now,+ };+}++export function reportSkips(ledger: BackfillSkipLedger, name: string): BackfillSkip[] {+ return Object.values(ledger.items).sort((a, b) => a.id - b.id).map(record => ({+ key: String(record.id), id: record.id, code: record.code, class: record.class, state: record.state, attempts: record.attempts,+ message: record.message, fix: record.state === 'held' ? `gbrain backfill ${name} --fresh` : `gbrain backfill ${name}`,+ }));+}diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex d6c6afddac..bfafcffb01 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -27,6 +27,7 @@ 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 = {+ 'backfill.rows': 'A-47',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/test/pathological/a47-backfill-poison-row.test.ts b/test/pathological/a47-backfill-poison-row.test.tsnew file mode 100644index 0000000000..1017d68489--- /dev/null+++ b/test/pathological/a47-backfill-poison-row.test.ts@@ -0,0 +1,261 @@+/**+ * A-47 (GBRA-130): one poison row never wedges a backfill (src/core/backfill-base.ts).+ *+ * Protects: a row whose compute throws, or whose UPDATE violates a row+ * constraint, is isolated by bisecting its batch (each half in its own+ * transaction), recorded in `backfill.<name>.skipped` and the `skipped` result+ * field with a typed code and the command that retries it, and the checkpoint+ * moves past it while its siblings land. A content failure is held after 3+ * runs at the same row revision and gbrain version; a transient one is retried+ * on every run and never held. A run-scoped failure, a failed ROLLBACK, a lost+ * COMMIT acknowledgment or a systemic run stops the backfill, records nothing+ * and never moves the checkpoint past the batch.+ * Fails when: the batch is not bisected (the run throws and the checkpoint+ * stays before the batch), a skipped row is not recorded or not retried, a+ * transient failure is held, or an undecided batch is bisected or passed.+ * Seams: none in production; the ROLLBACK/COMMIT faults wrap the engine's+ * reserved connection in the test. PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runBackfill, type BackfillSpec } from '../../src/core/backfill-base.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++interface ProbeRow { id: number; slug: string; title: string }++const sqlError = (code: string, message: string) => Object.assign(new Error(message), { code });++async function seed(engine: BrainEngine, titles: string[]): Promise<{ sourceId: string; rows: ProbeRow[] }> {+ const sourceId = `bf-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [sourceId]);+ for (const [i, title] of titles.entries()) {+ await engine.putPage(`notes/row-${String(i).padStart(2, '0')}`, { type: 'note', title, compiled_truth: `# ${title}`, timeline: '' }, { sourceId });+ }+ const rows = await engine.executeRaw<ProbeRow>('SELECT id, slug, title FROM pages WHERE source_id = $1 ORDER BY id', [sourceId]);+ return { sourceId, rows: rows.map(r => ({ ...r, id: Number(r.id) })) };+}++type Compute = BackfillSpec<ProbeRow>['compute'];++/**+ * A backfill over one source's pages: it stamps effective_date and updated_at. A row titled `poison` writes an+ * invalid page_kind (a CHECK violation, 23514) unless `validWrites`; `computeFault` makes compute throw for any+ * batch holding a row it returns an error for.+ */+function probeSpec(sourceId: string, opts: { computeFault?: (row: ProbeRow) => unknown; computed?: ProbeRow[][]; validWrites?: boolean } = {}): BackfillSpec<ProbeRow> {+ const compute: Compute = async rows => {+ opts.computed?.push(rows);+ for (const row of rows) {+ const fault = opts.computeFault?.(row);+ if (fault) throw fault;+ }+ return rows.map(row => ({ id: Number(row.id), updates: { effective_date: '2026-01-01T00:00:00Z', updated_at: '2026-02-02T00:00:00Z',+ page_kind: row.title === 'poison' && !opts.validWrites ? 'bogus' : 'markdown' } }));+ };+ return { name: `probe_${sourceId.replace(/-/g, '_')}`, table: 'pages', selectColumns: ['slug', 'title'],+ needsBackfill: `effective_date IS NULL AND source_id = '${sourceId}'`, compute };+}++type RawConn = { executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]> };++/** The engine with its reserved connection's statements routed through `fault` (the batch's BEGIN/UPDATE/COMMIT/ROLLBACK). */+function withConnectionFault(engine: BrainEngine, fault: (sql: string, run: () => Promise<unknown[]>) => Promise<unknown[]>): BrainEngine {+ return 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: (sql, params) => fault(sql, () => conn.executeRaw(sql, params)) }), opts);+ }+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++const config = async (engine: BrainEngine, key: string) => (await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1', [key]))[0]?.value ?? null;+const skipLedger = async (engine: BrainEngine, name: string) => {+ const raw = await config(engine, `backfill.${name}.skipped`);+ return raw ? JSON.parse(raw) as { version: number; items: Record<string, Record<string, unknown>> } : null;+};+const checkpoint = (engine: BrainEngine, name: string) => config(engine, `backfill.${name}.last_id`);+const titles = (poisonAt: number[], count = 8) => Array.from({ length: count }, (_, i) => poisonAt.includes(i) ? 'poison' : `healthy ${i}`);++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-47 backfill poison row (${backend})`, () => {+ let engine: BrainEngine;+ let closePostgres: (() => Promise<void>) | null = null;++ beforeAll(async () => {+ if (databaseUrl) ({ engine, close: closePostgres } = await isolatedPersistencePostgres(databaseUrl));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 180_000);++ afterAll(async () => {+ if (closePostgres) await closePostgres();+ else await engine.disconnect();+ });++ test('item: a row whose UPDATE violates a CHECK is skipped, recorded and passed; its siblings land', async () => {+ const { sourceId, rows } = await seed(engine, titles([3]));+ const spec = probeSpec(sourceId);+ const poison = rows[3]!;+ const before = await snapshotItems(engine, sourceId);+ const result = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect(result.updated).toBe(7);+ expect(result.skipped.map(s => s.id)).toEqual([poison.id]);+ expectItemFailure(result.skipped[0], { key: String(poison.id), code: 'invalid_data', fix: new RegExp(`^gbrain backfill ${spec.name}$`) });+ expect(result.skipped[0]).toMatchObject({ class: 'content', state: 'failing', attempts: 1 });+ expect(await checkpoint(engine, spec.name)).toBe(String(rows.at(-1)!.id));+ expect(Object.keys((await skipLedger(engine, spec.name))!.items)).toEqual([String(poison.id)]);+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId), { expectProgress: rows.filter(r => r !== poison).map(r => r.slug), progressFields: ['updated_at'] });++ const again = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect({ updated: again.updated, skipped: again.skipped.map(s => [s.id, s.attempts]) }).toEqual({ updated: 0, skipped: [[poison.id, 2]] });+ });++ test('item: a row whose compute throws is isolated by bisection', async () => {+ const { sourceId, rows } = await seed(engine, titles([5]));+ const computed: ProbeRow[][] = [];+ const spec = probeSpec(sourceId, { computed, validWrites: true, computeFault: row => row.title === 'poison' ? sqlError('22007', 'invalid input syntax for type timestamp') : null });+ const poison = rows[5]!;+ const before = await snapshotItems(engine, sourceId);+ const result = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect(result.updated).toBe(7);+ expect(result.skipped.length).toBe(1);+ expectItemFailure(result.skipped[0], { key: String(poison.id), code: 'invalid_data', fix: /^gbrain backfill / });+ expect(computed.length).toBeLessThan(2 * rows.length);+ expect(await checkpoint(engine, spec.name)).toBe(String(rows.at(-1)!.id));+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId), { expectProgress: rows.filter(r => r !== poison).map(r => r.slug), progressFields: ['updated_at'] });+ });++ test('hold: a content failure is held after 3 runs at the same revision and gbrain version, then not retried', async () => {+ const { sourceId, rows } = await seed(engine, titles([2]));+ const computed: ProbeRow[][] = [];+ const spec = probeSpec(sourceId, { computed });+ const poison = rows[2]!;+ for (let run = 1; run <= 3; run++) await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ const held = (await skipLedger(engine, spec.name))!.items[String(poison.id)]!;+ expect(held).toMatchObject({ state: 'held', attempts: 3, code: 'invalid_data', class: 'content' });+ computed.length = 0;+ const fourth = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect(computed.flat().map(r => Number(r.id))).toEqual([]);+ expectItemFailure(fourth.skipped[0], { key: String(poison.id), code: 'invalid_data', fix: new RegExp(`^gbrain backfill ${spec.name} --fresh$`) });+ expect(fourth.skipped[0]).toMatchObject({ state: 'held', attempts: 3 });+ });++ test('transient: an unknown compute error is never held and is retried on every run', async () => {+ const { sourceId, rows } = await seed(engine, titles([4]));+ const spec = probeSpec(sourceId, { validWrites: true, computeFault: row => row.title === 'poison' ? new TypeError('frontmatter.date is undefined') : null });+ const poison = rows[4]!;+ let last;+ for (let run = 1; run <= 4; run++) last = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expectItemFailure(last!.skipped[0], { key: String(poison.id), code: 'internal', fix: /^gbrain backfill / });+ expect(last!.skipped[0]).toMatchObject({ class: 'transient', state: 'failing', attempts: 4 });+ });++ test('recovery: a held row is retried and lands once its content or the gbrain version changes, or on --fresh', async () => {+ const { sourceId, rows } = await seed(engine, titles([1, 4, 7], 10));+ const spec = probeSpec(sourceId);+ for (let run = 1; run <= 3; run++) await runBackfill(engine, spec, { batchSize: 100 });+ expect(Object.values((await skipLedger(engine, spec.name))!.items).map(i => i.state)).toEqual(['held', 'held', 'held']);+ const [contentFixed, versionMoved, freshRetried] = [rows[1]!, rows[4]!, rows[7]!];+ await engine.executeRaw(`UPDATE pages SET title = 'fixed' WHERE id = $1`, [contentFixed.id]);+ const ledger = (await skipLedger(engine, spec.name))!;+ ledger.items[String(versionMoved.id)]!.producer = '0.0.1';+ await engine.setConfig(`backfill.${spec.name}.skipped`, JSON.stringify(ledger));+ const before = await snapshotItems(engine, sourceId);+ // The version-moved row is retried and still fails (its count restarts); the content-fixed row lands.+ const retried = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect(retried.updated).toBe(1);+ expect(retried.skipped.map(s => [s.id, s.state, s.attempts])).toEqual([[versionMoved.id, 'failing', 1], [freshRetried.id, 'held', 3]]);+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId), { expectProgress: [contentFixed.slug], progressFields: ['updated_at'] });+ await engine.executeRaw(`UPDATE pages SET title = 'fixed' WHERE id IN ($1, $2)`, [versionMoved.id, freshRetried.id]);+ const fresh = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100, fresh: true }));+ expect({ updated: fresh.updated, skipped: fresh.skipped }).toEqual({ updated: 2, skipped: [] });+ expect(await skipLedger(engine, spec.name)).toEqual({ version: 1, items: {} });+ });++ 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);+ const before = await snapshotItems(engine, sourceId);+ const error = await runBackfill(engine, spec, { batchSize: 100 }).catch(e => e);+ expect(error?.code).toBe('item_failures_systemic');+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ });++ for (const { name, error } of runScopedErrors()) {+ test(`run: a run-scoped failure (${name}) in compute stops the backfill and records nothing`, async () => {+ const { sourceId } = await seed(engine, titles([3]));+ const injected = error();+ const spec = probeSpec(sourceId, { computeFault: row => row.title === 'poison' ? injected : null });+ const before = await snapshotItems(engine, sourceId);+ const thrown = await runBackfill(engine, spec, { batchSize: 100 }).catch(e => e);+ expect(thrown).toBe(injected);+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ });+ }++ test('run: a failed transaction (25P02) on a row UPDATE stops the backfill without bisecting', async () => {+ const { sourceId } = await seed(engine, titles([]));+ const computed: ProbeRow[][] = [];+ const spec = probeSpec(sourceId, { computed });+ let updates = 0;+ const faulty = withConnectionFault(engine, async (sql, run) => {+ if (sql.startsWith('UPDATE') && ++updates === 2) throw sqlError('25P02', 'current transaction is aborted, commands ignored until end of transaction block');+ return run();+ });+ const before = await snapshotItems(engine, sourceId);+ const thrown = await runBackfill(faulty, spec, { batchSize: 100 }).catch(e => e);+ expect(thrown?.code).toBe('25P02');+ expect(computed.length).toBe(1);+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ });++ test('rollback: a failed ROLLBACK after a row-constraint failure stops without bisecting or recording', async () => {+ const { sourceId } = await seed(engine, titles([3]));+ const computed: ProbeRow[][] = [];+ const spec = probeSpec(sourceId, { computed });+ const faulty = withConnectionFault(engine, async (sql, run) => {+ if (sql === 'ROLLBACK') { await run(); throw sqlError('08006', 'connection failure during ROLLBACK'); }+ return run();+ });+ const before = await snapshotItems(engine, sourceId);+ const thrown = await runBackfill(faulty, spec, { batchSize: 100 }).catch(e => e);+ expect(thrown?.name).toBe('BackfillRollbackError');+ expect(computed.length).toBe(1);+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId));+ });++ test('commit: a lost COMMIT acknowledgment stops without bisecting and never passes the batch', async () => {+ const { sourceId } = await seed(engine, titles([], 6));+ const computed: ProbeRow[][] = [];+ const spec = probeSpec(sourceId, { computed });+ const faulty = withConnectionFault(engine, async (sql, run) => {+ if (sql === 'COMMIT') { await run(); throw sqlError('08006', 'Connection terminated unexpectedly'); }+ return run();+ });+ const thrown = await runBackfill(faulty, spec, { batchSize: 100 }).catch(e => e);+ expect(thrown?.name).toBe('BackfillCommitIndeterminateError');+ expect(thrown?.fix).toBe(`gbrain backfill ${spec.name} --resume`);+ expect(computed.length).toBe(1);+ expect(await skipLedger(engine, spec.name)).toBeNull();+ expect(await checkpoint(engine, spec.name)).toBeNull();+ // The resumed run finds the committed rows done and nothing to redo.+ const resumed = await expectUnitNotAborted(() => runBackfill(engine, spec, { batchSize: 100 }));+ expect({ examined: resumed.examined, skipped: resumed.skipped }).toEqual({ examined: 0, skipped: [] });+ });+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 038e54eda2..400df3396f 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -18,4 +18,7 @@ export interface SiteCases {}export const CATALOGUE: Record<IsolateSite, SiteCases> = {+ 'backfill.rows': { file: 'test/pathological/a47-backfill-poison-row.test.ts',+ item: 'item: a row whose UPDATE violates a CHECK is skipped, recorded and passed; its siblings land',+ run: 'run: a run-scoped failure (' },};diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 12e8291655..f81f46fa02 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/a47-backfill-poison-row.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts