Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(page spend): meterPaidCall books only attempts the provider answered; synopsis cases on the derivation ledger; drop the dead billed set
garrytan2f36c08b304d
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cb04a07f2e..ab8b0ba1fc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1050,10 +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: '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.' },+ { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, and one the provider rejected without answering (a rate limit, an auth or server error, a failed embedding) books nothing. Doctor lists the pages a cap stopped.' },// 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. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks; a window whose synopsis or embedding fails counts only the synopsis calls the provider may have billed against the cap. 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.' },+ { since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },// PR 4 (Wave B incremental derivation, transcripts)// 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/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 40cda7282a..f9c9b44c62 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -719,8 +719,6 @@ async function synopsisWrappedTexts(opts: {args: ReembedPageArgs;synopsisModel: string;synopsisMaxTokens?: number;- /** Collects the chunks whose synopsis call the provider may have billed (see SYNOPSIS_UNBILLED). */- billed?: Set<SynopsisChunk>;}): Promise<string[] | Exclude<Phase1Result, Phase1Success>> {const { chunks, args } = opts;const wrappedTexts: string[] = new Array(chunks.length);@@ -748,9 +746,6 @@ async function synopsisWrappedTexts(opts: {return wrappedTexts;}-/** Synopsis results the provider returns before billing the call: a call that ended with one of these is not booked. */-const SYNOPSIS_UNBILLED: ReadonlySet<string> = new Set<SynopsisFailureKind>(['auth_failure', 'rate_limit', 'provider_5xx']);-class ChunkSynopsisPhase1Error extends Error {constructor(readonly result: Exclude<Phase1Result, Phase1Success>) {super(`chunk synopsis failed: ${result.kind}`);@@ -766,9 +761,8 @@ async function buildWrappedChunkText(opts: {synopsisModel: string;/** #3883: resolved output-token cap (undefined → page-summary default). */synopsisMaxTokens?: number;- billed?: Set<SynopsisChunk>;}): Promise<string> {- const { chunk: c, sourceText, title, args, synopsisModel, synopsisMaxTokens, billed } = opts;+ const { chunk: c, sourceText, title, args, synopsisModel, synopsisMaxTokens } = opts;// Code chunks always bypass the wrapper (D20-T4) — pass through.if (c.chunk_source === 'fenced_code') {@@ -796,7 +790,6 @@ async function buildWrappedChunkText(opts: {}leaseAcquired = true;}- billed?.add(c);synopsisResult = await (args.generateSynopsis ?? generatePerChunkSynopsis)({documentText: sourceText,chunkText: c.chunk_text,@@ -819,7 +812,6 @@ async function buildWrappedChunkText(opts: {}}- if (SYNOPSIS_UNBILLED.has(synopsisResult.kind)) billed?.delete(c);if (synopsisResult.kind === 'success') {const prefix = buildContextualPrefix(title, synopsisResult.synopsis);return wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source);diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 435bdea3d4..a8a4e1b1e0 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -37,7 +37,7 @@ import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './conteimport 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, type BudgetKind } from './budget/reservation-cost.ts';+import { reservationCostUsd, usageCostUsd, 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';@@ -247,12 +247,37 @@ export function estimateFactsExtractionUsd(model: string, chars: number, maxOutpconst TOUCHPOINT_KIND: Partial<Record<string, BudgetKind>> = { embedding: 'embed', rerank: 'rerank' };+/**+ * A metered step's tracker, which also sums what the provider billed: every attempt it answered, at its reported usage+ * (a success without reported usage at its estimate). An attempt that failed with no reported usage carries the+ * gateway's pessimistic fallback (a rate limit, an auth or server error, a connection that got no answer): the provider+ * billed nothing, so the page ledger books nothing for it, while the step's caps still count it.+ */+class MeteredStepTracker extends BudgetTracker {+ billedUsd = 0;+ billedAttempts = 0;+ unpricedAttempts = 0;+ constructor(opts: ConstructorParameters<typeof BudgetTracker>[0], private readonly pricing?: PricingOverrides) { super(opts); }++ override record(actual: Parameters<BudgetTracker['record']>[0]): void {+ const failed = actual.failed === true || (actual.label?.endsWith('.failed') ?? false);+ if (!(failed && actual.estimated === true)) {+ const cost = usageCostUsd(actual.modelId, actual.inputTokens, actual.outputTokens ?? 0, actual.kind ?? 'chat', this.pricing);+ this.billedAttempts++;+ if (cost === null) this.unpricedAttempts++;+ else this.billedUsd += cost;+ }+ super.record(actual);+ }+}+/*** 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+ * Every attempt the provider answered is booked whatever the step's outcome (a truncated, malformed or refused answer, a+ * throw after the provider answered); an attempt that failed with no provider-reported usage (a rate limit, an auth or+ * server error, an embedding that failed) is not; an unpriced model books the reservation; a step with no billed attempt+ * (the provider was never called or never answered) books nothing. The attempts are recorded on the caller's tracker too, and the caller's* remaining cap bounds them.*/export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, signature: PageSpendSignature, estimateUsd: number,@@ -262,8 +287,8 @@ export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, siif (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 } : {}) });+ const tracker = new MeteredStepTracker({ label: `page-spend:${signature}`, pricingOverrides: opts.pricingOverrides,+ ...(parent && parentCap !== undefined ? { maxCostUsd: Math.max(0, parentCap - parent.totalSpent), capSource: parent.capSource } : {}) }, opts.pricingOverrides);try {return { value: await withBudgetTracker(tracker, call) };} finally {@@ -272,8 +297,7 @@ export async function meterPaidCall<T>(engine: BrainEngine, page: BudgetPage, sirecordOnTracker(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 });+ await decision.grant.settle({ ok: tracker.billedAttempts > 0, usd: tracker.unpricedAttempts > 0 ? decision.grant.reservedUsd : tracker.billedUsd });}}diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.tsindex 1e281cf351..c5999cdef2 100644--- a/test/helpers/synopsis-segment-hash-cases.ts+++ b/test/helpers/synopsis-segment-hash-cases.ts@@ -21,13 +21,15 @@ import { expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../../src/core/engine.ts';import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';-import { SYNOPSIS_DOC_MAX_CHARS, estimateSynopsisCallUsd, segmentSynopsisWindows, type GeneratePerChunkSynopsisArgs, type GeneratePerChunkSynopsisResult } from '../../src/core/page-summary.ts';+import { DEFAULT_SYNOPSIS_MODEL, SYNOPSIS_DOC_MAX_CHARS, segmentSynopsisWindows, type GeneratePerChunkSynopsisArgs, type GeneratePerChunkSynopsisResult } from '../../src/core/page-summary.ts';import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';import { segmentSynopsisInputHashes, segmentSynopsisLead } from '../../src/core/page-body/segment-synopsis.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 { reservationCostUsd } from '../../src/core/budget/reservation-cost.ts';import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';-import { __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { __setChatTransportForTests, __setEmbedTransportForTests, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';import { embedStalePages } from '../../src/core/embed-stale.ts';import { pageEmbeddingLeaseProbe } from '../../src/core/page-embedding-lease.ts';import { installSegmentedVectors, readSegmentedEmbedPage } from '../../src/core/page-body/segmented-embedding.ts';@@ -61,14 +63,11 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraconst calls: GeneratePerChunkSynopsisArgs[] = [];let segmentReads = 0;let refuse: ((args: GeneratePerChunkSynopsisArgs) => boolean) | null = null;- let fail: ((args: GeneratePerChunkSynopsisArgs) => GeneratePerChunkSynopsisResult | null) | null = null;let onSynopsis: ((args: GeneratePerChunkSynopsisArgs) => Promise<void>) | null = null;const generateSynopsis = async (args: GeneratePerChunkSynopsisArgs): Promise<GeneratePerChunkSynopsisResult> => {calls.push(args);await onSynopsis?.(args);if (refuse?.(args)) return { kind: 'refusal', detail: 'fixture refusal' };- const failed = fail?.(args);- if (failed) return failed;return { kind: 'success', synopsis: `Synopsis of chunk ${args.chunkIndex}.` };};const counting = (engine: BrainEngine): BrainEngine => new Proxy(engine, {@@ -93,7 +92,10 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraconst synopsisRows = async (pageId: number) => opts.getBrain().engine.readSegmentDerivations(pageId, { kind: 'synopsis' });const nonCode = (rows: ChunkRow[]) => rows.filter(c => c.chunk_source !== 'fenced_code');/** The cap is set high enough for a whole 2.3 MB page at the upper-bound estimate (uncached prompts at list price). */- const roomyCap = () => opts.getBrain().engine.setConfig(PAGE_EMBED_CAP_KEY, '1000');+ const roomyCap = async () => {+ await opts.getBrain().engine.setConfig(PAGE_EMBED_CAP_KEY, '1000');+ await opts.getBrain().engine.setConfig(PAGE_DERIVATION_CAP_KEY, '1000');+ };test('append invalidation: a segmented page leaves the title tier, a rerun does no work, an append pays only for the windows it changed', async () => {const brain = opts.getBrain();@@ -181,8 +183,9 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraconst slug = 'notes/synopsis-capped';await brain.seed(slug, page(days(1_300_000).body));const { id } = await pageRow(slug);- await brain.engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, cap_usd, spent_usd) VALUES ($1, 1, 1)- ON CONFLICT (page_id) DO UPDATE SET cap_usd = 1, spent_usd = 1`, [id]);+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '1');+ await brain.engine.executeRaw(`INSERT INTO page_derivation_spend (page_id, family, spent_usd) VALUES ($1, 'synopsis', 1)+ ON CONFLICT (page_id, family) DO UPDATE SET spent_usd = 1`, [id]);const before = await pageRow(slug);reset();expect(await run(slug)).toEqual({ kind: 'skipped', reason: 'budget_limited' });@@ -190,7 +193,7 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraexpect(await pageRow(slug)).toEqual(before);expect((await chunks(slug)).some(c => c.vector !== null)).toBe(false);- await brain.engine.executeRaw('UPDATE page_embedding_budget SET cap_usd = 1000 WHERE page_id = $1', [id]);+ await roomyCap();reset();const all = await chunks(slug);expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: all.length });@@ -371,7 +374,7 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBra}const cappedSlug = 'notes/synopsis-doctor-capped';await brain.seed(cappedSlug, page(days(1_300_000).body + '\nDoctor cap fixture.\n'));- await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, '0.000001');+ await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');try {reset();expect(await run(cappedSlug)).toEqual({ kind: 'skipped', reason: 'budget_limited' });@@ -388,53 +391,68 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraexpect(check.status).not.toBe('warn');}, 300_000);- const ledger = async (pageId: number) => (await opts.getBrain().engine.executeRaw<{ spent: number | string; reserved: number | string }>(- 'SELECT spent_usd AS spent, reserved_usd AS reserved FROM page_embedding_budget WHERE page_id = $1', [pageId])).map(r => ({ spent: Number(r.spent), reserved: Number(r.reserved) }))[0]!;- const callUsd = (calls: readonly GeneratePerChunkSynopsisArgs[]) => calls.reduce((n, c) => n + estimateSynopsisCallUsd(c.model!, c.documentText, c.chunkText, c.maxTokens), 0);+ const ledger = async (pageId: number, table: 'page_derivation_spend' | 'page_embedding_budget') => (await opts.getBrain().engine.executeRaw<{ spent: number | string; reserved: number | string }>(+ `SELECT spent_usd AS spent, reserved_usd AS reserved FROM ${table} WHERE page_id = $1${table === 'page_derivation_spend' ? " AND family = 'synopsis'" : ''}`, [pageId]))+ .map(r => ({ spent: Number(r.spent), reserved: Number(r.reserved) }))[0] ?? null;+ /** The real synopsis call (generatePerChunkSynopsis) through the gateway's chat transport: usage on a priced model, a quarter token per input character and 20 output tokens. */+ const runPaid = (slug: string, answer: (o: ChatOpts) => ChatResult | Error, answered: ChatResult[]) => {+ __setChatTransportForTests(async (o: ChatOpts) => {+ const out = answer(o);+ if (out instanceof Error) throw out;+ answered.push(out);+ return out;+ });+ return reembedPageWithContextualRetrieval({ engine: opts.getBrain().engine, pageSlug: slug, sourceId: 'default', globalMode: 'per_chunk_synopsis', chunkConcurrency: 4 })+ .finally(() => __setChatTransportForTests(null));+ };+ const paidAnswer = (o: ChatOpts): ChatResult => {+ const chars = o.messages.reduce((n, m) => n + (typeof m.content === 'string' ? m.content.length : JSON.stringify(m.content).length), 0) + (o.system?.length ?? 0);+ return { text: 'A short synopsis of the chunk.', blocks: [], stopReason: 'end', model: DEFAULT_SYNOPSIS_MODEL, providerId: 'anthropic',+ usage: { input_tokens: Math.ceil(chars / 4), output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ };+ const answeredUsd = (answered: readonly ChatResult[]) => answered.reduce((n, a) => n + reservationCostUsd(a.model, 'chat', a.usage.input_tokens, a.usage.output_tokens)!, 0);- test('spend: a window whose synopsis fails books only the calls the provider may have billed (a rate-limited call is not), never its embedding', async () => {+ test('spend: a window whose synopsis is rate limited books the calls the provider answered and never the rejected one or an embedding; the embedding ledger is untouched', async () => {const brain = opts.getBrain();await roomyCap();const slug = 'notes/synopsis-spend-synopsis-failure';await brain.seed(slug, page(days(1_300_000).body + '\nSpend fixture one.\n'));const { id } = await pageRow(slug);- let limited: GeneratePerChunkSynopsisArgs | null = null;- fail = args => { if (limited) return null; limited = args; return { kind: 'rate_limit', detail: 'fixture rate limit' }; };+ const answered: ChatResult[] = [];+ let rejected = 0;reset();- try {- expect(await run(slug)).toMatchObject({ kind: 'transient_error', cause: 'rate_limit' });- } finally {- fail = null;- }- expect(calls.length).toBeGreaterThan(0);+ const result = await runPaid(slug, o => rejected++ === 0 ? Object.assign(new Error('fixture rate limit'), { status: 429 }) : paidAnswer(o), answered);+ expect(result).toMatchObject({ kind: 'transient_error', cause: 'rate_limit' });expect(brain.embedded.length).toBe(0);- const billed = calls.filter(c => c !== limited);- const { spent, reserved } = await ledger(id);- expect(reserved).toBeCloseTo(0, 12);- expect(spent).toBeCloseTo(callUsd(billed), 12);+ const spend = await ledger(id, 'page_derivation_spend');+ expect(spend!.reserved).toBeCloseTo(0, 12);+ expect(spend!.spent).toBeCloseTo(answeredUsd(answered), 12);+ expect(await ledger(id, 'page_embedding_budget')).toBeNull();}, 300_000);- test('spend: a window whose embedding fails books its synopsis calls and not the embedding', async () => {+ test('spend: a window whose embedding fails books its answered synopsis calls and not the embedding', async () => {const brain = opts.getBrain();await roomyCap();const slug = 'notes/synopsis-spend-embed-failure';await brain.seed(slug, page(days(1_300_000).body + '\nSpend fixture two.\n'));const { id } = await pageRow(slug);const dims = (await embeddingWriteTarget(brain.engine)).column.dimensions;+ const answered: ChatResult[] = [];__setEmbedTransportForTests((async () => { throw new Error('fixture embedding outage'); }) as never);reset();try {- expect(await run(slug)).toMatchObject({ kind: 'transient_error' });+ expect(await runPaid(slug, paidAnswer, answered)).toMatchObject({ kind: 'transient_error' });} finally {__setEmbedTransportForTests((async ({ values }: { values: string[] }) => {brain.embedded.push(...values);return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };}) as never);}- expect(calls.length).toBeGreaterThan(0);- const { spent, reserved } = await ledger(id);- expect(reserved).toBeCloseTo(0, 12);- expect(spent).toBeCloseTo(callUsd(calls), 12);+ expect(answered.length).toBeGreaterThan(0);+ const spend = await ledger(id, 'page_derivation_spend');+ expect(spend!.reserved).toBeCloseTo(0, 12);+ expect(spend!.spent).toBeCloseTo(answeredUsd(answered), 12);+ expect(await ledger(id, 'page_embedding_budget')).toBeNull();}, 300_000);test('an inline page keeps the synopsisBodyHash input', async () => {diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.tsindex aa8039bf41..8b59558ff2 100644--- a/test/page-spend-reservation.test.ts+++ b/test/page-spend-reservation.test.ts@@ -8,7 +8,7 @@* 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+ * reservation for an unpriced model and nothing when the provider was never called or rejected the attempt unanswered; 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.@@ -243,6 +243,25 @@ describe('per-page spend ledgers', () => {}});+ test('meterPaidCall books nothing for an attempt the provider rejected before answering (a rate limit), and the answered attempts beside it', async () => {+ for (const { name, engine } of engines) {+ const page = await segmentedPage(engine);+ const ask = () => chat({ model: HAIKU, messages: [{ role: 'user', content: 'window' }], maxTokens: 500 });+ let rejected = 0;+ __setChatTransportForTests(async () => {+ if (rejected++ === 0) throw Object.assign(new Error('fixture rate limit'), { status: 429 });+ return answer(1000, 200);+ });+ const out = await meterPaidCall(engine, page, `synopsis:${HAIKU}`, 0.2, async () => { await ask().catch(() => null); await ask(); return 'done'; });+ expect({ out, ledger: await familyLedger(engine, page.id, 'synopsis') }, name)+ .toEqual({ out: { value: 'done' }, ledger: { spent: expect.closeTo(reservationCostUsd(HAIKU, 'chat', 1000, 200)!, 12), reserved: 0 } });+ __setChatTransportForTests(async () => { throw Object.assign(new Error('fixture rate limit'), { status: 429 }); });+ await meterPaidCall(engine, page, `atoms:${HAIKU}`, 0.2, () => ask().catch(() => null));+ expect(await familyLedger(engine, page.id, 'atoms'), name).toEqual({ spent: 0, 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 } }));