fix(pricing): version the pricing cache and drop codex-credits' dead reasoning param

The pricing cache written to disk had no schema version, so a cache written
by a pre-#1078 binary lacked cacheWriteCostIsExplicit on every entry. Reading
it back resolved the missing key to undefined (falsy), silently reintroducing
the surcharge-fabrication bug #1078 killed for up to CACHE_TTL_MS after an
upgrade. loadCachedPricing now rejects any cache whose version doesn't match
the current schema instead of reading it verbatim.

codexCredits() still accepted an optional reasoningTokens param that added it
to output - the exact double-count #1078 removed from every real caller. The
only caller never passed it; deleted it so it can't be reintroduced by
accident.

parser.ts's activeGeneratedTokens fallback went through billableOutputTokens
in #1078, but codex is the only caller of activeDurationMs/activeGeneratedTokens
and always sets both together, so the fallback branch is unreachable for it.
Reverted to reduce diff noise.
This commit is contained in:
iamtoruk 2026-08-21 12:48:55 -07:00
parent 91ddf58d15
commit 7876c8e9d7
5 changed files with 50 additions and 11 deletions

View file

@ -36,9 +36,9 @@ export type CodexCreditTokens = {
inputTokens: number
/// Cache-read (cached input) tokens, billed at the cheaper cached rate.
cachedReadTokens: number
/// Billable output tokens: reasoning is already included (billableOutputTokens
/// in models.ts), so callers must not add it on top here.
outputTokens: number
/// Reasoning tokens are billed as output, matching CodeBurn's cost model.
reasoningTokens?: number
}
/// Credits consumed for one Codex usage record. Returns null when the model has
@ -48,10 +48,9 @@ export function codexCredits(model: string, tokens: CodexCreditTokens): number |
if (!rate) return null
const safe = (n: number) => (Number.isFinite(n) && n > 0 ? n : 0)
const PER_MILLION = 1_000_000
const output = safe(tokens.outputTokens) + safe(tokens.reasoningTokens ?? 0)
return (
(safe(tokens.inputTokens) / PER_MILLION) * rate.input +
(safe(tokens.cachedReadTokens) / PER_MILLION) * rate.cachedInput +
(output / PER_MILLION) * rate.output
(safe(tokens.outputTokens) / PER_MILLION) * rate.output
)
}

View file

@ -59,6 +59,11 @@ type SnapshotEntry = [number, number, number | null, number | null, (number | nu
const LITELLM_URL = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json'
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
// Bump whenever a ModelCosts field changes pricing behavior (cacheWriteCostIsExplicit,
// added in #1075/#1078). A cache written under an older/missing version is treated as a
// miss instead of read verbatim, so a stale on-disk file can't reintroduce a killed bug
// for up to CACHE_TTL_MS after an upgrade.
const CACHE_SCHEMA_VERSION = 2
const WEB_SEARCH_COST = 0.01
const ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE = 1.6
@ -223,6 +228,7 @@ async function fetchAndCachePricing(): Promise<Map<string, ModelCosts>> {
await mkdir(getCodeburnCacheDir(), { recursive: true })
await writeFile(getCachePath(), JSON.stringify({
version: CACHE_SCHEMA_VERSION,
timestamp: Date.now(),
data: Object.fromEntries(pricing),
}))
@ -233,7 +239,8 @@ async function fetchAndCachePricing(): Promise<Map<string, ModelCosts>> {
async function loadCachedPricing(): Promise<Map<string, ModelCosts> | null> {
try {
const raw = await readFile(getCachePath(), 'utf-8')
const cached = JSON.parse(raw) as { timestamp: number; data: Record<string, ModelCosts> }
const cached = JSON.parse(raw) as { version?: number; timestamp: number; data: Record<string, ModelCosts> }
if (cached.version !== CACHE_SCHEMA_VERSION) return null
if (Date.now() - cached.timestamp > CACHE_TTL_MS) return null
return new Map(Object.entries(cached.data))
} catch {

View file

@ -1768,7 +1768,7 @@ function buildSessionSummary(
modelBreakdown[modelKey].tokens.reasoningTokens += call.usage.reasoningTokens
if (call.activeDurationMs !== undefined) {
modelBreakdown[modelKey].activeDurationMs = (modelBreakdown[modelKey].activeDurationMs ?? 0) + call.activeDurationMs
modelBreakdown[modelKey].activeGeneratedTokens = (modelBreakdown[modelKey].activeGeneratedTokens ?? 0) + (call.activeGeneratedTokens ?? billableOutputTokens(call.provider, call.usage.outputTokens, call.usage.reasoningTokens))
modelBreakdown[modelKey].activeGeneratedTokens = (modelBreakdown[modelKey].activeGeneratedTokens ?? 0) + (call.activeGeneratedTokens ?? call.usage.outputTokens + call.usage.reasoningTokens)
modelBreakdown[modelKey].toolWaitMs = (modelBreakdown[modelKey].toolWaitMs ?? 0) + (call.toolWaitMs ?? 0)
}

View file

@ -32,11 +32,6 @@ describe('codexCredits', () => {
expect(codexCredits('gpt-5.5', { inputTokens: 0, cachedReadTokens: 1_000_000, outputTokens: 0 })).toBe(12.5)
})
it('folds reasoning tokens into the output rate', () => {
// 500k output + 500k reasoning = 1M output-billed => 750 credits.
expect(codexCredits('gpt-5.5', { inputTokens: 0, cachedReadTokens: 0, outputTokens: 500_000, reasoningTokens: 500_000 })).toBe(750)
})
it('sums a mixed record (gpt-5.4)', () => {
// 2M input (125) + 1M cached (6.25) + 0.5M output (187.5) = 318.75
const credits = codexCredits('gpt-5.4', { inputTokens: 2_000_000, cachedReadTokens: 1_000_000, outputTokens: 500_000 })

View file

@ -753,6 +753,7 @@ describe('DeepSeek v4 models resolve to pricing', () => {
process.env['CODEBURN_CACHE_DIR'] = cacheRoot
await mkdir(cacheRoot, { recursive: true })
await writeFile(join(cacheRoot, 'litellm-pricing.json'), JSON.stringify({
version: 2, // must match models.ts's CACHE_SCHEMA_VERSION or the cache is treated as a miss
timestamp: Date.now(),
data: {
'gpt-4o-mini': {
@ -778,6 +779,42 @@ describe('DeepSeek v4 models resolve to pricing', () => {
})
})
describe('pricing cache schema version (#1075/#1078 follow-up)', () => {
it('discards a cache written by a pre-#1078 binary instead of reading its missing cacheWriteCostIsExplicit as false', async () => {
const cacheRoot = await mkdtemp(join(tmpdir(), 'codeburn-pricing-cache-'))
try {
process.env['CODEBURN_CACHE_DIR'] = cacheRoot
await mkdir(cacheRoot, { recursive: true })
// Shape of a cache file written before #1078 added `version` and
// `cacheWriteCostIsExplicit`: no version field, and entries missing the
// key despite carrying a real (non-default) cache-write rate.
await writeFile(join(cacheRoot, 'litellm-pricing.json'), JSON.stringify({
timestamp: Date.now(),
data: {
'gpt-5.6': {
inputCostPerToken: 5e-6,
outputCostPerToken: 3e-5,
cacheWriteCostPerToken: 6.25e-6,
cacheReadCostPerToken: 5e-7,
webSearchCostPerRequest: 0.01,
fastMultiplier: 1,
},
},
}), 'utf-8')
await loadPricing()
// Pre-fix, loadCachedPricing had no version check: it would read this
// cache verbatim, and gpt-5.6's missing key would resolve to undefined
// (falsy) here instead of the true its LiteLLM entry actually carries.
expect(getModelCosts('gpt-5.6')!.cacheWriteCostIsExplicit).toBe(true)
} finally {
await rm(cacheRoot, { recursive: true, force: true })
await loadPricing()
}
})
})
describe('provider pricing suffix variants', () => {
const cases: Array<[string, string]> = [
['GLM-4.7-TEE', 'glm-4.7'],
@ -915,6 +952,7 @@ describe('findUnpricedModels', () => {
try {
process.env['CODEBURN_CACHE_DIR'] = cacheRoot
await writeFile(join(cacheRoot, 'litellm-pricing.json'), JSON.stringify({
version: 2, // must match models.ts's CACHE_SCHEMA_VERSION or the cache is treated as a miss
timestamp: Date.now(),
data: {
'zz-zero-stub-model': {