Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): PR 4 4b round 3: window coverage by message position, pinned-grammar continuations, billed-on-failure booking, per-window retry cap, reservation-aware caps

garrytan0e164788fcb7
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index 337adea093..0854ea2c1d 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -13,7 +13,9 @@
* PR 4 (Wave B incremental derivation, transcripts): a segmented page's paid
* derivations keep their receipt per occurrence on page_segment_derivations
* (`unread_windows`: the run stopped before every window was read, at the
- * per-page spend cap or a window limit; the next run resumes there). Both tables
+ * per-page spend cap or a window limit; the next run resumes there; `failed_windows`:
+ * a conversation window whose extraction failed run after run was skipped, and its
+ * sample names the window). Both tables
* are read; a page counts once per pipeline and receipt kind. A derivation receipt
* without a `kind` (the synopsis pass's tier fallback or refused reservation) is
* not an input-truncation receipt and is not counted.
@@ -34,7 +36,9 @@ const REMEDY: Record<string, string> = {
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 remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : REMEDY[g.pipeline] ?? null;
+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 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'}`;
@@ -44,13 +48,14 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Che
try {
const rows = await connectedEngine(ctx).executeRaw<{ pipeline: string; kind: string; pages: number; samples: string[] }>(
`WITH receipts AS (
- SELECT s.page_id, s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, s.updated_at
+ SELECT s.page_id, s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, s.updated_at, NULL::text AS detail
FROM page_extraction_state s WHERE s.input_truncated IS NOT NULL
UNION ALL
- SELECT d.page_id, d.pipeline, COALESCE(d.receipt->>'kind', 'unknown') AS kind, max(d.updated_at) AS updated_at
+ SELECT d.page_id, d.pipeline, COALESCE(d.receipt->>'kind', 'unknown') AS kind, max(d.updated_at) AS updated_at,
+ min(CASE WHEN d.receipt->>'kind' = '${FAILED_WINDOWS}' THEN ' window ' || (d.receipt->'windows'->0->>'ordinal') || ' of occurrence ' || d.occurrence_id END) AS detail
FROM page_segment_derivations d WHERE d.receipt->>'kind' IS NOT NULL GROUP BY 1, 2, 3)
SELECT r.pipeline, r.kind, count(DISTINCT r.page_id)::int AS pages,
- (array_agg(p.source_id || ':' || p.slug ORDER BY r.updated_at DESC))[1:3] AS samples
+ (array_agg(p.source_id || ':' || p.slug || COALESCE(r.detail, '') ORDER BY r.updated_at DESC))[1:3] AS samples
FROM receipts r JOIN pages p ON p.id = r.page_id AND p.deleted_at IS NULL
GROUP BY 1, 2 ORDER BY 1, 2`);
const groups: ReceiptGroup[] = rows.map(r => ({ pipeline: r.pipeline, kind: r.kind, pages: Number(r.pages), samples: r.samples ?? [] }));
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 92c976a26f..594ca59683 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -1201,7 +1201,7 @@ export async function runExtractConversationFactsCore(
// delete-orphans-first makes that replay deterministic.
state.cpMap.delete(cpMapKey(sourceId, currentPage.slug));
if (isSegmentedPage(currentPage) && !state.managed && !hasRawTranscriptSidecar(currentPage)) {
- const { newestEnd } = await processSegmentedConversationPage(state, currentPage, { gapMinutes: pageSegmentGapMinutes(currentPage) ?? null, sinceIso: opts.sinceIso });
+ const { newestEnd } = await processSegmentedConversationPage(state, currentPage, { gapMinutes: pageSegmentGapMinutes(currentPage) ?? null, sinceIso: opts.sinceIso, retryFailed: opts.force });
if (newestEnd) state.cpMap.set(cpMapKey(sourceId, currentPage.slug), newestEnd);
return { newEndIso: newestEnd };
}
diff --git a/src/core/ai/budget-record.ts b/src/core/ai/budget-record.ts
index 4b71212ef1..f45d94e62e 100644
--- a/src/core/ai/budget-record.ts
+++ b/src/core/ai/budget-record.ts
@@ -4,6 +4,7 @@
* surfaces on the NEXT `reserve()`, and the call's own result or error wins.
*/
+import { readProviderFailureSignals } from './errors.ts';
import {
usageFromError,
type BudgetActualUsage,
@@ -22,17 +23,21 @@ export function recordOnTracker(tracker: BudgetTracker | null, actual: BudgetAct
/**
* Usage fields for a failed call: what the SDK error reports, else the
- * pessimistic fallback (A3 amended) flagged `estimated`.
+ * 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.
*/
export function failedCallUsage(
err: unknown,
fallback: { inputTokens: number; outputTokens: number },
-): { inputTokens: number; outputTokens: number; failed: true; estimated: boolean } {
+): { inputTokens: number; outputTokens: number; failed: true; estimated: boolean; rejected: boolean } {
const found = usageFromError(err);
+ const { status } = readProviderFailureSignals(err);
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,
};
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ecb7f82274..6cc9e76888 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1053,7 +1053,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, and one the provider rejected without answering (a rate limit, an auth or server error, a failed embedding) books nothing. Doctor lists the pages a cap stopped.' },
+ { 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.' },
// 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 27f23a032d..53b69b60b6 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -95,6 +95,12 @@ export interface BudgetActualUsage {
countsAsCall?: boolean;
/** 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.
+ */
+ rejected?: boolean;
}
export interface BudgetSnapshot {
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 11d5172cb9..fc58a4f724 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -6,7 +6,8 @@
* facts.source_window (owner occurrence, ordinal, rendered-text sha). Per occurrence, a page_segment_derivations row
* (kind conversation_facts) records the segment sha, a context hash (every page-level input the windows depend on:
* title, gap setting, date context, extraction model, effective fact visibility), the windows it owns (ordinal, sha,
- * facts, first and last message time), its predecessor and whether its first message opens a gap group. A run:
+ * facts, the positions of its first and last message), its predecessor, whether its first message opens a gap group,
+ * the grammar the page was parsed under, and the failed attempts of windows not extracted yet. A run:
* - finds the first occurrence that is new, rewritten, moved or context-changed and streams the windows from the
* nearest earlier occurrence that opens a gap group (the windows before it cannot change), one segment at a time
* and in runs, newest run first (a run ends where the next occurrence certainly opens a gap group), so a stop
@@ -17,8 +18,13 @@
* 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;
* - clears facts only when that is safe: an unsettled run clears the facts of windows it extracted again and of
- * earlier windows whose messages the current windows cover, nothing else; a settled run (every live window
+ * 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
* 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
@@ -28,7 +34,8 @@
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import { deriveDateContext } from '../conversation-parser/parse.ts';
-import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';
+import { BudgetExhausted, loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';
+import { classifyGlobalLlmError } from '../ai/errors.ts';
import { writeDerivedFacts } from '../persistence/derived-facts.ts';
import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';
import { setExtractionReceipt } from '../extraction-watermark.ts';
@@ -39,7 +46,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 } from './conversation-stream.ts';
+import { 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';
@@ -51,6 +58,13 @@ const KIND = 'conversation_facts';
export const CONVERSATION_FACTS_DERIVATION_VERSION = 1;
/** Windows extracted between two publications of a page's facts and rows. */
export const CONVERSATION_FACTS_CHECKPOINT_WINDOWS = 8;
+/**
+ * Runs in which one window's extraction may throw before it is marked failed and skipped. extract.ts already retries a
+ * truncated or malformed answer inside one run and the gateway retries transient provider errors, so a window that
+ * still throws in three separate runs fails for a reason of its own (its text, a deterministic provider refusal); three
+ * also rides out a transient outage spanning two runs, and bounds what a doomed window costs at three reservations.
+ */
+export const WINDOW_FAILURE_LIMIT = 3;
/** The run counters this pass moves (a subset of ExtractConversationFactsResult). */
export interface SegmentedConversationCounters {
@@ -68,17 +82,23 @@ export interface SegmentedConversationRun extends ConversationWindowRun {
segmentLimit: number;
}
-/** A window an occurrence row records: ordinal, rendered-text sha, facts produced, and its first and last message times. */
-interface WindowRecord { ordinal: number; sha: string; facts: number; start?: string; end?: string }
-interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null }
-/** One window of the stream: `reused` (an earlier run's facts stand), `todo`, or `extracted` by this run. */
-interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow; state: 'reused' | 'todo' | 'extracted'; facts: number }
+/** Where a window's first and last message start: [occurrence id, ordinal, occurrence id, ordinal] (MessagePosition). */
+type Span = [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> }
+/** 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 }
type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;
/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */
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 };
+ 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 : [] };
}
const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });
@@ -91,24 +111,39 @@ async function conversationContext(engine: BrainEngine, page: Page, gapMinutes:
return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, visibility } };
}
-/** Window keys of earlier windows whose first and last message times fall inside one run of consecutive live windows. */
-function coveredKeys(windows: readonly StreamWindow[], earlier: ReadonlyArray<{ key: string; start?: string; end?: string }>): string[] {
- const runs: Array<[string, string]> = [];
- let open: [string, string] | null = null;
+/**
+ * Window keys of earlier windows whose first and last message positions fall inside one run of consecutive windows
+ * 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;
for (const w of windows) {
- if (w.state === 'todo') { open = null; continue; }
- if (open) open[1] = w.seg.endIso;
- else runs.push(open = [w.seg.startIso, w.seg.endIso]);
+ 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])!;
+ if (open) open[1] = end;
+ else runs.push(open = [start, end]);
}
- return earlier.filter(e => e.start && e.end && runs.some(([start, end]) => e.start! >= start && e.end! <= end)).map(e => e.key);
+ 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);
+ }).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;
+
/**
* One segmented page's conversation facts, incrementally (module doc). `gapMinutes` is the page's own
* conversation_segment_gap_minutes (null: the default). Returns the end of the newest window it extracted.
*/
export async function processSegmentedConversationPage(run: SegmentedConversationRun, page: Page,
- opts: { gapMinutes: number | null; sinceIso?: string }): Promise<{ newestEnd: string | null }> {
+ opts: { gapMinutes: number | null; sinceIso?: string; retryFailed?: boolean }): Promise<{ newestEnd: string | null }> {
const { engine, sourceId, result } = run;
result.pages_considered++;
const versionToken = regularPageVersionToken(page);
@@ -122,7 +157,10 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));
const current = new Set(plan.current.map(row => row.occurrenceId));
const prevOf = (i: number) => (i === 0 ? null : liveIds[i - 1]!);
- const intact = (i: number) => current.has(liveIds[i]!) && (rowOutput(priorRow.get(liveIds[i]!)).prev ?? null) === prevOf(i);
+ const intact = (i: number) => {
+ const output = rowOutput(priorRow.get(liveIds[i]!));
+ return current.has(liveIds[i]!) && (output.prev ?? null) === prevOf(i) && !(opts.retryFailed && output.windows.some(w => w.failed));
+ };
// The first occurrence whose windows may have changed (one past the last when only trailing occurrences left), and
// the nearest earlier occurrence that opens a gap group: the stream starts there.
let first = liveIds.findIndex((_, i) => !intact(i));
@@ -135,14 +173,18 @@ 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; start?: string; end?: string }> = [];
+ const earlier: Array<{ key: string; span?: Span }> = [];
+ const failures = new Map<string, WindowFailure>();
+ let pattern = prior.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);
- for (const record of rowOutput(row).windows) {
- earlier.push({ key: keyOf(row.occurrenceId, record), start: record.start, end: record.end });
- if (same) reusable.set(record.sha, [...(reusable.get(record.sha) ?? []), { occurrenceId: row.occurrenceId, record }]);
+ const output = rowOutput(row);
+ for (const record of output.windows) {
+ earlier.push({ key: keyOf(row.occurrenceId, record), span: record.span });
+ 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 });
}
const windows: StreamWindow[] = [];
const pendingMoves: Array<{ from: string; to: SourceWindow }> = [];
@@ -150,7 +192,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const startsGroup = new Map<number, boolean>();
const ordinals = new Map<number, number>();
const pageTitle = page.title || page.slug;
- const streamOpts = { page, gapMinutes: opts.gapMinutes, sinceIso: opts.sinceIso };
+ const streamOpts = { page, gapMinutes: opts.gapMinutes, sinceIso: opts.sinceIso, pattern };
const texts = new Map<number, string>();
const readText = async (i: number) => {
const cached = texts.get(i);
@@ -164,19 +206,21 @@ 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[] = [];
- await streamConversationWindows(occurrences, start, end, streamOpts, readText, {
- window(ownerIndex, seg) {
- const owner = liveIds[ownerIndex]!;
+ 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, {
+ window(first, last, seg) {
+ const owner = liveIds[first.owner]!;
const ordinal = ordinals.get(owner) ?? 0;
ordinals.set(owner, ordinal + 1);
const text = renderSegmentForExtraction(pageTitle, seg);
const window = sourceWindowFor(owner, ordinal, text);
const hit = reusable.get(window.window_text_sha)?.shift();
- if (!hit) { runWindows.push({ owner, seg, text, window, state: 'todo', facts: 0 }); return; }
+ const span = spanOf(first, last);
+ if (!hit) { runWindows.push({ owner, seg, text, window, span, state: 'todo', facts: 0 }); return; }
const was = keyOf(hit.occurrenceId, hit.record);
reused.add(was);
if (was !== sourceWindowKey(window)) pendingMoves.push({ from: was, to: window });
- runWindows.push({ owner, seg, text: null, window, state: 'reused', facts: hit.record.facts });
+ runWindows.push({ owner, seg, text: null, window, span, state: hit.record.failed ? 'failed' : 'reused', facts: hit.record.facts, failed: hit.record.failed });
},
occurrence(index, starts) { startsGroup.set(liveIds[index]!, starts); },
});
@@ -214,20 +258,24 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
// Rows of the occurrences this run finished or reached; an occurrence it never reached keeps its row (still unsettled).
const derived: SegmentDerivationInput[] = liveIds.slice(streamedFrom).flatMap((occurrenceId, k) => {
const mine = owned.get(occurrenceId) ?? [];
- const records = mine.filter(w => w.state !== 'todo')
- .map(w => ({ ordinal: w.window.window_ordinal, sha: w.window.window_text_sha, facts: w.facts, start: w.seg.startIso, end: w.seg.endIso }));
+ 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 finished = records.length === mine.length;
if (!finished && !records.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) },
- receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop ?? 'in_progress', windows_read: records.length, windows_total: mine.length } }];
+ contextHash, state: finished && !opts.sinceIso ? 'done' : 'partial',
+ output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}) },
+ 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))).filter(key => !cleared.has(key))];
+ const clear = settled ? [] : [...batch.keys, ...coveredKeys(windows, earlier.filter(e => !reused.has(e.key)), position).filter(key => !cleared.has(key))];
const outcome = !settled ? null : keep!.length ? terminalAuditFact(page.slug, 0, versionToken)
: nonExtractableAuditFact(page.slug, 0, versionToken, 'fewer than two eligible messages');
- const moves = pendingMoves.splice(0);
+ 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 } });
@@ -235,6 +283,7 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
return published;
});
+ pendingMoves.splice(0, moves.length);
cleared = new Set([...cleared, ...clear]);
batch = { rows: [], windows: [], keys: [] };
result.facts_inserted += out.facts_inserted;
@@ -257,8 +306,22 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
paid ??= { pricingOverrides: await loadPricingOverrides(engine), entityHints: await conversationEntityHints(engine, sourceId, page.slug, run.factVisibility) };
const { pricingOverrides, entityHints } = paid;
const text = w.text!;
- const metered = await meterPaidCall(engine, page, `facts:${model}`, estimateFactsExtractionUsd(model, text.length, maxTokens, pricingOverrides),
- () => extractConversationWindow(run, page, w.seg, text, 0, entityHints), { pricingOverrides });
+ const sha = w.window.window_text_sha;
+ let metered: Awaited<ReturnType<typeof meterPaidCall<Awaited<ReturnType<typeof extractConversationWindow>>>>>;
+ try {
+ metered = await meterPaidCall(engine, page, `facts:${model}`, estimateFactsExtractionUsd(model, text.length, maxTokens, pricingOverrides),
+ () => extractConversationWindow(run, page, w.seg, text, 0, entityHints), { pricingOverrides });
+ } catch (error) {
+ if (!windowFailure(error, run.signal)) throw error;
+ const failure = { attempts: (failures.get(sha)?.attempts ?? 0) + 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) };
+ failures.set(sha, failure);
+ if (failure.attempts < WINDOW_FAILURE_LIMIT) throw error;
+ failures.delete(sha);
+ Object.assign(w, { state: 'failed', failed: failure, 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;
+ }
if ('refused' in metered) { stop = 'cap_reached'; break; }
const out = metered.value;
w.state = 'extracted';
diff --git a/src/core/facts/conversation-stream.ts b/src/core/facts/conversation-stream.ts
index 8b8b06f62a..441101ec81 100644
--- a/src/core/facts/conversation-stream.ts
+++ b/src/core/facts/conversation-stream.ts
@@ -2,13 +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 the page's winning pattern (the segmenter's, in the first
- * occurrence's entry state) when it has one. 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; 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. Reads one occurrence's text at a time and holds the carried message and the open window, never the
- * whole body.
+ * 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
+ * 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
+ * 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
* the whole stream's, because every window before that occurrence closed at the gap. startsConversationRun tells, from
@@ -17,35 +21,47 @@
*/
import type { Page } from '../types.ts';
import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';
-import { DAY_HEADER_RE, isAnchorLine, parseConversation } from '../conversation-parser/parse.ts';
+import { normalizeBlockConversation } from '../conversation-parser/normalize-block.ts';
+import { DAY_HEADER_RE, applyPattern, deriveDateContext, isAnchorLine, parseConversation } from '../conversation-parser/parse.ts';
import type { ConversationOccurrence } from '../page-body/segment-conversation.ts';
-import type { ConversationSegment } from './conversation-types.ts';
+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 }
+
export interface ConversationStreamSink {
- /** A closed window, owned by occurrence `owner` (an index into the occurrences). */
- window(owner: number, seg: ConversationSegment): void;
+ /** A closed window: the positions of its first message (whose occurrence owns the window) and its last. */
+ window(first: MessagePosition, last: MessagePosition, seg: ConversationSegment): void;
/** Occurrence `index` was read; `startsGroup`: its first message opens a gap group. */
occurrence(index: number, startsGroup: boolean): void;
}
-export interface ConversationStreamOpts { page: Page; gapMinutes: number | null; sinceIso?: string }
+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. */
+ pattern?: string | null;
+}
/** The last message of an occurrence, held back to be parsed with the next occurrence's text. */
-interface Carry { text: string; date: string | undefined; owner: number; region: string }
-
-/** The page's winning pattern (the segmenter's) and the parser options that pin it. */
-function pinnedPattern(occurrences: readonly ConversationOccurrence[]) {
- const pattern = occurrences[0]?.conversation?.pattern ?? null;
- const forced = pattern && BUILTIN_PATTERNS.some(p => p.id === pattern) ? BUILTIN_PATTERNS.filter(p => p.id !== pattern).map(p => p.id) : undefined;
- return { pattern, forced };
-}
+interface Carry { parts: string[]; date: string | undefined; owner: number; region: string }
const gapMinutesFor = (opts: ConversationStreamOpts, patternId: string | null) =>
opts.gapMinutes ?? (patternId === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);
-function parseChunk(text: string, page: Page, fallbackDate: string | undefined, forced: string[] | undefined) {
- return parseConversation(text, { page, ...(fallbackDate ? { fallbackDate } : {}), ...(forced ? { disabledBuiltinIds: forced } : {}) });
+/** 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;
+
+/** 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 } {
+ const dated = { page: opts.page, ...(fallbackDate ? { fallbackDate } : {}) };
+ const entry = patternId ? BUILTIN_PATTERNS.find(p => p.id === patternId) : undefined;
+ if (entry) return { messages: applyPattern(normalizeBlockConversation(text), entry, deriveDateContext(dated)), patternId };
+ const parsed = parseConversation(text, dated);
+ return { messages: parsed.messages, patternId: patternId ?? parsed.matched_pattern_id ?? null };
}
/** The offset of the first (`last`) line of `text` that opens a message under `patternId`, or -1. */
@@ -89,65 +105,76 @@ export function startsConversationRun(occurrences: readonly ConversationOccurren
opts: ConversationStreamOpts): boolean {
if (index === 0) return true;
const occurrence = occurrences[index]!;
- const { pattern, forced } = pinnedPattern(occurrences);
- const parsed = parseChunk(text, opts.page, occurrence.conversation?.fallbackDate ?? undefined, forced);
- const patternId = pattern ?? parsed.matched_pattern_id ?? null;
+ const parsed = parseUnder(text, knownPattern(occurrences, opts), 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;
if (at < 0 || !Number.isFinite(first)) return false;
const date = occurrence.conversation?.lastDate ?? dateAt(previous, at, occurrences[index - 1]!.conversation?.fallbackDate ?? undefined);
- const last = parseChunk(previous.slice(at), opts.page, date, forced).messages[0];
+ const last = parseUnder(previous.slice(at), patternId, opts, date).messages[0];
const gapMs = (gapMinutesFor(opts, patternId) ?? DEFAULT_SEGMENT_GAP_MINUTES) * 60_000;
return !!last && first - Date.parse(last.timestamp) > gapMs;
}
/**
- * Stream the windows of occurrences `from`..`to` (exclusive) of a segmented conversation page (module doc) into `sink`.
- * `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.
+ * 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.
*/
export async function streamConversationWindows(occurrences: readonly ConversationOccurrence[], from: number, to: number, opts: ConversationStreamOpts,
- readText: (index: number) => Promise<string>, sink: ConversationStreamSink): Promise<void> {
- const { pattern, forced } = pinnedPattern(occurrences);
+ readText: (index: number) => Promise<string>, sink: ConversationStreamSink): Promise<string | null> {
const pageTitle = opts.page.title || opts.page.slug;
- let stream: ReturnType<typeof createWindowStream<number>> | null = null;
+ let patternId = knownPattern(occurrences, opts);
+ let stream: ReturnType<typeof createWindowStream<MessagePosition>> | null = null;
let carry: Carry | null = null;
- let lastPattern: string | null = null;
+ let counted: MessagePosition = { owner: -1, n: 0 };
+ const positionOf = (owner: number): MessagePosition => {
+ if (counted.owner !== owner) counted = { owner, n: 0 };
+ return { owner, n: counted.n++ };
+ };
+ const joint = (region: string, next: string) => (region === next ? '' : '\n\n');
for (let i = from; i < to; i++) {
const occurrence = occurrences[i]!;
+ const region = occurrence.row.region;
let text = await readText(i);
- const leadPattern = pattern ?? lastPattern;
- if (i === to - 1 && to < occurrences.length && leadPattern) {
+ if (i === to - 1 && to < occurrences.length && patternId) {
const next = await readText(to);
- const lead = anchorOffset(leadPattern, next, false);
- if (lead > 0) text += (occurrences[to]!.row.region === occurrence.row.region ? '' : '\n\n') + next.slice(0, lead);
+ const lead = anchorOffset(patternId, next, false);
+ if (lead > 0) text += joint(region, occurrences[to]!.row.region) + next.slice(0, lead);
+ }
+ if (carry && patternId && i < to - 1 && anchorOffset(patternId, text, false) < 0) {
+ carry.parts.push(joint(carry.region, region), text);
+ carry.region = region;
+ sink.occurrence(i, false);
+ continue;
}
- const carried: string = carry ? carry.text + (carry.region === occurrence.row.region ? '' : '\n\n') : '';
+ const carried: string = carry ? carry.parts.join('') + joint(carry.region, region) : '';
const chunk: string = carried + text;
const fallbackDate: string | undefined = carry ? carry.date : occurrence.conversation?.fallbackDate ?? undefined;
- const parsed = parseChunk(chunk, opts.page, fallbackDate, forced);
- const patternId: string | null = pattern ?? parsed.matched_pattern_id ?? lastPattern;
- lastPattern = patternId;
- stream ??= createWindowStream<number>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });
+ const parsed = parseUnder(chunk, patternId, opts, fallbackDate);
+ patternId = parsed.patternId;
+ stream ??= createWindowStream<MessagePosition>({ pageTitle, sinceIso: opts.sinceIso, gapMinutes: gapMinutesFor(opts, patternId) });
let messages = parsed.messages;
- const firstOwner: number = carry ? carry.owner : i;
+ const firstOwner = carry ? carry.owner : i;
let next: Carry | null = null;
if (i < to - 1 && messages.length && patternId) {
- const at = anchorOffset(patternId, chunk, true);
- if (at >= 0) {
- next = { text: chunk.slice(at), date: dateAt(chunk, at, fallbackDate), owner: at < carried.length ? firstOwner : i, region: occurrence.row.region };
+ const inText = anchorOffset(patternId, text, true);
+ if (inText >= 0) {
+ const at: number = carried.length + inText;
+ next = { parts: [chunk.slice(at)], date: dateAt(chunk, at, fallbackDate), owner: i, region };
messages = messages.slice(0, -1);
}
}
let startsGroup: boolean | null = null;
messages.forEach((message, k) => {
const owner = k === 0 ? firstOwner : i;
- const pushed = stream!.push(message, owner);
+ 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.seg);
+ for (const w of pushed.windows) sink.window(w.tag, w.last, w.seg);
});
sink.occurrence(i, startsGroup === true);
carry = next;
}
- for (const w of stream?.end() ?? []) sink.window(w.tag, w.seg);
+ for (const w of stream?.end() ?? []) sink.window(w.tag, w.last, w.seg);
+ return patternId;
}
diff --git a/src/core/facts/conversation-windows.ts b/src/core/facts/conversation-windows.ts
index 3de2e3b309..e4f15859f1 100644
--- a/src/core/facts/conversation-windows.ts
+++ b/src/core/facts/conversation-windows.ts
@@ -134,8 +134,8 @@ function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars:
return splitTurnText(m.text, budget).map((text) => ({ ...m, text }));
}
-/** A closed window and the tag of the message it starts with (the caller's owner of that message). */
-export interface TaggedWindow<Tag> { seg: ConversationSegment; tag: Tag }
+/** 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 }
/** 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>[] };
@@ -156,9 +156,10 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {
let groupMessages = 0;
let cur: ConversationMessage[] = [];
let curTag: Tag | undefined;
+ let lastTag: Tag | undefined;
let held: TaggedWindow<Tag>[] = [];
const close = (out: TaggedWindow<Tag>[]) => {
- if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag });
+ if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag, last: lastTag as Tag });
cur = [];
if (groupMessages >= MIN_SEGMENT_MESSAGES) { out.push(...held); held = []; }
};
@@ -180,6 +181,7 @@ export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {
for (const part of parts) {
if (cur.length >= maxMessages || (cur.length > 0 && renderedLength(pageTitle, [...cur, part]) > maxChars)) close(windows);
if (cur.length === 0) curTag = tag;
+ lastTag = tag;
cur.push(part);
}
if (groupMessages >= MIN_SEGMENT_MESSAGES && held.length) { windows.push(...held); held = []; }
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index a8a4e1b1e0..e955ddbe93 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -37,7 +37,7 @@ import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './conte
import type { BodyStorage, ManifestRow } from './page-body/types.ts';
import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';
import { estimateCostFromChars } from './embedding-pricing.ts';
-import { reservationCostUsd, usageCostUsd, type BudgetKind } from './budget/reservation-cost.ts';
+import { reservationCostUsd, usageCostUsd } from './budget/reservation-cost.ts';
import { BudgetTracker, type PricingOverrides } from './budget/budget-tracker.ts';
import { getCurrentBudgetTracker, withBudgetTracker } from './ai/gateway.ts';
import { recordOnTracker } from './ai/budget-record.ts';
@@ -245,29 +245,43 @@ export function estimateFactsExtractionUsd(model: string, chars: number, maxOutp
return estimateChatCallUsd(model, chars, maxOutputTokens, pricingOverrides) + 2 * estimateChatCallUsd(model, chars, 2 * maxOutputTokens, pricingOverrides);
}
-const TOUCHPOINT_KIND: Partial<Record<string, BudgetKind>> = { embedding: 'embed', rerank: 'rerank' };
-
/**
- * A metered step's tracker, which also sums what the provider billed: every attempt it answered, at its reported usage
- * (a success without reported usage at its estimate). An attempt that failed with no reported usage carries the
- * gateway's pessimistic fallback (a rate limit, an auth or server error, a connection that got no answer): the provider
- * billed nothing, so the page ledger books nothing for it, while the step's caps still count it.
+ * 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.
+ *
+ * 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.
*/
class MeteredStepTracker extends BudgetTracker {
billedUsd = 0;
billedAttempts = 0;
unpricedAttempts = 0;
- constructor(opts: ConstructorParameters<typeof BudgetTracker>[0], private readonly pricing?: PricingOverrides) { super(opts); }
+ constructor(opts: ConstructorParameters<typeof BudgetTracker>[0], private readonly parent: BudgetTracker | null, private readonly pricing?: PricingOverrides) { super(opts); }
+
+ override reserve(estimate: Parameters<BudgetTracker['reserve']>[0]): ReturnType<BudgetTracker['reserve']> {
+ super.reserve(estimate);
+ return this.parent?.reserve(estimate);
+ }
+
+ override release(reservation: ReturnType<BudgetTracker['reserve']>): void {
+ this.parent?.release(reservation);
+ }
override record(actual: Parameters<BudgetTracker['record']>[0]): void {
const failed = actual.failed === true || (actual.label?.endsWith('.failed') ?? false);
- if (!(failed && actual.estimated === true)) {
+ const unbilled = failed && (actual.rejected === true || ((actual.kind ?? 'chat') === 'embed' && actual.estimated === true));
+ if (!unbilled) {
const cost = usageCostUsd(actual.modelId, actual.inputTokens, actual.outputTokens ?? 0, actual.kind ?? 'chat', this.pricing);
this.billedAttempts++;
if (cost === null) this.unpricedAttempts++;
else this.billedUsd += cost;
}
- super.record(actual);
+ recordOnTracker(this.parent, actual);
+ super.record({ ...actual, reservation: undefined });
}
}
@@ -285,18 +299,10 @@ export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, si
const decision = await reservePageSpend(engine, page, signature, estimateUsd);
if (decision.kind === 'refused') return { refused: decision };
if (decision.kind === 'unmetered') return { value: await call() };
- const parent = getCurrentBudgetTracker();
- const parentCap = parent?.cap;
- const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides,
- ...(parent && parentCap !== undefined ? { maxCostUsd: Math.max(0, parentCap - parent.totalSpent), capSource: parent.capSource } : {}) }, opts.pricingOverrides);
+ const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides }, getCurrentBudgetTracker(), opts.pricingOverrides);
try {
return { value: await withBudgetTracker(tracker, call) };
} finally {
- const models = tracker.snapshot().models.filter(m => m.attempts > 0);
- for (const m of models) {
- recordOnTracker(parent, { modelId: m.model, requestedModelId: m.requested_model, inputTokens: m.input_tokens, outputTokens: m.output_tokens,
- label: 'page-spend', kind: TOUCHPOINT_KIND[m.touchpoint] ?? 'chat' });
- }
await decision.grant.settle({ ok: tracker.billedAttempts > 0, usd: tracker.unpricedAttempts > 0 ? decision.grant.reservedUsd : tracker.billedUsd });
}
}
diff --git a/test/conversation-stream-work.test.ts b/test/conversation-stream-work.test.ts
new file mode 100644
index 0000000000..6d5424ab37
--- /dev/null
+++ b/test/conversation-stream-work.test.ts
@@ -0,0 +1,72 @@
+/**
+ * PR 4 (Wave B incremental derivation, transcripts), lane 4b round 3: the cross-occurrence window stream
+ * (src/core/facts/conversation-stream.ts) parses a message that spans many segment cuts once, and reads continuations
+ * under the page's grammar instead of detecting it again per occurrence. Engine-free: synthetic occurrences and an
+ * in-memory reader; the parse work is counted by spying on the parser.
+ *
+ * 1. Protects: the parse work over a message spanning 40 occurrences stays linear in the page (at most three times its
+ * length), and the streamed windows equal the whole-page pass's windows exactly, for a time-less transcript
+ * (plain-role-no-time, which only a whole-body score detects) whose continuations alone would fail detection.
+ * 2. Fails when: the held message is re-parsed with every occurrence it grows through (quadratic), or a continuation is
+ * dropped because its occurrence was run through pattern detection again.
+ */
+import { expect, spyOn, test } from 'bun:test';
+import * as parser from '../src/core/conversation-parser/parse.ts';
+import type { Page } from '../src/core/types.ts';
+import type { ConversationOccurrence } from '../src/core/page-body/segment-conversation.ts';
+import { streamConversationWindows } from '../src/core/facts/conversation-stream.ts';
+import { renderSegmentForExtraction, splitIntoSegments } from '../src/core/facts/conversation-windows.ts';
+
+const page = { slug: 'notes/stream-work', title: 'Stream work', frontmatter: { date: '2025-03-01', type: 'conversation' } } as unknown as Page;
+const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency'];
+const prose = (seed: number, words: number) => Array.from({ length: words }, (_, i) => WORDS[(seed * 7 + i * 3) % WORDS.length]).join(' ');
+
+/** Turns of a time-less transcript; turn `long` carries `longLines` continuation lines. */
+function transcript(turns: number, long: number, longLines: number): string {
+ const lines: string[] = [];
+ for (let t = 0; t < turns; t++) {
+ lines.push(`${t % 2 === 0 ? 'user' : 'assistant'}: ${prose(t, 12)}`);
+ const continuation = t === long ? longLines : 2;
+ for (let c = 0; c < continuation; c++) lines.push(prose(t + c, 14));
+ }
+ return lines.join('\n') + '\n';
+}
+
+/** Cut `text` at line ends into pieces of about `size` characters, as the segmenter cuts a long message. */
+function cut(text: string, size: number): string[] {
+ const pieces: string[] = [];
+ let start = 0;
+ while (start < text.length) {
+ let end = Math.min(text.length, start + size);
+ if (end < text.length) end = text.indexOf('\n', end) + 1 || text.length;
+ pieces.push(text.slice(start, end));
+ start = end;
+ }
+ return pieces;
+}
+
+test('a message spanning 40 occurrences is parsed once, and the windows equal the whole-page windows', async () => {
+ const body = transcript(600, 300, 40 * 160);
+ const texts = cut(body, 20_000);
+ const occurrences = texts.map((_, i) => ({ row: { region: 'truth', occurrenceId: i + 1 }, conversation: { pattern: null, fallbackDate: null, lastDate: null, open: false } })) as unknown as ConversationOccurrence[];
+ const expected = splitIntoSegments(parser.parseConversation(body, { page }).messages, { pageTitle: 'Stream work' }).map(seg => renderSegmentForExtraction('Stream work', seg));
+ let parsed = 0;
+ const original = parser.parseConversation;
+ const originalApply = parser.applyPattern;
+ const parseSpy = spyOn(parser, 'parseConversation').mockImplementation(((text: string, opts?: parser.ParseConversationOpts) => { parsed += text.length; return original(text, opts); }) as never);
+ const applySpy = spyOn(parser, 'applyPattern').mockImplementation(((text: string, ...rest: unknown[]) => { parsed += text.length; return (originalApply as (...a: unknown[]) => unknown)(text, ...rest); }) as never);
+ const windows: string[] = [];
+ try {
+ await streamConversationWindows(occurrences, 0, occurrences.length, { page, gapMinutes: null }, async i => texts[i]!, {
+ window(_first, _last, seg) { windows.push(renderSegmentForExtraction('Stream work', seg)); },
+ occurrence() {},
+ });
+ } finally {
+ parseSpy.mockRestore();
+ applySpy.mockRestore();
+ }
+ expect(texts.length).toBeGreaterThan(40);
+ expect(expected.length).toBeGreaterThan(10);
+ expect({ windows: windows.length, same: windows.join('\n---\n') === expected.join('\n---\n'), linear: parsed <= 3 * body.length })
+ .toEqual({ windows: expected.length, same: true, linear: true });
+});
diff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.ts
index de138e1ac0..936a8b5721 100644
--- a/test/e2e/conversation-facts-incremental-postgres.test.ts
+++ b/test/e2e/conversation-facts-incremental-postgres.test.ts
@@ -6,6 +6,7 @@
import { afterAll, beforeAll, describe } from 'bun:test';
import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';
+import { defineConversationFactsRecoveryCases } from '../helpers/conversation-facts-recovery-cases.ts';
import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';
import { hasDatabase } from './helpers.ts';
@@ -18,4 +19,5 @@ import { hasDatabase } from './helpers.ts';
defineSegmentedAtomsCases({ getBrain: () => brain });
defineSegmentReceiptDoctorCases({ getBrain: () => brain });
defineDerivationSpendCases({ getBrain: () => brain });
+ defineConversationFactsRecoveryCases({ getBrain: () => brain });
});
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
index defb968d12..16751483ef 100644
--- a/test/helpers/conversation-facts-incremental-cases.ts
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -41,7 +41,7 @@ const clock = (minutes: number) => { const h = 9 + Math.floor(minutes / 60); ret
const dateOf = (day: number) => new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10);
/** Timed turns two minutes apart: one gap group per day. Deterministic per seed. */
-function turns(day: number, from: number, count: number, seed: number): string {
+export function turns(day: number, from: number, count: number, seed: number): string {
let s = seed * 7919 + day * 104_729 + from;
const next = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };
const out: string[] = [];
@@ -105,17 +105,20 @@ 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; `abortAfter`: the run is aborted after that many calls.
+ * call (1-based) after the provider answered; `failOn`: it throws 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; abortAfter?: number; sinceIso?: string } = {}) {
+export async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean; paid?: boolean; failAt?: number; failOn?: (text: string) => boolean;
+ abortAfter?: number; sinceIso?: string; segmentLimit?: number } = {}) {
const calls: string[] = [];
const controller = new AbortController();
const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: opts.force,
- sinceIso: opts.sinceIso,
+ sinceIso: opts.sinceIso, segmentLimit: opts.segmentLimit,
extractor: async input => {
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 (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
new file mode 100644
index 0000000000..75f548953f
--- /dev/null
+++ b/test/helpers/conversation-facts-recovery-cases.ts
@@ -0,0 +1,176 @@
+/**
+ * Conversation facts on a segmented page when things go wrong (wave-b spec 8.2, 8.3; PR 4 lane 4b round 3), shared by
+ * the PGLite arm (test/large-pages/conversation-facts-incremental.test.ts) and the Postgres arm
+ * (test/e2e/conversation-facts-incremental-postgres.test.ts). Fake extractors only; appends go through the remote
+ * append_page operation (remote=true).
+ *
+ * 1. Protects: a partial run on a transcript without per-message times (every message at the page date) clears only
+ * the windows it extracted again; a time-less transcript whose turns cross segment cuts streams exactly the
+ * 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
+ * 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.
+ */
+import { expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { AppendBrain } from './append-brain.ts';
+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';
+import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';
+import { parseConversation } from '../../src/core/conversation-parser/parse.ts';
+import { renderSegmentForExtraction, splitIntoSegments } from '../../src/core/facts/conversation-windows.ts';
+import { WINDOW_FAILURE_LIMIT } from '../../src/core/facts/conversation-incremental.ts';
+import { outcomeSession, regularPageVersionToken } from '../../src/core/facts/conversation-window-extract.ts';
+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';
+
+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(' ');
+const sha = (text: string) => createHash('sha256').update(text).digest('hex');
+const caps = async (engine: BrainEngine, usd: string) => { await engine.setConfig(PAGE_DERIVATION_CAP_KEY, usd); await engine.setConfig(PAGE_EMBED_CAP_KEY, usd); };
+
+/**
+ * A time-less transcript (plain-role-no-time: no per-message times, so every message is at the page date): `turns`
+ * turns of a line plus continuation lines; turn `long` (if any) carries `longLines` of them, enough to span segment cuts.
+ */
+function timeless(count: number, seed: number, long = -1, longLines = 0): string {
+ const lines: string[] = [];
+ for (let t = 0; t < count; t++) {
+ lines.push(`${t % 2 === 0 ? 'user' : 'assistant'}: ${prose(seed + t, 14)}`);
+ const continuation = t === long ? longLines : 1 + ((t * 5 + seed) % 4);
+ for (let c = 0; c < continuation; c++) lines.push(prose(seed + t + c, 12 + (c % 9)));
+ }
+ return lines.join('\n');
+}
+
+const terminalStamps = async (engine: BrainEngine, slug: string) => {
+ const page = await engine.getPage(slug, { sourceId: 'default' });
+ return Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug=$1 AND source=$2 AND source_session=$3',
+ [slug, TERMINAL_AUDIT_SOURCE, outcomeSession(TERMINAL_AUDIT_SOURCE, slug, regularPageVersionToken(page!))]))[0]!.n);
+};
+
+export function defineConversationFactsRecoveryCases(opts: { getBrain: () => AppendBrain }): void {
+ test('a partial run on a transcript without message times clears only the window it extracted again', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/timeless-partial-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Timeless T1', timeless(9000, 1)));
+ const all = await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ expect((await derivations(brain.engine, slug)).live.length).toBeGreaterThan(2);
+ expect(before.length).toBe(all.calls.length);
+ expect(before.length).toBeGreaterThan(50);
+ await brain.seed(slug, chatPage('Timeless 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, before: before.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, before: before.length, after: before.length, cleaned: 1, kept: before.length - 1 });
+ }, 600_000);
+
+ test('a time-less transcript whose turns cross segment cuts streams exactly the whole-page windows before it settles', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/timeless-cuts-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Timeless cuts', timeless(9000, 2, 4500, 25000)));
+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
+ const truth = (await brain.body(slug)).truth;
+ expect(truth.length).toBeGreaterThan(3_000_000);
+ expect((await brain.engine.readManifest(page.id)).length).toBeGreaterThan(3);
+ const expected = splitIntoSegments(parseConversation(truth, { page }).messages, { pageTitle: 'Timeless cuts' }).map(seg => renderSegmentForExtraction('Timeless cuts', seg));
+ const { calls } = await extract(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect(expected.length).toBeGreaterThan(100);
+ expect({ calls: calls.length, same: [...calls].sort().join('\n') === [...expected].sort().join('\n'), stamped: await terminalStamps(brain.engine, slug),
+ states: [...new Set(rows.states)] }).toEqual({ calls: expected.length, same: true, stamped: 1, states: ['done'] });
+ }, 600_000);
+
+ test('a checkpoint write that fails keeps its window moves for the next write; no re-anchored fact is lost', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-checkpoint-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Chat checkpoint', chatDays(3000, 100, 21)));
+ const first = await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ // Three hundred more turns on the last day: one gap group with its earlier turns, so the rewritten tail's windows
+ // move to their new occurrence in the same run that extracts the new windows, before its first checkpoint.
+ expect(await brain.call('append_page', { slug, text: turns(3099, 50, 300, 21), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ let armed = true;
+ const failing = (tx: BrainEngine): BrainEngine => new Proxy(tx, {
+ get(target, prop) {
+ if (prop === 'upsertSegmentDerivations') {
+ return async (rows: Parameters<BrainEngine['upsertSegmentDerivations']>[0]) => {
+ if (armed && rows.some(row => row.kind === 'conversation_facts')) { armed = false; throw new Error('fixture: checkpoint write failed'); }
+ return target.upsertSegmentDerivations(rows);
+ };
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const engine = new Proxy(brain.engine, {
+ get(target, prop) {
+ if (prop === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(failing(tx)));
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const broken = await extract(engine, slug).catch(error => ({ error, calls: [] as string[] }));
+ expect(armed).toBe(false);
+ // Right after the failed checkpoint, the write that followed it carried its moves: every fact of a window still on
+ // the page is anchored to that window on its live occurrence, not to the occurrence the append retired.
+ const mid = await derivations(brain.engine, slug);
+ const liveKeys = new Set(mid.rows.filter(row => mid.live.includes(row.occurrenceId))
+ .flatMap(row => ((row.output as { windows?: Array<{ ordinal: number; sha: string }> })?.windows ?? []).map(w => `${row.occurrenceId}:${w.ordinal}:${w.sha}`)));
+ const liveShasMid = new Set([...liveKeys].map(key => key.split(':')[2]));
+ const midFacts = await factsOf(brain.engine, slug);
+ expect(midFacts.filter(f => liveShasMid.has(f.key.split(':')[2]) && !liveKeys.has(f.key)).length).toBe(0);
+ const resumed = await extract(brain.engine, slug);
+ const after = await factsOf(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ const liveShas = new Set(rows.keys.map(key => key.split(':')[2]));
+ const kept = before.filter(f => liveShas.has(f.key.split(':')[2]));
+ const byId = new Map(after.map(f => [f.id, f]));
+ const moved = kept.filter(f => byId.get(f.id) && byId.get(f.id)!.key !== f.key);
+ expect(moved.length).toBeGreaterThan(0);
+ expect({ keptLost: kept.filter(f => !byId.has(f.id)).length, facts: after.length, keys: rows.keys.length,
+ repeats: resumed.calls.filter(text => first.calls.includes(text)).length, anchored: after.every(f => rows.keys.includes(f.key)) })
+ .toEqual({ keptLost: 0, facts: rows.keys.length, keys: rows.keys.length, repeats: 0, anchored: true });
+ expect('error' in broken || broken.calls.length > 0).toBe(true);
+ }, 600_000);
+
+ test('a window that fails run after run is marked failed after the limit and the older windows are extracted; doctor names it, --force retries it', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-stuck-window-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Chat stuck', chatDays(3200, 100, 22)));
+ let stuck = null as string | null;
+ const failOn = (text: string) => { stuck ??= text; return text === stuck; };
+ const runs: Array<{ calls: number; failed: number }> = [];
+ for (let run = 1; run < WINDOW_FAILURE_LIMIT; run++) {
+ const { calls, result } = await extract(brain.engine, slug, { failOn });
+ runs.push({ calls: calls.length, failed: result.pages_failed });
+ expect(calls[0]).toBe(stuck!);
+ }
+ const last = await extract(brain.engine, slug, { failOn });
+ const rows = await derivations(brain.engine, slug);
+ const facts = await factsOf(brain.engine, slug);
+ expect({ runs, failed: last.result.pages_failed, first: last.calls[0] === stuck, facts: facts.length, stuckFacts: facts.filter(f => f.key.endsWith(':' + sha(stuck!))).length,
+ receipts: rows.receipts.filter(Boolean).map(r => (r as { kind: string }).kind), stamped: await terminalStamps(brain.engine, slug) })
+ .toEqual({ runs: Array.from({ length: WINDOW_FAILURE_LIMIT - 1 }, () => ({ calls: 1, failed: 1 })), failed: 0, first: true, facts: last.calls.length - 1,
+ stuckFacts: 0, receipts: ['failed_windows'], stamped: 1 });
+ expect(rows.keys.length).toBe(last.calls.length);
+ 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[]; remedy: string | null }> }).groups;
+ const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'failed_windows');
+ expect({ status: check.status, named: group?.samples.some(s => s.startsWith(`default:${slug} window `)), retry: group?.remedy?.includes('--force') }).toEqual({ status: 'warn', named: true, retry: true });
+ expect((await extract(brain.engine, slug, { failOn })).calls).toEqual([]);
+ 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);
+}
diff --git a/test/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.ts
index 40d97e6a13..f994b1108b 100644
--- a/test/large-pages/conversation-facts-incremental.test.ts
+++ b/test/large-pages/conversation-facts-incremental.test.ts
@@ -5,6 +5,7 @@
import { afterAll, beforeAll, describe } from 'bun:test';
import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';
import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';
+import { defineConversationFactsRecoveryCases } from '../helpers/conversation-facts-recovery-cases.ts';
import { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';
let brain: AppendBrain;
@@ -18,4 +19,5 @@ describe('conversation facts incremental [pglite]', () => {
defineSegmentedAtomsCases({ getBrain: () => brain });
defineSegmentReceiptDoctorCases({ getBrain: () => brain });
defineDerivationSpendCases({ getBrain: () => brain });
+ defineConversationFactsRecoveryCases({ getBrain: () => brain });
});
diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.ts
index 8b59558ff2..8ab0d85f77 100644
--- a/test/page-spend-reservation.test.ts
+++ b/test/page-spend-reservation.test.ts
@@ -8,7 +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 and nothing when the provider was never called or rejected the attempt unanswered; the estimate honors
+ * 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
+ * --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
* runs the call, a race overspends, a folded grant is booked twice, or booking ignores what the provider reported.
@@ -21,9 +24,10 @@ 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, type ChatResult } from '../src/core/ai/gateway.ts';
+import { __setChatTransportForTests, chat, withBudgetTracker, type ChatResult } from '../src/core/ai/gateway.ts';
import { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';
-import { parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';
+import { BudgetExhausted, BudgetTracker, parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';
+import { estimateChatInputTokens } from '../src/core/ai/chat-input-estimate.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
const engines: Array<{ name: string; engine: BrainEngine }> = [];
@@ -262,6 +266,99 @@ 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 () => {
+ 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 }> = {};
+ 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 };
+ }
+ __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((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 () => {
+ 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;
+ 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) / 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) });
+ }
+ });
+
+ test('concurrent metered calls under one --max-usd tracker count each other\'s in-flight attempts', async () => {
+ for (const { name, engine } of engines) {
+ const page = await segmentedPage(engine);
+ const big = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 100_000 });
+ const projected = reservationCostUsd(HAIKU, 'chat', estimateChatInputTokens({ messages: [{ content: 'window' }] }), 100_000)!;
+ const parent = new BudgetTracker({ label: 'workers', maxCostUsd: projected * 1.5, auditPath: '/dev/null' });
+ let calls = 0;
+ let entered!: () => void;
+ const inFlight = new Promise<void>(resolve => { entered = resolve; });
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ __setChatTransportForTests(async () => {
+ calls++;
+ entered();
+ if (calls === 1) await gate;
+ return answer(1000, 200);
+ });
+ try {
+ const first = withBudgetTracker(parent, () => meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, big));
+ await inFlight;
+ const second = await withBudgetTracker(parent, () => meterPaidCall(engine, page, `atoms:${HAIKU}`, 0.2, big))
+ .then(() => 'ran', (error: unknown) => (error instanceof BudgetExhausted ? 'refused by --max-usd' : String(error)));
+ release();
+ expect({ second, first: await first }, name).toEqual({ second: 'refused by --max-usd', first: { value: answer(1000, 200) } });
+ } finally {
+ release();
+ __setChatTransportForTests(null);
+ }
+ expect({ calls, spent: parent.totalSpent }, name).toEqual({ calls: 1, spent: expect.closeTo(reservationCostUsd(HAIKU, 'chat', 1000, 200)!, 12) });
+ }
+ });
+
test('the estimate honors pricing.overrides and a facts extraction reserves its call and both retries', () => {
const base = estimateChatCallUsd(HAIKU, 4000, 1000);
const overrides = parsePricingOverrides(JSON.stringify({ [HAIKU]: { input: 10, output: 100 } }));