Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
extract_health: record why rounds halted (halt_reasons, migration v239) (#5495)
garrytan180a278cbdb6
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 399f193a81..35406acad0 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -96,7 +96,7 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-frontmatter.ts` — `resolveIncludeFrontmatter(engine, explicit?)`: the single answer for "extract `related:`/`sources:` frontmatter link edges too?" (`autopilot.incremental_extract_include_frontmatter`; explicit flag > file plane > DB plane via `isConfigTruthy` > false, fail-closed on an unreadable config table). Resolved INSIDE the shared helpers — `extractLinksForSlugs` and `extractStaleFromDB` default `opts.includeFrontmatter` through it, the same in-helper pattern as `isGlobalBasenameEnabled` — so sync's inline extract, the GitHub/Google source inline extracts, the `extract_stale` minion, `gbrain maintain`, the cycle's extract phase and `gbrain extract --stale` (flag absent → configured knob) all agree; no caller passes a literal `false`. Pinned by `test/extract-include-frontmatter-config.serial.test.ts` (resolver precedence + a source-text guard on the call sites + a PGLite link-row test through `extractLinksForSlugs`).-- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).+- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. Migration v239 adds `halt_reasons JSONB NOT NULL DEFAULT '{}'` (DDL only, no backfill): `classifyRunStop({ error })` takes `true` (an unclassified halt) or one word of the closed `HALT_REASONS` vocabulary (`provider_auth`, `provider_billing`, `provider_rate_limit`, `provider_model_not_found`, `no_pricing`, `integrity_guard`, `item_error`; a budget or deadline cap is an expected stop, never a reason), and the same UPSERT increments that key with bound parameters (`$N::text`, `jsonb_set`). `unknown` is never stored: the doctor read computes it as `halt_count - sum(halt_reasons)` (`haltReasonsWithUnknown`), so pre-v239 rows and older writers on the same day stay consistent. A brain whose schema is behind v239 loses rollup rows (one stderr line names `migrations_pending` and `gbrain apply-migrations --yes --no-autopilot-install`) and never throws. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0, lists `halt_reasons` and `top_halt_reason` per kind and names the top reason in the warn line (`atoms=42.9%, last halt 1d ago (top reason: item_error ×3)`); pre-v104 brains report `ok`. Pinned by `test/extract-rollup-halt-reasons-5495.test.ts` (both engines). CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4b0e05bd22..64bee91aa8 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -42,5 +42,5 @@ src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap asrc/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)-src/commands/doctor/checks/extraction-sync.ts 1512 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)+src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 7e9b5bae3e..05c2fda03d 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -34,6 +34,7 @@ import { ownedContentFreshness } from '../../../core/shared-skills/content-freshimport { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';import { checkError } from '../check-fix.ts';+import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */const _resolveEnvNumber = resolveEnvNumber;@@ -1050,6 +1051,8 @@ export async function computeExtractHealthCheck(if (!/expected_limit_count/i.test(msg)) throw err;rows = await engine.executeRaw<RollupRow>(rollupQuery(false), []);}+ // #5495: recorded halt reasons per kind over the same 7 days (migration v239).+ const recordedReasons = await readRecordedHaltReasons7d(engine);if (rows.length === 0) {return {@@ -1072,6 +1075,9 @@ export async function computeExtractHealthCheck(round_completed_count: number;expected_limit_count: number;halt_rate: number;+ /** #5495: 7-day halts per reason, `unknown` for halts no reason was recorded for. */+ halt_reasons: Record<string, number>;+ top_halt_reason: string | null;last_updated_at: string | null;last_halt_age_days: number | null;};@@ -1085,6 +1091,7 @@ export async function computeExtractHealthCheck(// not self-imposed capacity limits. A backlog-bigger-than-budget brain// whose every run banks progress and stops at the cap reads 0%.const total = halts + completed + expectedLimits;+ const haltReasons = haltReasonsWithUnknown(halts, recordedReasons.get(r.kind) ?? {});return {kind: r.kind,cost_7d_usd: Number(r.cost_7d_usd) || 0,@@ -1094,6 +1101,8 @@ export async function computeExtractHealthCheck(round_completed_count: completed,expected_limit_count: expectedLimits,halt_rate: total > 0 ? halts / total : 0,+ halt_reasons: haltReasons,+ top_halt_reason: topHaltReason(haltReasons)?.reason ?? null,last_updated_at: r.last_updated_at? new Date(r.last_updated_at).toISOString(): null,@@ -1126,7 +1135,9 @@ export async function computeExtractHealthCheck(.map(k => {const ageDays = k.last_halt_age_days;const ageSuffix = ageDays === null ? '' : ageDays <= 0 ? ', last halt today' : `, last halt ${ageDays}d ago`;- return `${k.kind}=${(k.halt_rate * 100).toFixed(1)}%${ageSuffix}`;+ const top = topHaltReason(k.halt_reasons);+ const reasonSuffix = top ? ` (top reason: ${top.reason} ×${top.count})` : '';+ return `${k.kind}=${(k.halt_rate * 100).toFixed(1)}%${ageSuffix}${reasonSuffix}`;}).join(', ');return {diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 4b4ca97005..79d3780049 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -1747,7 +1747,7 @@ async function writeRunReceiptAndRollup(cost_delta: result.spent_usd ?? 0,...classifyRunStop({budget_exhausted: halted,- error: result.pages_failed > 0 || result.budget_reason === 'no_pricing',+ error: result.budget_reason === 'no_pricing' ? 'no_pricing' : result.pages_failed > 0 ? 'item_error' : false,}),});}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex d49b60b8d2..069793e234 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -77,7 +77,7 @@ import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';import { connectorAtomExclusionSql } from './connector-atoms.ts';import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate, settleExtractAtomsCostGate } from './extract-atoms-cost-gate.ts';import { writeReceipt } from '../extract/receipt-writer.ts';-import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';+import { classifyRunStop, providerHaltReason, upsertExtractRollup } from '../extract/rollup-writer.ts';import { abortableSleep } from '../retry.ts';import { throwIfAborted } from '../abort-check.ts';import { createHash } from 'crypto';@@ -1419,7 +1419,7 @@ export async function runPhaseExtractAtoms(kind: 'atoms',source_id: sourceId,cost_delta: estimatedSpendUsd,- ...classifyRunStop({ deadline_hit: stoppedEarly, error: hardFailureCount > 0 }),+ ...classifyRunStop({ deadline_hit: stoppedEarly, error: hardFailureCount > 0 ? providerHaltReason(abortedGlobalError) ?? 'item_error' : false }),});}diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 00dbd4f09d..ea8e923338 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -860,6 +860,7 @@ export async function runExtractFacts(cost_delta: 0,round_completed_delta: 0,halt_delta: 1,+ halt_reason: 'integrity_guard',});}}@@ -1134,7 +1135,7 @@ export async function runExtractFacts(kind: 'facts.fence',source_id: sourceId,cost_delta: 0,- ...classifyRunStop({ error: result.pagesFailed > 0 }),+ ...classifyRunStop({ error: result.pagesFailed > 0 ? 'item_error' : false }),});}diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex 993ac91c74..6572f8f143 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -50,7 +50,7 @@ import { createGlobalLlmHaltTracker, haltedClassOf, type GlobalLlmErrorClass } fimport { normalizeModelId } from '../model-id.ts';import { writeReceipt } from '../extract/receipt-writer.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';-import { upsertExtractRollup, classifyRunStop } from '../extract/rollup-writer.ts';+import { upsertExtractRollup, classifyRunStop, providerHaltReason } from '../extract/rollup-writer.ts';import { GBrainError } from '../types.ts';import { isConfigTruthy } from '../config.ts';import { matchingCloseBracket } from '../llm-json.ts';@@ -1120,8 +1120,8 @@ class ProposeTakesPhase extends BaseCyclePhase {budget_exhausted: result.budget_exhausted === true,deadline_hit: result.deadline_hit === true,error:- result.aborted_global_error !== undefined ||- result.aborted_failure_streak === true,+ result.aborted_global_error !== undefined ? providerHaltReason(result.aborted_global_error) ?? 'item_error'+ : result.aborted_failure_streak === true ? 'item_error' : false,}),});diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.tsindex c38c4f3fbe..b5defc05f4 100644--- a/src/core/cycle/synthesize-concepts.ts+++ b/src/core/cycle/synthesize-concepts.ts@@ -608,6 +608,7 @@ export async function runPhaseSynthesizeConcepts(cost_delta: estimatedSpendUsd,round_completed_delta: failures.length === 0 && publicationDeferred.length === 0 && publicationHeld.length === 0 ? 1 : 0,halt_delta: failures.length > 0 ? 1 : 0,+ halt_reason: 'item_error',});}diff --git a/src/core/extract/rollup-writer.ts b/src/core/extract/rollup-writer.tsindex 93874a2433..c1c0cb918c 100644--- a/src/core/extract/rollup-writer.ts+++ b/src/core/extract/rollup-writer.ts@@ -29,6 +29,86 @@import type { BrainEngine } from '../engine.ts';+/**+ * #5495: why a round halted, as a closed vocabulary stored per reason in+ * `extract_rollup_7d.halt_reasons` (migration v239) next to `halt_count`.+ * No provider text and no paths ever enter the table: a caller passes one of+ * these, or `true` for a halt it cannot classify, which reads back as+ * `unknown` (`halt_count - sum(halt_reasons)`, computed on read, so rows+ * written before the column and by older writers need no backfill).+ */+export const HALT_REASONS = Object.freeze([+ 'provider_auth',+ 'provider_billing',+ 'provider_rate_limit',+ 'provider_model_not_found',+ 'no_pricing',+ 'integrity_guard',+ 'item_error',+] as const);+export type HaltReason = (typeof HALT_REASONS)[number];+/** The read-side bucket for halts no reason was recorded for; never written. */+export const UNKNOWN_HALT_REASON = 'unknown';++/** The provider error classes a phase's global LLM halt tracker reports, as halt reasons. */+export function providerHaltReason(cls: 'auth' | 'billing' | 'rate_limit' | 'model_not_found' | null | undefined): HaltReason | null {+ switch (cls) {+ case 'auth': return 'provider_auth';+ case 'billing': return 'provider_billing';+ case 'rate_limit': return 'provider_rate_limit';+ case 'model_not_found': return 'provider_model_not_found';+ default: return null;+ }+}++/** Reasons recorded on 7-day rows plus the read-side `unknown` bucket for the halts no reason covers. */+export function haltReasonsWithUnknown(haltCount: number, recorded: Record<string, number | string>): Record<string, number> {+ const reasons: Record<string, number> = {};+ let classified = 0;+ for (const [reason, n] of Object.entries(recorded)) {+ const count = Number(n) || 0;+ if (count <= 0) continue;+ reasons[reason] = count;+ classified += count;+ }+ const unknown = haltCount - classified;+ if (unknown > 0) reasons[UNKNOWN_HALT_REASON] = unknown;+ return reasons;+}++/**+ * The halt reasons recorded over the last 7 days, summed per kind. A brain+ * whose schema is behind v239 has no column: every halt then reads as+ * `unknown` (a backfill never runs; `unknown` is computed on read).+ */+export async function readRecordedHaltReasons7d(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, Record<string, number>>> {+ const recorded = new Map<string, Record<string, number>>();+ try {+ const rows = await engine.executeRaw<{ kind: string; reason: string; n: number | string }>(+ `SELECT r.kind, e.key AS reason, SUM(e.value::int) AS n+ FROM extract_rollup_7d r, jsonb_each_text(r.halt_reasons) e+ WHERE r.day >= CURRENT_DATE - 7+ GROUP BY r.kind, e.key`, []);+ for (const row of rows) {+ const perKind = recorded.get(row.kind) ?? {};+ perKind[row.reason] = Number(row.n) || 0;+ recorded.set(row.kind, perKind);+ }+ } catch (err) {+ if (!/halt_reasons/i.test((err as Error).message || String(err))) throw err;+ }+ return recorded;+}++/** The most frequent halt reason, `unknown` included, or null without halts. */+export function topHaltReason(reasons: Record<string, number>): { reason: string; count: number } | null {+ let top: { reason: string; count: number } | null = null;+ for (const [reason, count] of Object.entries(reasons)) {+ if (!top || count > top.count || (count === top.count && reason < top.reason)) top = { reason, count };+ }+ return top;+}+/*** One UPSERT increments per audit event. All counters default to 0 so* callers only specify the deltas they care about (e.g. a round-completed@@ -54,6 +134,8 @@ export interface RollupUpsertInput {/** Increment rollup_write_failures inside the table (used by the* self-healing path that records its own write failures forensically). */failure_delta?: number;+ /** #5495: the reason `halt_delta` halts are counted under in `halt_reasons`; omitted halts read as `unknown`. */+ halt_reason?: HaltReason;}/**@@ -71,10 +153,11 @@ export interface RollupUpsertInput {export function classifyRunStop(stop: {budget_exhausted?: boolean;deadline_hit?: boolean;- error?: boolean;-}): { round_completed_delta: number; halt_delta: number; expected_limit_delta: number } {- if (stop.error === true) {- return { round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0 };+ /** `true` for an unclassified error halt (reads as `unknown`); a HaltReason names it (#5495). A cap is never a halt reason. */+ error?: boolean | HaltReason;+}): { round_completed_delta: number; halt_delta: number; expected_limit_delta: number; halt_reason?: HaltReason } {+ if (stop.error === true || (typeof stop.error === 'string' && (HALT_REASONS as readonly string[]).includes(stop.error))) {+ return { round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0, ...(typeof stop.error === 'string' ? { halt_reason: stop.error } : {}) };}if (stop.budget_exhausted === true || stop.deadline_hit === true) {return { round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1 };@@ -110,15 +193,20 @@ export async function upsertExtractRollup(const completed = input.round_completed_delta ?? 0;const expectedLimits = input.expected_limit_delta ?? 0;const failures = input.failure_delta ?? 0;+ // #5495: the reason bucket this event's halts land in (null: unclassified,+ // read back as `unknown`). Bound as text and keyed in SQL: never JSON text+ // cast to jsonb (the #2339 class), and only vocabulary words reach the table.+ const reason = halts > 0 && input.halt_reason && (HALT_REASONS as readonly string[]).includes(input.halt_reason) ? input.halt_reason : null;try {await engine.executeRaw(`INSERT INTO extract_rollup_7d (kind, source_id, day,cost_usd, halt_count, eval_fail_count, eval_pass_count,- round_completed_count, expected_limit_count, rollup_write_failures, updated_at+ round_completed_count, expected_limit_count, rollup_write_failures, halt_reasons, updated_at)- VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, $10, now())+ VALUES ($1, $2, $3::date, $4, $5, $6, $7, $8, $9, $10,+ CASE WHEN $11::text IS NULL THEN '{}'::jsonb ELSE jsonb_build_object($11::text, $5::int) END, now())ON CONFLICT (kind, source_id, day) DO UPDATE SETcost_usd = extract_rollup_7d.cost_usd + EXCLUDED.cost_usd,halt_count = extract_rollup_7d.halt_count + EXCLUDED.halt_count,@@ -127,12 +215,22 @@ export async function upsertExtractRollup(round_completed_count = extract_rollup_7d.round_completed_count + EXCLUDED.round_completed_count,expected_limit_count = extract_rollup_7d.expected_limit_count + EXCLUDED.expected_limit_count,rollup_write_failures = extract_rollup_7d.rollup_write_failures + EXCLUDED.rollup_write_failures,+ halt_reasons = CASE WHEN $11::text IS NULL THEN extract_rollup_7d.halt_reasons+ ELSE jsonb_set(extract_rollup_7d.halt_reasons, ARRAY[$11::text],+ to_jsonb(COALESCE((extract_rollup_7d.halt_reasons->>$11::text)::int, 0) + $5::int)) END,updated_at = now()`,- [input.kind, input.source_id, day, cost, halts, evalFails, evalPasses, completed, expectedLimits, failures],+ [input.kind, input.source_id, day, cost, halts, evalFails, evalPasses, completed, expectedLimits, failures, reason],);return { ok: true };} catch (err) {const msg = (err as Error).message || String(err);+ // #5495 (no fallback by design): a brain whose schema is behind v239 has no+ // halt_reasons column. The rollup is a best-effort cache, so the row is+ // lost until the migration runs; say which fix restores it.+ if (/halt_reasons/i.test(msg)) {+ rollupErrorLogOnce(input.kind, day, `${msg} (the schema is behind: doctor reports migrations_pending; run gbrain apply-migrations --yes --no-autopilot-install)`);+ return { ok: false, error: msg };+ }// #4482 back-compat: a brain that hasn't applied migration v141 yet has// no expected_limit_count column. Rather than losing the WHOLE rollup// write (best-effort would swallow it), retry the pre-v141 statement —diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex f36b1a624e..2f887f8c54 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 238;+export const LATEST_SCHEMA_VERSION = 239;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 3ab2aac153..f2297d1e85 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -239,6 +239,7 @@ import { v235 } from './v235-pinned-questions.ts';import { v236 } from './v236-open-loops-counterparty-source.ts';import { v237 } from './v237-facts-question-recall-indexes.ts';import { v238 } from './v238-persistence-client-request-id.ts';+import { v239 } from './v239-extract-rollup-halt-reasons.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -476,4 +477,5 @@ export const MIGRATIONS: Migration[] = [v236,v237,v238,+ v239,];diff --git a/src/core/schema-migrations/v239-extract-rollup-halt-reasons.ts b/src/core/schema-migrations/v239-extract-rollup-halt-reasons.tsnew file mode 100644index 0000000000..0f0cccd965--- /dev/null+++ b/src/core/schema-migrations/v239-extract-rollup-halt-reasons.ts@@ -0,0 +1,22 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); extract_rollup_7d+// has no fresh-install copy in schema.sql (migration v106 creates it), so this+// column lives here only.+export const v239: Migration = {+ version: 239,+ name: 'extract_rollup_halt_reasons',+ // #5495: why a round halted, as a closed vocabulary (rollup-writer.ts+ // HALT_REASONS) counted per reason in one JSONB object next to halt_count.+ // DDL only: a metadata-only ADD COLUMN takes a brief ACCESS EXCLUSIVE lock+ // under migrate.ts's lock timeout and no row is rewritten. There is NO+ // backfill here (the runner applies one file in one transaction, so an+ // UPDATE would hold that lock for its whole duration): halts recorded+ // before this column, and halts the writer could not classify, read as+ // `unknown` = halt_count - sum(halt_reasons), computed by the doctor read.+ idempotent: true,+ sql: `+ ALTER TABLE extract_rollup_7d+ ADD COLUMN IF NOT EXISTS halt_reasons JSONB NOT NULL DEFAULT '{}'::jsonb;+ `,+};diff --git a/test/e2e/extract-rollup-halt-reasons-5495-postgres.test.ts b/test/e2e/extract-rollup-halt-reasons-5495-postgres.test.tsnew file mode 100644index 0000000000..f5130f1f7e--- /dev/null+++ b/test/e2e/extract-rollup-halt-reasons-5495-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../extract-rollup-halt-reasons-5495.test.ts'));diff --git a/test/extract-rollup-halt-reasons-5495.test.ts b/test/extract-rollup-halt-reasons-5495.test.tsnew file mode 100644index 0000000000..e8682e5129--- /dev/null+++ b/test/extract-rollup-halt-reasons-5495.test.ts@@ -0,0 +1,205 @@+/**+ * #5495: extract_health reports WHY rounds halted.+ *+ * Protects: migration v239 adds `extract_rollup_7d.halt_reasons JSONB NOT+ * NULL DEFAULT '{}'` as DDL only (no backfill statement in the file);+ * `classifyRunStop` keeps its three-way split (a cap is an expected stop,+ * never a halt or a halt reason) and carries a named reason only when the+ * caller classified the error; `upsertExtractRollup` increments the reason in+ * the same UPSERT with bound parameters; halts written before the column,+ * by an older writer or unclassified read as `unknown` =+ * halt_count - sum(halt_reasons), so reason totals never exceed halt_count+ * with old and new writers on one day; doctor names the top reason; a brain+ * whose schema is behind keeps extracting and loses rollup rows with one+ * stderr line naming the migration fix, never a throw; extract_atoms records+ * a credentials abort as provider_auth and extract_facts' fence guard as+ * integrity_guard.+ * Fails when: the migration backfills, a cap becomes a halt reason, reasons+ * are JSON-stringified into the jsonb, unknown is stored instead of+ * computed, or the doctor ignores the column.+ * PGLite always; Postgres when DATABASE_URL is set+ * (test/e2e/extract-rollup-halt-reasons-5495-postgres.test.ts; the PgBouncer+ * matrix pass runs that file too).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { classifyRunStop, haltReasonsWithUnknown, HALT_REASONS, providerHaltReason, topHaltReason, upsertExtractRollup } from '../src/core/extract/rollup-writer.ts';+import { computeExtractHealthCheck } from '../src/commands/doctor/checks/extraction-sync.ts';+import { v239 } from '../src/core/schema-migrations/v239-extract-rollup-halt-reasons.ts';+import { MIGRATIONS } from '../src/core/migrate.ts';+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+});++const TODAY = new Date().toISOString().slice(0, 10);+let kindSeq = 0;+const freshKind = () => `probe.${++kindSeq}`;++/** An older binary's rollup statement: no halt_reasons column named, halts land in halt_count only. */+async function oldWriterUpsert(engine: BrainEngine, kind: string, halts: number): Promise<void> {+ await engine.executeRaw(`INSERT INTO extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_fail_count, eval_pass_count,+ round_completed_count, expected_limit_count, rollup_write_failures, updated_at)+ VALUES ($1, 'default', $2::date, 0, $3, 0, 0, 0, 0, 0, now())+ ON CONFLICT (kind, source_id, day) DO UPDATE SET halt_count = extract_rollup_7d.halt_count + EXCLUDED.halt_count, updated_at = now()`, [kind, TODAY, halts]);+}++async function rollupRow(engine: BrainEngine, kind: string) {+ const [row] = await engine.executeRaw<{ halt_count: number; round_completed_count: number; expected_limit_count: number; halt_reasons: Record<string, number> | string }>(+ `SELECT halt_count, round_completed_count, expected_limit_count, halt_reasons FROM extract_rollup_7d WHERE kind=$1 AND source_id='default' AND day=$2::date`, [kind, TODAY]);+ const reasons = typeof row!.halt_reasons === 'string' ? JSON.parse(row!.halt_reasons) : row!.halt_reasons;+ return { ...row!, halt_reasons: reasons as Record<string, number> };+}++async function doctorKind(engine: BrainEngine, kind: string) {+ const check = await computeExtractHealthCheck(engine);+ const kinds = (check.details as { kinds: Array<{ kind: string; halt_count: number; halt_reasons: Record<string, number>; top_halt_reason: string | null }> }).kinds;+ return { check, kind: kinds.find(k => k.kind === kind)! };+}++describe('classifyRunStop keeps its three-way split and names a reason only when given one (#5495)', () => {+ test('a cap is an expected stop, never a halt reason', () => {+ expect(classifyRunStop({ budget_exhausted: true })).toEqual({ round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1 });+ expect(classifyRunStop({ deadline_hit: true })).toEqual({ round_completed_delta: 0, halt_delta: 0, expected_limit_delta: 1 });+ expect((HALT_REASONS as readonly string[]).includes('budget_cap')).toBe(false);+ expect((HALT_REASONS as readonly string[]).includes('unknown')).toBe(false);+ });+ test('an unclassified error halts without a reason; a classified one carries it, a cap alongside it stays an error', () => {+ expect(classifyRunStop({ error: true })).toEqual({ round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0 });+ expect(classifyRunStop({ error: 'item_error' })).toEqual({ round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0, halt_reason: 'item_error' });+ expect(classifyRunStop({ budget_exhausted: true, error: 'provider_auth' })).toEqual({ round_completed_delta: 0, halt_delta: 1, expected_limit_delta: 0, halt_reason: 'provider_auth' });+ expect(classifyRunStop({ error: false })).toEqual({ round_completed_delta: 1, halt_delta: 0, expected_limit_delta: 0 });+ });+ test('provider classes map onto the closed vocabulary; unknown reads as the remainder', () => {+ expect(['auth', 'billing', 'rate_limit', 'model_not_found'].map(c => providerHaltReason(c as 'auth'))).toEqual(['provider_auth', 'provider_billing', 'provider_rate_limit', 'provider_model_not_found']);+ expect(providerHaltReason(null)).toBeNull();+ expect(haltReasonsWithUnknown(5, { provider_auth: 2, item_error: 1 })).toEqual({ provider_auth: 2, item_error: 1, unknown: 2 });+ expect(haltReasonsWithUnknown(0, {})).toEqual({});+ expect(topHaltReason({ provider_auth: 2, item_error: 1, unknown: 2 })).toEqual({ reason: 'provider_auth', count: 2 });+ expect(topHaltReason({})).toBeNull();+ });+});++test('migration v239 is additive DDL only: no backfill statement, idempotent, default {}', () => {+ expect(MIGRATIONS.find(m => m.name === 'extract_rollup_halt_reasons')?.version).toBe(239);+ expect(v239.idempotent).toBe(true);+ expect(v239.sql).toMatch(/ADD COLUMN IF NOT EXISTS halt_reasons JSONB NOT NULL DEFAULT '\{\}'::jsonb/);+ expect(v239.sql).not.toMatch(/\bUPDATE\b|\bbackfill\b|jsonb_build_object/i);+ expect(v239.sql.trim().split(';').filter(Boolean)).toHaveLength(1);+});++test('the column exists with its default on every engine, and a reason-less row reads as unknown', async () => {+ for (const engine of engines) {+ const [column] = await engine.executeRaw<{ data_type: string; column_default: string; is_nullable: string }>(+ `SELECT data_type, column_default, is_nullable FROM information_schema.columns WHERE table_name='extract_rollup_7d' AND column_name='halt_reasons'`);+ expect(column).toMatchObject({ data_type: 'jsonb', is_nullable: 'NO' });+ expect(column!.column_default).toContain("'{}'::jsonb");+ const kind = freshKind();+ await oldWriterUpsert(engine, kind, 3);+ expect((await rollupRow(engine, kind)).halt_reasons).toEqual({});+ const { kind: read } = await doctorKind(engine, kind);+ expect(read).toMatchObject({ halt_count: 3, halt_reasons: { unknown: 3 }, top_halt_reason: 'unknown' });+ }+}, 120_000);++test('reasons increment in the same UPSERT; old and new writers on one day keep sum(reasons) <= halt_count; doctor names the top reason', async () => {+ for (const engine of engines) {+ const kind = freshKind();+ for (const _ of [1, 2]) expect(await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({ error: 'provider_auth' }) })).toEqual({ ok: true });+ expect(await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({ error: 'item_error' }) })).toEqual({ ok: true });+ expect(await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({ error: true }) })).toEqual({ ok: true });+ expect(await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({ budget_exhausted: true }) })).toEqual({ ok: true });+ // A reason on a non-halt event is ignored: nothing is counted under it.+ expect(await upsertExtractRollup(engine, { kind, source_id: 'default', halt_reason: 'item_error', ...classifyRunStop({}) })).toEqual({ ok: true });+ await oldWriterUpsert(engine, kind, 1);+ const row = await rollupRow(engine, kind);+ expect(row).toMatchObject({ halt_count: 5, round_completed_count: 1, expected_limit_count: 1, halt_reasons: { provider_auth: 2, item_error: 1 } });+ expect(Object.values(row.halt_reasons).reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(row.halt_count);+ const { check, kind: read } = await doctorKind(engine, kind);+ expect(read).toMatchObject({ halt_count: 5, halt_reasons: { provider_auth: 2, item_error: 1, unknown: 2 }, top_halt_reason: 'provider_auth' });+ expect(check.status).toBe('warn');+ expect(check.message).toContain(`${kind}=71.4%`);+ expect(check.message).toContain('(top reason: provider_auth ×2)');++ // Concurrent old and new writers on the same (kind, day): the UPSERT is atomic per row.+ const racy = freshKind();+ await Promise.all([+ ...Array.from({ length: 10 }, () => upsertExtractRollup(engine, { kind: racy, source_id: 'default', ...classifyRunStop({ error: 'item_error' }) })),+ ...Array.from({ length: 10 }, () => oldWriterUpsert(engine, racy, 1)),+ ]);+ const raced = await rollupRow(engine, racy);+ expect(raced).toMatchObject({ halt_count: 20, halt_reasons: { item_error: 10 } });+ expect((await doctorKind(engine, racy)).kind.halt_reasons).toEqual({ item_error: 10, unknown: 10 });+ }+}, 120_000);++test('a brain whose schema is behind v239 keeps extracting: the rollup write returns ok:false with one stderr line naming the migration fix, and never throws', async () => {+ for (const engine of engines) {+ const kind = freshKind();+ await engine.executeRaw('ALTER TABLE extract_rollup_7d DROP COLUMN halt_reasons');+ const lines: string[] = [];+ const error = console.error;+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };+ try {+ const first = await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({ error: 'item_error' }) });+ const second = await upsertExtractRollup(engine, { kind, source_id: 'default', ...classifyRunStop({}) });+ expect(first.ok).toBe(false);+ expect(second.ok).toBe(false);+ expect(first.error).toMatch(/halt_reasons/);+ } finally { console.error = error; }+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('migrations_pending');+ expect(lines[0]).toContain('gbrain apply-migrations --yes --no-autopilot-install');+ expect(await engine.executeRaw('SELECT 1 FROM extract_rollup_7d WHERE kind=$1', [kind])).toEqual([]);+ // The doctor read still works without the column: every halt is unknown.+ const seen = freshKind();+ await oldWriterUpsert(engine, seen, 2);+ expect((await doctorKind(engine, seen)).kind).toMatchObject({ halt_count: 2, halt_reasons: { unknown: 2 } });+ await engine.executeRaw(v239.sql);+ expect((await rollupRow(engine, seen)).halt_reasons).toEqual({});+ }+}, 120_000);++test('extract_atoms records a credentials abort as provider_auth; extract_facts records its fence guard as integrity_guard', async () => {+ const engine = engines.find(e => e.kind === 'pglite');+ if (!engine) return;+ for (const slug of ['note/auth-1', 'note/auth-2']) await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'seed body prose' } as never, { sourceId: 'default' });+ await runPhaseExtractAtoms(engine as PGLiteEngine, {+ sourceId: 'default', _transcripts: [],+ _pages: ['note/auth-1', 'note/auth-2'].map((slug, i) => ({ slug, content: 'prose', contentHash: String(i).repeat(16) })),+ _chat: async () => { throw Object.assign(new Error('invalid x-api-key'), { status: 401 }); },+ });+ expect(await rollupRow(engine, 'atoms')).toMatchObject({ halt_count: 1, halt_reasons: { provider_auth: 1 } });++ const calls: Array<{ sql: string; params: unknown[] }> = [];+ const stub = {+ async executeRaw(sql: string, params: unknown[] = []) {+ calls.push({ sql: sql.replace(/\s+/g, ' '), params });+ if (/COUNT\(\*\) AS n/.test(sql)) return [{ n: '3' }];+ return [];+ },+ async getAllSlugs() { return []; }, async getPage() { return null; },+ async deleteFactsForPage() { return { deleted: 0 }; }, async insertFacts() { return { inserted: 0, ids: [], warnings: [], deleted: 0 }; },+ async transaction<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<T> { return fn(stub); },+ } as unknown as BrainEngine;+ expect((await runExtractFacts(stub, { slugs: [], sourceId: 'default' })).guardTriggered).toBe(true);+ const rollups = calls.filter(c => c.sql.includes('INSERT INTO extract_rollup_7d'));+ expect(rollups).toHaveLength(1);+ expect(rollups[0]!.params[4]).toBe(1);+ expect(rollups[0]!.params[10]).toBe('integrity_guard');+ expect(rollups[0]!.sql).not.toContain('JSON.stringify');+}, 120_000);diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f88a9bc89b..cbf296ad1e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -1941,7 +1941,8 @@"8 round_completed_count integer/int4 NOT NULL DEFAULT 0","9 rollup_write_failures integer/int4 NOT NULL DEFAULT 0","10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0"+ "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0",+ "12 halt_reasons jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 9c5b2ea4a8..152c1ca406 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -1941,7 +1941,8 @@"8 round_completed_count integer/int4 NOT NULL DEFAULT 0","9 rollup_write_failures integer/int4 NOT NULL DEFAULT 0","10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0"+ "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0",+ "12 halt_reasons jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 092cc293cc..e856bc2caa 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -1937,7 +1937,8 @@"8 round_completed_count integer/int4 NOT NULL DEFAULT 0","9 rollup_write_failures integer/int4 NOT NULL DEFAULT 0","10 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",- "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0"+ "11 expected_limit_count integer/int4 NOT NULL DEFAULT 0",+ "12 halt_reasons jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex f122c3775d..21e023ce33 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 233,+ "count": 234,"gaps": [17,18,@@ -52,7 +52,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 238,+ "latest": 239,"records": [{"handler": {@@ -3610,6 +3610,19 @@"transaction": "absent","verify": "absent","version": 238+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "extract_rollup_halt_reasons",+ "sql": {+ "length": 117,+ "sha256": "75898ef6f707541c890079219b85e0ea1e85cf35cc87a2952917086f24a719a1"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 239}],"versions": [@@ -3845,7 +3858,8 @@235,236,237,- 238+ 238,+ 239]},"normalizer": "migrations-record-v1"