Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(large-pages): PR 4 4b round 2: per-family derivation spend ledger, metered paid calls, checkpointed conversation facts across segment cuts

garrytanc03b8b1cde4b
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index fce2b657bc..dbe9b5520d 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -20,7 +20,7 @@ import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { agentFix, checkError } from '../check-fix.ts';
import { EXTRACT_MAX_INPUT_CHARS_KEY } from '../../../core/cycle/extract-atoms-input.ts';
-import { PAGE_EMBED_CAP_KEY } from '../../../core/page-embedding-budget.ts';
+import { PAGE_DERIVATION_CAP_KEY } from '../../../core/page-spend.ts';
interface ReceiptGroup { pipeline: string; kind: string; pages: number; samples: string[] }
@@ -31,7 +31,7 @@ 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_EMBED_CAP_KEY} <usd>`;
+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 describe = (g: ReceiptGroup): string =>
@@ -71,7 +71,7 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Che
'A higher cap lets the next extract_atoms cycle read more of each cut page; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',
{ ask_user: true, consent: ['paid'], inputs: [{ name: 'n', how: 'a character count above the cut pages\' sizes, chosen with the user' }] }) }
: capped
- ? { fix: agentFix(['gbrain', 'config', 'set', PAGE_EMBED_CAP_KEY, '<usd>'],
+ ? { fix: agentFix(['gbrain', 'config', 'set', PAGE_DERIVATION_CAP_KEY, '<usd>'],
'A higher per-page cap lets the next run read the windows the cap stopped; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',
{ ask_user: true, consent: ['paid'], inputs: [{ name: 'usd', how: 'a per-page dollar cap chosen with the user' }] }) }
: { fix_unavailable_reason: 'operator_judgement' as const }) });
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1068b4fc4e..1573a3411e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1050,9 +1050,9 @@ 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: 'The per-page spend cap now also covers fact and atom extraction on large pages; doctor lists pages it 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. Doctor lists the pages a cap stopped.' },
// 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 spend cap (`embed.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. Pages read whole are unchanged.' },
+ { 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. Pages read whole are unchanged.' },
// PR 4 (Wave B incremental derivation, transcripts)
// PR 4 4a
{ since: 'TBD', text: 'Links, mentions, timeline entries and facts/takes fences of a large (segmented) page are now kept per segment, so a write reads only the segments it changed, and an append reads its new tail instead of the whole page. A rewrite of the whole page does the same work as before. The results are unchanged.' },
diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.ts
index 8d6d5235e4..9dff4edee8 100644
--- a/src/core/config-runtime-keys.ts
+++ b/src/core/config-runtime-keys.ts
@@ -7,6 +7,7 @@
*/
export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = [
'embed.max_usd_per_page', // page-embedding-budget.ts: large-page embedding cap, default $2 (unlimited under spend.posture tokenmax)
+ 'derive.max_usd_per_page', // page-spend.ts: large-page cap per paid derivation (facts, atoms, synopsis), default $2 (unlimited under spend.posture tokenmax)
'embed.content_drift.pass_interval_hours', // content-drift-sweep.ts: hours between completed content-drift passes, default 24 (0 = every run)
'facts.absorb_warn_threshold', // doctor facts_extraction_health absorb-refusal warn threshold, default 10 per 24 h
'think.trajectory_enabled', // think/index.ts: trajectory substrate on temporal intents, default on
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index d1d5a02369..b745d26731 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -74,7 +74,7 @@ import { planSegmentDerivations, segmentDerivationContextHash } from './page-bod
import { SEGMENTED_CHUNKER_VERSION } from './page-body/segment-chunks.ts';
import { embeddingInputHash, synopsisDocumentHash, type EmbeddingTier } from './embedding-input-hash.ts';
import { currentEmbeddingSignature } from './embedding.ts';
-import { estimatePageEmbedUsd, reservePageSpend, spendGrant } from './page-embedding-budget.ts';
+import { estimatePageEmbedUsd, meterPaidCall } from './page-embedding-budget.ts';
import { segmentSynopsisLead } from './page-body/segment-synopsis.ts';
/**
@@ -561,12 +561,7 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
const estimateUsd = todo.reduce((usd, c) => usd
+ (c.chunk_source === 'fenced_code' ? 0 : estimateSynopsisCallUsd(synopsisModel, window.document, c.chunk_text, synopsisMaxTokens)), 0)
+ estimatePageEmbedUsd(todo.reduce((n, c) => n + wrapChunkForEmbedding(c.chunk_text, titlePrefix, c.chunk_source).length + SYNOPSIS_WRAPPER_CHARS, 0), embedSignature);
- const decision = await reservePageSpend(engine, page, `synopsis:${synopsisModel}`, estimateUsd);
- if (decision.kind === 'refused') {
- await derivation(segment, 'partial', anchors, { reason: 'budget_limited', cap_usd: decision.capUsd, estimate_usd: decision.estimateUsd });
- return { kind: 'skipped', reason: 'budget_limited' };
- }
- const built = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined, async () => {
+ const metered = await meterPaidCall(engine, page, `synopsis:${synopsisModel}`, estimateUsd, async () => {
const synopsized = await synopsisWrappedTexts({ chunks: todo, sourceText: window.document, title: page.title, args, synopsisModel, synopsisMaxTokens });
if (!Array.isArray(synopsized) && synopsized.kind !== 'page_level_fallback_requested') return synopsized;
const tier: EmbeddingTier = Array.isArray(synopsized) ? 'per_chunk_synopsis' : 'title';
@@ -577,6 +572,11 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promi
return classifyEmbedError(err, err instanceof Error ? err.message : String(err));
}
});
+ if ('refused' in metered) {
+ await derivation(segment, 'partial', anchors, { reason: 'budget_limited', cap_usd: metered.refused.capUsd, estimate_usd: metered.refused.estimateUsd });
+ return { kind: 'skipped', reason: 'budget_limited' };
+ }
+ const built = metered.value;
if (built.kind !== 'built') {
return { kind: built.kind === 'permanent' ? 'permanent_error' : 'transient_error', cause: built.cause, detail: built.detail };
}
diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.ts
index 6bc3f1da2a..0589cf6b12 100644
--- a/src/core/cycle/extract-atoms-page-state.ts
+++ b/src/core/cycle/extract-atoms-page-state.ts
@@ -3,7 +3,6 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { stableJson } from '../persistence/digest.ts';
import type { BrainEngine } from '../engine.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
-import type { PageEmbedGrant } from '../page-embedding-budget.ts';
/**
* gbrain#4148: consecutive same-content failures of a content-deterministic
@@ -33,8 +32,8 @@ export interface AtomPageInput {
// PR 4 (Wave B incremental derivation, transcripts)
/** One window of a segmented page (extract-atoms-segments.ts); its methods are bound to the page's derivation plan. */
export interface AtomPageWindow {
- /** Reserve this window's model call against the page's spend cap. Null: refused, the page's remaining windows are skipped and the receipt recorded. */
- reserve(model: string, maxOutputTokens: number): Promise<{ grant?: Pick<PageEmbedGrant, 'settle'> } | null>;
+ /** Run this window's model call metered against the page's atoms cap. Null: refused, the page's remaining windows are skipped and the receipt recorded. */
+ run<T>(model: string, maxOutputTokens: number, call: () => Promise<T>): Promise<{ value: T } | null>;
/** Record the window extracted with these atoms. Returns the atom slugs retired when this settles the page. */
settle(atomSlugs: string[]): Promise<string[]>;
}
@@ -157,6 +156,38 @@ export async function transferLegacyAtomPageState(engine: SqlEngine, before: Pag
return rows.length > 0;
}
+/**
+ * Soft-delete an origin's atoms that are not current, inside the caller's transaction (errors propagate, so the caller's
+ * transaction rolls back). PR 4 (Wave B incremental derivation, transcripts): a segmented page settles with its scan
+ * state's revision check first, then this, in one transaction.
+ */
+export async function retireStaleAtomsIn(
+ tx: BrainEngine,
+ sourceId: string,
+ origin: { key: 'source_slug' | 'source_path'; value: string },
+ hash16: string,
+ currentSlugs: string[],
+): Promise<string[]> {
+ const stale = await staleAtomSlugs(tx, sourceId, origin, hash16, currentSlugs);
+ for (let i = 0; i < stale.length; i += 500) await tx.softDeletePages(stale.slice(i, i + 500), { sourceId });
+ return stale;
+}
+
+async function staleAtomSlugs(engine: BrainEngine, sourceId: string, origin: { key: 'source_slug' | 'source_path'; value: string },
+ hash16: string, currentSlugs: string[]): Promise<string[]> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages
+ WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL
+ AND frontmatter->>'${origin.key}' = $2
+ AND COALESCE(frontmatter->>'source_hash', '') <> $3
+ AND (frontmatter->>'imported_from') IS NULL
+ AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'
+ AND NOT (slug = ANY($4::text[]))`,
+ [sourceId, origin.value, hash16, currentSlugs],
+ );
+ return rows.map(r => r.slug);
+}
+
/**
* Soft-delete a source's atoms from earlier extractions (a different or
* provisional source_hash) that the current, completed extraction did not
@@ -171,17 +202,7 @@ export async function retireStaleAtoms(
currentSlugs: string[],
): Promise<string[]> {
try {
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages
- WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL
- AND frontmatter->>'${origin.key}' = $2
- AND COALESCE(frontmatter->>'source_hash', '') <> $3
- AND (frontmatter->>'imported_from') IS NULL
- AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'
- AND NOT (slug = ANY($4::text[]))`,
- [sourceId, origin.value, hash16, currentSlugs],
- );
- const stale = rows.map(r => r.slug);
+ const stale = await staleAtomSlugs(engine, sourceId, origin, hash16, currentSlugs);
for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));
return stale;
} catch (err) {
diff --git a/src/core/cycle/extract-atoms-segments.ts b/src/core/cycle/extract-atoms-segments.ts
index 9f9b2f348c..76f57a8a6a 100644
--- a/src/core/cycle/extract-atoms-segments.ts
+++ b/src/core/cycle/extract-atoms-segments.ts
@@ -7,20 +7,23 @@
* the atom slugs it produced). An append offers only the new text's windows; a window whose text an earlier run
* extracted under the same context is never offered again, so a rewritten tail keeps its earlier windows' atoms.
*
- * Each window's call reserves against the page's spend cap (reservePageSpend, atoms:<model>) first; a refusal skips the
- * page's remaining windows and records an unread_windows receipt on each unfinished occurrence's row. When every live
- * occurrence is settled, atoms of windows that left the page (and atoms of an earlier whole-page extraction) are
- * retired and the page's scan state is stamped complete for its content hash, so discovery skips it until it changes.
+ * Each window's call is metered against the page's atoms cap (meterPaidCall, atoms:<model>: reserved first, the
+ * provider-reported cost booked); a refusal skips the page's remaining windows and records an unread_windows receipt on
+ * each unfinished occurrence's row. When every live occurrence is settled, the page's scan state is stamped complete
+ * for its content hash (the revision check) and then, in the same transaction, atoms of windows that left the page (and
+ * atoms of an earlier whole-page extraction) are retired, so a page that changed meanwhile retires nothing.
* The completion CAS stays on content_hash + knowledge_revision (completeAtomReceipts). Managed brains do not extract
* segmented pages (their publication path is whole-page).
*/
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
-import { estimateChatCallUsd, reservePageSpend } from '../page-embedding-budget.ts';
+import { loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { estimateChatCallUsd, meterPaidCall } from '../page-embedding-budget.ts';
import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';
import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
import { lineWindows } from '../facts/backstop-segments.ts';
-import { retireStaleAtoms, writeAtomPageState, type AtomPageInput, type AtomPageWindow } from './extract-atoms-page-state.ts';
+import { retireStaleAtomsIn, writeAtomPageState, type AtomPageInput, type AtomPageWindow } from './extract-atoms-page-state.ts';
const KIND = 'extract_atoms';
/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */
@@ -81,9 +84,11 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInp
const keep = new Set<string>();
for (const current of plan.current) for (const w of records(current)) for (const slug of w.atoms ?? []) keep.add(slug);
for (const state of states.values()) for (const w of state.done.values()) for (const slug of w.atoms) keep.add(slug);
- const gone = await retireStaleAtoms(engine, sourceId, { key: 'source_slug', value: page.slug }, '', [...keep]);
- await writeAtomPageState(engine, sourceId, page, 'complete');
- return gone;
+ // PR 4 (Wave B incremental derivation, transcripts): the revision check, then the retire, in one transaction.
+ return maintenanceTransaction(engine, async tx => {
+ await writeAtomPageState(tx, sourceId, page, 'complete');
+ return retireStaleAtomsIn(tx, sourceId, { key: 'source_slug', value: page.slug }, '', [...keep]);
+ });
};
for (const occurrence of [...occurrences].reverse()) {
const segment = todo.get(occurrence.row.occurrenceId);
@@ -105,13 +110,13 @@ async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInp
if (items.length >= MAX_ATOM_WINDOWS_PER_PAGE_RUN) { unread = true; continue; }
open++;
const window: AtomPageWindow = {
- async reserve(model, maxOutputTokens) {
- if (opts.dryRun) return {};
+ async run(model, maxOutputTokens, call) {
+ if (opts.dryRun) return { value: await call() };
if (stop) return null;
- const decision = await reservePageSpend(engine, { id: pageId, body_storage: 'segmented' }, `atoms:${model}`,
- estimateChatCallUsd(model, text.length, maxOutputTokens));
- if (decision.kind === 'grant') return { grant: decision.grant };
- if (decision.kind !== 'refused') return {};
+ const pricingOverrides = await loadPricingOverrides(engine);
+ const metered = await meterPaidCall(engine, { id: pageId, body_storage: 'segmented' }, `atoms:${model}`,
+ estimateChatCallUsd(model, text.length, maxOutputTokens, pricingOverrides), call, { pricingOverrides });
+ if (!('refused' in metered)) return metered;
stop = 'cap_reached';
const unfinished = [...states.values()].filter(s => s.done.size < s.total);
if (unfinished.length) await engine.upsertSegmentDerivations(unfinished.map(row));
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 2753db3113..af8ee3bfec 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -72,7 +72,6 @@ import { serializeMarkdown } from '../markdown.ts';
import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';
import { commitExtractionPlan, readPageWatermark } from '../extraction-watermark.ts';
import { expandSegmentedAtomPages } from './extract-atoms-segments.ts';
-import { spendGrant } from '../page-embedding-budget.ts';
import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';
@@ -1006,9 +1005,9 @@ export async function runPhaseExtractAtoms(
}
/** PR 4 4b: a segmented page's window reserves its call against the page's spend cap first; null: refused, the item is skipped. */
async function chatWithinPageCap<T>(item: WorkItem, call: () => Promise<T>): Promise<T | null> {
- const reserved = item.kind === 'page' && item.window ? await item.window.reserve(extractModel, maxOutputTokens) : {};
- if (!reserved) pagesSkipped++;
- return reserved ? spendGrant(reserved.grant, call) : null;
+ const metered = item.kind === 'page' && item.window ? await item.window.run(extractModel, maxOutputTokens, call) : { value: await call() };
+ if (!metered) pagesSkipped++;
+ return metered ? metered.value : null;
}
/** Large pages A7: a page's watermark moves past the text this item read once its writes committed (a pending batch keeps the old one). */
async function commitAtomsWatermark(item: ExtractAtomsItem, input: ExtractAtomsInput, published: readonly { state: string }[]): Promise<void> {
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index d3d4b027ad..c5efd13a67 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -112,6 +112,7 @@ const ROWS: readonly Row[] = [
['page_body_staging_parts', 'swept', 'body_stagings', 'sha256 body', 'body'],
['page_body_stagings', 'swept', 'body_stagings', 'kind principal_kind principal_id source_id slug mode declared_sha256 state'],
['page_body_staging_texts', 'swept', 'body_stagings', 'source_id sha256'],
+ ['page_derivation_spend', 'out_of_scope', 'no_memory_text', 'family'],
['page_embedding_budget', 'out_of_scope', 'no_memory_text', 'state reason embedding_signature'],
['page_extraction_state', 'out_of_scope', 'no_memory_text', 'pipeline watermark_sha256 input_truncated'],
['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],
diff --git a/src/core/facts/backstop-segments.ts b/src/core/facts/backstop-segments.ts
index 1a866498a5..048a432a22 100644
--- a/src/core/facts/backstop-segments.ts
+++ b/src/core/facts/backstop-segments.ts
@@ -1,18 +1,21 @@
/**
* The facts backstop over a segmented page (wave-b spec 8.2 "Facts backstop", 8.3; PR 4 lane 4b): new occurrences
- * only, in MAX_TURN_TEXT_CHARS windows cut at line starts, newest first, each window reserved against the page's
- * spend cap (reservePageSpend, facts:<model>) before its extraction.
+ * only, in MAX_TURN_TEXT_CHARS windows cut at line starts, newest first, each window metered against the page's facts
+ * cap (meterPaidCall, facts:<model>: every attempt reserved, the provider-reported cost booked) around its extraction.
*
* Per occurrence a page_segment_derivations row (kind facts_backstop) records the segment sha, a context hash (region,
* model, window cap, observation date) and the windows extracted (ordinal, text sha, facts inserted). A window an
* earlier run extracted under the same context is never extracted again: in the same occurrence (a partial run), or
* verbatim in a retired one (a rewritten tail keeps its earlier windows), so an append pays for its new text plus the
* one window it grew. Replaces planSegmentedExtraction's whole-body pass and its watermark for segmented pages; the
- * page_extraction_state receipt is cleared, a stopped occurrence's receipt lives on its row.
+ * page_extraction_state receipt is cleared, a stopped occurrence's receipt lives on its row. The rows are written when a
+ * window throws or the run aborts too, so the windows already extracted (their facts are written per window) are never
+ * extracted again.
*/
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
-import { estimateChatCallUsd, reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
+import { loadPricingOverrides } from '../budget/budget-tracker.ts';
+import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';
import { setExtractionReceipt } from '../extraction-watermark.ts';
import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';
import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
@@ -65,6 +68,7 @@ export interface SegmentedBackstopRun<R extends { inserted: number; skipped_reas
*/
export async function runSegmentedBackstop<R extends { inserted: number; skipped_reason?: unknown }>(run: SegmentedBackstopRun<R>):
Promise<{ results: R[]; stop: 'cap_reached' | 'skipped' | null }> {
+ // PR 4 (Wave B incremental derivation, transcripts)
const { engine, page } = run;
const { body, occurrences } = await readConversationOccurrences(engine, page.id);
const context = { model: run.model, cap: MAX_TURN_TEXT_CHARS, observation: run.observation };
@@ -78,38 +82,49 @@ export async function runSegmentedBackstop<R extends { inserted: number; skipped
if (row.version === FACTS_BACKSTOP_DERIVATION_VERSION) for (const w of records(row)) extracted.add(`${hex(row.contextHash)}:${w.sha}`);
}
const maxTokens = await getFactsExtractionMaxTokens(engine);
+ const pricingOverrides = plan.todo.length ? await loadPricingOverrides(engine) : undefined;
const results: R[] = [];
- const derived: SegmentDerivationInput[] = [];
- let stop: 'cap_reached' | 'skipped' | null = null;
- const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
- for (const occurrence of [...occurrences].reverse()) {
- const segment = todo.get(occurrence.row.occurrenceId);
- if (!segment || stop) continue;
- const old = priorRow.get(segment.occurrenceId);
- const done = new Map((old && old.version === FACTS_BACKSTOP_DERIVATION_VERSION && hex(old.contextHash) === hex(segment.contextHash) ? records(old) : [])
- .map(w => [w.ordinal, w]));
- const windows = lineWindows(await readOccurrenceText(engine, body, occurrence.row), MAX_TURN_TEXT_CHARS);
- for (let ordinal = windows.length - 1; ordinal >= 0; ordinal--) {
- const text = windows[ordinal]!;
- const key = sha(text);
- if (done.get(ordinal)?.sha === key) continue;
- if (extracted.has(`${hex(segment.contextHash)}:${key}`) || !text.trim()) { done.set(ordinal, { ordinal, sha: key, facts: 0 }); continue; }
- if (run.signal?.aborted) { stop = 'skipped'; break; }
- const decision = await reservePageSpend(engine, page, `facts:${run.model}`, estimateChatCallUsd(run.model, text.length, maxTokens));
- if (decision.kind === 'refused') { stop = 'cap_reached'; break; }
- const result = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined, () => run.extract(text));
- results.push(result);
- if (result.skipped_reason) { stop = 'skipped'; break; }
- done.set(ordinal, { ordinal, sha: key, facts: result.inserted });
- extracted.add(`${hex(segment.contextHash)}:${key}`);
- }
+ const touched: Array<{ segment: (typeof plan.todo)[number]; windows: string[]; done: Map<number, WindowRecord> }> = [];
+ let stop: 'cap_reached' | 'skipped' | 'interrupted' | null = null;
+ const rowsOf = (): SegmentDerivationInput[] => touched.map(({ segment, windows, done }) => {
const kept = windows.flatMap((text, ordinal) => done.get(ordinal)?.sha === sha(text) ? [done.get(ordinal)!] : []);
const finished = kept.length === windows.length;
- derived.push({ pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: FACTS_BACKSTOP_DERIVATION_VERSION,
+ return { pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: FACTS_BACKSTOP_DERIVATION_VERSION,
segmentSha256: segment.sha256, contextHash: segment.contextHash, state: finished ? 'done' : 'partial', output: { windows: kept },
- receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: kept.length, windows_total: windows.length } });
+ receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: kept.length, windows_total: windows.length } };
+ });
+ const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
+ try {
+ for (const occurrence of [...occurrences].reverse()) {
+ const segment = todo.get(occurrence.row.occurrenceId);
+ if (!segment || stop) continue;
+ const old = priorRow.get(segment.occurrenceId);
+ const done = new Map((old && old.version === FACTS_BACKSTOP_DERIVATION_VERSION && hex(old.contextHash) === hex(segment.contextHash) ? records(old) : [])
+ .map(w => [w.ordinal, w]));
+ const windows = lineWindows(await readOccurrenceText(engine, body, occurrence.row), MAX_TURN_TEXT_CHARS);
+ touched.push({ segment, windows, done });
+ for (let ordinal = windows.length - 1; ordinal >= 0; ordinal--) {
+ const text = windows[ordinal]!;
+ const key = sha(text);
+ if (done.get(ordinal)?.sha === key) continue;
+ if (extracted.has(`${hex(segment.contextHash)}:${key}`) || !text.trim()) { done.set(ordinal, { ordinal, sha: key, facts: 0 }); continue; }
+ if (run.signal?.aborted) { stop = 'skipped'; break; }
+ const metered = await meterPaidCall(engine, page, `facts:${run.model}`, estimateFactsExtractionUsd(run.model, text.length, maxTokens, pricingOverrides),
+ () => run.extract(text), { pricingOverrides });
+ if ('refused' in metered) { stop = 'cap_reached'; break; }
+ const result = metered.value;
+ results.push(result);
+ if (result.skipped_reason) { stop = 'skipped'; break; }
+ done.set(ordinal, { ordinal, sha: key, facts: result.inserted });
+ extracted.add(`${hex(segment.contextHash)}:${key}`);
+ }
+ }
+ } catch (error) {
+ stop = 'interrupted';
+ if (touched.length) await engine.upsertSegmentDerivations(rowsOf()).catch(() => {});
+ throw error;
}
- if (derived.length) await engine.upsertSegmentDerivations(derived);
+ if (touched.length) await engine.upsertSegmentDerivations(rowsOf());
await engine.retireSegmentDerivations(page.id, live.map(segment => segment.occurrenceId), { kind: KIND });
await setExtractionReceipt(engine, page.id, KIND, null);
return { results, stop };
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index 1acf2b5170..11d5172cb9 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -1,43 +1,56 @@
/**
* Incremental conversation facts for a segmented page (wave-b spec 8.1, 8.2 "Conversation facts", 8.3; PR 4 lane 4b).
*
- * Windows are packed inside one occurrence (segments cut at message lines and day headers; a gap group never spans a
- * cut). Each window's facts carry its anchor in facts.source_window (occurrence, ordinal, rendered-text sha). Per
- * occurrence, a page_segment_derivations row (kind conversation_facts) records the segment sha, a context hash (the
- * occurrence's conversation entry state plus every page-level input the windows depend on: title, gap setting, date
- * context, extraction model, --since) and the window keys it produced. A run then:
- * - extracts only the windows of new, rewritten or context-changed occurrences, newest first, each one reserved
- * against the page's spend cap (reservePageSpend, facts:<model>) before the call;
- * - keeps every fact whose window is still live (its row and id are untouched);
- * - clears the facts of windows no live occurrence produces any more (retired occurrences, rewritten tails), and the
- * page's unanchored facts from older full-pass runs once every live occurrence is settled;
- * - reads only the text of the occurrences it extracts (one segment at a time), never the whole body.
- * A title or gap change re-extracts every window (documented cost); a no-op rewrite extracts nothing. An occurrence a
- * run stops inside (--segment-limit, the spend cap) is stored as partial with the windows it finished, and the next
- * run resumes after them. Unmanaged brains only: a managed brain keeps the receipted whole-page publication.
+ * Windows run over message boundaries across occurrences (conversation-stream.ts), so a window can span a segment cut;
+ * each window belongs to the occurrence its first message starts in. Each window's facts carry its anchor in
+ * 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:
+ * - 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
+ * reads only the runs it reached; a page nothing changed on reads nothing;
+ * - reuses every window an earlier run extracted with the same rendered text under the same context (re-anchored
+ * when it moved), so an append extracts only its new windows and the one it grew;
+ * - extracts the rest newest first, each call metered against the page's facts cap (meterPaidCall, facts:<model>,
+ * 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;
+ * - 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
+ * 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
+ * window (documented cost); a no-op rewrite extracts nothing. Unmanaged brains only: a managed brain keeps the
+ * receipted whole-page publication.
*/
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
-import { deriveDateContext, parseConversation } from '../conversation-parser/parse.ts';
+import { deriveDateContext } from '../conversation-parser/parse.ts';
+import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';
import { writeDerivedFacts } from '../persistence/derived-facts.ts';
-import { estimateChatCallUsd, reservePageSpend, spendGrant } from '../page-embedding-budget.ts';
+import { estimateFactsExtractionUsd, meterPaidCall } from '../page-embedding-budget.ts';
import { setExtractionReceipt } from '../extraction-watermark.ts';
import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey, type SegmentDerivationInput,
type SegmentDerivationRow, type SourceWindow } from '../page-body/derivations.ts';
-import { readConversationOccurrences, readOccurrenceText, type ConversationOccurrence } from '../page-body/segment-conversation.ts';
-import type { SegmentedBody } from '../page-body/read-range.ts';
+import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
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 type { ConversationSegment } from './conversation-types.ts';
-import { MAX_PAGE_SEGMENT_GAP_MINUTES, renderSegmentForExtraction, splitIntoSegments } from './conversation-windows.ts';
+import { renderSegmentForExtraction } from './conversation-windows.ts';
import { extractConversationWindow, nonExtractableAuditFact, regularPageVersionToken, terminalAuditFact, type ConversationWindowRun } from './conversation-window-extract.ts';
-import { getFactsExtractionMaxTokens, resolveFactsExtractionModel } from './extract.ts';
+import { getFactsExtractionMaxTokens, resolveFactsExtractionModel, type ExtractInput } from './extract.ts';
+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;
+/** Windows extracted between two publications of a page's facts and rows. */
+export const CONVERSATION_FACTS_CHECKPOINT_WINDOWS = 8;
/** The run counters this pass moves (a subset of ExtractConversationFactsResult). */
export interface SegmentedConversationCounters {
@@ -55,42 +68,43 @@ export interface SegmentedConversationRun extends ConversationWindowRun {
segmentLimit: number;
}
-/** One window of an occurrence: what the extractor reads and its anchor. */
-interface OccurrenceWindow { seg: ConversationSegment; text: string; window: SourceWindow }
-/** A window an occurrence row records: its ordinal, rendered-text sha and how many facts it produced. */
-interface WindowRecord { ordinal: number; sha: string; facts: 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 }
+type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;
/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */
-function windowRecords(row: SegmentDerivationRow | undefined): WindowRecord[] {
- const windows = (row?.output as { windows?: unknown } | null)?.windows;
- return Array.isArray(windows) ? windows as WindowRecord[] : [];
+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 };
}
const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });
+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
-/** Every page-level input the windows of an occurrence depend on (the context hash's \`page\` part). */
-async function conversationContext(engine: BrainEngine, page: Page, gapMinutes: number | null, sinceIso: string | undefined) {
+/** Every page-level input the windows depend on: the context hash. */
+async function conversationContext(engine: BrainEngine, page: Page, gapMinutes: number | null, visibility: FactVisibility) {
const dates = deriveDateContext({ page });
const model = (await resolveFactsExtractionModel(engine)).model;
- return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, since: sinceIso ?? null } };
+ return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, visibility } };
}
-/** The windows of one occurrence: its own text parsed alone (with the date context its entry state carries in) and packed under the window caps. */
-async function occurrenceWindows(engine: BrainEngine, body: SegmentedBody, occurrence: ConversationOccurrence, page: Page,
- opts: { gapMinutes: number | null; sinceIso?: string }): Promise<OccurrenceWindow[]> {
- const text = await readOccurrenceText(engine, body, occurrence.row);
- const fallbackDate = occurrence.conversation?.fallbackDate ?? undefined;
- const parsed = parseConversation(text, { page, ...(fallbackDate ? { fallbackDate } : {}) });
- const gapMinutes = opts.gapMinutes ?? (parsed.matched_pattern_id === 'email-thread-heading' ? MAX_PAGE_SEGMENT_GAP_MINUTES : undefined);
- const pageTitle = page.title || page.slug;
- return splitIntoSegments(parsed.messages, { gapMinutes, sinceIso: opts.sinceIso, pageTitle }).map((seg, ordinal) => {
- const rendered = renderSegmentForExtraction(pageTitle, seg);
- return { seg, text: rendered, window: sourceWindowFor(occurrence.row.occurrenceId, ordinal, rendered) };
- });
+/** 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;
+ 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]);
+ }
+ return earlier.filter(e => e.start && e.end && runs.some(([start, end]) => e.start! >= start && e.end! <= end)).map(e => e.key);
}
/**
- * One segmented page's conversation facts, incrementally (module doc). \`gapMinutes\` is the page's own
+ * 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,
@@ -98,112 +112,192 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
const { engine, sourceId, result } = run;
result.pages_considered++;
const versionToken = regularPageVersionToken(page);
- const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, opts.sinceIso);
+ const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, run.factVisibility);
+ const contextHash = segmentDerivationContextHash(KIND, { entryState: null, page: inputs });
const { body, occurrences } = await readConversationOccurrences(engine, page.id);
- const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256,
- contextHash: segmentDerivationContextHash(KIND, { entryState: { region: o.row.region, conversation: o.conversation }, page: inputs }) }));
+ const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256, contextHash }));
+ const liveIds = live.map(segment => segment.occurrenceId);
const prior = await engine.readSegmentDerivations(page.id, { kind: KIND });
const plan = planSegmentDerivations(KIND, CONVERSATION_FACTS_DERIVATION_VERSION, live, prior);
const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));
- const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));
- // Windows of retired occurrences by (context, rendered-text sha): a rewritten tail re-cut under a new occurrence id
- // brings most of its windows back verbatim, and those keep their facts, re-anchored, instead of a new call.
- const retiredWindows = new Map<string, { occurrenceId: number; record: WindowRecord }>();
- for (const row of plan.retired) {
- if (row.version !== CONVERSATION_FACTS_DERIVATION_VERSION) continue;
- for (const record of windowRecords(row)) retiredWindows.set(`${Buffer.from(row.contextHash).toString('hex')}:${record.sha}`, { occurrenceId: row.occurrenceId, record });
+ 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);
+ // 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));
+ if (first < 0) first = plan.retired.length ? liveIds.length : -1;
+ let from = first < 0 ? liveIds.length : 0;
+ for (let i = Math.min(first, liveIds.length) - 1; i > 0; i--) {
+ if (intact(i) && rowOutput(priorRow.get(liveIds[i]!)).starts_group === true) { from = i; break; }
}
- const moves: Array<{ from: string; to: SourceWindow }> = [];
-
- const maxTokens = await getFactsExtractionMaxTokens(engine);
- const entityHints = todo.size && !run.dryRun ? await conversationEntityHints(engine, sourceId, page.slug, run.factVisibility) : undefined;
- const resolution = emptySaveTimeResolutionCounts();
- const rows: ConversationFactRow[] = [];
- const windows: SourceWindow[] = [];
- const derived = new Map<number, SegmentDerivationInput>();
- let extractedWindows = 0;
- const extractedKeys = new Set<string>();
- let stop: 'segment_limit' | 'cap_reached' | null = null;
- let newestEnd: string | null = null;
- // Newest occurrences first, and newest windows first inside each, so a cap or a limit spends on the newest messages.
- for (const occurrence of [...occurrences].reverse()) {
- const segment = todo.get(occurrence.row.occurrenceId);
- if (!segment || stop) continue;
- // A window the occurrence's stored row already extracted under the same context (a partial run, or a tail rewrite
- // that left it intact) keeps its facts: same ordinal and rendered-text sha.
- const old = priorRow.get(segment.occurrenceId);
- const reusable = old && old.version === CONVERSATION_FACTS_DERIVATION_VERSION && Buffer.from(old.contextHash).equals(Buffer.from(segment.contextHash));
- const done = new Map((reusable ? windowRecords(old) : []).map(w => [w.ordinal, w]));
- const all = await occurrenceWindows(engine, body, occurrence, page, opts);
- for (const w of [...all].reverse()) {
- const record = done.get(w.window.window_ordinal);
- if (record?.sha === w.window.window_text_sha) continue;
- const moved = retiredWindows.get(`${Buffer.from(segment.contextHash).toString('hex')}:${w.window.window_text_sha}`);
- if (moved) {
- retiredWindows.delete(`${Buffer.from(segment.contextHash).toString('hex')}:${w.window.window_text_sha}`);
- moves.push({ from: keyOf(moved.occurrenceId, moved.record), to: w.window });
- done.set(w.window.window_ordinal, { ordinal: w.window.window_ordinal, sha: w.window.window_text_sha, facts: moved.record.facts });
- continue;
- }
- if (run.segmentLimit > 0 && extractedWindows >= run.segmentLimit) { stop = 'segment_limit'; break; }
- if (run.signal?.aborted) throw new Error('aborted');
- if (run.dryRun) { extractedWindows++; continue; }
- const decision = await reservePageSpend(engine, page, `facts:${model}`, estimateChatCallUsd(model, w.text.length, maxTokens));
- if (decision.kind === 'refused') { stop = 'cap_reached'; break; }
- const out = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined,
- () => extractConversationWindow(run, page, w.seg, w.text, 0, entityHints));
- extractedWindows++;
- result.segments_processed++;
- result.facts_extracted += out.extracted;
- mergeSaveTimeResolutionCounts(resolution, out.resolution);
- for (const row of out.rows) { rows.push(row); windows.push(w.window); }
- done.set(w.window.window_ordinal, { ordinal: w.window.window_ordinal, sha: w.window.window_text_sha, facts: out.extracted });
- extractedKeys.add(sourceWindowKey(w.window));
- if (!newestEnd || w.seg.endIso > newestEnd) newestEnd = w.seg.endIso;
- if (run.sleepMs > 0) await new Promise(resolve => setTimeout(resolve, run.sleepMs));
+ const position = new Map(liveIds.map((id, i) => [id, i]));
+ // 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 }> = [];
+ 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 finished = all.every(w => done.get(w.window.window_ordinal)?.sha === w.window.window_text_sha);
- const kept = all.flatMap(w => { const r = done.get(w.window.window_ordinal); return r?.sha === w.window.window_text_sha ? [r] : []; });
- derived.set(segment.occurrenceId, { pageId: page.id, kind: KIND, occurrenceId: segment.occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION,
- segmentSha256: segment.sha256, contextHash: segment.contextHash, state: finished ? 'done' : 'partial', output: { windows: kept },
- receipt: finished ? null : { kind: 'unread_windows', pipeline: KIND, reason: stop, windows_read: kept.length, windows_total: all.length } });
}
- result.fallback_slugify_count += resolution.fallback_slugify_count;
- result.resolution_errors += resolution.resolution_errors;
+ const windows: StreamWindow[] = [];
+ const pendingMoves: Array<{ from: string; to: SourceWindow }> = [];
+ const reused = new Set<string>();
+ 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 texts = new Map<number, string>();
+ const readText = async (i: number) => {
+ const cached = texts.get(i);
+ if (cached !== undefined) return cached;
+ const text = await readOccurrenceText(engine, body, occurrences[i]!.row);
+ texts.set(i, text);
+ return text;
+ };
+ /** Stream the newest run not streamed yet: from the nearest occurrence before `end` whose first message opens a gap group (module doc). */
+ const streamRun = async (end: number): Promise<{ start: number; windows: StreamWindow[] }> => {
+ 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 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 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 });
+ },
+ occurrence(index, starts) { startsGroup.set(liveIds[index]!, starts); },
+ });
+ for (const i of [...texts.keys()]) if (i > start) texts.delete(i);
+ windows.unshift(...runWindows);
+ return { start, windows: runWindows };
+ };
if (run.dryRun) {
+ let todo = 0;
+ for (let end = liveIds.length; end > from;) { const next = await streamRun(end); todo += next.windows.filter(w => w.state === 'todo').length; end = next.start; }
+ result.segments_processed += run.segmentLimit > 0 ? Math.min(todo, run.segmentLimit) : todo;
result.pages_processed++;
return { newestEnd: null };
}
- // Window keys whose facts stay: every live occurrence's newest row (this run's, else the stored one), minus the
- // windows extracted again this run (their earlier facts give way to the new ones).
- const liveIds = live.map(segment => segment.occurrenceId);
- const liveKeys = liveIds.flatMap(id => windowRecords((derived.get(id) ?? priorRow.get(id)) as SegmentDerivationRow | undefined).map(w => keyOf(id, w)));
- const keep = liveKeys.filter(key => !extractedKeys.has(key));
- const settled = liveIds.every(id => derived.has(id) ? derived.get(id)!.state === 'done' : !todo.has(id));
- const current = await engine.getPage(page.slug, { sourceId });
- const unchanged = !!current && current.id === page.id && regularPageVersionToken(current) === versionToken;
- const outcome = !settled || !unchanged ? null : liveKeys.length
- ? terminalAuditFact(page.slug, 0, versionToken) : nonExtractableAuditFact(page.slug, 0, versionToken, 'fewer than two eligible messages');
- const published = await writeDerivedFacts(engine, sourceId, page.slug, async db => {
- const out = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...rows, outcome] : rows,
- { scope: 'window', segments: { windows, moves, keep: unchanged ? keep : [...keep, ...plan.retired.flatMap(row => windowRecords(row).map(w => keyOf(row.occurrenceId, w)))], retireUnanchored: settled && unchanged } });
- if (derived.size) await db.upsertSegmentDerivations([...derived.values()]);
- if (unchanged) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
- return out;
- });
+ const resolution = emptySaveTimeResolutionCounts();
+ let streamedFrom = liveIds.length;
+ let stop: Stop = null;
+ let stopOwner: number | null = null;
+ let newestEnd: string | null = null;
+ let extracted = 0;
+ let batch: { rows: ConversationFactRow[]; windows: SourceWindow[]; keys: string[] } = { rows: [], windows: [], keys: [] };
+ let cleared = new Set<string>();
+ let settledPage = false;
+ /** Publish the facts extracted since the last publication and the rows of the streamed occurrences; `final` settles a finished page. */
+ const publish = async (final: boolean) => {
+ let unchanged = true;
+ if (final) {
+ const now = await engine.getPage(page.slug, { sourceId });
+ unchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;
+ }
+ const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;
+ 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).
+ 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 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 } }];
+ });
+ 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 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 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 } });
+ if (derived.length) await db.upsertSegmentDerivations(derived);
+ if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
+ return published;
+ });
+ cleared = new Set([...cleared, ...clear]);
+ batch = { rows: [], windows: [], keys: [] };
+ result.facts_inserted += out.facts_inserted;
+ result.orphan_facts_cleaned += out.deleted;
+ settledPage = settled;
+ return { unchanged, settled, keep, outcome };
+ };
+
+ const maxTokens = await getFactsExtractionMaxTokens(engine);
+ let paid: { pricingOverrides: PricingOverrides | undefined; entityHints: ExtractInput['entityHints'] } | null = null;
+ try {
+ // Newest runs first, and newest windows first inside each, so a cap or a limit spends on the newest messages.
+ for (let end = liveIds.length; end > from && !stop;) {
+ const next = await streamRun(end);
+ streamedFrom = end = next.start;
+ for (const w of next.windows.filter(x => x.state === 'todo').reverse()) {
+ stopOwner = w.owner;
+ if (run.segmentLimit > 0 && extracted >= run.segmentLimit) { stop = 'segment_limit'; break; }
+ if (run.signal?.aborted) throw new Error('aborted');
+ 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 });
+ if ('refused' in metered) { stop = 'cap_reached'; break; }
+ const out = metered.value;
+ w.state = 'extracted';
+ w.facts = out.extracted;
+ w.text = null;
+ extracted++;
+ result.segments_processed++;
+ result.facts_extracted += out.extracted;
+ mergeSaveTimeResolutionCounts(resolution, out.resolution);
+ for (const row of out.rows) { batch.rows.push(row); batch.windows.push(w.window); }
+ batch.keys.push(sourceWindowKey(w.window));
+ if (!newestEnd || w.seg.endIso > newestEnd) newestEnd = w.seg.endIso;
+ stopOwner = null;
+ if (batch.keys.length >= CONVERSATION_FACTS_CHECKPOINT_WINDOWS) await publish(false);
+ if (run.sleepMs > 0) await new Promise(resolve => setTimeout(resolve, run.sleepMs));
+ }
+ }
+ } catch (error) {
+ stop = 'interrupted';
+ await publish(false).catch(publishError => {
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: could not publish the finished windows: ${publishError instanceof Error ? publishError.message : String(publishError)}\n`);
+ });
+ throw error;
+ } finally {
+ result.fallback_slugify_count += resolution.fallback_slugify_count;
+ result.resolution_errors += resolution.resolution_errors;
+ }
+
+ const { unchanged, keep, outcome } = await publish(true);
await setExtractionReceipt(engine, page.id, KIND, null);
- result.facts_inserted += published.facts_inserted;
- result.orphan_facts_cleaned += published.deleted;
if (!unchanged) {
process.stderr.write(`[extract-conversation-facts] ${page.slug} changed during extraction; its finished windows were kept, the rest wait for the next run\n`);
result.pages_failed++;
recordFailedPage(result, page.slug, 'the page changed during extraction; left unfinished for replay');
return { newestEnd: null };
}
- if (outcome && !liveKeys.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }
+ if (outcome && !keep!.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }
else result.pages_processed++;
- process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${published.facts_inserted} facts inserted across ${extractedWindows} new window(s) `
- + `(${plan.todo.length} of ${live.length} occurrence(s) to extract, ${plan.retired.length} retired)${stop ? `; stopped: ${stop}` : ''}\n`);
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${extracted} new window(s) of ${windows.length} streamed from occurrence ${streamedFrom + 1} of ${liveIds.length}`
+ + `${stop ? `; stopped: ${stop}` : settledPage ? '; settled' : ''}\n`);
return { newestEnd };
}
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 3bb768c1b9..647389a482 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -416,15 +416,17 @@ type UnnumberedFact = Omit<ConversationFactRow, 'row_num' | 'source_markdown_slu
/**
* A segmented page's incremental publication (wave-b spec 8.2, PR 4): `windows[i]` anchors `rows[i]` (facts.source_window;
- * null for an outcome row). Nothing is replaced wholesale: the page's extractor facts whose window key is not in `keep`
- * (windows of retired or rewritten occurrences) are cleared, and so are its unanchored facts (older full-pass runs)
- * when `retireUnanchored` (every live occurrence is settled); every other fact keeps its row and id.
+ * null for an outcome row). Nothing is replaced wholesale. A settled page (every live window extracted) passes `keep`: its
+ * extractor facts whose window key is not in it (windows that left the page) are cleared, and so are its unanchored facts
+ * (older full-pass runs) when `retireUnanchored`. An unsettled page passes `keep: null` and clears only the window keys in
+ * `clear` (windows extracted again, or covered by windows extracted since); every other fact keeps its row and id.
*/
export interface ConversationSegmentsPublication {
windows: ReadonlyArray<SourceWindow | null>;
/** Facts re-anchored, not re-extracted: the same rendered window under the same context now lives in another occurrence. */
moves: ReadonlyArray<{ from: string; to: SourceWindow }>;
- keep: readonly string[];
+ keep: readonly string[] | null;
+ clear?: readonly string[];
retireUnanchored: boolean;
}
@@ -539,10 +541,10 @@ export async function countConversationFacts(db: BrainEngine, sourceId: string,
}
export async function clearConversationFacts(db: BrainEngine, sourceId: string, slug: string,
- windows?: Pick<ConversationSegmentsPublication, 'keep' | 'retireUnanchored'>): Promise<number> {
+ windows?: Pick<ConversationSegmentsPublication, 'keep' | 'clear' | 'retireUnanchored'>): Promise<number> {
const page = `f.source_id=$1 AND f.source_markdown_slug=$2 AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%'` + (windows
- ? ` AND NOT (f.source = ANY($3::text[])) AND (CASE WHEN f.source_window IS NULL THEN $4::boolean ELSE NOT (${WINDOW_KEY_SQL} = ANY($5::text[])) END)` : '');
- const params = windows ? [sourceId, slug, [...AUDIT_ROW_SOURCES], windows.retireUnanchored, [...windows.keep]] : [sourceId, slug];
+ ? ` AND NOT (f.source = ANY($3::text[])) AND (CASE WHEN f.source_window IS NULL THEN $4::boolean ELSE (${WINDOW_KEY_SQL} = ANY($5::text[])) = $6::boolean END)` : '');
+ const params = windows ? [sourceId, slug, [...AUDIT_ROW_SOURCES], windows.retireUnanchored, [...(windows.keep ?? windows.clear ?? [])], windows.keep === null] : [sourceId, slug];
const referenced = 'EXISTS (SELECT 1 FROM open_loops o WHERE o.fact_id=f.id) OR EXISTS (SELECT 1 FROM facts g WHERE g.superseded_by=f.id)';
await db.executeRaw(`DELETE FROM facts f WHERE ${page} AND f.expired_at IS NOT NULL AND ${RELINKED_DERIVED_ROW} AND NOT (${referenced})`, params);
const [relinked] = await db.executeRaw<{ count: string }>(`WITH up AS (UPDATE facts f SET expired_at=now()
diff --git a/src/core/facts/conversation-stream.ts b/src/core/facts/conversation-stream.ts
new file mode 100644
index 0000000000..8b8b06f62a
--- /dev/null
+++ b/src/core/facts/conversation-stream.ts
@@ -0,0 +1,153 @@
+/**
+ * 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.
+ *
+ * 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
+ * an occurrence's text and the one before it, whether its first message opens a gap group, so the newest run of a page
+ * is read without the rest.
+ */
+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 type { ConversationOccurrence } from '../page-body/segment-conversation.ts';
+import type { ConversationSegment } from './conversation-types.ts';
+import { DEFAULT_SEGMENT_GAP_MINUTES, MAX_PAGE_SEGMENT_GAP_MINUTES, createWindowStream } from './conversation-windows.ts';
+
+export interface ConversationStreamSink {
+ /** A closed window, owned by occurrence `owner` (an index into the occurrences). */
+ window(owner: number, 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 }
+
+/** 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 };
+}
+
+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 offset of the first (`last`) line of `text` that opens a message under `patternId`, or -1. */
+function anchorOffset(patternId: string, text: string, last: boolean): number {
+ if (last) {
+ let end = text.length;
+ while (end > 0) {
+ const start = text.lastIndexOf('\n', end - 1) + 1;
+ if (isAnchorLine(patternId, text.slice(start, end).replace(/\r$/, ''))) return start;
+ end = start - 1;
+ }
+ return -1;
+ }
+ let start = 0;
+ while (start < text.length) {
+ const end = text.indexOf('\n', start);
+ if (isAnchorLine(patternId, text.slice(start, end < 0 ? text.length : end).replace(/\r$/, ''))) return start;
+ if (end < 0) break;
+ start = end + 1;
+ }
+ return -1;
+}
+
+/** The day-header date in force at `offset` of `text`, else `fallback`. */
+function dateAt(text: string, offset: number, fallback: string | undefined): string | undefined {
+ let end = offset;
+ while (end > 0) {
+ const start = text.lastIndexOf('\n', end - 2) + 1;
+ const match = DAY_HEADER_RE.exec(text.slice(start, end).trim());
+ if (match) return match[1];
+ end = start;
+ }
+ return fallback;
+}
+
+/**
+ * Whether occurrence `index`'s first message opens a gap group: it comes more than the gap after the last message of
+ * the occurrence before it (`previous`, read with the date in force at its last anchor).
+ */
+export function startsConversationRun(occurrences: readonly ConversationOccurrence[], index: number, text: string, previous: string,
+ 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 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 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.
+ */
+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);
+ const pageTitle = opts.page.title || opts.page.slug;
+ let stream: ReturnType<typeof createWindowStream<number>> | null = null;
+ let carry: Carry | null = null;
+ let lastPattern: string | null = null;
+ for (let i = from; i < to; i++) {
+ const occurrence = occurrences[i]!;
+ let text = await readText(i);
+ const leadPattern = pattern ?? lastPattern;
+ if (i === to - 1 && to < occurrences.length && leadPattern) {
+ 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 carried: string = carry ? carry.text + (carry.region === occurrence.row.region ? '' : '\n\n') : '';
+ 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) });
+ let messages = parsed.messages;
+ const firstOwner: number = 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 };
+ 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);
+ if (pushed.accepted && owner === i && startsGroup === null) startsGroup = pushed.startsGroup;
+ for (const w of pushed.windows) sink.window(w.tag, w.seg);
+ });
+ sink.occurrence(i, startsGroup === true);
+ carry = next;
+ }
+ for (const w of stream?.end() ?? []) sink.window(w.tag, w.seg);
+}
diff --git a/src/core/facts/conversation-windows.ts b/src/core/facts/conversation-windows.ts
index 0faef3c9a4..3de2e3b309 100644
--- a/src/core/facts/conversation-windows.ts
+++ b/src/core/facts/conversation-windows.ts
@@ -122,29 +122,6 @@ export function splitTurnText(text: string, budget: number): string[] {
return pieces;
}
-/**
- * Bounded windows over one eligible gap group. Every message lands in
- * exactly one window; a message whose own line overflows the budget is
- * replaced by its pieces (same speaker and timestamp) before packing.
- */
-function windowGroup(group: ConversationMessage[], pageTitle: string, maxMessages: number, maxChars: number): ConversationSegment[] {
- const out: ConversationSegment[] = [];
- let cur: ConversationMessage[] = [];
- const close = () => {
- if (cur.length > 0) out.push(segmentOf(cur));
- cur = [];
- };
- for (const m of group) {
- const parts = renderedLength(pageTitle, [m]) <= maxChars ? [m] : splitOversizedTurn(m, pageTitle, maxChars);
- for (const part of parts) {
- if (cur.length >= maxMessages || (cur.length > 0 && renderedLength(pageTitle, [...cur, part]) > maxChars)) close();
- cur.push(part);
- }
- }
- close();
- return out;
-}
-
function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars: number): ConversationMessage[] {
const fixed = renderedLength(pageTitle, [{ ...m, text: '' }]);
const budget = maxChars - fixed;
@@ -157,6 +134,65 @@ 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 }
+
+/** 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>[] };
+
+/**
+ * splitIntoSegments as a stream: push messages in order, get each window as it closes, then `end()` for the rest.
+ * Holds only the open window (and, while its gap group has a single original message, that message's split pieces), so
+ * a caller can window a conversation of any length one segment at a time. The windows equal splitIntoSegments' over the
+ * same messages.
+ */
+export function createWindowStream<Tag>(opts: SplitSegmentsOpts = {}) {
+ const gapMs = (opts.gapMinutes ?? DEFAULT_SEGMENT_GAP_MINUTES) * 60_000;
+ const maxMessages = opts.maxMessages ?? DEFAULT_SEGMENT_MAX_MESSAGES;
+ const maxChars = opts.maxChars ?? SEGMENT_TEXT_CHAR_LIMIT;
+ const pageTitle = opts.pageTitle ?? '';
+ const sinceMs = opts.sinceIso ? Date.parse(opts.sinceIso) : NaN;
+ let lastTs: number | null = null;
+ let groupMessages = 0;
+ let cur: ConversationMessage[] = [];
+ let curTag: Tag | undefined;
+ let held: TaggedWindow<Tag>[] = [];
+ const close = (out: TaggedWindow<Tag>[]) => {
+ if (cur.length > 0) held.push({ seg: segmentOf(cur), tag: curTag as Tag });
+ cur = [];
+ if (groupMessages >= MIN_SEGMENT_MESSAGES) { out.push(...held); held = []; }
+ };
+ const endGroup = (out: TaggedWindow<Tag>[]) => {
+ close(out);
+ held = [];
+ groupMessages = 0;
+ };
+ return {
+ push(m: ConversationMessage, tag: Tag): WindowPush<Tag> {
+ const ts = Date.parse(m.timestamp);
+ if (!Number.isFinite(ts) || (Number.isFinite(sinceMs) && ts <= sinceMs)) return { accepted: false, windows: [] };
+ const windows: TaggedWindow<Tag>[] = [];
+ const startsGroup = lastTs === null || ts - lastTs > gapMs;
+ if (startsGroup) endGroup(windows);
+ lastTs = ts;
+ groupMessages++;
+ const parts = renderedLength(pageTitle, [m]) <= maxChars ? [m] : splitOversizedTurn(m, pageTitle, maxChars);
+ 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;
+ cur.push(part);
+ }
+ if (groupMessages >= MIN_SEGMENT_MESSAGES && held.length) { windows.push(...held); held = []; }
+ return { accepted: true, startsGroup, windows };
+ },
+ end(): TaggedWindow<Tag>[] {
+ const windows: TaggedWindow<Tag>[] = [];
+ endGroup(windows);
+ return windows;
+ },
+ };
+}
+
/**
* Split parsed messages into bounded extraction windows.
*
@@ -164,37 +200,19 @@ function splitOversizedTurn(m: ConversationMessage, pageTitle: string, maxChars:
* 2. Cut gap groups on `gapMinutes`; a group with fewer than
* MIN_SEGMENT_MESSAGES messages is ineligible and dropped whole.
* 3. Window each eligible group under `maxMessages` and `maxChars`
- * (the rendered budget, header included, for `pageTitle`).
+ * (the rendered budget, header included, for `pageTitle`): a window
+ * closes when the next message would exceed either, and a turn that cannot
+ * fit alone is replaced by its pieces (same speaker and timestamp).
*/
export function splitIntoSegments(
messages: ConversationMessage[],
opts: SplitSegmentsOpts = {},
): ConversationSegment[] {
- const gapMs = (opts.gapMinutes ?? DEFAULT_SEGMENT_GAP_MINUTES) * 60_000;
- const maxMessages = opts.maxMessages ?? DEFAULT_SEGMENT_MAX_MESSAGES;
- const maxChars = opts.maxChars ?? SEGMENT_TEXT_CHAR_LIMIT;
- const pageTitle = opts.pageTitle ?? '';
- const sinceMs = opts.sinceIso ? Date.parse(opts.sinceIso) : NaN;
-
- const groups: ConversationMessage[][] = [];
- let cur: ConversationMessage[] = [];
- let lastTs: number | null = null;
- for (const m of messages) {
- const ts = Date.parse(m.timestamp);
- if (!Number.isFinite(ts)) continue;
- if (Number.isFinite(sinceMs) && ts <= sinceMs) continue;
- if (lastTs !== null && ts - lastTs > gapMs) {
- groups.push(cur);
- cur = [];
- }
- cur.push(m);
- lastTs = ts;
- }
- groups.push(cur);
-
- return groups
- .filter((g) => g.length >= MIN_SEGMENT_MESSAGES)
- .flatMap((g) => windowGroup(g, pageTitle, maxMessages, maxChars));
+ const stream = createWindowStream<null>(opts);
+ const out: ConversationSegment[] = [];
+ for (const m of messages) for (const w of stream.push(m, null).windows) out.push(w.seg);
+ for (const w of stream.end()) out.push(w.seg);
+ return out;
}
/**
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index b374906f3b..6ad65c0ada 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -183,6 +183,10 @@ const sqlList = (values: readonly string[]) => values.map(v => `'${v}'`).join(',
* live occurrences without a settled row whose segment sha, context hash and version match, found from metadata alone.
* Rows of an occurrence that left the live generation are deleted by their pipeline (retireSegmentDerivations); a page
* delete cascades. The output holds link context and window anchors, so the table gets the segment tables' RLS posture.
+ *
+ * PR 4 (Wave B incremental derivation, transcripts): page_derivation_spend is the per-page lifetime spend ledger of each
+ * paid derivation family (`facts`, `atoms`, `synopsis`; page-spend.ts), each capped by `derive.max_usd_per_page` on its own,
+ * apart from the embedding ledger (page_embedding_budget), so derivation spend never starves a page's embeddings.
*/
export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_segment_derivations (
page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
@@ -198,7 +202,16 @@ export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_seg
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (page_id, pipeline, occurrence_id)
);
-CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');`;
+CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+CREATE TABLE IF NOT EXISTS page_derivation_spend (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, family)
+);`;
/**
* The segment tables hold page text (`page_segment_texts`, `page_body_staging_parts`) or a page's shape and
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index bf7ff850ad..435bdea3d4 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -37,7 +37,12 @@ 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 } from './budget/reservation-cost.ts';
+import { reservationCostUsd, type BudgetKind } 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';
+import { RESERVATION_WINDOW_SQL, RESERVED_AT_SQL, reserveDerivationSpend, settleLedgerReservation, type PageSpendDecision, type PageSpendGrant,
+ type PageSpendKind, type PageSpendSignature } from './page-spend.ts';
import { PAGE_INLINE_MAX_BYTES, budgetRowAppliesFilter, isLargePageBytes } from './page-size-policy.ts';
import { isEmbedSkipped } from './embed-skip.ts';
import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';
@@ -46,6 +51,9 @@ import { quoteIdentifier } from './search/embedding-column.ts';
import { embeddingWriteTarget } from './page-state/projections.ts';
import { approvalAmount, approvalBasis, heldApproveAction, heldPreviewCommand, ledgerPricePerMTok, renderedCommand } from './held-embedding-action.ts';
+export type { PageSpendDecision, PageSpendGrant, PageSpendKind, PageSpendSignature } from './page-spend.ts';
+export { PAGE_DERIVATION_CAP_KEY } from './page-spend.ts';
+
export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';
export const DEFAULT_PAGE_EMBED_CAP_USD = 2;
@@ -78,36 +86,6 @@ export type PageEmbedDecision =
interface BudgetRow { state: PageBudgetState; reason: string | null; embedding_signature: string | null; spent_usd: number; reserved_usd: number; stale_reservation: boolean; cap_usd: number | null }
-// PR 4 (Wave B incremental derivation, transcripts)
-/**
- * The ledger's open reservations form one window: `reserved_at` is the time the window opened (the first reservation
- * after the ledger had none), and it identifies the window. Reservations nobody settled for an hour (no reservation or
- * settle on the ledger since: `updated_at`) are folded into spent by the next reservation, and so are the reservations
- * of a ledger a new embedding model replaced; either way the next reservation opens a new window. A grant settles only
- * inside the window it reserved in, so a reservation that was already folded is never booked twice and never releases
- * a newer one. The window closes (reserved_at NULL) when its last reservation settles.
- */
-const RESERVED_EPSILON_USD = 1e-9;
-/** A window's id: reserved_at in whole microseconds, as text (a bound timestamp parameter would lose the microseconds). */
-const RESERVATION_WINDOW_SQL = '(extract(epoch FROM reserved_at) * 1000000)::bigint::text';
-
-/**
- * The reserved_at a reservation leaves: the open window's (`keep`), a new window's, or NULL when nothing is reserved. A new
- * window's id is later than the one it replaces even on a millisecond clock (PGLite), so the two never compare equal.
- */
-const RESERVED_AT_SQL = (total: string, keep: string) =>
- `reserved_at = CASE WHEN ${total} <= 0 THEN NULL WHEN ${keep} THEN reserved_at ELSE GREATEST(now(), reserved_at + interval '1 millisecond') END`;
-
-/** Book (`ok`) or release one grant's reservation, only while the window it reserved in is still open. */
-async function settleReservation(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, window: string | null, usd: number, ok: boolean, unpriced = 0): Promise<void> {
- if (usd === 0 || window === null) return;
- await engine.executeRaw(`UPDATE page_embedding_budget SET
- reserved_usd = CASE WHEN reserved_usd - $2::float8 <= $5::float8 THEN 0 ELSE reserved_usd - $2::float8 END,
- reserved_at = CASE WHEN reserved_usd - $2::float8 <= $5::float8 THEN NULL ELSE reserved_at END,
- spent_usd = spent_usd + $3::float8, unpriced_calls = unpriced_calls + $4::int, updated_at = now()
- WHERE page_id = $1 AND ${RESERVATION_WINDOW_SQL} = $6::text`, [pageId, usd, ok ? usd : 0, ok ? unpriced : 0, RESERVED_EPSILON_USD, window]);
-}
-
/** A segmented page (Wave B) carries `body_bytes` and no body strings; an inline page carries its body. */
type BudgetPage = { id: number; body_storage?: BodyStorage | null; body_bytes?: number | null; compiled_truth?: string; timeline?: string | null };
@@ -198,42 +176,26 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,
approved && Number.isFinite(capUsd) ? capUsd : row.cap_usd, openWindow]);
const grant: PageEmbedGrant = {
chunkIndexes, reservedUsd, deferred, capUsd,
- settle: ({ ok }) => settleReservation(engine, page.id, written?.reservation_window ?? null, reservedUsd, ok, priced ? 0 : 1),
+ settle: ({ ok }) => settleLedgerReservation(engine, { table: 'page_embedding_budget', pageId: page.id }, written?.reservation_window ?? null,
+ reservedUsd, ok ? reservedUsd : 0, ok && !priced ? 1 : 0),
};
return { kind: 'grant', grant } as const;
});
}
-/** What a paid step spends on a page (wave-b spec 8.3): the kind and its model, `embedding:<signature>`, `facts:<model>`, `atoms:<model>`, `synopsis:<model>`. */
-export type PageSpendKind = 'embedding' | 'facts' | 'atoms' | 'synopsis';
-export type PageSpendSignature = `${PageSpendKind}:${string}`;
-
-export interface PageSpendGrant {
- reservedUsd: number;
- capUsd: number;
- /** Book the reservation as spent (`ok`) or release it (the provider call failed before billing). */
- settle(outcome: { ok: boolean }): Promise<void>;
-}
-
-/** `refused`: the estimate does not fit what the cap leaves (`cap_reached`), or an embedding waits for approval (`held`); nothing was reserved. */
-export type PageSpendDecision =
- | { kind: 'unmetered' }
- | { kind: 'refused'; reason: 'cap_reached' | 'held'; capUsd: number; spentUsd: number; reservedUsd: number; estimateUsd: number }
- | { kind: 'grant'; grant: PageSpendGrant };
-
/**
* Reserve `estimateUsd` of one paid step on `page` against its per-page cap (wave-b spec 8.3), before the provider call.
- * Every kind shares the page's one ledger in page_embedding_budget and its lifetime cap (`embed.max_usd_per_page`):
- * the kind lives in the signature, not in a new table. Only an embedding signature names the ledger's model, so only a
- * new embedding model starts a new ledger, as planPageEmbedding does; derivation spend (facts, atoms, synopsis) never
- * resets it. Metered: segmented pages and pages over `pages.inline_max_bytes`; any other page is unmetered. A
- * refusal reserves nothing, so the caller skips the call. Settle the grant (spendGrant) when the call returns or throws.
+ * An embedding reserves on page_embedding_budget under `embed.max_usd_per_page` (a new embedding model starts a new
+ * ledger, as planPageEmbedding does); a derivation (facts, atoms, synopsis) on its own family's ledger (page-spend.ts).
+ * Metered: segmented pages and pages over `pages.inline_max_bytes`; any other page is unmetered. A refusal reserves
+ * nothing, so the caller skips the call. A derivation runs its call through meterPaidCall, which books the actual cost.
*/
export async function reservePageSpend(engine: BrainEngine, page: BudgetPage, signature: PageSpendSignature, estimateUsd: number): Promise<PageSpendDecision> {
if (!isSegmentedPage(page) && !isLargePageBytes(pageBodyBytes(page))) return { kind: 'unmetered' };
const split = signature.indexOf(':');
const kind = signature.slice(0, split) as PageSpendKind;
- const embeddingSignature = kind === 'embedding' ? signature.slice(split + 1) : null;
+ if (kind !== 'embedding') return reserveDerivationSpend(engine, page.id, kind, estimateUsd);
+ const embeddingSignature = signature.slice(split + 1);
const configured = await resolvePageEmbedCapUsd(engine);
const estimate = Math.max(0, estimateUsd);
return engine.transaction(async tx => {
@@ -242,12 +204,12 @@ export async function reservePageSpend(engine: BrainEngine, page: BudgetPage, si
(reserved_usd > 0 AND updated_at < now() - interval '1 hour') AS stale_reservation
FROM page_embedding_budget WHERE page_id = $1 FOR UPDATE`, [page.id]);
if (!row) return { kind: 'unmetered' } as const;
- const sameLedger = !embeddingSignature || !row.embedding_signature || row.embedding_signature === embeddingSignature;
+ const sameLedger = !row.embedding_signature || row.embedding_signature === embeddingSignature;
const spent = sameLedger ? Number(row.spent_usd) + (row.stale_reservation ? Number(row.reserved_usd) : 0) : 0;
const reserved = sameLedger && !row.stale_reservation ? Number(row.reserved_usd) : 0;
const capUsd = row.cap_usd === null ? configured : Number(row.cap_usd);
const refused = (reason: 'cap_reached' | 'held') => ({ kind: 'refused', reason, capUsd, spentUsd: spent, reservedUsd: reserved, estimateUsd: estimate } as const);
- if (kind === 'embedding' && row.state === 'held') return refused('held');
+ if (row.state === 'held') return refused('held');
if (spent + reserved + estimate > capUsd) return refused('cap_reached');
const [written] = await tx.executeRaw<{ reservation_window: string | null }>(`UPDATE page_embedding_budget SET embedding_signature = COALESCE($2, embedding_signature),
spent_usd = $3::float8, reserved_usd = $4::float8, ${RESERVED_AT_SQL('$4::float8', '$5::boolean')}, updated_at = now()
@@ -255,7 +217,8 @@ export async function reservePageSpend(engine: BrainEngine, page: BudgetPage, si
[page.id, embeddingSignature, spent, reserved + estimate, reserved > 0]);
const grant: PageSpendGrant = {
reservedUsd: estimate, capUsd,
- settle: ({ ok }) => settleReservation(engine, page.id, written?.reservation_window ?? null, estimate, ok),
+ settle: ({ ok, usd }) => settleLedgerReservation(engine, { table: 'page_embedding_budget', pageId: page.id }, written?.reservation_window ?? null,
+ estimate, ok ? usd ?? estimate : 0),
};
return { kind: 'grant', grant } as const;
});
@@ -267,10 +230,51 @@ const PROMPT_OVERHEAD_TOKENS = 1500;
/** Per-1M-token rates for a chat model without a price: the reservation still bounds the spend. */
const UNPRICED_CHAT_RATE = { input: 15, output: 75 };
-/** What one chat call over `chars` of input may cost at most (the prompt estimate plus the full output ceiling): the estimate a paid derivation reserves. */
-export function estimateChatCallUsd(model: string, chars: number, maxOutputTokens: number): number {
+/**
+ * What one chat call over `chars` of input may cost at most (the prompt estimate plus the full output ceiling), at the
+ * operator's `pricing.overrides` rate when one is set: the estimate a paid derivation reserves.
+ */
+export function estimateChatCallUsd(model: string, chars: number, maxOutputTokens: number, pricingOverrides?: PricingOverrides): number {
const input = Math.ceil(chars / CHARS_PER_TOKEN) + PROMPT_OVERHEAD_TOKENS;
- return reservationCostUsd(model, 'chat', input, maxOutputTokens) ?? (input * UNPRICED_CHAT_RATE.input + maxOutputTokens * UNPRICED_CHAT_RATE.output) / 1_000_000;
+ return reservationCostUsd(model, 'chat', input, maxOutputTokens, pricingOverrides)
+ ?? (input * UNPRICED_CHAT_RATE.input + maxOutputTokens * UNPRICED_CHAT_RATE.output) / 1_000_000;
+}
+
+/** The worst case of one facts extraction (extract.ts): the call, a truncation retry at twice the output cap, and a malformed-output retry at that cap. */
+export function estimateFactsExtractionUsd(model: string, chars: number, maxOutputTokens: number, pricingOverrides?: PricingOverrides): number {
+ return estimateChatCallUsd(model, chars, maxOutputTokens, pricingOverrides) + 2 * estimateChatCallUsd(model, chars, 2 * maxOutputTokens, pricingOverrides);
+}
+
+const TOUCHPOINT_KIND: Partial<Record<string, BudgetKind>> = { embedding: 'embed', rerank: 'rerank' };
+
+/**
+ * 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 gateway recorded is booked whatever the step's outcome (a truncated, malformed or refused answer, a
+ * throw after the provider answered, an abort); an unpriced model books the reservation; a step that recorded no attempt
+ * (the provider was never called) books nothing. The attempts are recorded on the caller's tracker too, and the caller's
+ * remaining 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 parent = getCurrentBudgetTracker();
+ const parentCap = parent?.cap;
+ const tracker = new BudgetTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides,
+ ...(parent && parentCap !== undefined ? { maxCostUsd: Math.max(0, parentCap - parent.totalSpent), capSource: parent.capSource } : {}) });
+ 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' });
+ }
+ const unpriced = models.some(m => m.cost_usd === null);
+ await decision.grant.settle({ ok: models.length > 0, usd: unpriced ? decision.grant.reservedUsd : tracker.totalSpent });
+ }
}
export interface PageBudgetReport { slug: string; source_id: string; state: Exclude<PageBudgetState, 'open'>; reason: string | null;
diff --git a/src/core/page-spend.ts b/src/core/page-spend.ts
new file mode 100644
index 0000000000..8b2f07717f
--- /dev/null
+++ b/src/core/page-spend.ts
@@ -0,0 +1,103 @@
+/**
+ * PR 4 (Wave B incremental derivation, transcripts): the per-page spend ledgers of the paid derivations on a large page
+ * (wave-b spec 8.3) and the reservation window both ledgers use.
+ *
+ * Families: every paid derivation family (conversation facts and the facts backstop as `facts`, `atoms`, `synopsis`)
+ * has its own lifetime ledger per page in page_derivation_spend, each capped by `derive.max_usd_per_page` (default $2;
+ * unlimited under `spend.posture tokenmax` when unset; `off` disables it). Embedding keeps its own ledger and cap
+ * (page_embedding_budget, `embed.max_usd_per_page`), so derivation spend never starves a page's embeddings, and a new
+ * embedding model resets only the embedding ledger.
+ *
+ * Reservation window: a ledger's open reservations form one window. `reserved_at` is the time the window opened (the
+ * first reservation after the ledger had none) and identifies it. Reservations nobody settled for an hour (no
+ * reservation or settle on the ledger since: `updated_at`) are folded into spent by the next reservation, and so are
+ * those of a ledger a new embedding model replaced; either way the next reservation opens a new window. A grant settles
+ * only inside the window it reserved in, so a reservation that was already folded is never booked twice and never
+ * releases a newer one. The window closes (reserved_at NULL) when its last reservation settles.
+ */
+import type { BrainEngine } from './engine.ts';
+import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';
+
+export const PAGE_DERIVATION_CAP_KEY = 'derive.max_usd_per_page';
+export const DEFAULT_PAGE_DERIVATION_CAP_USD = 2;
+
+/** What a paid step spends on a page: the kind and its model, `embedding:<signature>`, `facts:<model>`, `atoms:<model>`, `synopsis:<model>`. */
+export type PageSpendKind = 'embedding' | 'facts' | 'atoms' | 'synopsis';
+export type PageSpendSignature = `${PageSpendKind}:${string}`;
+export type DerivationFamily = Exclude<PageSpendKind, 'embedding'>;
+
+export interface PageSpendGrant {
+ reservedUsd: number;
+ capUsd: number;
+ /** Book the reservation as spent (`ok`: `usd`, the call's actual cost, else the reservation) or release it (the provider was never called). */
+ settle(outcome: { ok: boolean; usd?: number }): Promise<void>;
+}
+
+/** `refused`: the estimate does not fit what the cap leaves (`cap_reached`), or an embedding waits for approval (`held`); nothing was reserved. */
+export type PageSpendDecision =
+ | { kind: 'unmetered' }
+ | { kind: 'refused'; reason: 'cap_reached' | 'held'; capUsd: number; spentUsd: number; reservedUsd: number; estimateUsd: number }
+ | { kind: 'grant'; grant: PageSpendGrant };
+
+const RESERVED_EPSILON_USD = 1e-9;
+/** A window's id: reserved_at in whole microseconds, as text (a bound timestamp parameter would lose the microseconds). */
+export const RESERVATION_WINDOW_SQL = '(extract(epoch FROM reserved_at) * 1000000)::bigint::text';
+
+/**
+ * The reserved_at a reservation leaves: the open window's (`keep`), a new window's, or NULL when nothing is reserved. A new
+ * window's id is later than the one it replaces even on a millisecond clock (PGLite), so the two never compare equal.
+ */
+export const RESERVED_AT_SQL = (total: string, keep: string) =>
+ `reserved_at = CASE WHEN ${total} <= 0 THEN NULL WHEN ${keep} THEN reserved_at ELSE GREATEST(now(), reserved_at + interval '1 millisecond') END`;
+
+type Ledger = { table: 'page_embedding_budget'; pageId: number } | { table: 'page_derivation_spend'; pageId: number; family: DerivationFamily };
+
+/** Book `bookedUsd` and drop one grant's `reservedUsd` hold, only while the window it reserved in is still open. */
+export async function settleLedgerReservation(engine: Pick<BrainEngine, 'executeRaw'>, ledger: Ledger, window: string | null,
+ reservedUsd: number, bookedUsd: number, unpriced = 0): Promise<void> {
+ if (window === null || (reservedUsd === 0 && bookedUsd === 0)) return;
+ const embedding = ledger.table === 'page_embedding_budget';
+ await engine.executeRaw(`UPDATE ${ledger.table} SET
+ reserved_usd = CASE WHEN reserved_usd - $2::float8 <= $4::float8 THEN 0 ELSE reserved_usd - $2::float8 END,
+ reserved_at = CASE WHEN reserved_usd - $2::float8 <= $4::float8 THEN NULL ELSE reserved_at END,
+ spent_usd = spent_usd + $3::float8,${embedding ? ` unpriced_calls = unpriced_calls + ${Math.trunc(unpriced)},` : ''} updated_at = now()
+ WHERE page_id = $1 AND ${RESERVATION_WINDOW_SQL} = $5::text${embedding ? '' : ' AND family = $6'}`,
+ [ledger.pageId, reservedUsd, Math.max(0, bookedUsd), RESERVED_EPSILON_USD, window, ...(embedding ? [] : [ledger.family])]);
+}
+
+/** The configured per-family derivation cap: `derive.max_usd_per_page`, else unlimited under `spend.posture tokenmax`, else $2. `off` is Infinity. */
+export async function resolvePageDerivationCapUsd(engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>): Promise<number> {
+ const raw = await engine.getConfig(PAGE_DERIVATION_CAP_KEY).catch(() => null);
+ if (raw === null || raw === undefined || raw === '') {
+ return await resolveSpendPosture(engine as BrainEngine).catch(() => 'gated') === 'tokenmax' ? Infinity : DEFAULT_PAGE_DERIVATION_CAP_USD;
+ }
+ return parseUsdLimit(raw, DEFAULT_PAGE_DERIVATION_CAP_USD);
+}
+
+/** Reserve `estimateUsd` on one family's ledger of a page (row-locked, so concurrent reservations never overspend the cap). */
+export async function reserveDerivationSpend(engine: BrainEngine, pageId: number, family: DerivationFamily, estimateUsd: number): Promise<PageSpendDecision> {
+ const capUsd = await resolvePageDerivationCapUsd(engine);
+ const estimate = Math.max(0, estimateUsd);
+ return engine.transaction(async tx => {
+ await tx.executeRaw('INSERT INTO page_derivation_spend (page_id, family) VALUES ($1, $2) ON CONFLICT (page_id, family) DO NOTHING', [pageId, family]);
+ const [row] = await tx.executeRaw<{ spent_usd: number; reserved_usd: number; stale_reservation: boolean }>(`SELECT spent_usd, reserved_usd,
+ (reserved_usd > 0 AND updated_at < now() - interval '1 hour') AS stale_reservation
+ FROM page_derivation_spend WHERE page_id = $1 AND family = $2 FOR UPDATE`, [pageId, family]);
+ if (!row) return { kind: 'unmetered' } as const;
+ const spent = Number(row.spent_usd) + (row.stale_reservation ? Number(row.reserved_usd) : 0);
+ const reserved = row.stale_reservation ? 0 : Number(row.reserved_usd);
+ if (spent + reserved + estimate > capUsd) {
+ return { kind: 'refused', reason: 'cap_reached', capUsd, spentUsd: spent, reservedUsd: reserved, estimateUsd: estimate } as const;
+ }
+ const [written] = await tx.executeRaw<{ reservation_window: string | null }>(`UPDATE page_derivation_spend SET spent_usd = $3::float8,
+ reserved_usd = $4::float8, ${RESERVED_AT_SQL('$4::float8', '$5::boolean')}, updated_at = now()
+ WHERE page_id = $1 AND family = $2 RETURNING ${RESERVATION_WINDOW_SQL} AS reservation_window`,
+ [pageId, family, spent, reserved + estimate, reserved > 0]);
+ const ledger: Ledger = { table: 'page_derivation_spend', pageId, family };
+ const grant: PageSpendGrant = {
+ reservedUsd: estimate, capUsd,
+ settle: ({ ok, usd }) => settleLedgerReservation(engine, ledger, written?.reservation_window ?? null, estimate, ok ? usd ?? estimate : 0),
+ };
+ return { kind: 'grant', grant } as const;
+ });
+}
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 02383b0f2a..75e5f39fe9 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -112,6 +112,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_body_staging_parts', 'operational', 'Raw parts of open upload sessions; without them a client resuming an upload starts over.'),
carry('page_body_stagings', 'operational', 'Body stagings of segmented writes and upload sessions (idempotent begin and commit, expiry deadlines).'),
carry('page_body_staging_texts', 'operational', 'The segment texts each live body staging needs, so a page purge keeps an unpublished write\'s texts.'),
+ carry('page_derivation_spend', 'operational', 'Large-page derivation spend ledger: per-page lifetime spend of fact, atom and synopsis extraction under derive.max_usd_per_page; without it a page could be paid for past its cap.'),
carry('page_embedding_budget', 'operational', 'Large-page embedding spend ledger: per-page spend, holds awaiting approval and caps; without it held pages would embed without consent.'),
carry('page_extraction_state', 'operational', 'Extraction watermarks and partial-input receipts per page and pipeline; without them the next extraction of a large page reads its head again and records the receipt anew.'),
carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),
@@ -120,6 +121,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),
carry('page_purges', 'user_data', 'Text-free page purge tombstones (#5575); dropping them would let purged pages re-import.'),
carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),
+ carry('page_segment_derivations', 'operational', 'Per-segment derivation records of large pages (links, mentions, timeline, fences, facts, atoms, synopses): segment sha, context hash and window anchors; without them every segment is derived again at full price and facts lose the windows they were extracted from.'),
carry('page_segment_texts', 'user_data', 'Segment texts of segmented page bodies, stored once per source; without them a large page has no body.'),
carry('page_versions', 'user_data', 'Page revision history with attribution.'),
carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 44220d101a..2a024c8615 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1404,6 +1404,15 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (
PRIMARY KEY (page_id, pipeline, occurrence_id)
);
CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+CREATE TABLE IF NOT EXISTS page_derivation_spend (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, family)
+);
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 75b6c73ff8..c9e27e65d6 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2148,6 +2148,15 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (
PRIMARY KEY (page_id, pipeline, occurrence_id)
);
CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+CREATE TABLE IF NOT EXISTS page_derivation_spend (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, family)
+);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
diff --git a/src/schema.sql b/src/schema.sql
index 1b0f51c53a..859577e230 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2144,6 +2144,15 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (
PRIMARY KEY (page_id, pipeline, occurrence_id)
);
CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+CREATE TABLE IF NOT EXISTS page_derivation_spend (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),
+ spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),
+ reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),
+ reserved_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, family)
+);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
diff --git a/test/e2e/conversation-facts-incremental-postgres.test.ts b/test/e2e/conversation-facts-incremental-postgres.test.ts
index 24b193dd2a..de138e1ac0 100644
--- a/test/e2e/conversation-facts-incremental-postgres.test.ts
+++ b/test/e2e/conversation-facts-incremental-postgres.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 { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';
import { hasDatabase } from './helpers.ts';
@@ -16,4 +17,5 @@ import { hasDatabase } from './helpers.ts';
defineSegmentedBackstopCases({ getBrain: () => brain });
defineSegmentedAtomsCases({ getBrain: () => brain });
defineSegmentReceiptDoctorCases({ getBrain: () => brain });
+ defineDerivationSpendCases({ getBrain: () => brain });
});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index a3cc1b0a44..78d1d388cc 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -234,6 +234,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -776,6 +781,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1296,6 +1304,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2866,6 +2875,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 3c561d619c..5098f59d9a 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -234,6 +234,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -776,6 +781,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1296,6 +1304,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2866,6 +2875,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 657b3cc1b7..5efd1fda39 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -234,6 +234,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -776,6 +781,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1292,6 +1300,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2862,6 +2871,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 02f1c206a8..97d0049efa 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -168,6 +168,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -574,6 +579,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -954,6 +962,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2153,6 +2162,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index e615c9fe52..4122e4b8fc 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -168,6 +168,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -574,6 +579,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -954,6 +962,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2153,6 +2162,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index b5e42fa8a3..3cdd416cf4 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -168,6 +168,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -574,6 +579,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -953,6 +961,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2152,6 +2161,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 3df780b38c..1e6d355fb8 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -179,6 +179,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -594,6 +599,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -982,6 +990,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2221,6 +2230,17 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 249eb07711..2e40b0ea0b 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -238,6 +238,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -783,6 +788,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1300,6 +1308,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2878,6 +2887,17 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index c83ddebe69..75e69302c3 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -238,6 +238,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -783,6 +788,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1300,6 +1308,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2878,6 +2887,17 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 8a659dad8e..35b2643603 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -238,6 +238,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -783,6 +788,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1296,6 +1304,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2874,6 +2883,17 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 82711a0785..45485b0d93 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -234,6 +234,11 @@
"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",
"page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",
+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",
+ "page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)",
+ "page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",
+ "page_derivation_spend.page_derivation_spend_spent_usd_check": "c CHECK ((spent_usd >= (0)::double precision))",
"page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))",
"page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",
@@ -776,6 +781,9 @@
"page_body_stagings": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_derivation_spend": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_embedding_budget": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1296,6 +1304,7 @@
"page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",
"page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",
"page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)",
+ "page_derivation_spend_pkey": "CREATE UNIQUE INDEX page_derivation_spend_pkey ON public.page_derivation_spend USING btree (page_id, family)",
"page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)",
"page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)",
"page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
@@ -2866,6 +2875,17 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_derivation_spend": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 family text/text NOT NULL",
+ "3 spent_usd double precision/float8 NOT NULL DEFAULT 0",
+ "4 reserved_usd double precision/float8 NOT NULL DEFAULT 0",
+ "5 reserved_at timestamp with time zone/timestamptz NULL",
+ "6 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_embedding_budget": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 0f1cfbc62c..f3f0dbc1a5 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 136, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 138, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.ts
index b43d404942..defb968d12 100644
--- a/test/helpers/conversation-facts-incremental-cases.ts
+++ b/test/helpers/conversation-facts-incremental-cases.ts
@@ -2,7 +2,8 @@
* Incremental conversation facts on a segmented page (wave-b spec 8.2 "Conversation facts", PR 4 lane 4b), 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). A fake extractor counts calls by window text; no model
- * is called. Spend is metered (reservePageSpend) but the fake call costs nothing.
+ * is called. Spend is metered (meterPaidCall, the facts ledger); the cap case's fake extractor calls the gateway, whose
+ * fake transport reports token usage on a priced model, so its windows cost what that usage costs.
*
* 1. Protects: an import extracts each window once and anchors every fact (facts.source_window, a JSONB object); an
* append (by a remote writer) extracts only windows no earlier run extracted, keeps the facts (same ids) of every
@@ -19,12 +20,13 @@ import type { BrainEngine } from '../../src/core/engine.ts';
import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';
import { parseSourceWindow, sourceWindowKey, type SourceWindow } from '../../src/core/page-body/derivations.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 type { AppendBrain } from './append-brain.ts';
import { runFactsBackstop } from '../../src/core/facts/backstop.ts';
import { lineWindows } from '../../src/core/facts/backstop-segments.ts';
import { MAX_TURN_TEXT_CHARS } from '../../src/core/facts/extract.ts';
import { truthLead } from '../../src/core/page-body/segment-blocks.ts';
-import { __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
+import { __setChatTransportForTests, chat as gatewayChat, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';
import { MAX_ATOM_WINDOWS_PER_PAGE_RUN } from '../../src/core/cycle/extract-atoms-segments.ts';
import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';
@@ -33,7 +35,7 @@ import type { Check } from '../../src/commands/doctor.ts';
const SPEAKERS = ['Alice Example', 'Bob Example', 'Carol Example'];
const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast', 'retention', 'deploy'];
-const SOURCE = 'cli:extract-conversation-facts';
+export const SOURCE = 'cli:extract-conversation-facts';
const clock = (minutes: number) => { const h = 9 + Math.floor(minutes / 60); return `${h > 12 ? h - 12 : h}:${String(minutes % 60).padStart(2, '0')} ${h >= 12 ? 'PM' : 'AM'}`; };
const dateOf = (day: number) => new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10);
@@ -70,7 +72,7 @@ const sha = (text: string) => createHash('sha256').update(text).digest('hex');
interface FactRow { id: number; key: string; type: string }
/** The page's live extractor facts (audit rows aside) with their window keys and the stored JSONB type. */
-async function factsOf(engine: BrainEngine, slug: string): Promise<FactRow[]> {
+export async function factsOf(engine: BrainEngine, slug: string): Promise<FactRow[]> {
const rows = await engine.executeRaw<{ id: number; w: unknown; t: string | null }>(
`SELECT id, source_window AS w, jsonb_typeof(source_window) AS t FROM facts WHERE source_id='default' AND source_markdown_slug=$1 AND source=$2 AND expired_at IS NULL ORDER BY id`,
[slug, SOURCE]);
@@ -81,7 +83,7 @@ async function factsOf(engine: BrainEngine, slug: string): Promise<FactRow[]> {
}
/** Window keys every live occurrence's derivation row records, and the rows' states and receipts. */
-async function derivations(engine: BrainEngine, slug: string) {
+export async function derivations(engine: BrainEngine, slug: string) {
const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);
const pageId = Number(page!.id);
const rows = await engine.readSegmentDerivations(pageId, { kind: 'conversation_facts' });
@@ -91,14 +93,32 @@ async function derivations(engine: BrainEngine, slug: string) {
return { pageId, rows, keys, live: live.map(row => row.occurrenceId), states: rows.map(row => row.state), receipts: rows.map(row => row.receipt) };
}
-/** One extraction run with a fake extractor; \`calls\` lists every window text it was handed, in call order. */
-async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean } = {}) {
+export const PAID_MODEL = 'anthropic:claude-sonnet-4-6';
+
+/** A fake chat transport reporting usage on a priced model: a quarter token per input character, 32 output tokens. */
+export function paidTransport(o: ChatOpts): Promise<ChatResult> {
+ const chars = o.messages.reduce((n, m) => n + (typeof m.content === 'string' ? m.content.length : JSON.stringify(m.content).length), 0);
+ return Promise.resolve({ text: '{"facts":[]}', blocks: [], stopReason: 'end', model: PAID_MODEL, providerId: 'anthropic',
+ usage: { input_tokens: Math.ceil(chars / 4), output_tokens: 32, cache_read_tokens: 0, cache_creation_tokens: 0 } });
+}
+
+/**
+ * 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.
+ */
+export async function extract(engine: BrainEngine, slug: string, opts: { force?: boolean; paid?: boolean; failAt?: number; abortAfter?: number; sinceIso?: string } = {}) {
const calls: string[] = [];
+ const controller = new AbortController();
const result = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0, force: opts.force,
+ sinceIso: opts.sinceIso,
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 (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);
return { calls, result };
}
@@ -111,6 +131,7 @@ export function defineConversationFactsIncrementalCases(opts: { getBrain: () =>
test('an import extracts every window exactly once and anchors every fact to its window', async () => {
const { engine, seed } = opts.getBrain();
await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
await seed(slug, chatPage('Chat A', BODY));
const { calls, result } = await extract(engine, slug);
const facts = await factsOf(engine, slug);
@@ -189,18 +210,21 @@ ${chatDays(100, 3, 1)}`;
await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, confidence)
VALUES ('default', NULL, 'Bob Example owns the forecast', 'fact', 'private', 'medium', $2, $1, 5000, 0.9)`, [capped, SOURCE]);
const unanchored = async () => (await factsOf(engine, capped)).filter(f => f.key === 'unanchored').length;
- await engine.setConfig(PAGE_EMBED_CAP_KEY, '0.3');
- const first = await extract(engine, capped);
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.5');
+ __setChatTransportForTests(paidTransport);
+ const first = await extract(engine, capped, { paid: true }).finally(() => __setChatTransportForTests(null));
const partial = await derivations(engine, capped);
- const [ledger] = await engine.executeRaw<{ spent: number }>('SELECT spent_usd AS spent FROM page_embedding_budget WHERE page_id=$1', [partial.pageId]);
+ const [ledger] = await engine.executeRaw<{ spent: number }>("SELECT spent_usd AS spent FROM page_derivation_spend WHERE page_id=$1 AND family='facts'", [partial.pageId]);
expect(first.calls.length).toBeGreaterThanOrEqual(1);
- expect(Number(ledger!.spent)).toBeLessThanOrEqual(0.3);
+ expect(Number(ledger!.spent)).toBeLessThanOrEqual(0.5);
expect(Number(ledger!.spent)).toBeGreaterThan(0);
+ // A cap stop partway through the page publishes the windows it finished: one fact each, anchored to its window.
+ expect((await factsOf(engine, capped)).filter(f => f.key !== 'unanchored').length).toBe(first.calls.length);
expect(partial.receipts.filter(Boolean)).toEqual([expect.objectContaining({ kind: 'unread_windows', reason: 'cap_reached' })]);
expect(await unanchored()).toBe(1);
// The newest windows: the last day's turns are in the first call.
expect(first.calls[0]).toContain(`${dateOf(299)}`);
- await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
const second = await extract(engine, capped);
const done = await derivations(engine, capped);
expect({ repeats: second.calls.filter(text => first.calls.includes(text)).length, total: first.calls.length + second.calls.length,
@@ -239,6 +263,7 @@ export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain
test('an import extracts each window of each occurrence once; an unchanged page extracts nothing', async () => {
const { engine, seed, body } = opts.getBrain();
await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
await seed(slug, chatPage('Backstop', chatDays(400, 100, 5)).replace('type: conversation', 'type: note'));
const page = await pageOf(engine, slug);
const truth = Buffer.from((await body(slug)).truth, 'utf8');
@@ -278,7 +303,7 @@ export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain
const { engine, seed } = opts.getBrain();
const capped = `notes/backstop-capped-${randomUUID().slice(0, 8)}`;
await seed(capped, chatPage('Backstop capped', chatDays(600, 100, 6)).replace('type: conversation', 'type: note'));
- await engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000001');
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');
install();
try {
await backstop(engine, capped);
@@ -288,7 +313,7 @@ export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain
.toEqual({ calls: 0, receipts: [expect.objectContaining({ kind: 'unread_windows', pipeline: 'facts_backstop', reason: 'cap_reached', windows_read: 0 })] });
} finally {
__setChatTransportForTests(null);
- await engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
}
}, 600_000);
}
@@ -341,6 +366,7 @@ export function defineSegmentedAtomsCases(opts: { getBrain: () => AppendBrain })
test('an import extracts every window of every occurrence once, one atom each; a settled page extracts nothing', async () => {
const brain = opts.getBrain();
await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
await brain.engine.setConfig('cycle.extract_atoms.max_input_chars', String(cap));
await brain.seed(slug, chatPage('Atoms', chatDays(700, 100, 5)).replace('type: conversation', 'type: meeting'));
before = await windowsOf(brain, slug);
@@ -375,7 +401,7 @@ export function defineSegmentedAtomsCases(opts: { getBrain: () => AppendBrain })
const brain = opts.getBrain();
const capped = `notes/atoms-capped-${randomUUID().slice(0, 8)}`;
await brain.seed(capped, chatPage('Atoms capped', chatDays(900, 100, 6)).replace('type: conversation', 'type: meeting'));
- await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000001');
+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');
try {
const made = await drain(brain.engine, capped);
const rows = await rowsOf(brain.engine, capped);
@@ -383,7 +409,7 @@ export function defineSegmentedAtomsCases(opts: { getBrain: () => AppendBrain })
.toEqual({ calls: 0, receipts: [JSON.stringify({ state: 'partial', reason: 'cap_reached' })] });
expect(rows.length).toBeGreaterThan(0);
} finally {
- await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');
+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
}
}, 600_000);
}
@@ -403,6 +429,6 @@ export function defineSegmentReceiptDoctorCases(opts: { getBrain: () => AppendBr
const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[] }> }).groups;
expect({ status: check.status, argv: (check as { fix?: { argv: string[] } }).fix?.argv,
listed: groups.some(g => g.pipeline === 'extract_atoms' && g.kind === 'unread_windows' && g.samples.includes(`default:${s}`)) })
- .toEqual({ status: 'warn', argv: ['gbrain', 'config', 'set', PAGE_EMBED_CAP_KEY, '<usd>'], listed: true });
+ .toEqual({ status: 'warn', argv: ['gbrain', 'config', 'set', PAGE_DERIVATION_CAP_KEY, '<usd>'], listed: true });
}, 600_000);
}
diff --git a/test/helpers/derivation-spend-cases.ts b/test/helpers/derivation-spend-cases.ts
new file mode 100644
index 0000000000..e9a4570c3c
--- /dev/null
+++ b/test/helpers/derivation-spend-cases.ts
@@ -0,0 +1,286 @@
+/**
+ * Paid derivations on a segmented page under their spend caps (wave-b spec 8.2, 8.3; PR 4 lane 4b round 2), 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 and fake chat transports only.
+ *
+ * 1. Protects: a window that throws after the provider answered is booked and the windows finished before it keep their
+ * facts and rows; an abort partway through a page keeps the finished windows; a facts call reserves every attempt
+ * extract.ts may make and books what the provider reported for each attempt; a cap stop after a title change keeps
+ * the facts of the windows it did not extract again; a --since run keeps the facts before it and never settles the
+ * page; windows run across segment cuts exactly as the whole-page pass cuts them; extract_atoms retires nothing when
+ * the page changed before it settled; a visibility change re-extracts; the facts backstop keeps its finished windows'
+ * rows when a window throws.
+ * 2. Fails when: a throw or an abort drops finished windows or their spend, a retry is paid past the cap, a partial or
+ * filtered run deletes facts it did not replace, windows stop at segment cuts, or atoms are retired by a settle whose
+ * revision check failed.
+ */
+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 { __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';
+import { reservationCostUsd } from '../../src/core/budget/reservation-cost.ts';
+import { parseConversation } from '../../src/core/conversation-parser/parse.ts';
+import { renderSegmentForExtraction, splitIntoSegments } from '../../src/core/facts/conversation-windows.ts';
+import { outcomeSession, regularPageVersionToken } from '../../src/core/facts/conversation-window-extract.ts';
+import { TERMINAL_AUDIT_SOURCE } from '../../src/core/facts/audit-sources.ts';
+import { runFactsBackstop } from '../../src/core/facts/backstop.ts';
+import { truthLead } from '../../src/core/page-body/segment-blocks.ts';
+import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';
+import { chatDays, chatPage, derivations, extract, factsOf, PAID_MODEL, paidTransport } from './conversation-facts-incremental-cases.ts';
+
+const pageIdOf = async (engine: BrainEngine, slug: string) =>
+ Number((await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.id);
+const factsSpent = async (engine: BrainEngine, slug: string) => Number((await engine.executeRaw<{ spent: number }>(
+ "SELECT spent_usd AS spent FROM page_derivation_spend WHERE page_id=$1 AND family='facts'", [await pageIdOf(engine, slug)]))[0]?.spent ?? 0);
+/** What one paidTransport call over `text` costs (the fake extractor sends the window text alone). */
+const paidCost = (text: string) => reservationCostUsd(PAID_MODEL, 'chat', Math.ceil(text.length / 4), 32)!;
+const createSha = (text: string) => createHash('sha256').update(text).digest('hex');
+const sum = (values: number[]) => values.reduce((a, b) => a + b, 0);
+const caps = async (engine: BrainEngine, usd: string) => { await engine.setConfig(PAGE_DERIVATION_CAP_KEY, usd); await engine.setConfig(PAGE_EMBED_CAP_KEY, usd); };
+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 defineDerivationSpendCases(opts: { getBrain: () => AppendBrain }): void {
+ test('a window that throws after the provider answered is booked; the windows finished before it keep their facts and rows', async () => {
+ const { engine, seed } = opts.getBrain();
+ const slug = `notes/chat-throw-${randomUUID().slice(0, 8)}`;
+ await caps(engine, 'off');
+ await seed(slug, chatPage('Chat throw', chatDays(1000, 100, 7)));
+ __setChatTransportForTests(paidTransport);
+ try {
+ const first = await extract(engine, slug, { paid: true, failAt: 3 });
+ const rows = await derivations(engine, slug);
+ expect({ calls: first.calls.length, failed: first.result.pages_failed, facts: (await factsOf(engine, slug)).length, recorded: rows.keys.length })
+ .toEqual({ calls: 3, failed: 1, facts: 2, recorded: 2 });
+ expect(await factsSpent(engine, slug)).toBeCloseTo(sum(first.calls.map(paidCost)), 9);
+ const second = await extract(engine, slug, { paid: true });
+ expect(second.calls.filter(text => first.calls.slice(0, 2).includes(text))).toEqual([]);
+ expect(second.calls[0]).toBe(first.calls[2]);
+ expect(await factsSpent(engine, slug)).toBeCloseTo(sum([...first.calls, ...second.calls].map(paidCost)), 9);
+ } finally { __setChatTransportForTests(null); }
+ }, 600_000);
+
+ test('an abort partway through a page keeps the finished windows; the next run resumes without repeats', async () => {
+ const { engine, seed } = opts.getBrain();
+ const slug = `notes/chat-abort-${randomUUID().slice(0, 8)}`;
+ await caps(engine, 'off');
+ await seed(slug, chatPage('Chat abort', chatDays(1200, 100, 8)));
+ const first = await extract(engine, slug, { abortAfter: 3 }).catch(error => ({ error }));
+ const facts = await factsOf(engine, slug);
+ const rows = await derivations(engine, slug);
+ expect({ facts: facts.length, recorded: rows.keys.length, anchored: facts.every(f => rows.keys.includes(f.key)) }).toEqual({ facts: 3, recorded: 3, anchored: true });
+ const second = await extract(engine, slug);
+ const done = await derivations(engine, slug);
+ expect({ repeats: second.calls.filter(text => facts.some(f => f.key.endsWith(':' + createSha(text)))).length, facts: (await factsOf(engine, slug)).length,
+ total: second.calls.length + 3, states: [...new Set(done.states)] }).toEqual({ repeats: 0, facts: done.keys.length, total: done.keys.length, states: ['done'] });
+ expect('error' in first || first.result.pages_failed === 1).toBe(true);
+ }, 600_000);
+
+ test('a facts call reserves every attempt extract.ts may make and books each attempt the provider answered', async () => {
+ const { engine, seed } = opts.getBrain();
+ const slug = `notes/chat-attempts-${randomUUID().slice(0, 8)}`;
+ await engine.setConfig('facts.extraction_model', PAID_MODEL);
+ await seed(slug, chatPage('Chat attempts', chatDays(1400, 100, 9)));
+ // One call fits $0.2 (about $0.07 at most); its truncation and malformed-output retries (twice the output each) do not.
+ await caps(engine, '0.2');
+ const usage: number[] = [];
+ let n = 0;
+ __setChatTransportForTests(async (o: ChatOpts): Promise<ChatResult> => {
+ const chars = o.messages.reduce((c, m) => c + (typeof m.content === 'string' ? m.content.length : 0), 0) + (o.system?.length ?? 0);
+ const input = Math.ceil(chars / 4);
+ usage.push(reservationCostUsd(PAID_MODEL, 'chat', input, 50)!);
+ return { text: '{"facts":[]}', blocks: [], stopReason: ++n % 2 === 1 ? 'length' : 'end', model: PAID_MODEL, providerId: 'anthropic',
+ usage: { input_tokens: input, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ try {
+ await extractProduction(engine, slug);
+ expect({ attempts: usage.length, receipts: (await derivations(engine, slug)).receipts.filter(Boolean).map(r => (r as { reason: string }).reason) })
+ .toEqual({ attempts: 0, receipts: ['cap_reached'] });
+ await caps(engine, '1');
+ await extractProduction(engine, slug);
+ expect(usage.length).toBeGreaterThanOrEqual(2);
+ expect(usage.length % 2).toBe(0);
+ expect(await factsSpent(engine, slug)).toBeCloseTo(sum(usage), 9);
+ expect(await factsSpent(engine, slug)).toBeLessThanOrEqual(1);
+ } finally {
+ __setChatTransportForTests(null);
+ await engine.setConfig('facts.extraction_model', '');
+ await caps(engine, 'off');
+ }
+ }, 600_000);
+
+ test('a cap stop after a title change keeps every fact of the windows it did not extract again', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-retitle-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Chat T1', chatDays(1600, 100, 10)));
+ await extract(brain.engine, slug);
+ const before = (await factsOf(brain.engine, slug)).map(f => f.id);
+ expect(before.length).toBeGreaterThan(100);
+ await brain.seed(slug, chatPage('Chat T2', (await brain.body(slug)).truth));
+ await caps(brain.engine, '0.000001');
+ const capped = await extract(brain.engine, slug);
+ expect({ calls: capped.calls.length, facts: (await factsOf(brain.engine, slug)).map(f => f.id) }).toEqual({ calls: 0, facts: before });
+ await caps(brain.engine, 'off');
+ const full = await extract(brain.engine, slug);
+ const after = await factsOf(brain.engine, slug);
+ expect({ calls: full.calls.length, survivors: after.filter(f => before.includes(f.id)).length, facts: after.length })
+ .toEqual({ calls: (await derivations(brain.engine, slug)).keys.length, survivors: 0, facts: full.calls.length });
+ }, 600_000);
+
+ test('a --since run keeps every fact before it and never settles the page; the next full run settles it without repeats', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-since-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ const body = chatDays(1800, 100, 11);
+ await brain.seed(slug, chatPage('Chat since', body));
+ await extract(brain.engine, slug);
+ const before = await factsOf(brain.engine, slug);
+ await brain.seed(slug, chatPage('Chat since', `${body}\n\n${chatDays(1900, 2, 11)}`));
+ const sinceIso = `${new Date(Date.UTC(2025, 0, 1) + 1850 * 86_400_000).toISOString().slice(0, 10)}T00:00:00Z`;
+ // Windows never span a day (a day's turns end hours before the next day's), so a fact whose window starts before the
+ // --since day comes from a window wholly before it.
+ const early = (await brain.engine.executeRaw<{ id: number }>(
+ "SELECT id FROM facts WHERE source_markdown_slug=$1 AND source='cli:extract-conversation-facts' AND expired_at IS NULL AND valid_from < $2::timestamptz",
+ [slug, sinceIso])).map(r => ({ id: Number(r.id) }));
+ const filtered = await extract(brain.engine, slug, { sinceIso });
+ const kept = (await factsOf(brain.engine, slug)).map(f => f.id);
+ expect({ calls: filtered.calls.length > 0, earlyKept: early.filter(f => !kept.includes(f.id)).length, stamped: await terminalStamps(brain.engine, slug) })
+ .toEqual({ calls: true, earlyKept: 0, stamped: 0 });
+ expect(early.length).toBeGreaterThan(before.length / 3);
+ const full = await extract(brain.engine, slug);
+ expect({ repeats: full.calls.filter(text => filtered.calls.includes(text)).length, stamped: await terminalStamps(brain.engine, slug),
+ facts: (await factsOf(brain.engine, slug)).length }).toEqual({ repeats: 0, stamped: 1, facts: (await derivations(brain.engine, slug)).keys.length });
+ }, 600_000);
+
+ test('windows run across segment cuts: the segmented page extracts exactly the whole-page windows', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-cuts-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ const words = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast'];
+ const clock = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
+ // One day header and one gap group (turns a minute apart), so the segment cuts fall inside the group.
+ const lines = ['## 2025-03-01', ''];
+ // Turn lengths vary, so window boundaries do not line up with the segment cuts.
+ for (let t = 0; t < 1400; t++) lines.push(`**${['Alice Example', 'Bob Example'][t % 2]}** (${clock(t)}): ${Array.from({ length: 50 + (t * 37) % 80 }, (_, i) => words[(t * 7 + i) % words.length]).join(' ')}.`, '');
+ await brain.seed(slug, chatPage('Chat cuts', lines.join('\n')));
+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
+ expect((await brain.engine.readManifest(page.id)).length).toBeGreaterThan(2);
+ const truth = (await brain.body(slug)).truth;
+ const expected = splitIntoSegments(parseConversation(truth, { page }).messages, { pageTitle: 'Chat cuts' }).map(seg => renderSegmentForExtraction('Chat cuts', seg));
+ const { calls } = await extract(brain.engine, slug);
+ expect(expected.length).toBeGreaterThan(10);
+ expect([...calls].sort()).toEqual([...expected].sort());
+ }, 600_000);
+
+ test('a change of facts.default_visibility re-extracts every window', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/chat-visibility-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Chat visibility', chatDays(2000, 100, 12)));
+ const first = await extract(brain.engine, slug);
+ await brain.engine.setConfig('facts.default_visibility', 'world');
+ try {
+ const second = await extract(brain.engine, slug, { force: true });
+ expect({ calls: second.calls.length, same: [...second.calls].sort().join('\n') === [...first.calls].sort().join('\n') }).toEqual({ calls: first.calls.length, same: true });
+ } finally { await brain.engine.setConfig('facts.default_visibility', 'private'); }
+ }, 600_000);
+
+ test('the facts backstop keeps the rows of the windows it finished when a window throws', async () => {
+ const { engine, seed } = opts.getBrain();
+ const slug = `notes/backstop-throw-${randomUUID().slice(0, 8)}`;
+ await caps(engine, 'off');
+ await seed(slug, chatPage('Backstop throw', chatDays(2200, 100, 13)).replace('type: conversation', 'type: note'));
+ const pageId = await pageIdOf(engine, slug);
+ const prompts: string[] = [];
+ const controller = new AbortController();
+ const lead = await truthLead(engine, pageId, 4096);
+ const backstop = (signal?: AbortSignal) => runFactsBackstop({ slug, type: 'note', compiled_truth: lead, frontmatter: {}, segmentedPageId: pageId },
+ { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline', abortSignal: signal });
+ __setChatTransportForTests(async (o: ChatOpts): Promise<ChatResult> => {
+ prompts.push(JSON.stringify(o.messages));
+ if (prompts.length === 3 && !controller.signal.aborted) { controller.abort(); throw Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }); }
+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ try {
+ await backstop(controller.signal).catch(() => null);
+ const firstTwo = prompts.slice(0, 2);
+ const rows = await engine.readSegmentDerivations(pageId, { kind: 'facts_backstop' });
+ expect(rows.flatMap(r => (r.output as { windows: unknown[] }).windows).length).toBe(2);
+ prompts.length = 0;
+ await backstop();
+ expect(prompts.filter(p => firstTwo.includes(p))).toEqual([]);
+ expect(prompts.length).toBeGreaterThan(0);
+ } finally { __setChatTransportForTests(null); }
+ }, 600_000);
+
+ test('extract_atoms retires no atom when the page changed between its last window and its settle', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/atoms-race-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.engine.setConfig('cycle.extract_atoms.max_input_chars', '50000');
+ await brain.seed(slug, chatPage('Atoms race', chatDays(2400, 100, 14)).replace('type: conversation', 'type: meeting'));
+ const pageId = await pageIdOf(brain.engine, slug);
+ const prompts: string[] = [];
+ let n = 0;
+ const chat = async (o: ChatOpts): Promise<ChatResult> => {
+ prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));
+ const title = `race atom ${++n}`;
+ const text = JSON.stringify({ atoms: [{ title, atom_type: 'insight', body: `Body for ${title}.`, source_quote: null, lesson: null, concepts: null, virality_score: null, emotional_register: null }] });
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ };
+ // The page is edited right after a window of this page settles on its derivation row: with one window offered, that
+ // is between the last window and the page's settle.
+ let armed = false;
+ let edited = false;
+ const engine = new Proxy(brain.engine, {
+ get(target, prop) {
+ if (prop === 'upsertSegmentDerivations') {
+ return async (rows: Parameters<BrainEngine['upsertSegmentDerivations']>[0]) => {
+ const out = await target.upsertSegmentDerivations(rows);
+ if (armed && rows.some(row => row.pageId === pageId && row.kind === 'extract_atoms' && row.state === 'done')) {
+ armed = false;
+ expect(await brain.call('append_page', { slug, text: chatDays(2600, 1, 14), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ edited = true;
+ }
+ return out;
+ };
+ }
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const drain = async () => { for (let run = 0; run < 20; run++) { const made = n; await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] }); if (n === made) break; } };
+ const live = async () => (await brain.engine.executeRaw<{ slug: string }>(
+ "SELECT slug FROM pages WHERE source_id='default' AND type='atom' AND deleted_at IS NULL AND frontmatter->>'source_slug'=$1", [slug])).map(r => r.slug).sort();
+ await drain();
+ // An atom of an earlier whole-page extraction: the page's next settle retires it.
+ const earlier = `atoms/earlier-${randomUUID().slice(0, 8)}`;
+ await brain.engine.putPage(earlier, { type: 'atom', title: 'Earlier atom', compiled_truth: 'From a whole-page extraction.', frontmatter: { source_slug: slug, source_hash: 'earlier00000000' } });
+ const settled = await live();
+ expect(settled).toContain(earlier);
+ // One more turn grows the tail window only: one window is offered.
+ expect(await brain.call('append_page', { slug, text: 'Bob Example (11:59 PM): one more budget review.', request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ prompts.length = 0;
+ armed = true;
+ await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] });
+ expect({ edited, offered: prompts.filter(p => p.includes('Source: ' + slug + '\n')).length }).toEqual({ edited: true, offered: 1 });
+ const after = await live();
+ expect(settled.filter(s => !after.includes(s))).toEqual([]);
+ // Once the page stops changing, its windows settle and the earlier atom is retired.
+ await drain();
+ expect(await live()).not.toContain(earlier);
+ }, 600_000);
+}
+
+/** A production-extractor run (no injected extractor): the gateway's fake transport answers. */
+async function extractProduction(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/large-pages/conversation-facts-incremental.test.ts b/test/large-pages/conversation-facts-incremental.test.ts
index a2db329e47..40d97e6a13 100644
--- a/test/large-pages/conversation-facts-incremental.test.ts
+++ b/test/large-pages/conversation-facts-incremental.test.ts
@@ -4,6 +4,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 { defineConversationFactsIncrementalCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases, defineSegmentReceiptDoctorCases } from '../helpers/conversation-facts-incremental-cases.ts';
let brain: AppendBrain;
@@ -16,4 +17,5 @@ describe('conversation facts incremental [pglite]', () => {
defineSegmentedBackstopCases({ getBrain: () => brain });
defineSegmentedAtomsCases({ getBrain: () => brain });
defineSegmentReceiptDoctorCases({ getBrain: () => brain });
+ defineDerivationSpendCases({ getBrain: () => brain });
});
diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.ts
index 6c70352685..aa8039bf41 100644
--- a/test/page-spend-reservation.test.ts
+++ b/test/page-spend-reservation.test.ts
@@ -1,20 +1,29 @@
/**
- * reservePageSpend (wave-b spec 8.3, PR 4 lane 4b): every paid step on a segmented page reserves against the page's
- * one lifetime cap in page_embedding_budget, the kind carried in the signature.
+ * Per-page spend ledgers (wave-b spec 8.3, PR 4 lane 4b): embeddings reserve on page_embedding_budget under
+ * `embed.max_usd_per_page`; each paid derivation family (facts, atoms, synopsis) reserves on its own page_derivation_spend
+ * row under `derive.max_usd_per_page`; meterPaidCall books what the provider reported.
*
- * 1. Protects: two kinds share one cap; a reservation over what the cap leaves refuses before the (fake) provider call
- * and reserves nothing; a failed call releases its reservation; only a new embedding model starts a new ledger;
- * inline pages under the large-page threshold are unmetered; the embedding planner sees derivation spend.
- * 2. Fails when: a kind gets its own budget, a refusal still runs the call or books spend, a facts model change
- * forgives spend, or planPageEmbedding grants past spend another kind already booked.
- * 3. Why existing coverage misses it: page_embedding_budget was metered only by the embedding planner.
+ * 1. Protects: each family has its own cap and the embedding cap counts embeddings only; a reservation over what a cap
+ * leaves refuses before the (fake) provider call and reserves nothing; a failed call releases its reservation; a new
+ * 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; 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.
* PGLite always; Postgres too when DATABASE_URL is set (test/postgres-unit-arms.txt).
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { PAGE_EMBED_CAP_KEY, planPageEmbedding, reservePageSpend, spendGrant, type PageSpendSignature } from '../src/core/page-embedding-budget.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 { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';
+import { parsePricingOverrides } from '../src/core/budget/budget-tracker.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
const engines: Array<{ name: string; engine: BrainEngine }> = [];
@@ -30,15 +39,16 @@ beforeAll(async () => {
engines.push({ name: 'postgres', engine: pg.engine });
closePostgres = pg.close;
}
- for (const { engine } of engines) await engine.setConfig(PAGE_EMBED_CAP_KEY, '1');
+ for (const { engine } of engines) { await engine.setConfig(PAGE_EMBED_CAP_KEY, '1'); await engine.setConfig(PAGE_DERIVATION_CAP_KEY, '1'); }
}, 120_000);
afterAll(async () => {
+ __setChatTransportForTests(null);
for (const { name, engine } of engines) if (name === 'pglite') await engine.disconnect();
await closePostgres?.();
});
-/** A stored page row standing in for a segmented page of `bytes` (the ledger reads only its id and shape). */
+/** A stored page row standing in for a segmented page of `bytes` (the ledgers read only its id and shape). */
async function segmentedPage(engine: BrainEngine, bytes = 40 * 1024 * 1024) {
const slug = `conversations/spend-${randomUUID().slice(0, 8)}`;
await engine.putPage(slug, { type: 'conversation', title: 'Spend probe', compiled_truth: 'body' });
@@ -46,13 +56,19 @@ async function segmentedPage(engine: BrainEngine, bytes = 40 * 1024 * 1024) {
return { id: Number(row!.id), body_storage: 'segmented' as const, body_bytes: bytes };
}
-async function ledger(engine: BrainEngine, pageId: number) {
+async function embedLedger(engine: BrainEngine, pageId: number) {
const [row] = await engine.executeRaw<{ spent_usd: number; reserved_usd: number; embedding_signature: string | null }>(
'SELECT spent_usd, reserved_usd, embedding_signature FROM page_embedding_budget WHERE page_id = $1', [pageId]);
return row ? { spent: Number(row.spent_usd), reserved: Number(row.reserved_usd), signature: row.embedding_signature } : null;
}
-/** One fake paid call under a reservation: the call runs only on a grant. */
+async function familyLedger(engine: BrainEngine, pageId: number, family: string) {
+ const [row] = await engine.executeRaw<{ spent_usd: number; reserved_usd: number }>(
+ 'SELECT spent_usd, reserved_usd FROM page_derivation_spend WHERE page_id = $1 AND family = $2', [pageId, family]);
+ return row ? { spent: Number(row.spent_usd), reserved: Number(row.reserved_usd) } : null;
+}
+
+/** One fake paid call under a reservation: the call runs only on a grant, and books its reservation. */
async function paidStep(engine: BrainEngine, page: Awaited<ReturnType<typeof segmentedPage>>, signature: PageSpendSignature, usd: number,
calls: { n: number }, fail = false) {
const decision = await reservePageSpend(engine, page, signature, usd);
@@ -64,51 +80,60 @@ async function paidStep(engine: BrainEngine, page: Awaited<ReturnType<typeof seg
return decision;
}
-describe('reservePageSpend', () => {
- test('two kinds share one per-page cap; a reservation over it refuses before the call and books nothing', async () => {
+const HAIKU = 'anthropic:claude-haiku-4-5';
+const answer = (input: number, output: number): ChatResult => ({ text: 'ok', blocks: [], stopReason: 'end', model: HAIKU, providerId: 'anthropic',
+ usage: { input_tokens: input, output_tokens: output, cache_read_tokens: 0, cache_creation_tokens: 0 } });
+
+describe('per-page spend ledgers', () => {
+ test('each derivation family has its own cap and the embedding cap counts embeddings only; a refusal books nothing', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const calls = { n: 0 };
expect((await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.6, calls)).kind, name).toBe('grant');
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.6, reserved: 0, signature: null });
- const refused = await paidStep(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.5, calls);
+ expect((await paidStep(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.5, calls)).kind, name).toBe('grant');
+ const refused = await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.5, calls);
expect(refused, name).toEqual({ kind: 'refused', reason: 'cap_reached', capUsd: 1, spentUsd: 0.6, reservedUsd: 0, estimateUsd: 0.5 });
- expect(calls.n, name).toBe(1);
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.6, reserved: 0, signature: null });
- expect((await paidStep(engine, page, 'embedding:openai:text-embedding-3-large:1536', 0.4, calls)).kind, name).toBe('grant');
- expect(calls.n, name).toBe(2);
- expect(await ledger(engine, page.id), name).toEqual({ spent: 1, reserved: 0, signature: 'openai:text-embedding-3-large:1536' });
- expect((await paidStep(engine, page, 'synopsis:anthropic:claude-haiku-5-5', 0.01, calls)).kind, name).toBe('refused');
expect(calls.n, name).toBe(2);
+ expect((await paidStep(engine, page, 'embedding:openai:text-embedding-3-large:1536', 1, calls)).kind, name).toBe('grant');
+ expect((await paidStep(engine, page, 'synopsis:anthropic:claude-haiku-5-5', 0.9, calls)).kind, name).toBe('grant');
+ expect(calls.n, name).toBe(4);
+ expect({ facts: await familyLedger(engine, page.id, 'facts'), atoms: await familyLedger(engine, page.id, 'atoms'),
+ synopsis: await familyLedger(engine, page.id, 'synopsis'), embedding: await embedLedger(engine, page.id) }, name).toEqual({
+ facts: { spent: 0.6, reserved: 0 }, atoms: { spent: 0.5, reserved: 0 }, synopsis: { spent: 0.9, reserved: 0 },
+ embedding: { spent: 1, reserved: 0, signature: 'openai:text-embedding-3-large:1536' } });
}
});
- test('an open reservation counts against the cap until it settles; a failed call releases it', async () => {
+ test('an open reservation counts against its family cap until it settles; a failed call releases it', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const first = await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.7);
expect(first.kind, name).toBe('grant');
- expect((await reservePageSpend(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.4)).kind, name).toBe('refused');
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0, reserved: 0.7, signature: null });
+ expect((await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.4)).kind, name).toBe('refused');
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0, reserved: 0.7 });
if (first.kind === 'grant') await first.grant.settle({ ok: false });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0, reserved: 0, signature: null });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0, reserved: 0 });
const calls = { n: 0 };
- expect((await paidStep(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.4, calls, true)).kind, name).toBe('grant');
+ expect((await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.4, calls, true)).kind, name).toBe('grant');
expect(calls.n, name).toBe(1);
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0, reserved: 0, signature: null });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0, reserved: 0 });
}
});
- test('only a new embedding model starts a new ledger; a facts model change keeps the spend', async () => {
+ test('a new embedding model resets the embedding ledger only; derivation spend and an open derivation reservation stay', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const calls = { n: 0 };
await paidStep(engine, page, 'embedding:openai:text-embedding-3-large:1536', 0.5, calls);
- await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.3, calls);
- expect((await paidStep(engine, page, 'facts:openai:gpt-6-luna', 0.3, calls)).kind, name).toBe('refused');
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.8, reserved: 0, signature: 'openai:text-embedding-3-large:1536' });
+ await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.5, calls);
+ const open = await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.25);
expect((await paidStep(engine, page, 'embedding:voyage:voyage-4:1024', 0.3, calls)).kind, name).toBe('grant');
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.3, reserved: 0, signature: 'voyage:voyage-4:1024' });
+ expect({ embedding: await embedLedger(engine, page.id), facts: await familyLedger(engine, page.id, 'facts') }, name)
+ .toEqual({ embedding: { spent: 0.3, reserved: 0, signature: 'voyage:voyage-4:1024' }, facts: { spent: 0.5, reserved: 0.25 } });
+ // A facts model change keeps the family's spend: 0.5 spent + 0.25 open + 0.3 is over the cap.
+ expect((await paidStep(engine, page, 'facts:openai:gpt-6-luna', 0.3, calls)).kind, name).toBe('refused');
+ if (open.kind === 'grant') await open.grant.settle({ ok: true });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0.75, reserved: 0 });
expect(calls.n, name).toBe(3);
}
});
@@ -117,11 +142,11 @@ describe('reservePageSpend', () => {
for (const { name, engine } of engines) {
const page = { id: (await segmentedPage(engine)).id, body_storage: 'inline' as const, compiled_truth: 'short', timeline: '' };
expect(await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 50), name).toEqual({ kind: 'unmetered' });
- expect(await ledger(engine, page.id), name).toBeNull();
+ expect({ embedding: await embedLedger(engine, page.id), facts: await familyLedger(engine, page.id, 'facts') }, name).toEqual({ embedding: null, facts: null });
}
});
- test('the embedding planner grants only what derivation spend left under the cap', async () => {
+ test('the embedding planner is not limited by derivation spend', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const calls = { n: 0 };
@@ -130,30 +155,43 @@ describe('reservePageSpend', () => {
const decision = await planPageEmbedding(engine, page, stale, { signature: 'openai:text-embedding-3-large:1536', approvedCapUsd: 0 });
expect(decision.kind, name).toBe('grant');
if (decision.kind !== 'grant') continue;
- expect({ granted: decision.grant.chunkIndexes.size, deferred: decision.grant.deferred }, name).toEqual({ granted: 0, deferred: 2 });
+ expect({ granted: decision.grant.chunkIndexes.size, deferred: decision.grant.deferred }, name).toEqual({ granted: 2, deferred: 0 });
await decision.grant.settle({ ok: true });
}
});
+
+ test('concurrent reservations on one family never overspend its cap', async () => {
+ for (const { name, engine } of engines) {
+ const page = await segmentedPage(engine);
+ const decisions = await Promise.all(Array.from({ length: 10 }, () => reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.3)));
+ const grants = decisions.filter(d => d.kind === 'grant');
+ expect({ grants: grants.length, refused: decisions.filter(d => d.kind === 'refused').length }, name).toEqual({ grants: 3, refused: 7 });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0, reserved: expect.closeTo(0.9, 9) });
+ await Promise.all(grants.map(d => d.kind === 'grant' ? d.grant.settle({ ok: true }) : null));
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: expect.closeTo(0.9, 9), reserved: 0 });
+ }
+ });
+
test('a settle after its reservation was folded into spent as stale changes nothing; the newer reservation is untouched', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
// The ledger is aged by rewriting its times; the 2 ms let the clock (1 ms resolution on PGLite) pass A's reservation time as an hour would.
- const age = async () => { await new Promise(resolve => setTimeout(resolve, 2)); await engine.executeRaw("UPDATE page_embedding_budget SET reserved_at = now() - interval '2 hours', updated_at = now() - interval '2 hours' WHERE page_id = $1", [page.id]); };
+ const age = async () => { await new Promise(resolve => setTimeout(resolve, 2)); await engine.executeRaw("UPDATE page_derivation_spend SET reserved_at = now() - interval '2 hours', updated_at = now() - interval '2 hours' WHERE page_id = $1", [page.id]); };
const a = await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.25);
await age();
- const b = await reservePageSpend(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.125);
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.25, reserved: 0.125, signature: null });
+ const b = await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.125);
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0.25, reserved: 0.125 });
if (a.kind !== 'grant' || b.kind !== 'grant') throw new Error(name + ': expected two grants');
await a.grant.settle({ ok: true });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.25, reserved: 0.125, signature: null });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0.25, reserved: 0.125 });
await a.grant.settle({ ok: false });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.25, reserved: 0.125, signature: null });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0.25, reserved: 0.125 });
await b.grant.settle({ ok: true });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.375, reserved: 0, signature: null });
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0.375, reserved: 0 });
}
});
- test('an embedding grant folded by a later derivation reservation is not booked twice', async () => {
+ test('an embedding grant folded by a later embedding reservation is not booked twice', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
const stale = [{ chunk_index: 0, chunk_text: 'alpha '.repeat(2000) }];
@@ -161,14 +199,15 @@ describe('reservePageSpend', () => {
if (a.kind !== 'grant' || a.grant.reservedUsd <= 0) throw new Error(name + ': expected an embedding grant with a reservation');
await new Promise(resolve => setTimeout(resolve, 2));
await engine.executeRaw("UPDATE page_embedding_budget SET reserved_at = now() - interval '2 hours', updated_at = now() - interval '2 hours' WHERE page_id = $1", [page.id]);
- const b = await reservePageSpend(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.125);
- if (b.kind !== 'grant') throw new Error(name + ': expected a facts grant');
- const folded = await ledger(engine, page.id);
+ const b = await reservePageSpend(engine, page, 'embedding:openai:text-embedding-3-large:1536', 0.125);
+ if (b.kind !== 'grant') throw new Error(name + ': expected an embedding grant');
+ const folded = await embedLedger(engine, page.id);
await a.grant.settle({ ok: true });
- expect(await ledger(engine, page.id), name).toEqual(folded);
+ expect(await embedLedger(engine, page.id), name).toEqual(folded);
expect(folded, name).toEqual({ spent: a.grant.reservedUsd, reserved: 0.125, signature: 'openai:text-embedding-3-large:1536' });
}
});
+
test('a new embedding model replaces the ledger: the old model\'s open grant settles into nothing', async () => {
for (const { name, engine } of engines) {
const page = await segmentedPage(engine);
@@ -176,9 +215,39 @@ describe('reservePageSpend', () => {
const b = await reservePageSpend(engine, page, 'embedding:voyage:voyage-4:1024', 0.125);
if (a.kind !== 'grant' || b.kind !== 'grant') throw new Error(name + ': expected two grants');
await a.grant.settle({ ok: true });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0, reserved: 0.125, signature: 'voyage:voyage-4:1024' });
+ expect(await embedLedger(engine, page.id), name).toEqual({ spent: 0, reserved: 0.125, signature: 'voyage:voyage-4:1024' });
await b.grant.settle({ ok: true });
- expect(await ledger(engine, page.id), name).toEqual({ spent: 0.125, reserved: 0, signature: 'voyage:voyage-4:1024' });
+ expect(await embedLedger(engine, page.id), name).toEqual({ spent: 0.125, reserved: 0, signature: 'voyage:voyage-4:1024' });
}
});
+
+ test('meterPaidCall books what the provider reported for every attempt, a throw after the answer included', async () => {
+ for (const { name, engine } of engines) {
+ const page = await segmentedPage(engine);
+ const answers = [answer(1000, 200), answer(3000, 400)];
+ __setChatTransportForTests(async () => answers.shift()!);
+ const ask = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 500 });
+ const out = await meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, async () => { await ask(); await ask(); return 'done'; });
+ const cost = reservationCostUsd(HAIKU, 'chat', 1000, 200)! + reservationCostUsd(HAIKU, 'chat', 3000, 400)!;
+ expect({ out, ledger: await familyLedger(engine, page.id, 'facts') }, name).toEqual({ out: { value: 'done' }, ledger: { spent: expect.closeTo(cost, 12), reserved: 0 } });
+ __setChatTransportForTests(async () => answer(2000, 100));
+ await expect(meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, async () => { await ask(); throw new Error('parse failed after the answer'); }), name).rejects.toThrow('parse failed');
+ const after = cost + reservationCostUsd(HAIKU, 'chat', 2000, 100)!;
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: expect.closeTo(after, 12), reserved: 0 });
+ await expect(meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, async () => { throw new Error('failed before any call'); }), name).rejects.toThrow('before any call');
+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: expect.closeTo(after, 12), reserved: 0 });
+ __setChatTransportForTests(async () => ({ ...answer(10, 10), model: 'test:unpriced-model' }));
+ await meterPaidCall(engine, page, 'atoms:test:unpriced-model', 0.05, () => chat({ model: 'test:unpriced-model', messages: [{ role: 'user', content: 'w' }], maxTokens: 50 }));
+ expect(await familyLedger(engine, page.id, 'atoms'), name).toEqual({ spent: 0.05, reserved: 0 });
+ __setChatTransportForTests(null);
+ }
+ });
+
+ 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 } }));
+ expect(estimateChatCallUsd(HAIKU, 4000, 1000, overrides)).toBeCloseTo(((4000 / 4 + 1500) * 10 + 1000 * 100) / 1_000_000, 12);
+ expect(estimateChatCallUsd(HAIKU, 4000, 1000, overrides)).toBeGreaterThan(base);
+ expect(estimateFactsExtractionUsd(HAIKU, 4000, 1000)).toBeCloseTo(base + 2 * estimateChatCallUsd(HAIKU, 4000, 2000), 12);
+ });
});