Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): PR 4 4b round 4: piece positions, grammar only from current rows or the page head, window-specific retry counting, fail-safe billed classification

garrytand18ddc9b825c
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 601be93740..1f66a98bd8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 1889 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
src/commands/jobs.ts 667 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts)
src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)
-src/core/ai/gateway.ts 4530 ratchet +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)
+src/core/ai/gateway.ts 4532 ratchet +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts)
src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine
src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index 0854ea2c1d..960d80e2ba 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -38,7 +38,10 @@ const UNREAD_WINDOWS = 'unread_windows';
const UNREAD_REMEDY = `the run stopped before every window of the page was read (the receipt's reason: the per-page spend cap, a window limit or a skipped window); the next run resumes where it stopped, and when the cap stopped it: gbrain config set ${PAGE_DERIVATION_CAP_KEY} <usd>`;
const FAILED_WINDOWS = 'failed_windows';
const FAILED_REMEDY = 'a conversation window failed to extract in run after run and is skipped, so the older windows still get extracted (the sample names the window, its receipt the last error); fix the cause, then gbrain extract-conversation-facts --slug <slug> --force tries it again';
-const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY : REMEDY[g.pipeline] ?? null;
+const NO_MESSAGES = 'no_messages';
+const NO_MESSAGES_REMEDY = 'the last run parsed no message from parts of the page that had conversation windows (a changed transcript format, or a parser fault), so it kept their facts and settled nothing; check that the page still reads as a conversation, then gbrain extract-conversation-facts --slug <slug>';
+const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY
+ : g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;
const describe = (g: ReceiptGroup): string =>
`${g.pipeline}/${g.kind}: ${g.pages} page(s) (e.g. ${g.samples.join(', ')}); ${remedy(g) ?? 'see the receipt in page_extraction_state'}`;
diff --git a/src/core/ai/budget-record.ts b/src/core/ai/budget-record.ts
index f45d94e62e..20a06f44ff 100644
--- a/src/core/ai/budget-record.ts
+++ b/src/core/ai/budget-record.ts
@@ -4,7 +4,7 @@
* surfaces on the NEXT `reserve()`, and the call's own result or error wins.
*/
-import { readProviderFailureSignals } from './errors.ts';
+import { numericStatusOf, wrappedErrorLayers } from './errors.ts';
import {
usageFromError,
type BudgetActualUsage,
@@ -21,23 +21,55 @@ export function recordOnTracker(tracker: BudgetTracker | null, actual: BudgetAct
}
}
+type Tokens = { inputTokens: number; outputTokens: number };
+
+/** The usage any layer of a thrown error reports (its wrappers opened: `cause`, a retry wrapper's `lastError`), or null. */
+function chainUsage(err: unknown): ReturnType<typeof usageFromError> {
+ for (const layer of wrappedErrorLayers(err)) {
+ const found = usageFromError(layer);
+ if (found) return found;
+ }
+ return null;
+}
+
/**
- * Usage fields for a failed call: what the SDK error reports, else the
- * pessimistic fallback (A3 amended) flagged `estimated`. `rejected`: the
- * provider refused it with an HTTP error status (a 4xx other than 408 Request
- * Timeout, or a 5xx) and reported no usage, so it billed nothing.
+ * PR 4 (Wave B incremental derivation, transcripts): what one provider attempt may have billed. Its reported usage
+ * (read through its wrappers), topped up with the fallback for a side it did not report; nothing only when the
+ * provider definitively refused it before generating: a 4xx other than 408 Request Timeout or 499 (a proxy's client
+ * closed request) on the attempt itself, with no usage. Everything else, a 5xx, a 529, a 504 from a proxy, a timeout,
+ * an abort, a reset connection, may have been billed and books the fallback (the attempt's worst case).
+ */
+function attemptBilled(attempt: unknown, fallback: Tokens): Tokens {
+ const found = chainUsage(attempt);
+ if (found) return { inputTokens: found.inputTokens ?? fallback.inputTokens, outputTokens: found.outputTokens ?? fallback.outputTokens };
+ const status = numericStatusOf(attempt);
+ if (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 499) return { inputTokens: 0, outputTokens: 0 };
+ return fallback;
+}
+
+/**
+ * Usage fields for a failed call: what the SDK error reports (any layer), else the
+ * pessimistic fallback (A3 amended) flagged `estimated`. `billed`: what the
+ * provider may have billed across the call's attempts, each classified on its
+ * own (attemptBilled): every entry of a retry wrapper (the AI SDK's RetryError
+ * keeps them on `errors`), else the error itself.
*/
export function failedCallUsage(
err: unknown,
- fallback: { inputTokens: number; outputTokens: number },
-): { inputTokens: number; outputTokens: number; failed: true; estimated: boolean; rejected: boolean } {
- const found = usageFromError(err);
- const { status } = readProviderFailureSignals(err);
+ fallback: Tokens,
+): Tokens & { failed: true; estimated: boolean; billed: Tokens } {
+ const found = chainUsage(err);
+ let attempts: unknown[] = [err];
+ for (const layer of wrappedErrorLayers(err)) {
+ if (Array.isArray(layer.errors) && layer.errors.length) { attempts = layer.errors; break; }
+ }
+ const billed = attempts.map(attempt => attemptBilled(attempt, fallback))
+ .reduce((sum, t) => ({ inputTokens: sum.inputTokens + t.inputTokens, outputTokens: sum.outputTokens + t.outputTokens }), { inputTokens: 0, outputTokens: 0 });
return {
inputTokens: found?.inputTokens ?? fallback.inputTokens,
outputTokens: found?.outputTokens ?? fallback.outputTokens,
failed: true,
estimated: found?.inputTokens == null || found?.outputTokens == null,
- rejected: found === null && status !== undefined && status >= 400 && status < 600 && status !== 408,
+ billed,
};
}
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 22016a1c37..916bd32614 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -287,7 +287,7 @@ const STRUCTURED_JSON_STATUS_RE =
const STRUCTURED_PROSE_STATUS_RE =
/(?:\bHTTP[ /]|\bstatus(?:\s+code)?\s*[:= ]\s*)(401|402|403|429)\b/i;
-function numericStatusOf(e: unknown): number | undefined {
+export function numericStatusOf(e: unknown): number | undefined {
const anyErr = e as Record<string, unknown> | null | undefined;
for (const key of ['status', 'statusCode', 'apiErrorStatus', 'api_error_status']) {
const v = anyErr?.[key];
@@ -303,7 +303,7 @@ function numericStatusOf(e: unknown): number | undefined {
* only, and the walk stops after `limit` layers or at a layer already seen,
* so a self-referencing chain cannot loop.
*/
-function* wrappedErrorLayers(err: unknown, limit = 5): Generator<Record<string, unknown>> {
+export function* wrappedErrorLayers(err: unknown, limit = 5): Generator<Record<string, unknown>> {
const seen = new Set<object>();
let layer = err;
while (layer !== null && typeof layer === 'object' && seen.size < limit && !seen.has(layer)) {
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index d05d85e6e8..45f61db566 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -3760,6 +3760,8 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
abortSignal: withDefaultTimeout(opts.abortSignal, opts.timeoutMs ?? AI_CHAT_TIMEOUT_MS),
providerOptions: Object.keys(providerOptions).length > 0 ? providerOptions : undefined,
...(requestHeaders ? { headers: requestHeaders } : {}),
+ // PR 4 (Wave B incremental derivation, transcripts): a metered page step sees every attempt it pays for.
+ ...(tracker?.providerRetries !== undefined ? { maxRetries: tracker.providerRetries } : {}),
});
try {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 7079b7da85..5f9c4ee6f6 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1059,8 +1059,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// PR 4 4b
{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },
{ since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },
- { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed without reporting usage (a timeout, an abort, a dropped connection) books its worst case, and one the provider refused with an error status (a rate limit, an auth or server error) or a failed embedding books nothing. Doctor lists the pages a cap stopped.' },
- { since: 'TBD', text: 'A conversation window whose fact extraction fails in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted; `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again.' },
+ { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped.' },
+ { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. A run that reads no message where a large conversation page had them (a changed format) keeps every fact and leaves a receipt doctor lists, instead of clearing the page.' },
// PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.
{ since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },
// PR 4 (Wave B incremental derivation, transcripts)
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 53b69b60b6..9f9e57c335 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -96,11 +96,10 @@ export interface BudgetActualUsage {
/** Token counts are a heuristic (char estimate or pessimistic failure fallback), not provider-reported. */
estimated?: boolean;
/**
- * PR 4 (Wave B incremental derivation, transcripts): a failed call the provider refused with an HTTP error status
- * and reported no usage for (failedCallUsage): it billed nothing. A failure without a status (a timeout, an abort,
- * a reset connection) or with partial usage may have been billed and is not marked.
+ * PR 4 (Wave B incremental derivation, transcripts): for a failed call, the tokens the provider may have billed
+ * across its attempts (failedCallUsage): zero only when it definitively refused every attempt before generating.
*/
- rejected?: boolean;
+ billed?: { inputTokens: number; outputTokens: number };
}
export interface BudgetSnapshot {
@@ -132,6 +131,12 @@ export interface BudgetTrackerOpts {
* Models with neither a table row nor an override stay fail-closed.
*/
pricingOverrides?: PricingOverrides;
+ /**
+ * PR 4 (Wave B incremental derivation, transcripts): the provider SDK's own retries for each call made under this
+ * tracker (chat's maxRetries); unset keeps the SDK default. A metered page step sets 0, so every attempt is a call
+ * it reserved for and sees.
+ */
+ providerRetries?: number;
/**
* A4: where `maxCostUsd` came from. `user` (an explicit flag or configured
* cap; the default whenever `maxCostUsd` is set) hard-fails an unpriced
@@ -286,6 +291,11 @@ export class BudgetTracker {
this.auditPath = opts.auditPath ?? defaultAuditPath();
}
+ /** The SDK retries each call under this tracker may make (BudgetTrackerOpts.providerRetries). */
+ get providerRetries(): number | undefined {
+ return this.opts.providerRetries;
+ }
+
/** Public read access. */
get totalSpent(): number {
return this.cumulativeUsd;
diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.ts
index 6aa6290d28..ef457308b5 100644
--- a/src/core/extraction-watermark.ts
+++ b/src/core/extraction-watermark.ts
@@ -36,7 +36,8 @@ export type HeadFallbackReason = 'no_watermark' | 'prefix_changed' | 'version_ch
/** The durable receipt of an extraction that did not read all of its input. */
export interface InputTruncated {
- kind: 'head' | 'tail_window' | 'skipped_too_large';
+ /** PR 4 (Wave B incremental derivation, transcripts): `no_messages`, a segmented conversation run parsed no message from occurrences that had windows and kept their facts. */
+ kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages';
pipeline: ExtractionPipeline;
/** Characters the extractor read (0 for a skipped page). */
processed_chars: number;
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index fc58a4f724..1b18eefc12 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -18,13 +18,19 @@
* reserved for every attempt and booked at the provider-reported cost), and publishes the facts and rows every
* CONVERSATION_FACTS_CHECKPOINT_WINDOWS windows, when it stops (--segment-limit, the cap) and when a window throws
* or the run aborts, so finished windows are never paid for twice;
- * - counts a window whose extraction throws (a per-window error: not an abort, a cap or a provider-wide failure such
- * as an auth error or a rate limit) against it across runs; the run stops there, and once a window has failed
- * WINDOW_FAILURE_LIMIT runs it is marked failed (facts 0, a failed_windows receipt doctor lists) and the run moves on
- * to older windows; a --force run (retryFailed) tries failed windows again;
+ * - counts a window whose extraction fails for a reason of its own (malformed or truncated output, a refusal or
+ * content filter, a provider refusal of the window's own input such as a context-length error; never a transport,
+ * provider, auth, rate-limit, 5xx, timeout or abort failure) against it across runs; the run stops there, and once a
+ * window has failed WINDOW_FAILURE_LIMIT runs it is marked failed (facts 0, a failed_windows receipt doctor lists)
+ * and the run moves on to older windows; a failed window keeps the facts of the earlier windows it overlaps until it
+ * is extracted, and a --force run (retryFailed) tries it again;
+ * - parses under the grammar a current row recorded, else the one the page's head detects (as the whole-page pass
+ * picks it), never one recorded under another context or text; a stream that parses no message from occurrences
+ * that had windows clears nothing and settles nothing (a no_messages receipt, the page counted failed);
* - clears facts only when that is safe: an unsettled run clears the facts of windows it extracted again and of
- * earlier windows whose messages (by position: occurrence and ordinal, never by timestamp, which a transcript
- * without per-message times shares across every message) a run of current windows covers, nothing else; a settled run (every live window
+ * earlier windows whose messages (by position: occurrence, ordinal and piece of an oversized message, never by
+ * timestamp, which a transcript without per-message times shares across every message) a run of current windows
+ * covers, nothing else; a settled run (every live window
* extracted, no --since, the page unchanged) clears the facts of windows that left the page and the unanchored
* facts of older full-pass runs, and stamps the page complete.
* A --since run extracts only the windows after it and never settles the page. A title or gap change re-extracts every
@@ -34,8 +40,9 @@
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import { deriveDateContext } from '../conversation-parser/parse.ts';
-import { BudgetExhausted, loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';
-import { classifyGlobalLlmError } from '../ai/errors.ts';
+import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';
+import { providerItemRefusal } from '../ai/errors.ts';
+import { truthLead } from '../page-body/segment-blocks.ts';
import { writeDerivedFacts } from '../persistence/derived-facts.ts';
import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';
import { setExtractionReceipt } from '../extraction-watermark.ts';
@@ -46,7 +53,7 @@ import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '..
import { conversationEntityHints } from './conversation-entity-hints.ts';
import { publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
import { recordFailedPage } from './conversation-run-status.ts';
-import { startsConversationRun, streamConversationWindows, type MessagePosition } from './conversation-stream.ts';
+import { detectConversationPattern, startsConversationRun, streamConversationWindows, type MessagePosition } from './conversation-stream.ts';
import type { ConversationSegment } from './conversation-types.ts';
import { renderSegmentForExtraction } from './conversation-windows.ts';
import { extractConversationWindow, nonExtractableAuditFact, regularPageVersionToken, terminalAuditFact, type ConversationWindowRun } from './conversation-window-extract.ts';
@@ -55,7 +62,7 @@ import type { FactVisibility } from './visibility.ts';
const KIND = 'conversation_facts';
/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */
-export const CONVERSATION_FACTS_DERIVATION_VERSION = 1;
+export const CONVERSATION_FACTS_DERIVATION_VERSION = 2;
/** Windows extracted between two publications of a page's facts and rows. */
export const CONVERSATION_FACTS_CHECKPOINT_WINDOWS = 8;
/**
@@ -82,13 +89,18 @@ export interface SegmentedConversationRun extends ConversationWindowRun {
segmentLimit: number;
}
-/** Where a window's first and last message start: [occurrence id, ordinal, occurrence id, ordinal] (MessagePosition). */
-type Span = [number, number, number, number];
+/** Characters of the page's head the grammar is detected from when no current row records it. */
+const PATTERN_HEAD_CHARS = 64 * 1024;
+/** Where a window's first and last message piece are: [occurrence id, ordinal, piece] twice (MessagePosition). */
+type Span = [number, number, number, number, number, number];
/** A window an occurrence row records: ordinal, rendered-text sha, facts produced, its span, and why it failed when it did. */
interface WindowRecord { ordinal: number; sha: string; facts: number; span?: Span; failed?: WindowFailure }
-/** Failed extraction attempts of one window (by rendered-text sha) and the last error. */
-interface WindowFailure { attempts: number; error: string }
-interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; retries?: Array<{ sha: string } & WindowFailure> }
+/** Failed extraction attempts of one window (by rendered-text sha), the last error, and (once failed) the keys of the earlier windows whose facts it keeps. */
+interface WindowFailure { attempts: number; error: string; keeps?: string[] }
+/** An earlier window whose facts still stand though no current window holds it yet (an unsettled run left it): its key and span. */
+interface StaleWindow { key: string; span?: Span }
+interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; retries?: Array<{ sha: string } & WindowFailure>;
+ stale?: StaleWindow[] }
/** One window of the stream: `reused` (an earlier run's facts stand), `todo`, `extracted` by this run, or `failed` past the limit. */
interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow; span: Span;
state: 'reused' | 'todo' | 'extracted' | 'failed'; facts: number; failed?: WindowFailure }
@@ -98,7 +110,7 @@ type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;
function rowOutput(row: SegmentDerivationRow | undefined): RowOutput {
const output = row?.output as Partial<RowOutput> | null | undefined;
return { windows: Array.isArray(output?.windows) ? output.windows : [], starts_group: output?.starts_group, prev: output?.prev,
- pattern: output?.pattern ?? null, retries: Array.isArray(output?.retries) ? output.retries : [] };
+ pattern: output?.pattern ?? null, retries: Array.isArray(output?.retries) ? output.retries : [], stale: Array.isArray(output?.stale) ? output.stale : [] };
}
const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });
@@ -116,27 +128,56 @@ async function conversationContext(engine: BrainEngine, page: Page, gapMinutes:
* with facts standing (reused or extracted). A position orders by its occurrence's place on the page, then its
* ordinal; a window in an occurrence that left the page is never covered.
*/
-function coveredKeys(windows: readonly StreamWindow[], earlier: ReadonlyArray<{ key: string; span?: Span }>, place: ReadonlyMap<number, number>): string[] {
- const at = (occurrenceId: number, n: number) => { const p = place.get(occurrenceId); return p === undefined ? null : p * 1_000_000_000 + n; };
- const runs: Array<[number, number]> = [];
- let open: [number, number] | null = null;
+function coveredKeys(windows: readonly StreamWindow[], earlier: readonly StaleWindow[], place: ReadonlyMap<number, number>): string[] {
+ const runs: Array<[Point, Point]> = [];
+ let open: [Point, Point] | null = null;
for (const w of windows) {
if (w.state !== 'reused' && w.state !== 'extracted') { open = null; continue; }
- const start = at(w.span[0], w.span[1])!;
- const end = at(w.span[2], w.span[3])!;
+ const [start, end] = ends(w.span, place) as [Point, Point];
if (open) open[1] = end;
else runs.push(open = [start, end]);
}
return earlier.filter(e => {
- const start = e.span ? at(e.span[0], e.span[1]) : null;
- const end = e.span ? at(e.span[2], e.span[3]) : null;
- return start !== null && end !== null && runs.some(([a, b]) => a <= start && end <= b);
+ const span = e.span ? ends(e.span, place) : null;
+ return span !== null && runs.some(([a, b]) => before(a, span[0]) && before(span[1], b));
}).map(e => e.key);
}
-/** Whether a window's extraction error counts against the window: not an abort, a cap, or a provider-wide failure. */
-const windowFailure = (error: unknown, signal: AbortSignal | undefined) =>
- !signal?.aborted && !(error instanceof BudgetExhausted) && !(error instanceof Error && error.name === 'AbortError') && classifyGlobalLlmError(error) === null;
+/** A message piece's place on the page: [occurrence place, ordinal, piece], ordered lexicographically. */
+type Point = [number, number, number];
+const before = (a: Point, b: Point) => a[0] !== b[0] ? a[0] < b[0] : a[1] !== b[1] ? a[1] < b[1] : a[2] <= b[2];
+/** A span's first and last point, or null when either occurrence left the page. */
+function ends(span: Span, place: ReadonlyMap<number, number>): [Point, Point] | null {
+ const first = place.get(span[0]);
+ const last = place.get(span[3]);
+ return first === undefined || last === undefined ? null : [[first, span[1], span[2]], [last, span[4], span[5]]];
+}
+
+/** Keys of earlier windows whose span overlaps `span` (a failed window keeps their facts). */
+function overlappingKeys(span: Span, earlier: readonly StaleWindow[], place: ReadonlyMap<number, number>): string[] {
+ const mine = ends(span, place);
+ if (!mine) return [];
+ return earlier.filter(e => {
+ const theirs = e.span ? ends(e.span, place) : null;
+ return theirs !== null && before(theirs[0], mine[1]) && before(mine[0], theirs[1]);
+ }).map(e => e.key);
+}
+
+/** extract.ts failure reasons caused by the window itself (its output or its content), which repeat until it changes. */
+const WINDOW_SPECIFIC_REASONS: ReadonlySet<string> = new Set(['malformed_output', 'truncated_output', 'refusal', 'content_filter']);
+
+/**
+ * Whether a window's extraction error counts against the window: a failure of the window's own (WINDOW_SPECIFIC_REASONS,
+ * or a provider refusal of its own input such as a context-length error). A transport, provider, auth, rate-limit,
+ * 5xx, timeout or abort failure, a cap, or an error with no extraction reason never counts.
+ */
+function windowFailure(error: unknown, signal: AbortSignal | undefined): boolean {
+ if (signal?.aborted) return false;
+ const reason = (error as { extractionReason?: unknown } | null)?.extractionReason;
+ if (typeof reason !== 'string') return false;
+ if (WINDOW_SPECIFIC_REASONS.has(reason)) return true;
+ return reason === 'provider_error' && providerItemRefusal((error as { cause?: unknown }).cause) !== null;
+}
/**
* One segmented page's conversation facts, incrementally (module doc). `gapMinutes` is the page's own
@@ -173,15 +214,17 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
// Earlier windows of the occurrences the stream covers (and of retired ones): reusable by rendered text under the same
// context, and candidates to clear once the current windows cover their messages.
const reusable = new Map<string, Array<{ occurrenceId: number; record: WindowRecord }>>();
- const earlier: Array<{ key: string; span?: Span }> = [];
+ const earlier: Array<StaleWindow & { occurrenceId: number }> = [];
const failures = new Map<string, WindowFailure>();
- let pattern = prior.map(row => rowOutput(row).pattern).find(Boolean) ?? null;
+ // The page's grammar: the one a current row recorded (same text, version and context), else the head's (below).
+ let pattern: string | null = plan.current.map(row => rowOutput(row).pattern).find(Boolean) ?? null;
for (const row of prior) {
if ((position.get(row.occurrenceId) ?? Infinity) < from) continue;
const same = row.version === CONVERSATION_FACTS_DERIVATION_VERSION && hex(row.contextHash) === hex(contextHash);
const output = rowOutput(row);
+ for (const stale of output.stale ?? []) earlier.push({ ...stale, occurrenceId: row.occurrenceId });
for (const record of output.windows) {
- earlier.push({ key: keyOf(row.occurrenceId, record), span: record.span });
+ earlier.push({ key: keyOf(row.occurrenceId, record), span: record.span, occurrenceId: row.occurrenceId });
if (same && !(record.failed && opts.retryFailed)) reusable.set(record.sha, [...(reusable.get(record.sha) ?? []), { occurrenceId: row.occurrenceId, record }]);
}
if (same && !opts.retryFailed) for (const { sha, attempts, error } of output.retries ?? []) failures.set(sha, { attempts, error });
@@ -192,7 +235,9 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const startsGroup = new Map<number, boolean>();
const ordinals = new Map<number, number>();
const pageTitle = page.title || page.slug;
+ if (!pattern && from < liveIds.length) pattern = detectConversationPattern(await truthLead(engine, page.id, PATTERN_HEAD_CHARS), page);
const streamOpts = { page, gapMinutes: opts.gapMinutes, sinceIso: opts.sinceIso, pattern };
+ let parsedMessages = 0;
const texts = new Map<number, string>();
const readText = async (i: number) => {
const cached = texts.get(i);
@@ -206,8 +251,8 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
let start = end - 1;
while (start > from && !startsConversationRun(occurrences, start, await readText(start), await readText(start - 1), streamOpts)) start--;
const runWindows: StreamWindow[] = [];
- const spanOf = (first: MessagePosition, last: MessagePosition): Span => [liveIds[first.owner]!, first.n, liveIds[last.owner]!, last.n];
- pattern = streamOpts.pattern = await streamConversationWindows(occurrences, start, end, streamOpts, readText, {
+ const spanOf = (first: MessagePosition, last: MessagePosition): Span => [liveIds[first.owner]!, first.n, first.piece, liveIds[last.owner]!, last.n, last.piece];
+ const streamed = await streamConversationWindows(occurrences, start, end, streamOpts, readText, {
window(first, last, seg) {
const owner = liveIds[first.owner]!;
const ordinal = ordinals.get(owner) ?? 0;
@@ -224,6 +269,8 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
},
occurrence(index, starts) { startsGroup.set(liveIds[index]!, starts); },
});
+ pattern = streamOpts.pattern = streamed.pattern;
+ parsedMessages += streamed.messages;
for (const i of [...texts.keys()]) if (i > start) texts.delete(i);
windows.unshift(...runWindows);
return { start, windows: runWindows };
@@ -253,6 +300,8 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
unchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;
}
const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;
+ const clear = settled ? [] : [...batch.keys, ...coveredKeys(windows, earlier.filter(e => !reused.has(e.key)), position).filter(key => !cleared.has(key))];
+ const gone = new Set([...cleared, ...clear]);
const owned = new Map<number, StreamWindow[]>();
for (const w of windows) owned.set(w.owner, [...(owned.get(w.owner) ?? []), w]);
// Rows of the occurrences this run finished or reached; an occurrence it never reached keeps its row (still unsettled).
@@ -261,24 +310,30 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const records: WindowRecord[] = mine.filter(w => w.state !== 'todo').map(w => ({ ordinal: w.window.window_ordinal, sha: w.window.window_text_sha,
facts: w.facts, span: w.span, ...(w.failed && w.state === 'failed' ? { failed: w.failed } : {}) }));
const retries = mine.flatMap(w => { const failure = w.state === 'todo' ? failures.get(w.window.window_text_sha) : undefined; return failure ? [{ sha: w.window.window_text_sha, ...failure }] : []; });
- const failed = records.filter(r => r.failed).map(r => ({ ordinal: r.ordinal, ...r.failed! }));
+ const failed = records.filter(r => r.failed).map(r => ({ ordinal: r.ordinal, attempts: r.failed!.attempts, error: r.failed!.error }));
const finished = records.length === mine.length;
- if (!finished && !records.length && occurrenceId !== stopOwner) return [];
+ const recorded = new Set(records.map(r => keyOf(occurrenceId, r)));
+ // Earlier windows of this occurrence whose facts this unsettled run neither replaced nor cleared stay on its row.
+ const stale = settled ? [] : earlier.filter(e => e.occurrenceId === occurrenceId && !reused.has(e.key) && !gone.has(e.key) && !recorded.has(e.key))
+ .map(({ key, span }) => ({ key, span }));
+ if (!finished && !records.length && !stale.length && occurrenceId !== stopOwner) return [];
return [{ pageId: page.id, kind: KIND, occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION, segmentSha256: live[streamedFrom + k]!.sha256,
contextHash, state: finished && !opts.sinceIso ? 'done' : 'partial',
- output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}) },
+ output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}), ...(stale.length ? { stale } : {}) },
receipt: !finished ? { kind: 'unread_windows', pipeline: KIND, reason: stop ?? 'in_progress', windows_read: records.length, windows_total: mine.length }
: failed.length ? { kind: 'failed_windows', pipeline: KIND, windows: failed } : null }];
});
- const keep = settled ? [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => keyOf(id, w))),
- ...windows.map(w => sourceWindowKey(w.window))] : null;
- const clear = settled ? [] : [...batch.keys, ...coveredKeys(windows, earlier.filter(e => !reused.has(e.key)), position).filter(key => !cleared.has(key))];
+ // A failed window keeps the facts of the earlier windows it overlaps (`keeps`) until it is extracted.
+ const settledWindows = [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => ({ key: keyOf(id, w), failed: w.failed }))),
+ ...windows.map(w => ({ key: sourceWindowKey(w.window), failed: w.state === 'failed' ? w.failed : undefined }))];
+ const anyFailed = settledWindows.some(w => w.failed);
+ const keep = settled ? settledWindows.flatMap(w => [w.key, ...(w.failed?.keeps ?? [])]) : null;
const outcome = !settled ? null : keep!.length ? terminalAuditFact(page.slug, 0, versionToken)
: nonExtractableAuditFact(page.slug, 0, versionToken, 'fewer than two eligible messages');
const moves = [...pendingMoves];
const out = await writeDerivedFacts(engine, sourceId, page.slug, async db => {
const published = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...batch.rows, outcome] : batch.rows,
- { scope: 'window', segments: { windows: batch.windows, moves, keep, clear, retireUnanchored: settled } });
+ { scope: 'window', segments: { windows: batch.windows, moves, keep, clear, retireUnanchored: settled && !anyFailed } });
if (derived.length) await db.upsertSegmentDerivations(derived);
if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
return published;
@@ -317,7 +372,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
failures.set(sha, failure);
if (failure.attempts < WINDOW_FAILURE_LIMIT) throw error;
failures.delete(sha);
- Object.assign(w, { state: 'failed', failed: failure, text: null });
+ Object.assign(w, { state: 'failed', failed: { ...failure, keeps: overlappingKeys(w.span, earlier.filter(e => !reused.has(e.key)), position) }, text: null });
stopOwner = null;
process.stderr.write(`[extract-conversation-facts] ${page.slug}: window ${w.window.window_ordinal} of occurrence ${w.owner} failed ${failure.attempts} runs (${failure.error}); skipped, gbrain doctor lists it, --force retries it\n`);
continue;
@@ -350,6 +405,15 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
result.resolution_errors += resolution.resolution_errors;
}
+ if (parsedMessages === 0 && earlier.length > 0) {
+ // Occurrences that had windows parsed into no message (a changed format the grammar no longer reads, a parser
+ // fault): clearing or settling would delete every fact they held. Nothing is published; the receipt says why.
+ await setExtractionReceipt(engine, page.id, KIND, { kind: 'no_messages', pipeline: KIND, processed_chars: 0 });
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: no message parsed from occurrences that had ${earlier.length} window(s); its facts were kept, nothing settled\n`);
+ result.pages_failed++;
+ recordFailedPage(result, page.slug, 'no message parsed from occurrences that had windows; facts kept for replay');
+ return { newestEnd: null };
+ }
const { unchanged, keep, outcome } = await publish(true);
await setExtractionReceipt(engine, page.id, KIND, null);
if (!unchanged) {
diff --git a/src/core/facts/conversation-stream.ts b/src/core/facts/conversation-stream.ts
index 441101ec81..4d35b67432 100644
--- a/src/core/facts/conversation-stream.ts
+++ b/src/core/facts/conversation-stream.ts
@@ -2,16 +2,17 @@
* PR 4 (Wave B incremental derivation, transcripts): the conversation windows of a segmented page, streamed across its
* occurrences (wave-b spec 8.2 "Conversation facts").
*
- * Messages are parsed one occurrence at a time under one grammar for the whole page: the segmenter's pattern (the first
- * occurrence's entry state), else the pattern an earlier run recorded (`opts.pattern`), else the pattern the first
- * parsed text detects. Once known, every later text is parsed under it without detection, so a continuation that would
+ * Messages are parsed one occurrence at a time under one grammar for the whole page: `opts.pattern` (the caller's: a
+ * current run's recorded grammar, or the one the page's head detects), else the pattern the first parsed text detects.
+ * Once known, every later text is parsed under it without detection, so a continuation that would
* fail the detector's density floor on its own is still read as the message it continues. The last message of an
* occurrence may continue into the next one, so it is held back and parsed again with the next occurrence's text, from
* its anchor line and with the day-header date in force there; an occurrence with no anchor line only extends the held
* message, unparsed, so a message spanning many occurrences is parsed once. The windows (createWindowStream, the same
* gap groups and bounds as the whole-page pass) then run over message boundaries, never over segment cuts, so a window
* can span a cut. Each window is owned by the occurrence its first message starts in and carries the positions of its
- * first and last message (the occurrence each starts in and its ordinal among the messages starting there). Reads one
+ * first and last message piece (the occurrence each message starts in, its ordinal among the messages starting there,
+ * and which piece of an oversized message the window starts or ends with). Reads one
* occurrence's text at a time and holds the carried message and the open window, never the whole body.
*
* A run of occurrences is streamed on its own when the occurrence after it opens a gap group: its windows then equal
@@ -27,8 +28,11 @@ import type { ConversationOccurrence } from '../page-body/segment-conversation.t
import type { ConversationMessage, ConversationSegment } from './conversation-types.ts';
import { DEFAULT_SEGMENT_GAP_MINUTES, MAX_PAGE_SEGMENT_GAP_MINUTES, createWindowStream } from './conversation-windows.ts';
-/** Where a message starts: the occurrence (an index into the occurrences) its anchor line is in, and its ordinal among the messages starting there. */
-export interface MessagePosition { owner: number; n: number }
+/**
+ * Where a piece of a message is: the occurrence (an index into the occurrences) the message's anchor line is in, its
+ * ordinal among the messages starting there, and the piece of it (an oversized message is split into pieces; 0 otherwise).
+ */
+export interface MessagePosition { owner: number; n: number; piece: number }
export interface ConversationStreamSink {
/** A closed window: the positions of its first message (whose occurrence owns the window) and its last. */
@@ -41,7 +45,7 @@ export interface ConversationStreamOpts {
page: Page;
gapMinutes: number | null;
sinceIso?: string;
- /** The grammar an earlier run of this page recorded, used when the segmenter recorded none. */
+ /** The page's grammar, when the caller knows it. */
pattern?: string | null;
}
@@ -51,9 +55,10 @@ interface Carry { parts: string[]; date: string | undefined; owner: number; regi
const gapMinutesFor = (opts: ConversationStreamOpts, patternId: string | null) =>
opts.gapMinutes ?? (patternId === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);
-/** The page's grammar before anything is parsed: the segmenter's pattern, else the recorded one. */
-const knownPattern = (occurrences: readonly ConversationOccurrence[], opts: ConversationStreamOpts) =>
- occurrences[0]?.conversation?.pattern ?? opts.pattern ?? null;
+/** The pattern the whole-page pass would pick for a page whose parser input starts with `head`, or null. */
+export function detectConversationPattern(head: string, page: Page): string | null {
+ return parseConversation(head, { page }).matched_pattern_id ?? null;
+}
/** Parse `text` under built-in `patternId` without detection, or detect the pattern when there is none yet. */
function parseUnder(text: string, patternId: string | null, opts: ConversationStreamOpts, fallbackDate: string | undefined): { messages: ConversationMessage[]; patternId: string | null } {
@@ -105,7 +110,7 @@ export function startsConversationRun(occurrences: readonly ConversationOccurren
opts: ConversationStreamOpts): boolean {
if (index === 0) return true;
const occurrence = occurrences[index]!;
- const parsed = parseUnder(text, knownPattern(occurrences, opts), opts, occurrence.conversation?.fallbackDate ?? undefined);
+ const parsed = parseUnder(text, opts.pattern ?? null, opts, occurrence.conversation?.fallbackDate ?? undefined);
const { patternId } = parsed;
const first = parsed.messages[0] ? Date.parse(parsed.messages[0].timestamp) : NaN;
const at = patternId ? anchorOffset(patternId, previous, true) : -1;
@@ -118,20 +123,23 @@ export function startsConversationRun(occurrences: readonly ConversationOccurren
/**
* Stream the windows of occurrences `from`..`to` (exclusive) of a segmented conversation page (module doc) into `sink`,
- * and return the grammar they were parsed under. `to` is the page's end or an occurrence whose first message opens a
- * gap group; the text before that occurrence's first anchor line still belongs to the last message before it.
+ * and return the grammar they were parsed under and how many messages were parsed. `to` is the page's end or an
+ * occurrence whose first message opens a gap group; the text before that occurrence's first anchor line still belongs
+ * to the last message before it.
*/
export async function streamConversationWindows(occurrences: readonly ConversationOccurrence[], from: number, to: number, opts: ConversationStreamOpts,
- readText: (index: number) => Promise<string>, sink: ConversationStreamSink): Promise<string | null> {
+ readText: (index: number) => Promise<string>, sink: ConversationStreamSink): Promise<{ pattern: string | null; messages: number }> {
const pageTitle = opts.page.title || opts.page.slug;
- let patternId = knownPattern(occurrences, opts);
- let stream: ReturnType<typeof createWindowStream<MessagePosition>> | null = null;
+ let patternId = opts.pattern ?? null;
+ let parsedMessages = 0;
+ let stream: ReturnType<typeof createWindowStream<{ owner: number; n: number }>> | null = null;
let carry: Carry | null = null;
- let counted: MessagePosition = { owner: -1, n: 0 };
- const positionOf = (owner: number): MessagePosition => {
+ let counted = { owner: -1, n: 0 };
+ const positionOf = (owner: number) => {
if (counted.owner !== owner) counted = { owner, n: 0 };
return { owner, n: counted.n++ };
};
+ const at = (position: { owner: number; n: number }, piece: number): MessagePosition => ({ ...position, piece });
const joint = (region: string, next: string) => (region === next ? '' : '\n\n');
for (let i = from; i < to; i++) {
const occurrence = occurrences[i]!;
@@ -153,8 +161,9 @@ export async function streamConversationWindows(occurrences: readonly Conversati
const fallbackDate: string | undefined = carry ? carry.date : occurrence.conversation?.fallbackDate ?? undefined;
const parsed = parseUnder(chunk, patternId, opts, fallbackDate);
patternId = parsed.patternId;
- stream ??= createWindowStream<MessagePosition>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });
+ stream ??= createWindowStream<{ owner: number; n: number }>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });
let messages = parsed.messages;
+ parsedMessages += messages.length;
const firstOwner = carry ? carry.owner : i;
let next: Carry | null = null;
if (i < to - 1 && messages.length && patternId) {
@@ -163,6 +172,7 @@ export async function streamConversationWindows(occurrences: readonly Conversati
const at: number = carried.length + inText;
next = { parts: [chunk.slice(at)], date: dateAt(chunk, at, fallbackDate), owner: i, region };
messages = messages.slice(0, -1);
+ parsedMessages--;
}
}
let startsGroup: boolean | null = null;
@@ -170,11 +180,11 @@ export async function streamConversationWindows(occurrences: readonly Conversati
const owner = k === 0 ? firstOwner : i;
const pushed = stream!.push(message, positionOf(owner));
if (pushed.accepted && owner === i && startsGroup === null) startsGroup = pushed.startsGroup;
- for (const w of pushed.windows) sink.window(w.tag, w.last, w.seg);
+ for (const w of pushed.windows) sink.window(at(w.tag, w.firstPiece), at(w.last, w.lastPiece), w.seg);
});
sink.occurrence(i, startsGroup === true);
carry = next;
}
- for (const w of stream?.end() ?? []) sink.window(w.tag, w.last, w.seg);
- return patternId;
+ for (const w of stream?.end() ?? []) sink.window(at(w.tag, w.firstPiece), at(w.last, w.lastPiece), w.seg);
+ return { pattern: patternId, messages: parsedMessages };
}
diff --git a/src/core/facts/conversation-window-extract.ts b/src/core/facts/conversation-window-extract.ts
index b17b750373..3e77419b18 100644
--- a/src/core/facts/conversation-window-extract.ts
+++ b/src/core/facts/conversation-window-extract.ts
@@ -72,8 +72,8 @@ export async function extractConversationWindow(run: ConversationWindowRun, page
if (!extraction.ok) {
if (extraction.error instanceof BudgetExhausted) throw extraction.error;
const detail = extraction.error instanceof Error ? `: ${extraction.error.message}` : '';
- throw Object.assign(new Error(`segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`),
- { extractionReason: extraction.reason });
+ throw Object.assign(new Error(`segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`,
+ extraction.error === undefined ? undefined : { cause: extraction.error }), { extractionReason: extraction.reason });
}
extracted = extraction.facts;
}
diff --git a/src/core/facts/conversation-windows.ts b/src/core/facts/conversation-windows.ts
index e4f15859f1..a8f85cab31 100644
--- a/src/core/facts/conversation-windows.ts
+++ b/src/core/facts/conversation-windows.ts
@@ -134,8 +134,11 @@ function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars:
return splitTurnText(m.text, budget).map((text) => ({ ...m, text }));
}
-/** A closed window, the tag of the message it starts with and the tag of the message it ends with. */
-export interface TaggedWindow<Tag> { seg: ConversationSegment; tag: Tag; last: Tag }
+/**
+ * A closed window: the tag of the message it starts with and of the message it ends with, and which piece of each
+ * (an oversized turn is split into pieces; 0 for a turn that fits whole).
+ */
+export interface TaggedWindow<Tag> { seg: ConversationSegment; tag: Tag; last: Tag; firstPiece: number; lastPiece: number }
/** What one pushed message did: dropped (filtered out), or accepted, opening a new gap group or not. */
export type WindowPush<Tag> = { accepted: false; windows: [] } | { accepted: true; startsGroup: boolean; windows: TaggedWindow<Tag>[] };
@@ -157,9 +160,11 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {
let cur: ConversationMessage[] = [];
let curTag: Tag | undefined;
let lastTag: Tag | undefined;
+ let firstPiece = 0;
+ let lastPiece = 0;
let held: TaggedWindow<Tag>[] = [];
const close = (out: TaggedWindow<Tag>[]) => {
- if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag, last: lastTag as Tag });
+ if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag, last: lastTag as Tag, firstPiece, lastPiece });
cur = [];
if (groupMessages >= MIN_SEGMENT_MESSAGES) { out.push(...held); held = []; }
};
@@ -178,12 +183,13 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {
lastTs = ts;
groupMessages++;
const parts = renderedLength(pageTitle, [m]) <= maxChars ? [m] : splitOversizedTurn(m, pageTitle, maxChars);
- for (const part of parts) {
+ parts.forEach((part, piece) => {
if (cur.length >= maxMessages || (cur.length > 0 && renderedLength(pageTitle, [...cur, part]) > maxChars)) close(windows);
- if (cur.length === 0) curTag = tag;
+ if (cur.length === 0) { curTag = tag; firstPiece = piece; }
lastTag = tag;
+ lastPiece = piece;
cur.push(part);
- }
+ });
if (groupMessages >= MIN_SEGMENT_MESSAGES && held.length) { windows.push(...held); held = []; }
return { accepted: true, startsGroup, windows };
},
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index e955ddbe93..c87eb4bbcc 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -246,12 +246,13 @@ export function estimateFactsExtractionUsd(model: string, chars: number, maxOutp
}
/**
- * A metered step's tracker, which also sums what the provider may have billed: every attempt at its reported usage (a
- * success without reported usage at its estimate), and every failed attempt the provider may have billed at what the
- * gateway recorded for it, its reported usage topped up with the pessimistic fallback (the attempt's worst case): a
- * timeout, an abort, a reset connection, partial usage. Only an attempt the provider refused with an error status and
- * no usage (failedCallUsage's `rejected`: a rate limit, an auth or server error) and an embedding that failed
- * without reported usage are booked as nothing.
+ * A metered step's tracker, which also sums what the provider may have billed: every answered attempt at its reported
+ * usage (a success without reported usage at its estimate), and every failed call at what failedCallUsage says its
+ * attempts may have billed (`billed`): each attempt, a retry wrapper's every entry included, at its reported usage
+ * topped up with the attempt's worst case, unless the provider definitively refused it before generating (a 4xx other
+ * than 408 or 499, with no usage). A 5xx, a 529, a proxy's 499 or 504, a timeout, an abort or a reset connection is
+ * booked. An embedding that failed without reported usage is booked as nothing (the embedding ledger's own rule).
+ * The step runs with the SDK's hidden retries off (providerRetries 0), so each attempt is a call it reserved for.
*
* Each attempt is also reserved and recorded on the caller's tracker (`parent`) as it happens, so the caller's cap
* (`--max-usd`) counts every in-flight attempt of every worker, its own outstanding reservations included.
@@ -273,9 +274,10 @@ class MeteredStepTracker extends BudgetTracker {
override record(actual: Parameters<BudgetTracker['record']>[0]): void {
const failed = actual.failed === true || (actual.label?.endsWith('.failed') ?? false);
- const unbilled = failed && (actual.rejected === true || ((actual.kind ?? 'chat') === 'embed' && actual.estimated === true));
+ const tokens = failed && actual.billed ? actual.billed : { inputTokens: actual.inputTokens, outputTokens: actual.outputTokens ?? 0 };
+ const unbilled = failed && (((actual.kind ?? 'chat') === 'embed' && actual.estimated === true) || (tokens.inputTokens === 0 && tokens.outputTokens === 0));
if (!unbilled) {
- const cost = usageCostUsd(actual.modelId, actual.inputTokens, actual.outputTokens ?? 0, actual.kind ?? 'chat', this.pricing);
+ const cost = usageCostUsd(actual.modelId, tokens.inputTokens, tokens.outputTokens, actual.kind ?? 'chat', this.pricing);
this.billedAttempts++;
if (cost === null) this.unpricedAttempts++;
else this.billedUsd += cost;
@@ -289,17 +291,17 @@ class MeteredStepTracker extends BudgetTracker {
* Run one paid derivation step on `page` under its family's cap (wave-b spec 8.3): reserve `estimateUsd` (every attempt the
* step may make), run `call`, and book what its provider calls actually cost, read from a budget tracker scoped to the call.
* Every attempt the provider answered is booked whatever the step's outcome (a truncated, malformed or refused answer, a
- * throw after the provider answered); an attempt that failed with no provider-reported usage (a rate limit, an auth or
- * server error, an embedding that failed) is not; an unpriced model books the reservation; a step with no billed attempt
- * (the provider was never called or never answered) books nothing. The attempts are recorded on the caller's tracker too, and the caller's
- * remaining cap bounds them.
+ * throw after the provider answered), and so is every failed attempt it may have billed (MeteredStepTracker); one it
+ * definitively refused before generating (a rate limit, an auth error) and a failed embedding are not; an unpriced
+ * model books the reservation; a step with no billed attempt books nothing. The attempts are reserved and recorded on
+ * the caller's tracker too, so the caller's cap bounds them.
*/
export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, signature: PageSpendSignature, estimateUsd: number,
call: () => Promise<T>, opts: { pricingOverrides?: PricingOverrides } = {}): Promise<{ refused: Extract<PageSpendDecision, { kind: 'refused' }> } | { value: T }> {
const decision = await reservePageSpend(engine, page, signature, estimateUsd);
if (decision.kind === 'refused') return { refused: decision };
if (decision.kind === 'unmetered') return { value: await call() };
- const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides }, getCurrentBudgetTracker(), opts.pricingOverrides);
+ const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides, providerRetries: 0 }, getCurrentBudgetTracker(), opts.pricingOverrides);
try {
return { value: await withBudgetTracker(tracker, call) };
} finally {
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
index 16751483ef..cc494d0fa8 100644
--- a/test/helpers/conversation-facts-incremental-cases.ts
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -105,7 +105,7 @@ export function paidTransport(o: ChatOpts): Promise<ChatResult> {
/**
* One extraction run with a fake extractor; `calls` lists every window text it was handed, in call order. `paid`: each
* window also calls the gateway (install paidTransport), so the call is booked. `failAt`: the extractor throws on that
- * call (1-based) after the provider answered; `failOn`: it throws on every window text the predicate accepts;
+ * call (1-based) after the provider answered; `failOn`: it fails with the window's own malformed output on every window text the predicate accepts;
* `abortAfter`: the run is aborted after that many calls; `segmentLimit`: at most that many windows per page.
*/
export async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean; paid?: boolean; failAt?: number; failOn?: (text: string) => boolean;
@@ -118,7 +118,7 @@ export async function extract(engine: BrainEngine, slug: string, opts: { force?:
calls.push(input.turnText);
if (opts.paid) await gatewayChat({ model: PAID_MODEL, messages: [{ role: 'user', content: input.turnText }], maxTokens: 64 });
if (calls.length === opts.failAt) throw new Error('fake extractor failure after the provider answered');
- if (opts.failOn?.(input.turnText)) throw new Error('fake extractor failure on this window');
+ if (opts.failOn?.(input.turnText)) throw Object.assign(new Error('fake extractor: malformed output on this window'), { extractionReason: 'malformed_output' });
if (calls.length === opts.abortAfter) controller.abort();
return [{ fact: `Alice Example noted window ${sha(input.turnText).slice(0, 12)}`, kind: 'fact', entity_slug: null, source: SOURCE }];
} }, controller.signal);
diff --git a/test/helpers/conversation-facts-recovery-cases.ts b/test/helpers/conversation-facts-recovery-cases.ts
index 75f548953f..76502a86ee 100644
--- a/test/helpers/conversation-facts-recovery-cases.ts
+++ b/test/helpers/conversation-facts-recovery-cases.ts
@@ -9,7 +9,11 @@
* whole-page windows and settles only then; a checkpoint write that fails keeps the window moves it carried for the
* write that follows, so no re-anchored fact is lost; a window that fails run after run is marked failed after
* WINDOW_FAILURE_LIMIT runs and the older windows are extracted, doctor names it and --force retries it.
- * 2. Fails when: coverage is judged by timestamps (one window "covers" every message at the page date), a continuation
+ * Round 4: a one-window run on oversized turns clears only the pieces that window holds; a page re-imported in
+ * another chat format is parsed in that format; a run parsing no message where windows were keeps every fact and
+ * leaves a no_messages receipt; provider-wide failures (auth, 503) never count against a window; a failed window
+ * keeps the facts of the window it replaced until it is extracted.
+ * 2. Fails when: coverage is judged by timestamps or by a message shared by many pieces, a stale grammar pins the page, (one window "covers" every message at the page date), a continuation
* is dropped by re-detecting the grammar per occurrence, moves are dropped before their write commits, or one
* failing window stalls every older window of the page.
*/
@@ -27,7 +31,8 @@ import { TERMINAL_AUDIT_SOURCE } from '../../src/core/facts/audit-sources.ts';
import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';
import type { DoctorContext } from '../../src/commands/doctor/context.ts';
import type { Check } from '../../src/commands/doctor.ts';
-import { chatDays, chatPage, derivations, extract, factsOf, turns } from './conversation-facts-incremental-cases.ts';
+import { __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
+import { chatDays, chatPage, derivations, extract, factsOf, PAID_MODEL, paidTransport, turns } from './conversation-facts-incremental-cases.ts';
const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast'];
const prose = (seed: number, words: number) => Array.from({ length: words }, (_, i) => WORDS[(seed * 7 + i * 3) % WORDS.length]).join(' ');
@@ -173,4 +178,115 @@ export function defineConversationFactsRecoveryCases(opts: { getBrain: () => App
const forced = await extract(brain.engine, slug, { force: true });
expect({ calls: forced.calls, receipts: (await derivations(brain.engine, slug)).receipts.filter(Boolean) }).toEqual({ calls: [stuck!], receipts: [] });
}, 600_000);
+
+ test('a one-window run on a page of oversized turns clears only the pieces that window holds', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/oversized-turns-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ // Thirty turns of about 100 KB each, a minute apart: each is split into many pieces, one window per few pieces.
+ const lines = ['## 2025-04-01', ''];
+ for (let t = 0; t < 30; t++) lines.push(`**${['Alice Example', 'Bob Example'][t % 2]}** (9:${String(t).padStart(2, '0')} AM): ${prose(t, 14_000)}.`, '');
+ await brain.seed(slug, chatPage('Oversized T1', lines.join('\n')));
+ const all = await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ expect(before.length).toBe(all.calls.length);
+ expect(before.length).toBeGreaterThan(60);
+ await brain.seed(slug, chatPage('Oversized T2', (await brain.body(slug)).truth));
+ const limited = await extract(brain.engine, slug, { segmentLimit: 1 });
+ const after = await factsOf(brain.engine, slug);
+ expect({ calls: limited.calls.length, after: after.length, cleaned: limited.result.orphan_facts_cleaned, kept: before.filter(f => after.some(a => a.id === f.id)).length })
+ .toEqual({ calls: 1, after: before.length, cleaned: 1, kept: before.length - 1 });
+ }, 600_000);
+
+ test('a page re-imported in another chat format is parsed in its new format, not the grammar its old rows recorded', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/reformatted-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Reformatted', chatDays(3400, 100, 23)));
+ await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ expect(before.length).toBeGreaterThan(100);
+ await brain.seed(slug, chatPage('Reformatted', timeless(9000, 3)));
+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
+ const truth = (await brain.body(slug)).truth;
+ const expected = splitIntoSegments(parseConversation(truth, { page }).messages, { pageTitle: 'Reformatted' }).map(seg => renderSegmentForExtraction('Reformatted', seg));
+ expect(parseConversation(truth, { page }).matched_pattern_id).toBe('plain-role-no-time');
+ const { calls, result } = await extract(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect({ calls: calls.length, same: [...calls].sort().join('\n') === [...expected].sort().join('\n'), nonExtractable: result.pages_marked_non_extractable,
+ facts: (await factsOf(brain.engine, slug)).length, states: [...new Set(rows.states)] })
+ .toEqual({ calls: expected.length, same: true, nonExtractable: 0, facts: expected.length, states: ['done'] });
+ }, 600_000);
+
+ test('a run that parses no message from occurrences that had windows keeps their facts, settles nothing and leaves a receipt doctor lists', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/unparsed-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Unparsed', chatDays(3500, 100, 24)));
+ await extract(brain.engine, slug);
+ const before = (await factsOf(brain.engine, slug)).map(f => f.id);
+ const prose = Array.from({ length: 6000 }, (_, i) => `Paragraph ${i} of the notes: the roadmap review moved to next quarter and the budget stays flat.`).join('\n\n');
+ await brain.seed(slug, chatPage('Unparsed', prose));
+ const { calls, result } = await extract(brain.engine, slug);
+ expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,
+ facts: (await factsOf(brain.engine, slug)).map(f => f.id), stamped: await terminalStamps(brain.engine, slug) })
+ .toEqual({ calls: 0, failed: 1, nonExtractable: 0, cleaned: 0, facts: before, stamped: 0 });
+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;
+ const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[] }> }).groups;
+ expect(groups.some(g => g.pipeline === 'conversation_facts' && g.kind === 'no_messages' && g.samples.includes(`default:${slug}`))).toBe(true);
+ }, 600_000);
+
+ test('provider-wide failures (an auth error, a 503) never count against a window: it is never marked failed and extracts once the provider recovers', async () => {
+ const brain = opts.getBrain();
+ await caps(brain.engine, 'off');
+ await brain.engine.setConfig('facts.extraction_model', PAID_MODEL);
+ try {
+ for (const [label, failure] of [['auth', () => Object.assign(new Error('invalid x-api-key'), { status: 401 })], ['503', () => Object.assign(new Error('upstream unavailable'), { status: 503 })]] as const) {
+ const slug = `notes/provider-down-${label}-${randomUUID().slice(0, 8)}`;
+ await brain.seed(slug, chatPage('Provider down', chatDays(3600, 100, 25)));
+ let attempts = 0;
+ __setChatTransportForTests(async () => { attempts++; throw failure(); });
+ const runs: Array<{ attempts: number; failed: number }> = [];
+ for (let run = 0; run < WINDOW_FAILURE_LIMIT + 2; run++) {
+ attempts = 0;
+ const result = await extractProductionRun(brain.engine, slug);
+ runs.push({ attempts, failed: result.pages_failed });
+ }
+ const receipts = (await derivations(brain.engine, slug)).receipts.filter(Boolean).map(r => (r as { kind: string }).kind);
+ __setChatTransportForTests(paidTransport);
+ const recovered = await extractProductionRun(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect({ label, runs, receipts, recovered: recovered.pages_failed, states: [...new Set(rows.states)], failedWindows: rows.receipts.filter(r => (r as { kind?: string } | null)?.kind === 'failed_windows').length }).toEqual({
+ label, runs: Array.from({ length: WINDOW_FAILURE_LIMIT + 2 }, () => ({ attempts: 1, failed: 1 })), receipts: ['unread_windows'], recovered: 0, states: ['done'], failedWindows: 0 });
+ }
+ } finally {
+ __setChatTransportForTests(null);
+ await brain.engine.setConfig('facts.extraction_model', '');
+ }
+ }, 600_000);
+
+ test('a window marked failed keeps the facts of the earlier window it replaced until it is extracted', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/failed-keeps-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Keeps T1', chatDays(3700, 100, 26)));
+ await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ await brain.seed(slug, chatPage('Keeps T2', (await brain.body(slug)).truth));
+ let stuck = null as string | null;
+ const failOn = (text: string) => { stuck ??= text; return text === stuck; };
+ for (let run = 1; run <= WINDOW_FAILURE_LIMIT; run++) await extract(brain.engine, slug, { failOn });
+ const settled = await factsOf(brain.engine, slug);
+ const survivors = before.filter(f => settled.some(s => s.id === f.id));
+ expect({ facts: settled.length, survivors: survivors.length, stamped: await terminalStamps(brain.engine, slug) }).toEqual({ facts: before.length, survivors: 1, stamped: 1 });
+ const forced = await extract(brain.engine, slug, { force: true });
+ const after = await factsOf(brain.engine, slug);
+ expect({ calls: forced.calls, facts: after.length, survivors: before.filter(f => after.some(a => a.id === f.id)).length }).toEqual({ calls: [stuck!], facts: before.length, survivors: 0 });
+ }, 600_000);
+}
+
+/** A production-extractor run (no injected extractor): the gateway's fake transport answers or fails. */
+async function extractProductionRun(engine: BrainEngine, slug: string) {
+ const { runExtractConversationFactsCore } = await import('../../src/commands/extract-conversation-facts.ts');
+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0 });
}
diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.ts
index 8ab0d85f77..bcffa11cb9 100644
--- a/test/page-spend-reservation.test.ts
+++ b/test/page-spend-reservation.test.ts
@@ -8,9 +8,10 @@
* embedding model resets the embedding ledger only, never derivation spend or an in-flight derivation reservation;
* concurrent reservations never overspend a cap; a settle after its reservation was folded as stale books nothing;
* a metered call books the provider-reported cost of every attempt (a throw after the answer included), the
- * reservation for an unpriced model, the worst case of an attempt the provider may have billed without reporting
- * usage (a timeout, an abort, a reset connection, partial usage) so a run of timeouts stops at the cap, and nothing
- * when the provider was never called or refused the attempt with an error status; concurrent metered calls under one
+ * reservation for an unpriced model, the worst case of every attempt the provider may have billed (a timeout, an
+ * abort, a reset, partial or wrapped usage, a 5xx, a proxy's 499 or 504, each entry of a retry wrapper) so a run of
+ * them stops at the cap, and nothing when the provider was never called or definitively refused the attempt (a 4xx
+ * on the attempt itself, no usage); a metered call turns the SDK's hidden retries off; concurrent metered calls under one
* --max-usd tracker count each other's in-flight attempts; the estimate honors
* pricing.overrides and covers every attempt of a facts extraction.
* 2. Fails when: derivation spend starves embeddings, an embedding switch forgives or drops derivation spend, a refusal
@@ -24,7 +25,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { PAGE_EMBED_CAP_KEY, estimateChatCallUsd, estimateFactsExtractionUsd, meterPaidCall, planPageEmbedding, reservePageSpend, spendGrant,
type PageSpendSignature } from '../src/core/page-embedding-budget.ts';
import { PAGE_DERIVATION_CAP_KEY } from '../src/core/page-spend.ts';
-import { __setChatTransportForTests, chat, withBudgetTracker, type ChatResult } from '../src/core/ai/gateway.ts';
+import { __setChatTransportForTests, __setGenerateTextTransportForTests, chat, configureGateway, resetGateway, withBudgetTracker, type ChatResult } from '../src/core/ai/gateway.ts';
import { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';
import { BudgetExhausted, BudgetTracker, parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';
import { estimateChatInputTokens } from '../src/core/ai/chat-input-estimate.ts';
@@ -266,64 +267,106 @@ describe('per-page spend ledgers', () => {
}
});
- test('meterPaidCall books the worst case of an attempt the provider may have billed (a timeout, an abort, a reset connection, partial usage) and nothing for one it refused with an error status', async () => {
+ test('meterPaidCall books every attempt the provider may have billed (a timeout, an abort, a reset, partial or wrapped usage, a 5xx, a 499 or 504, each entry of a retry wrapper) and nothing for one it definitively refused (a 4xx on the attempt itself, no usage)', async () => {
+ const status = (code: number, message = `http ${code}`) => Object.assign(new Error(message), { status: code });
+ const reset = () => Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' });
+ const retry = (...errors: Error[]) => Object.assign(new Error(`Failed after ${errors.length} attempts.`), { name: 'AI_RetryError', reason: 'maxRetriesExceeded', errors, lastError: errors.at(-1) });
+ const failures: Array<[string, Error]> = [
+ ['timeout', Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' })],
+ ['abort', Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })],
+ ['reset', reset()],
+ ['partial', Object.assign(new Error('stream interrupted'), { usage: { input_tokens: 1000 } })],
+ ['wrapped usage', Object.assign(status(400), { cause: { usage: { input_tokens: 1000, output_tokens: 300 } } })],
+ ['status only on a cause', Object.assign(new Error('wrapped'), { cause: status(401) })],
+ ['500', status(500)], ['504', status(504)], ['529', status(529)], ['499', status(499)], ['408', status(408)],
+ ['401', status(401)], ['429', status(429)], ['400', status(400)],
+ ['retry reset, reset, 500', retry(reset(), reset(), status(500))],
+ ['retry 408, 408, 529', retry(status(408), status(408), status(529))],
+ ['retry 429, 429, 500', retry(status(429), status(429), status(500))],
+ ['retry 429, 429, 429', retry(status(429), status(429), status(429))],
+ ];
+ const worst = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 500)!;
+ const expected: Record<string, number> = {
+ timeout: worst, abort: worst, reset: worst, partial: reservationCostUsd(HAIKU, 'chat', 1000, 500)!,
+ 'wrapped usage': reservationCostUsd(HAIKU, 'chat', 1000, 300)!, 'status only on a cause': worst,
+ 500: worst, 504: worst, 529: worst, 499: worst, 408: worst, 401: 0, 429: 0, 400: 0,
+ 'retry reset, reset, 500': 3 * worst, 'retry 408, 408, 529': 3 * worst, 'retry 429, 429, 500': worst, 'retry 429, 429, 429': 0,
+ };
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const ask = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 500 });
- const failures: Array<[string, Error]> = [
- ['timeout', Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' })],
- ['abort', Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })],
- ['reset', Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })],
- ['partial', Object.assign(new Error('stream interrupted'), { usage: { input_tokens: 1000 } })],
- ['server', Object.assign(new Error('overloaded'), { status: 529 })],
- ['auth', Object.assign(new Error('invalid x-api-key'), { status: 401 })],
- ];
- const booked: Record<string, { ledger: number; recorded: number }> = {};
+ const booked: Record<string, number> = {};
+ const recorded: Record<string, boolean> = {};
for (const [kind, error] of failures) {
const before = (await familyLedger(engine, page.id, 'facts'))?.spent ?? 0;
const parent = new BudgetTracker({ label: 'probe', auditPath: '/dev/null' });
__setChatTransportForTests(async () => { throw error; });
const out = await withBudgetTracker(parent, () => meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, () => ask().catch(() => 'failed')));
expect(out, name).toEqual({ value: 'failed' });
- booked[kind] = { ledger: (await familyLedger(engine, page.id, 'facts'))!.spent - before, recorded: parent.totalSpent };
+ booked[kind] = (await familyLedger(engine, page.id, 'facts'))!.spent - before;
+ recorded[kind] = parent.totalSpent > 0;
}
__setChatTransportForTests(null);
- const worst = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 500)!;
- expect(booked, name).toEqual({
- timeout: { ledger: expect.closeTo(worst, 12), recorded: expect.closeTo(worst, 12) },
- abort: { ledger: expect.closeTo(worst, 12), recorded: expect.closeTo(worst, 12) },
- reset: { ledger: expect.closeTo(worst, 12), recorded: expect.closeTo(worst, 12) },
- partial: { ledger: expect.closeTo(reservationCostUsd(HAIKU, 'chat', 1000, 500)!, 12), recorded: expect.closeTo(reservationCostUsd(HAIKU, 'chat', 1000, 500)!, 12) },
- server: { ledger: 0, recorded: expect.closeTo(worst, 12) },
- auth: { ledger: 0, recorded: expect.closeTo(worst, 12) },
- });
+ expect(Object.fromEntries(Object.entries(booked).map(([k, v]) => [k, Number(v.toFixed(12))])), name)
+ .toEqual(Object.fromEntries(Object.entries(expected).map(([k, v]) => [k, Number(v.toFixed(12))])));
+ // The caller's tracker still counts every failure at its pessimistic estimate (its caps are unchanged).
+ expect(Object.values(recorded).every(Boolean), name).toBe(true);
expect((await familyLedger(engine, page.id, 'facts'))!.reserved, name).toBe(0);
}
});
- test('timed-out attempts are booked, so a run of them stops at the family cap', async () => {
+ test('a metered call runs with the provider SDK\'s hidden retries off; an unmetered call keeps the SDK default', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
- const ask = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 500 });
- const worst = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 500)!;
- const cap = 0.0513;
- await engine.setConfig(PAGE_DERIVATION_CAP_KEY, String(cap));
- let calls = 0;
- __setChatTransportForTests(async () => { calls++; throw Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' }); });
- let steps = 0;
- let refused = false;
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-fake' } });
+ const seen: unknown[] = [];
+ __setGenerateTextTransportForTests((async (args: { maxRetries?: number }) => {
+ seen.push('maxRetries' in args ? args.maxRetries : 'default');
+ return { content: [{ type: 'text', text: 'ok' }], finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 1 } };
+ }) as never);
try {
- while (!refused && steps < 50) {
- steps++;
- refused = 'refused' in await meterPaidCall(engine, page, `facts:${HAIKU}`, 0.01, () => ask().catch(() => null));
- }
+ const ask = () => chat({ model: 'openai:gpt-4o', messages: [{ role: 'user', content: 'window' }], maxTokens: 50 });
+ await meterPaidCall(engine, page, 'facts:openai:gpt-4o', 0.2, ask);
+ await ask();
} finally {
- __setChatTransportForTests(null);
- await engine.setConfig(PAGE_DERIVATION_CAP_KEY, '1');
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ }
+ expect(seen, name).toEqual([0, 'default']);
+ }
+ });
+
+ test('failed attempts the provider may have billed are booked, so a run of them stops at the family cap: timeouts, retry-wrapped 408s and a 529, wrapped usage', async () => {
+ const worst = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 500)!;
+ const status = (code: number) => Object.assign(new Error(`http ${code}`), { status: code });
+ const kinds: Array<[string, () => Error, number]> = [
+ ['timeout', () => Object.assign(new Error('The operation timed out.'), { name: 'TimeoutError' }), worst],
+ ['retry 408, 408, 529', () => { const errors = [status(408), status(408), status(529)]; return Object.assign(new Error('Failed after 3 attempts.'), { name: 'AI_RetryError', errors, lastError: errors[2] }); }, 3 * worst],
+ ['wrapped usage', () => Object.assign(status(400), { cause: { usage: { input_tokens: 1000, output_tokens: 300 } } }), reservationCostUsd(HAIKU, 'chat', 1000, 300)!],
+ ];
+ for (const { name, engine } of engines) {
+ for (const [kind, failure, cost] of kinds) {
+ const page = await segmentedPage(engine);
+ const ask = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 500 });
+ const cap = 0.0513;
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, String(cap));
+ let calls = 0;
+ __setChatTransportForTests(async () => { calls++; throw failure(); });
+ let steps = 0;
+ let refused = false;
+ try {
+ while (!refused && steps < 50) {
+ steps++;
+ refused = 'refused' in await meterPaidCall(engine, page, `facts:${HAIKU}`, 0.01, () => ask().catch(() => null));
+ }
+ } finally {
+ __setChatTransportForTests(null);
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, '1');
+ }
+ const allowed = Math.floor((cap - 0.01) / cost) + 1;
+ expect({ kind, refused, calls, steps, spent: Number((await familyLedger(engine, page.id, 'facts'))!.spent.toFixed(12)) }, name)
+ .toEqual({ kind, refused: true, calls: allowed, steps: allowed + 1, spent: Number((allowed * cost).toFixed(12)) });
}
- const allowed = Math.floor((cap - 0.01) / worst) + 1;
- expect({ refused, calls, steps, spent: (await familyLedger(engine, page.id, 'facts'))!.spent }, name)
- .toEqual({ refused: true, calls: allowed, steps: allowed + 1, spent: expect.closeTo(allowed * worst, 12) });
}
});