codeburn/src/audit-report.ts
ozymandiashh 700e4d1a27
fix(pricing): carry long-context tier rates through bundling, applied where billing evidence exists (#1478)
* fix(pricing): carry long-context tier rates through bundling and price them where billing evidence exists

LiteLLM publishes *_above_<n>k_tokens rates for 418 models - OpenAI's
gpt-5.4/5.5/5.6 family above 272k, Anthropic above 200k, and 128k/256k/
512k tiers elsewhere - but the bundler flattened every entry to the
fixed five-slot tuple and calculateCost had no threshold dimension, so
a request past its threshold priced at the base rate forever (#1076).

The tuple gains an optional sixth slot {threshold, input, output,
cacheWrite, cacheRead}, the threshold parsed from the key suffix
because LiteLLM ships no numeric field (272k means 272,000; #1075
verified assuming 128k fabricates +64% spend). Old bundles parse
unchanged; CACHE_SCHEMA_VERSION moves to 5 (4 is taken on main by the
implicit cache-write billing) so a stale on-disk live-pricing cache
cannot reintroduce the old behavior; the live-fetch parser picks the
same tier up; service-tier _priority/_flex variants and the 1-hour
cache-write combination are not context thresholds and stay out.

A tier applies when the request's prompt tokens (input + cached input,
the existing grok-4.6 definition) reach the threshold, each published
rate replacing its base and omitted slots keeping the base.
Application is gated on billing evidence via TIERED_PRICING_PROVIDERS:
codex today, where the maintainer's corpus measurement shows the
surcharge passing through; a real Copilot session on gpt-5.6-terra
with ~6M-token prompts billed at the BASE rate, so Copilot keeps base
pricing until such evidence exists - applying it there would fabricate
spend, the exact class #1075 warned about. The audit report recomputes
through the same tier swap so recomputedTotalUSD keeps tracking
attributedCostUSD.

* fix(pricing): read tier rates only from the chosen threshold; e2e codex tier test

Repair pass from review: both tierOf implementations now collect rates
per threshold and read only from the largest one, so a hypothetical
two-tier entry can never mix the smaller tier's rates under the bigger
threshold; the bundler validates tier values exactly like the live
parser (finite, non-negative). A codex end-to-end test drives a real
rollout past gpt-5.5's 272k prompt threshold and asserts the tiered
arithmetic explicitly (a typo'd provider string in codex.ts would
leave the call at base rates and fail it), alongside the no-provider
base-rate control that keeps the real Copilot billing pin intact.
Comment fixes: the priceOverride wording, the grok pin's actual
resolution branch, and the threading note on TIERED_PRICING_PROVIDERS
for whoever adds the next provider.

* fix(pricing): recompute the audit tier per call and re-derive warm daily caches

Both review blockers:

- audit-report no longer feeds a bucket's SUMMED tokens into the
  per-call 272k threshold (a \,979 phantom gap on the reviewer's
  corpus, any tiered codex model clearing the threshold on the sum
  alone). The recompute accumulates per call, through the same tier
  swap calculateCost applies, with each call's own prompt total; a new
  fixture mixes one 300k call with 200 small ones whose sum blows past
  the threshold and pins that only the big call tiers. Web search
  stays on the base rates - it never participates in a tier.
- DAILY_CACHE_VERSION 33 -> 34 with MIN_SUPPORTED_VERSION raised to
  match, the cfdaa685 convention: a 33 file written under tierless
  pricing is below the floor, is not adopted as the finalized base,
  and its days re-derive off the warm session cache (\ of codex
  spend on the reviewer's corpus lives only in the daily cache). The
  migration tests pin the new floor contract: no version-diff repairs
  merge into a below-floor file, and the v30 adoption test tracks
  CURRENT.

Nits from review: the kimi precision tightening is reverted to (8, 5),
and the tieredCostsFor comment is rewrapped.

Measured on this machine's corpus, tier-only (branch vs the refresh
branch, same data): +\.43 lifetime codex - this corpus runs far
more sessions past 272k than the reviewer's 8-of-51,801 (+\.012964);
both numbers are real, the corpora differ.

* fix(pricing): preserve base alias selection when bundling context tiers

* fix(pricing): address the 28 Sep review - floor stays at 28, tier bills the implicit cache-write rate

Restore main's two carry-forward tests: with MIN_SUPPORTED_VERSION kept
at 28 (per the review's correction, warm caches re-derive identically
under 41/28, so raising the floor is unnecessary) a v33 file sits in
the adopt-with-repairs window again and main's expectations hold; the
tier's warm-cache coverage stays in daily-cache-version-rederivation.

The tier-omits-slot test bills an implicit cache-write at the input
rate of the costs object in effect (#1544), so the tiered expectation
is 1_000 * cacheWriteCostPerToken('gpt-5.5', tieredCosts).

Note on the Codex estimate path: an estimated prompt can cross a
long-context threshold and tier itself; measured corpora hold no
estimated calls that cross.

* fix(pricing): pin claude-opus-4 primary and keep carried fallback rows hygienic in the refreshed snapshot

The requested regeneration surfaced two upstream moves beside the tier
work. LiteLLM dropped `claude-opus-4`; a refresh carries dropped ids
into the fallback tier, but the Cursor-style alias `claude-4-opus`
resolves against primary rows, so the bare id fell to the snowflake
gateway row and under-priced by 3x. Pinned at Anthropic's list price
in MANUAL_ENTRIES so it stays primary. LiteLLM also repriced
grok-4.6's base input 2e-6 -> 1.25e-6 (tier rates unchanged); the
below-threshold literal follows. Both changes reproduce identically
with main's unchanged bundler on the same live responses.

Today's drops also exposed a gap in the #1483 carry-forward: primary
files legitimately hold @pin, date-suffixed and free-on-both rows, and
carrying those verbatim imports exactly what
tests/pricing-fallback-data.test.ts keeps out of the fallback file
(main's own next refresh fails those tests today). The carry now skips
@pin/date-suffixed keys (no query can arrive in those forms) and
free-on-both rows (an unpriced model falls to expected-free handling);
vendor-prefixed keys stay carriable since queries match them verbatim.

---------

Co-authored-by: Resham Joshi <65915470+iamtoruk@users.noreply.github.com>
2026-09-28 19:10:39 +02:00

253 lines
10 KiB
TypeScript

import { behavioralCallWeight } from './behavioral-weight.js'
import { billableOutputTokens, cacheWriteCostPerToken, fallbackRawModelDisplayName, getModelCosts, getShortModelName, sanitizeModelForDisplay, tieredCostsFor, type ModelCosts } from './models.js'
import { getProvider } from './providers/index.js'
import { formatCost, formatTokens } from './format.js'
import { renderTable, type TableColumn } from './text-table.js'
import type { ProjectSummary } from './types.js'
// One (provider, model) bucket, exposing both the raw token fields as recorded
// by the provider/transcript and the normalized totals codeburn actually
// prices, so a mismatch between the two is visible in one place.
export type AuditRow = {
provider: string
providerDisplayName: string
model: string
modelDisplayName: string
calls: number
// Summed straight from each call's usage, untouched.
raw: {
inputTokens: number
outputTokens: number
reasoningTokens: number
cacheCreationInputTokens: number
cacheReadInputTokens: number // Anthropic vocab
cachedInputTokens: number // OpenAI vocab
webSearchRequests: number
}
// What the reports display: reasoning folds into output, and the two
// cache-read vocabularies collapse to their max (providers fill one or both).
displayed: {
inputTokens: number
outputTokens: number
cacheWriteTokens: number
cacheReadTokens: number
}
// Per-token rates used for pricing; null when the model has no pricing entry.
rates: ModelCosts | null
// Cost split by component (displayed tokens x rate), plus the recomputed
// total. recomputedTotalUSD should track attributedCostUSD; a gap points at
// fast-mode multipliers or the 1-hour cache rate that calculateCost applies.
cost: {
input: number
output: number
cacheWrite: number
cacheRead: number
webSearch: number
recomputedTotalUSD: number
}
// The cost codeburn actually attributed to these calls (sum of call.costUSD).
attributedCostUSD: number
}
export async function aggregateAudit(projects: ProjectSummary[]): Promise<AuditRow[]> {
type Bucket = {
provider: string
model: string
calls: number
attributedCostUSD: number
cacheReadDisplayed: number
raw: AuditRow['raw']
/** Per-call recomputed components, each priced with THAT call's tier swap —
* a (provider, model) bucket's summed tokens must never cross the
* per-call 272k threshold on their own (review: a $4,979 phantom gap). */
recomputed: { input: number, output: number, cacheWrite: number, cacheRead: number, webSearch: number }
/** Resolved rates for the bucket's model, fetched once per bucket. */
rates: ModelCosts | null
}
const buckets = new Map<string, Bucket>()
for (const project of projects) {
for (const session of project.sessions) {
for (const turn of session.turns) {
for (const call of turn.assistantCalls) {
const provider = call.provider || 'unknown'
const model = call.model || 'unknown'
const key = `${provider} ${model}`
let bucket = buckets.get(key)
if (!bucket) {
bucket = {
provider,
model,
calls: 0,
attributedCostUSD: 0,
cacheReadDisplayed: 0,
recomputed: { input: 0, output: 0, cacheWrite: 0, cacheRead: 0, webSearch: 0 },
rates: null,
raw: {
inputTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
cacheCreationInputTokens: 0,
cacheReadInputTokens: 0,
cachedInputTokens: 0,
webSearchRequests: 0,
},
}
bucket.rates = getModelCosts(bucket.model)
buckets.set(key, bucket)
}
const u = call.usage
bucket.raw.inputTokens += u.inputTokens
bucket.raw.outputTokens += u.outputTokens
bucket.raw.reasoningTokens += u.reasoningTokens
bucket.raw.cacheCreationInputTokens += u.cacheCreationInputTokens
bucket.raw.cacheReadInputTokens += u.cacheReadInputTokens
bucket.raw.cachedInputTokens += u.cachedInputTokens
bucket.raw.webSearchRequests += u.webSearchRequests
// Per-call max (then summed) mirrors how the reports collapse the two
// cache-read vocabularies, so the audit's displayed total matches.
const cacheReadForCall = Math.max(u.cacheReadInputTokens, u.cachedInputTokens)
bucket.cacheReadDisplayed += cacheReadForCall
bucket.attributedCostUSD += call.costUSD
// Recompute per call through the same tier swap calculateCost applies
// (prompt tokens = input + cached input of THIS call), so a
// long-context request shows the rates that priced it while a bucket
// of small calls never crosses the threshold on the sum. Fast-mode
// and the 1-hour cache-write rate remain visible gaps on purpose.
if (bucket.rates) {
const promptTokens = u.inputTokens + cacheReadForCall
const tiered = tieredCostsFor(bucket.model, bucket.rates, promptTokens, bucket.provider)
const outputForCall = billableOutputTokens(bucket.provider, u.outputTokens, u.reasoningTokens)
bucket.recomputed.input += u.inputTokens * tiered.inputCostPerToken
bucket.recomputed.output += outputForCall * tiered.outputCostPerToken
bucket.recomputed.cacheWrite += u.cacheCreationInputTokens * cacheWriteCostPerToken(bucket.model, tiered)
bucket.recomputed.cacheRead += cacheReadForCall * tiered.cacheReadCostPerToken
// Web search never participates in a tier; keep it on the base row.
bucket.recomputed.webSearch += u.webSearchRequests * bucket.rates.webSearchCostPerRequest
}
// Supplementary accounting calls keep their tokens and cost above but are not
// distinct requests, so they add no call weight (see behavioral-weight.ts).
bucket.calls += behavioralCallWeight(call)
}
}
}
}
const providerCache = new Map<string, { displayName: string; formatModel: (m: string) => string }>()
async function resolveProvider(name: string) {
const cached = providerCache.get(name)
if (cached) return cached
const p = await getProvider(name)
const entry = {
displayName: p?.displayName ?? name,
formatModel: p
? (m: string) => sanitizeModelForDisplay(fallbackRawModelDisplayName(p.modelDisplayName(m), m))
: (m: string) => sanitizeModelForDisplay(getShortModelName(m)),
}
providerCache.set(name, entry)
return entry
}
const rows: AuditRow[] = []
for (const bucket of buckets.values()) {
const meta = await resolveProvider(bucket.provider)
// Buckets are keyed by (provider, model), so this provider test covers every call in one.
// Copilot reasoning tokens are already INSIDE outputTokens (same rule as cachedCallToApiCall
// in parser.ts), so folding them in would display phantom output for its store rows/rollups.
const displayed = {
inputTokens: bucket.raw.inputTokens,
outputTokens: billableOutputTokens(bucket.provider, bucket.raw.outputTokens, bucket.raw.reasoningTokens),
cacheWriteTokens: bucket.raw.cacheCreationInputTokens,
cacheReadTokens: bucket.cacheReadDisplayed,
}
const cost = {
input: bucket.recomputed.input,
output: bucket.recomputed.output,
cacheWrite: bucket.recomputed.cacheWrite,
cacheRead: bucket.recomputed.cacheRead,
webSearch: bucket.recomputed.webSearch,
recomputedTotalUSD: bucket.recomputed.input + bucket.recomputed.output + bucket.recomputed.cacheWrite + bucket.recomputed.cacheRead + bucket.recomputed.webSearch,
}
const rates = bucket.rates
rows.push({
provider: bucket.provider,
providerDisplayName: meta.displayName,
model: bucket.model,
modelDisplayName: meta.formatModel(bucket.model),
calls: bucket.calls,
raw: bucket.raw,
displayed,
rates,
cost,
attributedCostUSD: bucket.attributedCostUSD,
})
}
rows.sort((a, b) => b.attributedCostUSD - a.attributedCostUSD)
return rows
}
export function renderAuditTable(rows: AuditRow[]): string {
const columns: TableColumn[] = [
{ header: 'Provider' },
{ header: 'Model' },
{ header: 'Calls', right: true },
{ header: 'Input', right: true },
{ header: 'Output', right: true },
{ header: 'Reason', right: true },
{ header: 'Cache wr', right: true },
{ header: 'Cache rd', right: true },
{ header: 'Cost', right: true },
]
const body = rows.map((r) => [
r.providerDisplayName,
r.modelDisplayName,
r.calls.toLocaleString(),
formatTokens(r.raw.inputTokens),
formatTokens(r.raw.outputTokens),
formatTokens(r.raw.reasoningTokens),
formatTokens(r.raw.cacheCreationInputTokens),
formatTokens(r.displayed.cacheReadTokens),
formatCost(r.attributedCostUSD),
])
const totals = rows.reduce(
(a, r) => ({
calls: a.calls + r.calls,
input: a.input + r.raw.inputTokens,
output: a.output + r.raw.outputTokens,
reason: a.reason + r.raw.reasoningTokens,
cacheWrite: a.cacheWrite + r.raw.cacheCreationInputTokens,
cacheRead: a.cacheRead + r.displayed.cacheReadTokens,
cost: a.cost + r.attributedCostUSD,
}),
{ calls: 0, input: 0, output: 0, reason: 0, cacheWrite: 0, cacheRead: 0, cost: 0 },
)
body.push([
'Total',
'',
totals.calls.toLocaleString(),
formatTokens(totals.input),
formatTokens(totals.output),
formatTokens(totals.reason),
formatTokens(totals.cacheWrite),
formatTokens(totals.cacheRead),
formatCost(totals.cost),
])
const table = renderTable(columns, body, { boldRows: new Set([body.length - 1]) })
const legend = [
'',
'Columns are the raw token fields each provider records. codeburn then normalizes for pricing:',
' - Reason folds into Output (priced output = output + reasoning), except copilot, whose reasoning is already inside its output',
' - Cache rd = max(Anthropic cacheReadInput, OpenAI cached), since providers fill one or both',
' - Cache wr is priced at 1.25x the input rate, Cache rd at 0.1x, when a model omits explicit cache rates',
'Use --format json for per-component cost, the rates applied, and both raw cache-read fields.',
].join('\n')
return table + '\n' + legend
}
export function renderAuditJson(rows: AuditRow[]): string {
return JSON.stringify(rows, null, 2)
}