返回 CodeWhale
pricing.rs
根目录 / crates / engine / src / pricing.rs
1 //! Cost estimation for API usage.
2 //!
3 //! Pricing is stored per million tokens. DeepSeek rows include their published
4 //! CNY rates; OpenRouter-curated rows are USD-only. Direct Xiaomi MiMo Token
5 //! Plan usage is credit/quota based and is intentionally left unknown until a
6 //! reliable balance endpoint exists.
7
8 #[cfg(test)]
9 use chrono::TimeZone;
10 use chrono::{DateTime, Utc};
11 use codewhale_config::pricing::{
12 Currency, LIVE_PRICING_MAX_AGE_SECS, LivePricingDefect, OfferingPricing, PricingProvenance,
13 PricingQuoteError, TokenClass, TokenUsage,
14 };
15
16 use codewhale_config::ProviderKind;
17 #[cfg(test)]
18 use codewhale_config::descriptors::defaults::DEFAULT_STEPFUN_MODEL;
19 use codewhale_config::descriptors::defaults::{
20 DEFAULT_STEPFUN_BASE_URL, DEFAULT_STEPFUN_PLAN_BASE_URL,
21 };
22 use codewhale_config::pricing::CostCurrency;
23 use codewhale_models::hand_pricing::{
24 CacheWritePolicy, ModelPricing, currency_offering_pricing, deepseek_flash_effective_from,
25 deepseek_is_peak, deepseek_time_aware_pricing, is_grok_tiered, pricing_for_model_at,
26 provider_owned_hand_pricing_at, provider_owned_hand_quote_rows, usd_only_pricing, usd_pricing,
27 };
28 #[cfg(test)]
29 use codewhale_models::hand_pricing::{CurrencyPricing, DEEPSEEK_CACHE_WRITE_IS_FREE};
30 #[cfg(any(test, feature = "test-support"))]
31 use codewhale_models::hand_pricing::{
32 GROK_4_6_LONG_CONTEXT_THRESHOLD, MINIMAX_M3_LONG_CONTEXT_THRESHOLD, grok_tiered_pricing,
33 is_minimax_m3, minimax_m3_standard_pricing,
34 };
35 use codewhale_models::{Usage, has_date_snapshot_suffix};
36 use codewhale_runtime::config::DEEPSEEK_ALIAS_RETIREMENT_UTC;
37
38 /// Cost estimate in displayable currencies.
39 #[derive(Debug, Clone, Copy, Default, PartialEq)]
40 pub struct CostEstimate {
41 pub usd: f64,
42 pub cny: f64,
43 }
44
45 impl CostEstimate {
46 pub fn usd_only(usd: f64) -> Self {
47 Self { usd, cny: 0.0 }
48 }
49
50 pub fn is_positive(self) -> bool {
51 self.is_finite_nonnegative() && (self.usd > 0.0 || self.cny > 0.0)
52 }
53
54 /// A cost is safe to persist/display only when both carried currencies are
55 /// finite and nonnegative.
56 #[must_use]
57 pub fn is_finite_nonnegative(self) -> bool {
58 self.usd.is_finite() && self.usd >= 0.0 && self.cny.is_finite() && self.cny >= 0.0
59 }
60
61 #[must_use]
62 pub fn sanitized(self) -> Self {
63 Self {
64 usd: if self.usd.is_finite() && self.usd >= 0.0 {
65 self.usd
66 } else {
67 0.0
68 },
69 cny: if self.cny.is_finite() && self.cny >= 0.0 {
70 self.cny
71 } else {
72 0.0
73 },
74 }
75 }
76
77 /// Add cost without ever producing NaN, infinity, or a negative total.
78 /// Individual pricing rows are validated earlier; the saturation protects
79 /// long-running accumulation from floating-point overflow.
80 #[must_use]
81 pub fn saturating_add(self, rhs: Self) -> Self {
82 fn component(left: f64, right: f64) -> f64 {
83 let sum = left + right;
84 if sum.is_finite() { sum } else { f64::MAX }
85 }
86 let left = self.sanitized();
87 let right = rhs.sanitized();
88 Self {
89 usd: component(left.usd, right.usd),
90 cny: component(left.cny, right.cny),
91 }
92 }
93
94 pub fn amount(self, currency: CostCurrency) -> f64 {
95 match currency {
96 CostCurrency::Usd => self.usd,
97 CostCurrency::Cny => self.cny,
98 }
99 }
100 }
101
102 // === Provider Account Balance ===
103
104 /// Response from DeepSeek `GET /user/balance`. Other prepaid providers are
105 /// mapped onto [`BalanceInfo`] at the fetch seam.
106 #[derive(Debug, Clone, Default, serde::Deserialize)]
107 pub struct BalanceResponse {
108 pub is_available: bool,
109 pub balance_infos: Vec<BalanceInfo>,
110 }
111
112 /// Per-currency remaining-credit entry shown by `/balance` and the status chip.
113 #[derive(Debug, Clone, Default, serde::Deserialize)]
114 pub struct BalanceInfo {
115 pub currency: String,
116 #[serde(default)]
117 pub total_balance: String,
118 #[serde(default)]
119 pub topped_up_balance: String,
120 #[serde(default)]
121 pub granted_balance: String,
122 }
123
124 impl BalanceInfo {
125 /// Compact ledger chip, e.g. `$12.50` or `¥123.45`.
126 #[must_use]
127 pub fn chip_label(&self) -> Option<String> {
128 let amount = self.total_balance.trim();
129 if amount.is_empty() {
130 return None;
131 }
132 Some(format_balance_amount(amount, &self.currency))
133 }
134
135 /// Full `/balance` report for one prepaid provider.
136 #[must_use]
137 pub fn report(&self, provider_name: &str) -> String {
138 let amount = self
139 .chip_label()
140 .unwrap_or_else(|| self.total_balance.trim().to_string());
141 let mut report = if amount.is_empty() {
142 format!("{provider_name} account balance is unknown")
143 } else {
144 format!("{provider_name} account balance: {amount}")
145 };
146 let topped = self.topped_up_balance.trim();
147 let granted = self.granted_balance.trim();
148 if !topped.is_empty() || !granted.is_empty() {
149 let mut parts = Vec::new();
150 if !topped.is_empty() {
151 parts.push(format!("topped up {topped}"));
152 }
153 if !granted.is_empty() {
154 parts.push(format!("granted {granted}"));
155 }
156 report.push_str(&format!(" ({})", parts.join(", ")));
157 }
158 report
159 }
160 }
161
162 fn format_balance_amount(amount: &str, currency: &str) -> String {
163 match currency.trim().to_ascii_uppercase().as_str() {
164 "CNY" | "RMB" | "¥" => format!("¥{amount}"),
165 "USD" | "US$" | "$" => format!("${amount}"),
166 "" => amount.to_string(),
167 other => format!("{amount} {other}"),
168 }
169 }
170
171 pub const STEPFUN_PAYG_BILLING_SURFACE: &str = "stepfun-payg";
172 pub const STEPFUN_PLAN_BILLING_SURFACE: &str = "stepfun-plan";
173 const LEGACY_STEPFUN_PLAN_BASE_URL: &str = "https://api.stepfun.com/step_plan/v1";
174
175 /// Z.ai's dedicated Coding endpoint — the GLM Coding Plan subscription route.
176 pub const ZAI_CODING_PLAN_BILLING_SURFACE: &str = "zai-coding-plan";
177 /// Z.ai's ordinary public per-token API.
178 pub const ZAI_PAYG_BILLING_SURFACE: &str = "zai-payg";
179 /// Moonshot's Kimi Code subscription endpoint.
180 pub const MOONSHOT_KIMI_CODE_BILLING_SURFACE: &str = "moonshot-kimi-code";
181 /// Moonshot's ordinary public per-token API.
182 pub const MOONSHOT_PAYG_BILLING_SURFACE: &str = "moonshot-payg";
183 /// MiniMax's prepaid Token Plan endpoint.
184 pub const MINIMAX_TOKEN_PLAN_BILLING_SURFACE: &str = "minimax-token-plan";
185 /// MiniMax's ordinary public per-token API.
186 pub const MINIMAX_PAYG_BILLING_SURFACE: &str = "minimax-payg";
187 /// Xiaomi MiMo's prepaid token-plan endpoint.
188 pub const XIAOMI_TOKEN_PLAN_BILLING_SURFACE: &str = "xiaomi-mimo-token-plan";
189 /// Xiaomi MiMo's ordinary public per-token API.
190 pub const XIAOMI_PAYG_BILLING_SURFACE: &str = "xiaomi-mimo-payg";
191 /// An OAuth/subscription-brokered endpoint (Codex, Claude OAuth, Grok OAuth,
192 /// OpenCode Go). Never per-token metered from CodeWhale's side.
193 pub const OAUTH_SUBSCRIPTION_BILLING_SURFACE: &str = "oauth-subscription";
194 /// A loopback / self-hosted endpoint with no provider bill at all.
195 pub const LOCAL_BILLING_SURFACE: &str = "local-no-bill";
196 /// A provider's own first-party public per-token API, on its documented host.
197 pub const FIRST_PARTY_PAYG_BILLING_SURFACE: &str = "first-party-payg";
198 /// An aggregator/reseller endpoint: metered, but priced by the aggregator's own
199 /// catalog rather than by the upstream model owner's published rates.
200 pub const AGGREGATOR_BILLING_SURFACE: &str = "aggregator-payg";
201 pub const MODELSTUDIO_TOKEN_PLAN_BILLING_SURFACE: &str = "modelstudio-token-plan";
202 pub const MODELSTUDIO_CODING_PLAN_BILLING_SURFACE: &str = "modelstudio-coding-plan";
203 pub const VOLCENGINE_CODING_PLAN_BILLING_SURFACE: &str = "volcengine-coding-plan";
204 /// CSDN 星图's Coding Plan subscription product (the `glm_for_coding` route).
205 pub const CSDN_CODING_PLAN_BILLING_SURFACE: &str = "csdn-coding-plan";
206 /// CSDN 星图's ordinary metered marketplace access on the same endpoint.
207 pub const CSDN_PAYG_BILLING_SURFACE: &str = "csdn-payg";
208 /// A reachable endpoint CodeWhale could not match to any known billing surface.
209 /// Distinct from "not classified yet": this is a positive statement that the
210 /// surface is unknown, and it fails closed everywhere it is consumed.
211 pub const UNCLASSIFIED_BILLING_SURFACE: &str = "unclassified";
212
213 /// How a classified billing surface meters money.
214 ///
215 /// This is the fact every cost surface actually needs: whether a dollar figure
216 /// is even the right unit for the route. `Unknown` is a real answer and is
217 /// treated as *possibly* metered — it is counted as missing spend rather than
218 /// excused as a subscription (#4318).
219 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
220 pub enum EndpointMetering {
221 /// Per-token money, priced against published rates.
222 Money,
223 /// An exactly-identified subscription or prepaid-quota endpoint. Money is
224 /// the wrong unit here, so these turns are excluded from money coverage.
225 ExactSubscription,
226 /// Local/self-hosted: there is no provider bill.
227 LocalNoBill,
228 /// Could not be established. Fails closed as possibly-money.
229 Unknown,
230 }
231
232 /// Classify a billing-surface id into its metering shape.
233 ///
234 /// Unrecognized ids — including ones written by a newer build — resolve to
235 /// [`EndpointMetering::Unknown`] rather than being guessed into a bucket.
236 #[must_use]
237 pub fn endpoint_metering_for_billing_surface(billing_surface: Option<&str>) -> EndpointMetering {
238 let Some(surface) = billing_surface.map(str::trim).filter(|s| !s.is_empty()) else {
239 return EndpointMetering::Unknown;
240 };
241 // Exact, case-insensitive matches only. A prefix/substring rule here would
242 // let an unrecognized future surface impersonate a known one.
243 for (known, metering) in [
244 (STEPFUN_PAYG_BILLING_SURFACE, EndpointMetering::Money),
245 (ZAI_PAYG_BILLING_SURFACE, EndpointMetering::Money),
246 (MOONSHOT_PAYG_BILLING_SURFACE, EndpointMetering::Money),
247 (MINIMAX_PAYG_BILLING_SURFACE, EndpointMetering::Money),
248 (XIAOMI_PAYG_BILLING_SURFACE, EndpointMetering::Money),
249 (CSDN_PAYG_BILLING_SURFACE, EndpointMetering::Money),
250 (FIRST_PARTY_PAYG_BILLING_SURFACE, EndpointMetering::Money),
251 (AGGREGATOR_BILLING_SURFACE, EndpointMetering::Money),
252 (
253 MODELSTUDIO_TOKEN_PLAN_BILLING_SURFACE,
254 EndpointMetering::ExactSubscription,
255 ),
256 (
257 MODELSTUDIO_CODING_PLAN_BILLING_SURFACE,
258 EndpointMetering::ExactSubscription,
259 ),
260 (
261 VOLCENGINE_CODING_PLAN_BILLING_SURFACE,
262 EndpointMetering::ExactSubscription,
263 ),
264 (
265 STEPFUN_PLAN_BILLING_SURFACE,
266 EndpointMetering::ExactSubscription,
267 ),
268 (
269 ZAI_CODING_PLAN_BILLING_SURFACE,
270 EndpointMetering::ExactSubscription,
271 ),
272 (
273 MOONSHOT_KIMI_CODE_BILLING_SURFACE,
274 EndpointMetering::ExactSubscription,
275 ),
276 (
277 MINIMAX_TOKEN_PLAN_BILLING_SURFACE,
278 EndpointMetering::ExactSubscription,
279 ),
280 (
281 XIAOMI_TOKEN_PLAN_BILLING_SURFACE,
282 EndpointMetering::ExactSubscription,
283 ),
284 (
285 CSDN_CODING_PLAN_BILLING_SURFACE,
286 EndpointMetering::ExactSubscription,
287 ),
288 (
289 OAUTH_SUBSCRIPTION_BILLING_SURFACE,
290 EndpointMetering::ExactSubscription,
291 ),
292 (LOCAL_BILLING_SURFACE, EndpointMetering::LocalNoBill),
293 (UNCLASSIFIED_BILLING_SURFACE, EndpointMetering::Unknown),
294 ] {
295 if surface.eq_ignore_ascii_case(known) {
296 return metering;
297 }
298 }
299 EndpointMetering::Unknown
300 }
301
302 /// A base URL reduced to the non-secret parts a billing classification may
303 /// depend on: scheme, host, normalized path. `None` when the URL carries
304 /// embedded credentials, a query, a fragment, a non-default port, or is not
305 /// HTTPS — any of which means CodeWhale cannot vouch for which surface it is.
306 struct EndpointShape {
307 host: String,
308 path: String,
309 }
310
311 fn endpoint_shape(base_url: &str) -> Option<EndpointShape> {
312 let parsed = reqwest::Url::parse(base_url.trim()).ok()?;
313 if parsed.scheme() != "https"
314 || !parsed.username().is_empty()
315 || parsed.password().is_some()
316 || parsed.query().is_some()
317 || parsed.fragment().is_some()
318 || parsed.port_or_known_default() != Some(443)
319 {
320 return None;
321 }
322 Some(EndpointShape {
323 host: parsed.host_str()?.to_ascii_lowercase(),
324 path: parsed.path().trim_end_matches('/').to_string(),
325 })
326 }
327
328 fn host_of(url: &str) -> Option<String> {
329 reqwest::Url::parse(url)
330 .ok()?
331 .host_str()
332 .map(str::to_ascii_lowercase)
333 }
334
335 /// Historical Codex backend receipts retain their original quota basis.
336 /// New Sign in with ChatGPT requests use the public API and additionally need
337 /// captured grant provenance; this endpoint check never proves that grant.
338 pub fn is_chatgpt_codex_backend(base_url: &str) -> bool {
339 let Some(shape) = endpoint_shape(base_url) else {
340 return false;
341 };
342 shape.host == "chatgpt.com"
343 && (shape.path == "/backend-api" || shape.path.starts_with("/backend-api/"))
344 }
345
346 /// The public API base documented for official ChatGPT plan inference.
347 /// The same endpoint accepts metered API keys: this shape alone is not a
348 /// subscription claim. [`crate::route_billing`] also requires a verified grant.
349 pub fn is_official_chatgpt_api(base_url: &str) -> bool {
350 endpoint_shape(base_url)
351 .is_some_and(|shape| shape.host == "api.openai.com" && shape.path == "/v1")
352 }
353
354 /// Reduce a concrete request endpoint to non-secret billing provenance.
355 ///
356 /// Every reachable endpoint now gets a positive classification, including
357 /// [`UNCLASSIFIED_BILLING_SURFACE`] for one CodeWhale cannot place. `None` is
358 /// reserved for "no endpoint was supplied", which is a different failure and is
359 /// also treated as unknown downstream. Nothing here consults credentials or
360 /// echoes a URL, so the result is safe to persist and log.
361 pub fn billing_surface_for_route(
362 provider: ProviderKind,
363 base_url: Option<&str>,
364 ) -> Option<&'static str> {
365 // Routes whose billing shape is a property of the provider itself, not of
366 // the endpoint spelling.
367 match provider {
368 ProviderKind::Ollama | ProviderKind::Sglang | ProviderKind::Vllm => {
369 return Some(LOCAL_BILLING_SURFACE);
370 }
371 // Ollama Cloud publishes plan/account terms, not a Codewhale-owned
372 // per-token rate. Hosted is not local/free, but it is also not proof
373 // of PAYG dollars: keep it in money coverage as unclassified until an
374 // authoritative billing surface is available.
375 ProviderKind::OllamaCloud => return Some(UNCLASSIFIED_BILLING_SURFACE),
376 ProviderKind::OpencodeGo => return Some(OAUTH_SUBSCRIPTION_BILLING_SURFACE),
377 // Preserve historical backend provenance, but public API plan access
378 // is credential-shaped. Without the captured official grant it stays
379 // unknown, including when no endpoint was supplied.
380 ProviderKind::OpenaiCodex => {
381 return Some(if base_url.is_some_and(is_chatgpt_codex_backend) {
382 OAUTH_SUBSCRIPTION_BILLING_SURFACE
383 } else {
384 UNCLASSIFIED_BILLING_SURFACE
385 });
386 }
387 // A named custom endpoint is never assumed to be metered; the billing
388 // presentation layer decides that from explicit config.
389 ProviderKind::Custom => return Some(UNCLASSIFIED_BILLING_SURFACE),
390 _ => {}
391 }
392
393 let base_url = base_url.map(str::trim).filter(|url| !url.is_empty())?;
394 let Some(shape) = endpoint_shape(base_url) else {
395 return Some(UNCLASSIFIED_BILLING_SURFACE);
396 };
397
398 let surface = match provider {
399 ProviderKind::Stepfun => stepfun_surface(&shape),
400 ProviderKind::Zai => zai_surface(&shape),
401 ProviderKind::Moonshot => moonshot_surface(&shape),
402 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic => minimax_surface(&shape),
403 ProviderKind::Csdn => csdn_surface(&shape),
404 ProviderKind::XiaomiMimo => xiaomi_surface(&shape),
405 ProviderKind::ModelstudioTokenPlan
406 | ProviderKind::ModelstudioTokenPlanAnthropic
407 | ProviderKind::ModelstudioCodingPlan
408 | ProviderKind::ModelstudioCodingPlanAnthropic => modelstudio_surface(&shape),
409 ProviderKind::Volcengine => volcengine_surface(&shape),
410 ProviderKind::Openrouter
411 | ProviderKind::NvidiaNim
412 | ProviderKind::OpencodeZen
413 | ProviderKind::Orcarouter => {
414 is_official_default_endpoint(provider, &shape).then_some(AGGREGATOR_BILLING_SURFACE)
415 }
416 _ => is_official_default_endpoint(provider, &shape)
417 .then_some(FIRST_PARTY_PAYG_BILLING_SURFACE),
418 };
419 Some(surface.unwrap_or(UNCLASSIFIED_BILLING_SURFACE))
420 }
421
422 // Token Plan and Coding Plan keys/endpoints are isolated from PAYG.
423 // https://www.alibabacloud.com/help/en/model-studio/token-plan-quick-start
424 // https://www.alibabacloud.com/help/en/model-studio/coding-plan-faq
425 fn modelstudio_surface(shape: &EndpointShape) -> Option<&'static str> {
426 match (shape.host.as_str(), shape.path.as_str()) {
427 (
428 "token-plan.ap-southeast-1.maas.aliyuncs.com",
429 "/compatible-mode/v1" | "/apps/anthropic" | "/apps/anthropic/v1",
430 ) => Some(MODELSTUDIO_TOKEN_PLAN_BILLING_SURFACE),
431 (
432 "coding-intl.dashscope.aliyuncs.com" | "coding.dashscope.aliyuncs.com",
433 "/v1" | "/apps/anthropic" | "/apps/anthropic/v1",
434 ) => Some(MODELSTUDIO_CODING_PLAN_BILLING_SURFACE),
435 ("dashscope-intl.aliyuncs.com" | "dashscope.aliyuncs.com", "/compatible-mode/v1") => {
436 Some(FIRST_PARTY_PAYG_BILLING_SURFACE)
437 }
438 _ => None,
439 }
440 }
441
442 // The Coding Plan gateway consumes plan quota; /api/v3 is billed separately.
443 // https://www.volcengine.com/docs/82379/1925114
444 fn volcengine_surface(shape: &EndpointShape) -> Option<&'static str> {
445 match (shape.host.as_str(), shape.path.as_str()) {
446 ("ark.cn-beijing.volces.com", "/api/coding" | "/api/coding/v3") => {
447 Some(VOLCENGINE_CODING_PLAN_BILLING_SURFACE)
448 }
449 ("ark.cn-beijing.volces.com", "/api/v3") => Some(FIRST_PARTY_PAYG_BILLING_SURFACE),
450 _ => None,
451 }
452 }
453
454 fn stepfun_surface(shape: &EndpointShape) -> Option<&'static str> {
455 if host_of(DEFAULT_STEPFUN_BASE_URL).is_some_and(|official| shape.host == official)
456 && matches!(shape.path.as_str(), "" | "/v1")
457 {
458 return Some(STEPFUN_PAYG_BILLING_SURFACE);
459 }
460 let plan_host = [DEFAULT_STEPFUN_PLAN_BASE_URL, LEGACY_STEPFUN_PLAN_BASE_URL]
461 .iter()
462 .filter_map(|url| host_of(url))
463 .any(|plan| plan == shape.host);
464 if plan_host && matches!(shape.path.as_str(), "/step_plan" | "/step_plan/v1") {
465 return Some(STEPFUN_PLAN_BILLING_SURFACE);
466 }
467 None
468 }
469
470 fn zai_surface(shape: &EndpointShape) -> Option<&'static str> {
471 // The Coding Plan contract is the exact shipped Z.ai endpoint. Do not let
472 // arbitrary future `/api/coding/*` paths, or the separate BigModel host,
473 // inherit a subscription classification.
474 if shape.host == "api.z.ai" && shape.path == "/api/coding/paas/v4" {
475 Some(ZAI_CODING_PLAN_BILLING_SURFACE)
476 } else if matches!(shape.host.as_str(), "api.z.ai" | "open.bigmodel.cn")
477 && matches!(
478 shape.path.as_str(),
479 "/api/paas/v4" | "/api/anthropic" | "/v1" | ""
480 )
481 {
482 Some(ZAI_PAYG_BILLING_SURFACE)
483 } else {
484 None
485 }
486 }
487
488 fn moonshot_surface(shape: &EndpointShape) -> Option<&'static str> {
489 // Kimi Code is a distinct membership product on api.kimi.com. Accept the
490 // exact shipped endpoint as well as its slash-normalized parent; do not
491 // infer a plan from a model id or from an arbitrary host carrying a
492 // `/coding` path.
493 if shape.host == "api.kimi.com" && matches!(shape.path.as_str(), "/coding" | "/coding/v1") {
494 Some(MOONSHOT_KIMI_CODE_BILLING_SURFACE)
495 } else if matches!(shape.host.as_str(), "api.moonshot.ai" | "api.moonshot.cn")
496 && matches!(shape.path.as_str(), "" | "/v1" | "/anthropic")
497 {
498 Some(MOONSHOT_PAYG_BILLING_SURFACE)
499 } else {
500 None
501 }
502 }
503
504 fn minimax_surface(shape: &EndpointShape) -> Option<&'static str> {
505 // MiniMax API keys and subscription-plan keys use the same normal
506 // endpoints. The URL therefore proves neither PAYG nor plan billing; only
507 // an explicit saved mode may produce a concrete MiniMax surface.
508 let _is_supported_endpoint = matches!(
509 shape.host.as_str(),
510 "api.minimax.io" | "api.minimaxi.com" | "api.minimax.chat"
511 ) && matches!(shape.path.as_str(), "" | "/v1" | "/anthropic");
512 None
513 }
514
515 fn csdn_surface(shape: &EndpointShape) -> Option<&'static str> {
516 // Coding Plan keys and general marketplace keys share the one
517 // ai.csdn.net/api/model/v1 endpoint, so the URL proves neither product;
518 // only the captured credential product can produce a concrete surface.
519 let _is_supported_endpoint = shape.host == "ai.csdn.net"
520 && matches!(shape.path.as_str(), "/api/model" | "/api/model/v1");
521 None
522 }
523
524 fn xiaomi_surface(shape: &EndpointShape) -> Option<&'static str> {
525 if matches!(
526 shape.host.as_str(),
527 "token-plan-cn.xiaomimimo.com"
528 | "token-plan-sgp.xiaomimimo.com"
529 | "token-plan-ams.xiaomimimo.com"
530 ) && shape.path == "/v1"
531 {
532 return Some(XIAOMI_TOKEN_PLAN_BILLING_SURFACE);
533 }
534 if shape.host == "api.xiaomimimo.com" && shape.path == "/v1" {
535 return Some(XIAOMI_PAYG_BILLING_SURFACE);
536 }
537 None
538 }
539
540 /// Exact default endpoint match for built-in providers whose billing surface
541 /// has no provider-specific split above.
542 ///
543 /// A provider enum is not proof that a configured URL is that provider's own
544 /// billing surface. This allowlist keeps `https://proxy.example/v1` from
545 /// inheriting OpenAI/Anthropic/DeepSeek/OpenRouter prices merely because the
546 /// selected protocol/provider name is familiar.
547 fn is_official_default_endpoint(provider: ProviderKind, shape: &EndpointShape) -> bool {
548 let Some(default) =
549 endpoint_shape(codewhale_config::descriptors::compatibility_for_kind(provider).base_url)
550 else {
551 return false;
552 };
553 if shape.host != default.host {
554 return false;
555 }
556 if shape.path == default.path {
557 return true;
558 }
559 match provider {
560 ProviderKind::Deepseek => {
561 matches!(shape.path.as_str(), "" | "/v1" | "/beta")
562 }
563 ProviderKind::DeepseekAnthropic => {
564 matches!(shape.path.as_str(), "/anthropic" | "/anthropic/v1")
565 }
566 ProviderKind::Openai => matches!(shape.path.as_str(), "" | "/v1"),
567 ProviderKind::Anthropic => matches!(shape.path.as_str(), "" | "/v1"),
568 _ => false,
569 }
570 }
571
572 // Official PAYG rates; Step Plan consumes subscription quota instead.
573 // https://platform.stepfun.ai/docs/en/guides/pricing/details (2026-09-19).
574 fn stepfun_payg_pricing(model: &str) -> Option<ModelPricing> {
575 match model.trim().to_ascii_lowercase().as_str() {
576 "step-5-preview" => Some(usd_pricing(
577 0.05,
578 1.00,
579 2.70,
580 CacheWritePolicy::DocumentedAsInputRate(
581 "https://platform.stepfun.ai/docs/en/guides/pricing/details",
582 ),
583 )),
584 "step-3.7-flash" => Some(usd_only_pricing(0.04, 0.20, 1.15)),
585 "step-3.5-flash" | "step-3.5-flash-2603" => Some(usd_only_pricing(0.02, 0.10, 0.30)),
586 _ => None,
587 }
588 }
589
590 pub(crate) fn hand_pricing_overrides_catalog(provider: ProviderKind, model: &str) -> bool {
591 matches!(
592 provider,
593 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
594 ) || (matches!(
595 provider,
596 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
597 ) && model.eq_ignore_ascii_case("minimax-m3"))
598 || (provider == ProviderKind::Xai && is_grok_tiered(model))
599 || (provider == ProviderKind::Anthropic && model.eq_ignore_ascii_case("claude-sonnet-5"))
600 }
601
602 pub(crate) fn dispatch_hand_quote_rows(
603 provider: ProviderKind,
604 model: &str,
605 base_url: &str,
606 recorded_at: DateTime<Utc>,
607 ) -> Option<(OfferingPricing, Option<OfferingPricing>)> {
608 if provider == ProviderKind::Stepfun {
609 let pricing = pricing_for_billing_surface(
610 provider,
611 model,
612 billing_surface_for_route(provider, Some(base_url)),
613 )?;
614 let mut primary = currency_offering_pricing(pricing.usd, Currency::Usd);
615 primary.provider = provider.as_str().into();
616 primary.wire_model_id = model.into();
617 return Some((primary, None));
618 }
619 let normalized = model.trim();
620 let model_lower = normalized.to_ascii_lowercase();
621 let direct_deepseek = matches!(
622 provider,
623 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
624 );
625 let lookup = if direct_deepseek
626 && matches!(model_lower.as_str(), "deepseek-chat" | "deepseek-reasoner")
627 {
628 let retirement = DateTime::parse_from_rfc3339(DEEPSEEK_ALIAS_RETIREMENT_UTC)
629 .ok()?
630 .with_timezone(&Utc);
631 if recorded_at >= retirement {
632 return None;
633 }
634 "deepseek-v4-flash"
635 } else if direct_deepseek
636 && matches!(
637 model_lower.as_str(),
638 "flash-vision" | "deepseek-v4flashvisionexp"
639 )
640 && recorded_at < deepseek_flash_effective_from()
641 {
642 "deepseek-v4-flash-vision-exp"
643 } else {
644 normalized
645 };
646 provider_owned_hand_quote_rows(provider, lookup, recorded_at)
647 }
648
649 fn pricing_for_billing_surface(
650 provider: ProviderKind,
651 model: &str,
652 billing_surface: Option<&str>,
653 ) -> Option<ModelPricing> {
654 if provider == ProviderKind::Stepfun
655 && billing_surface
656 .is_some_and(|surface| surface.eq_ignore_ascii_case(STEPFUN_PAYG_BILLING_SURFACE))
657 {
658 stepfun_payg_pricing(model)
659 } else {
660 None
661 }
662 }
663
664 fn route_requires_billing_surface(provider: ProviderKind, model: &str) -> bool {
665 provider == ProviderKind::Stepfun || stepfun_payg_pricing(model).is_some()
666 }
667
668 /// Look up pricing for a model name.
669 fn pricing_for_model(model: &str) -> Option<ModelPricing> {
670 pricing_for_model_at(model, Utc::now())
671 }
672
673 /// Return whether a model has a row in the pricing table.
674 #[must_use]
675 pub fn has_pricing_for_model(model: &str) -> bool {
676 pricing_for_model(model).is_some()
677 }
678
679 /// Return whether the selected provider route exposes authoritative dollar
680 /// pricing for this model without endpoint provenance. ChatGPT/Codex OAuth is
681 /// subscription/account scoped, while StepFun needs PAYG-vs-Plan provenance.
682 #[must_use]
683 pub fn has_pricing_for_provider(provider: ProviderKind, model: &str) -> bool {
684 calculate_turn_cost_estimate_for_provider(provider, model, &Usage::default()).is_some()
685 }
686
687 /// Return whether a provider/model route has authoritative pricing for an
688 /// already-classified billing surface.
689 #[cfg(any(test, feature = "test-support"))]
690 #[must_use]
691 pub fn has_pricing_for_billing_surface(
692 provider: ProviderKind,
693 model: &str,
694 billing_surface: Option<&str>,
695 ) -> bool {
696 pricing_for_billing_surface(provider, model, billing_surface).is_some()
697 }
698 const OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD: u32 = 272_000;
699
700 /// OpenAI applies a higher price to the full request once these models exceed
701 /// 272K input tokens. Until the pricing layer can represent request-wide tiers,
702 /// refuse to report the lower static catalog price (#4317).
703 /// <https://developers.openai.com/api/docs/models/gpt-5.4>
704 /// <https://developers.openai.com/api/docs/models/gpt-5.5>
705 /// <https://developers.openai.com/api/docs/models/gpt-5.6-sol>
706 fn direct_openai_long_context_tier_is_unpriced(
707 provider: ProviderKind,
708 model: &str,
709 input_tokens: u32,
710 ) -> bool {
711 let model_lower = model.trim().to_ascii_lowercase();
712 let affected_model = matches!(
713 model_lower.as_str(),
714 "gpt-5.4"
715 | "gpt-5.4-pro"
716 | "gpt-5.5"
717 | "gpt-5.6"
718 | "gpt-5.6-sol"
719 | "gpt-5.6-terra"
720 | "gpt-5.6-luna"
721 | "gpt-6-sol"
722 | "gpt-6.1-sol"
723 | "gpt-6-luna"
724 ) || has_date_snapshot_suffix(&model_lower, "gpt-5.4-")
725 || has_date_snapshot_suffix(&model_lower, "gpt-5.4-pro-")
726 || has_date_snapshot_suffix(&model_lower, "gpt-5.5-");
727 provider == ProviderKind::Openai
728 && input_tokens > OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD
729 && affected_model
730 }
731
732 #[cfg(any(test, feature = "test-support"))]
733 fn pricing_for_model_and_usage(model: &str, usage: &Usage) -> Option<ModelPricing> {
734 if is_minimax_m3(model) {
735 return Some(minimax_m3_standard_pricing(
736 usage.input_tokens > MINIMAX_M3_LONG_CONTEXT_THRESHOLD,
737 ));
738 }
739 if is_grok_tiered(model) {
740 return grok_tiered_pricing(
741 &model.trim().to_ascii_lowercase(),
742 usage.input_tokens >= GROK_4_6_LONG_CONTEXT_THRESHOLD,
743 );
744 }
745 pricing_for_model(model)
746 }
747
748 /// The clock-dependent tier a DeepSeek route bills at right now: `Some(true)`
749 /// at peak, `Some(false)` off-peak, `None` for a model whose rates do not move
750 /// with the clock. The model set is exactly the time-aware arm of
751 /// [`pricing_for_model_at`], so the chip that shows this and the receipt that
752 /// prices the turn can never disagree about which routes are tiered.
753 #[must_use]
754 pub fn deepseek_time_tier(model: &str, now: DateTime<Utc>) -> Option<bool> {
755 let lower = model.trim().to_ascii_lowercase();
756 deepseek_time_aware_pricing(&lower, now).map(|_| deepseek_is_peak(now))
757 }
758
759 /// Calculate cost from provider usage, honoring DeepSeek context-cache fields.
760 #[must_use]
761 #[cfg(any(test, feature = "test-support"))]
762 pub fn calculate_turn_cost_from_usage(model: &str, usage: &Usage) -> Option<f64> {
763 calculate_turn_cost_estimate_from_usage(model, usage).map(|estimate| estimate.usd)
764 }
765
766 /// Calculate cost from provider usage in both official currencies.
767 #[must_use]
768 #[cfg(any(test, feature = "test-support"))]
769 pub fn calculate_turn_cost_estimate_from_usage(model: &str, usage: &Usage) -> Option<CostEstimate> {
770 let pricing = pricing_for_model_and_usage(model, usage)?;
771 Some(cost_estimate_with_pricing(pricing, usage))
772 }
773
774 /// Cost from a hand-sourced row, or `None` when the row cannot price a class
775 /// this turn actually used.
776 ///
777 /// Only cache-write can fail here: input, cache-read, and output rates are
778 /// mandatory on every hand row, while a cache-creation rate exists only where a
779 /// provider publishes one or documents that writes cost nothing extra.
780 #[cfg(any(test, feature = "test-support"))]
781 fn cost_estimate_with_pricing_checked(
782 pricing: ModelPricing,
783 usage: &Usage,
784 ) -> Result<CostEstimate, Vec<TokenClass>> {
785 let classes = token_usage_for_pricing(usage);
786 let usd = currency_offering_pricing(pricing.usd, Currency::Usd);
787 let missing = usd.unpriced_used_classes(&classes);
788 if !missing.is_empty() {
789 return Err(missing);
790 }
791 let Some(usd) = usd.estimate_cost(&classes) else {
792 return Err(Vec::new());
793 };
794 let cny = match pricing.cny {
795 Some(pricing) => currency_offering_pricing(pricing, Currency::Cny)
796 .estimate_cost(&classes)
797 .ok_or_else(Vec::new)?,
798 None => 0.0,
799 };
800 Ok(CostEstimate { usd, cny })
801 }
802
803 /// Unchecked projection for the legacy model-only test helpers, which construct
804 /// usage they have already established the row can price.
805 ///
806 /// Production paths must use [`cost_estimate_with_pricing_checked`] so an
807 /// unpublished cache-write rate fails closed instead of billing writes at the
808 /// input rate.
809 #[cfg(any(test, feature = "test-support"))]
810 fn cost_estimate_with_pricing(pricing: ModelPricing, usage: &Usage) -> CostEstimate {
811 cost_estimate_with_pricing_checked(pricing, usage)
812 .expect("validated hand row and usage classes")
813 }
814
815 /// Calculate cost from provider/model usage when that pair identifies a single
816 /// billing surface. ChatGPT/Codex OAuth has no authoritative API dollar price,
817 /// while StepFun needs endpoint-derived PAYG-vs-Plan provenance; both stay
818 /// unpriced here rather than fabricating spend.
819 #[must_use]
820 pub fn calculate_turn_cost_estimate_for_provider(
821 provider: ProviderKind,
822 model: &str,
823 usage: &Usage,
824 ) -> Option<CostEstimate> {
825 calculate_turn_cost_estimate_for_provider_at(provider, model, usage, Utc::now())
826 }
827
828 /// Calculate cost only for routes that are actually money-metered. OAuth and
829 /// token-plan routes deliberately return `None` even when the underlying model
830 /// also exists behind a separately-priced public API.
831 ///
832 /// Production callers use [`audit_turn_cost_for_route`] instead: a caller that
833 /// adds to a total must also record why a turn was left out of it.
834 #[must_use]
835 #[cfg(any(test, feature = "test-support"))]
836 pub fn calculate_turn_cost_estimate_for_route(
837 provider: ProviderKind,
838 model: &str,
839 usage: &Usage,
840 billing: crate::route_billing::BillingPresentation,
841 ) -> Option<CostEstimate> {
842 audit_turn_cost_for_route(provider, model, None, usage, Utc::now(), billing).estimate
843 }
844
845 /// Estimate a turn when endpoint-derived billing provenance is available.
846 /// StepFun's standard API and Step Plan share provider/model text but not a
847 /// billing system, so that route fails closed unless the PAYG surface is known.
848 #[must_use]
849 #[cfg(any(test, feature = "test-support"))]
850 pub fn calculate_turn_cost_estimate_for_billing_surface(
851 provider: ProviderKind,
852 model: &str,
853 billing_surface: Option<&str>,
854 usage: &Usage,
855 ) -> Option<CostEstimate> {
856 calculate_turn_cost_estimate_for_route_at(provider, model, billing_surface, usage, Utc::now())
857 }
858
859 /// Deterministic provider-aware estimate at the turn's recorded time.
860 #[must_use]
861 pub fn calculate_turn_cost_estimate_for_provider_at(
862 provider: ProviderKind,
863 model: &str,
864 usage: &Usage,
865 recorded_at: DateTime<Utc>,
866 ) -> Option<CostEstimate> {
867 audit_turn_cost_for_provider_at(provider, model, usage, recorded_at).estimate
868 }
869
870 /// Why a route produced no cost estimate.
871 ///
872 /// Every `None` from the estimator carries one of these so `/cost` and
873 /// `/cache` can say *why* a turn is missing from a total instead of letting
874 /// the total read as complete.
875 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
876 pub enum UnpricedReason {
877 /// The route is **exactly identified** as one where money is not the unit:
878 /// a named OAuth subscription, a named prepaid token plan, or a local
879 /// endpoint with no provider bill. Only this reason excuses a turn from
880 /// money coverage, and only exact evidence may produce it (#4318).
881 NotMoneyMetered,
882 /// The route may or may not meter money and CodeWhale could not establish
883 /// which. Distinct from [`Self::NotMoneyMetered`] on purpose: an unknown
884 /// basis is counted as *possibly missing spend*, never waved through as a
885 /// subscription. A cross-provider child route with no dispatch config is
886 /// the common case.
887 UnknownBillingBasis,
888 /// One provider/model pair spans several billing systems and the non-secret
889 /// endpoint provenance needed to pick one is missing.
890 AmbiguousBillingSurface,
891 /// No endpoint classification was supplied for the route at all.
892 ///
893 /// Distinct from [`Self::UnknownBillingBasis`], which means an endpoint was
894 /// classified and could not be placed. This means none was offered, so
895 /// there is no evidence the turn was served by the provider's own official
896 /// surface rather than a proxy, a gateway, or a self-hosted clone that
897 /// happens to speak the same protocol. A provider enum plus a familiar
898 /// model id is not that evidence (#4318).
899 UnestablishedEndpoint,
900 /// The turn's endpoint classified as a per-token surface, but the pricing
901 /// layer holds no rates for that specific surface (as opposed to no rates
902 /// for the model at all).
903 UnpricedBillingSurface,
904 /// The only pricing row found claims live provider provenance but is stale
905 /// or was fetched from a different endpoint, so it is not authoritative for
906 /// this turn. Never silently downgraded to "authoritative anyway".
907 UnverifiedLivePricing,
908 /// A compatibility alias whose published rate has been retired.
909 RetiredAlias,
910 /// The turn crossed a request-wide pricing tier the pricing layer cannot
911 /// represent yet (for example OpenAI's >272K long-context surcharge).
912 UnrepresentedTier,
913 /// No pricing row exists for this provider/model route.
914 NoPricingRow,
915 /// Automatic gateway routing has not identified the upstream rate owner.
916 RoutingDependentPrice,
917 /// Saved usage predates cost coverage, or carries an unknown reason code.
918 UnrecordedCoverage,
919 /// Saved background accounting could not be recovered.
920 LateUsageUnavailable,
921 /// The bounded saved accounting ledger reached its capacity.
922 LateUsageOverflow,
923 /// A row exists, but a token class this turn actually used has no published
924 /// price, so the estimate fails closed rather than under-reporting.
925 MissingClassPrice,
926 /// A catalog row contains a NaN, infinite, or negative rate. The whole row
927 /// is rejected at the trust boundary rather than partially billed.
928 InvalidPricingRow,
929 /// The row is denominated in a currency CodeWhale does not carry. No
930 /// conversion is invented.
931 UnsupportedCurrency,
932 /// Provider telemetry assigns more cache-hit/miss/write tokens than the
933 /// reported input total. Pricing that contradictory partition would
934 /// over-count input, so the call is retained but fails closed.
935 InconsistentUsage,
936 MissingUsageBreakdown,
937 RequestOutcomeUnknown,
938 RequestInProgress,
939 ProviderSuccessMissingUsage,
940 LegacyUsageUnverified,
941 UsageCorrectionUnverified,
942 }
943
944 impl UnpricedReason {
945 /// Decode persisted receipts without guessing from the current provider.
946 /// Older or future reason codes remain explicitly unrecorded coverage.
947 #[must_use]
948 pub fn from_label(label: &str) -> Self {
949 match label {
950 "not_money_metered" => Self::NotMoneyMetered,
951 "unknown_billing_basis" => Self::UnknownBillingBasis,
952 "ambiguous_billing_surface" => Self::AmbiguousBillingSurface,
953 "unestablished_endpoint" => Self::UnestablishedEndpoint,
954 "unpriced_billing_surface" => Self::UnpricedBillingSurface,
955 "unverified_live_pricing" => Self::UnverifiedLivePricing,
956 "retired_alias" => Self::RetiredAlias,
957 "unrepresented_pricing_tier" => Self::UnrepresentedTier,
958 "no_pricing_row" => Self::NoPricingRow,
959 "routing_dependent_price" => Self::RoutingDependentPrice,
960 "missing_class_price" => Self::MissingClassPrice,
961 "invalid_pricing_row" => Self::InvalidPricingRow,
962 "unsupported_currency" | "currency_not_published" => Self::UnsupportedCurrency,
963 "inconsistent_usage" => Self::InconsistentUsage,
964 "missing_usage_breakdown" => Self::MissingUsageBreakdown,
965 "late_usage_ledger_unavailable" => Self::LateUsageUnavailable,
966 "late_usage_ledger_overflow" => Self::LateUsageOverflow,
967 "request_outcome_unknown" => Self::RequestOutcomeUnknown,
968 "request_in_progress" => Self::RequestInProgress,
969 "provider_success_missing_usage" | "success_without_usage" => {
970 Self::ProviderSuccessMissingUsage
971 }
972 "legacy_usage_unverified" => Self::LegacyUsageUnverified,
973 "usage_correction_unverified" => Self::UsageCorrectionUnverified,
974 _ => Self::UnrecordedCoverage,
975 }
976 }
977
978 #[must_use]
979 pub const fn message_id(self) -> codewhale_localization::MessageId {
980 use codewhale_localization::MessageId;
981 match self {
982 Self::NotMoneyMetered => MessageId::CostReasonNotMoney,
983 Self::UnknownBillingBasis => MessageId::CostReasonBillingUnknown,
984 Self::AmbiguousBillingSurface | Self::UnestablishedEndpoint => {
985 MessageId::CostReasonEndpointUnknown
986 }
987 Self::UnpricedBillingSurface | Self::NoPricingRow => MessageId::CostReasonRateMissing,
988 Self::UnverifiedLivePricing => MessageId::CostReasonLiveUnverified,
989 Self::RetiredAlias => MessageId::CostReasonRetiredAlias,
990 Self::UnrepresentedTier => MessageId::CostReasonTierMissing,
991 Self::RoutingDependentPrice => MessageId::CostReasonRoutingDependent,
992 Self::UnrecordedCoverage | Self::LateUsageUnavailable | Self::LateUsageOverflow => {
993 MessageId::CostReasonCoverageMissing
994 }
995 Self::MissingClassPrice => MessageId::CostReasonTokenRateMissing,
996 Self::InvalidPricingRow => MessageId::CostReasonInvalidRate,
997 Self::UnsupportedCurrency => MessageId::CostReasonCurrencyMissing,
998 Self::InconsistentUsage => MessageId::CostReasonUsageConflict,
999 Self::MissingUsageBreakdown => MessageId::CostReasonUsageBreakdown,
1000 Self::RequestOutcomeUnknown => MessageId::CostReasonOutcomeUnknown,
1001 Self::RequestInProgress => MessageId::CostReasonInProgress,
1002 Self::ProviderSuccessMissingUsage => MessageId::CostReasonProviderUsageMissing,
1003 Self::LegacyUsageUnverified => MessageId::CostReasonLegacyUsageUnverified,
1004 Self::UsageCorrectionUnverified => MessageId::CostReasonUsageCorrectionUnverified,
1005 }
1006 }
1007
1008 /// Stable, non-localized identifier for logs and JSON.
1009 #[must_use]
1010 pub fn label(self) -> &'static str {
1011 match self {
1012 Self::NotMoneyMetered => "not_money_metered",
1013 Self::UnknownBillingBasis => "unknown_billing_basis",
1014 Self::AmbiguousBillingSurface => "ambiguous_billing_surface",
1015 Self::UnestablishedEndpoint => "unestablished_endpoint",
1016 Self::UnpricedBillingSurface => "unpriced_billing_surface",
1017 Self::UnverifiedLivePricing => "unverified_live_pricing",
1018 Self::RetiredAlias => "retired_alias",
1019 Self::UnrepresentedTier => "unrepresented_pricing_tier",
1020 Self::NoPricingRow => "no_pricing_row",
1021 Self::RoutingDependentPrice => "routing_dependent_price",
1022 Self::UnrecordedCoverage => "unrecorded_coverage",
1023 Self::LateUsageUnavailable => "late_usage_ledger_unavailable",
1024 Self::LateUsageOverflow => "late_usage_ledger_overflow",
1025 Self::MissingClassPrice => "missing_class_price",
1026 Self::InvalidPricingRow => "invalid_pricing_row",
1027 Self::UnsupportedCurrency => "unsupported_currency",
1028 Self::InconsistentUsage => "inconsistent_usage",
1029 Self::MissingUsageBreakdown => "missing_usage_breakdown",
1030 Self::RequestOutcomeUnknown => "request_outcome_unknown",
1031 Self::RequestInProgress => "request_in_progress",
1032 Self::ProviderSuccessMissingUsage => "provider_success_missing_usage",
1033 Self::LegacyUsageUnverified => "legacy_usage_unverified",
1034 Self::UsageCorrectionUnverified => "usage_correction_unverified",
1035 }
1036 }
1037
1038 /// Whether a turn with this reason belongs in the money-metered coverage
1039 /// denominator `/cost` reports against its dollar total.
1040 ///
1041 /// Only [`Self::NotMoneyMetered`] — an *exactly* identified subscription,
1042 /// token plan, or local route — is excluded. Everything else, including an
1043 /// unknown billing basis, counts as spend the total is missing, because
1044 /// treating "don't know" as "not billed" is what let unpriced turns
1045 /// disappear from a total that then read as complete (#4318).
1046 #[must_use]
1047 pub fn counts_toward_money_coverage(self) -> bool {
1048 self != Self::NotMoneyMetered
1049 }
1050 }
1051
1052 /// A turn cost plus the provenance and completeness needed to audit it.
1053 ///
1054 /// `estimate.is_some()` and `unpriced_reason.is_none()` always agree: this type
1055 /// is produced by the same code path that computes the estimate, so an audit
1056 /// can never disagree with the number a total was built from.
1057 #[derive(Debug, Clone, PartialEq)]
1058 pub struct TurnCostAudit {
1059 /// The cost, when the route is priced for every class this turn used.
1060 pub estimate: Option<CostEstimate>,
1061 /// Where the applied (or attempted) pricing row came from.
1062 pub provenance: Option<PricingProvenance>,
1063 /// Classes this turn used that carry no published price.
1064 pub unpriced_classes: Vec<TokenClass>,
1065 /// Why the estimate is absent, when it is.
1066 pub unpriced_reason: Option<UnpricedReason>,
1067 /// Set when a live catalog row could not be verified as authoritative for
1068 /// this route. Present both when the row was *degraded* to the bundled
1069 /// snapshot (the estimate is still priced, from the bundled row) and when
1070 /// there was no fallback at all. It is the receipt for the downgrade, so a
1071 /// `provider_live` label is never claimed for an unproven row.
1072 pub live_pricing_defect: Option<LivePricingDefect>,
1073 /// Whether the estimate is authoritative in each carried currency. A zero
1074 /// amount is still priced when usage is zero; these flags therefore cannot
1075 /// be inferred from `estimate > 0`.
1076 pub usd_priced: bool,
1077 pub cny_priced: bool,
1078 pub exact_usd: Option<String>,
1079 pub exact_cny: Option<String>,
1080 }
1081
1082 impl TurnCostAudit {
1083 fn priced(
1084 estimate: CostEstimate,
1085 provenance: PricingProvenance,
1086 usd_priced: bool,
1087 cny_priced: bool,
1088 ) -> Self {
1089 Self {
1090 estimate: Some(estimate),
1091 provenance: Some(provenance),
1092 unpriced_classes: Vec::new(),
1093 unpriced_reason: None,
1094 live_pricing_defect: None,
1095 usd_priced,
1096 cny_priced,
1097 exact_usd: None,
1098 exact_cny: None,
1099 }
1100 }
1101
1102 pub fn unpriced(reason: UnpricedReason) -> Self {
1103 Self {
1104 estimate: None,
1105 provenance: None,
1106 unpriced_classes: Vec::new(),
1107 unpriced_reason: Some(reason),
1108 live_pricing_defect: None,
1109 usd_priced: false,
1110 cny_priced: false,
1111 exact_usd: None,
1112 exact_cny: None,
1113 }
1114 }
1115
1116 fn missing_classes(provenance: PricingProvenance, classes: Vec<TokenClass>) -> Self {
1117 Self {
1118 estimate: None,
1119 provenance: Some(provenance),
1120 unpriced_classes: classes,
1121 unpriced_reason: Some(UnpricedReason::MissingClassPrice),
1122 live_pricing_defect: None,
1123 usd_priced: false,
1124 cny_priced: false,
1125 exact_usd: None,
1126 exact_cny: None,
1127 }
1128 }
1129
1130 fn unverified_live(defect: LivePricingDefect) -> Self {
1131 Self {
1132 estimate: None,
1133 // Deliberately not `ProviderLive`: an unverified row must never be
1134 // labelled with authoritative live provenance.
1135 provenance: Some(PricingProvenance::Unknown),
1136 unpriced_classes: Vec::new(),
1137 unpriced_reason: Some(UnpricedReason::UnverifiedLivePricing),
1138 live_pricing_defect: Some(defect),
1139 usd_priced: false,
1140 cny_priced: false,
1141 exact_usd: None,
1142 exact_cny: None,
1143 }
1144 }
1145
1146 /// Attach a live-pricing downgrade receipt to an otherwise complete audit.
1147 fn with_live_defect(mut self, defect: Option<LivePricingDefect>) -> Self {
1148 if let Some(defect) = defect {
1149 self.live_pricing_defect = Some(defect);
1150 }
1151 self
1152 }
1153
1154 /// Whether this turn contributed an authoritative number to a total.
1155 #[must_use]
1156 #[cfg(any(test, feature = "test-support"))]
1157 pub fn is_priced(&self) -> bool {
1158 self.estimate.is_some()
1159 }
1160
1161 /// Whether the estimate is authoritative in the requested display
1162 /// currency. Exact zero remains priced; the boolean provenance flags are
1163 /// intentionally not inferred from the numeric amount.
1164 #[must_use]
1165 pub fn is_priced_in(&self, currency: CostCurrency) -> bool {
1166 self.estimate.is_some()
1167 && match currency {
1168 CostCurrency::Usd => self.usd_priced,
1169 CostCurrency::Cny => self.cny_priced,
1170 }
1171 }
1172
1173 /// Whether this turn belongs in the money-metered coverage denominator.
1174 ///
1175 /// Priced turns always do. Unpriced ones do unless the route was *exactly*
1176 /// identified as non-metered.
1177 #[must_use]
1178 pub fn counts_toward_money_coverage(&self) -> bool {
1179 self.unpriced_reason
1180 .is_none_or(UnpricedReason::counts_toward_money_coverage)
1181 }
1182 }
1183
1184 /// Audit a turn on a provider/model route, without knowing which endpoint served
1185 /// it. A live catalog row cannot be *confirmed* for an unknown endpoint, so this
1186 /// path degrades to the bundled published snapshot; use
1187 /// [`audit_turn_cost_for_provider_on_endpoint_at`] when the base URL is known.
1188 #[must_use]
1189 pub fn audit_turn_cost_for_provider_at(
1190 provider: ProviderKind,
1191 model: &str,
1192 usage: &Usage,
1193 recorded_at: DateTime<Utc>,
1194 ) -> TurnCostAudit {
1195 audit_turn_cost_for_provider_on_endpoint_at(provider, model, None, usage, recorded_at)
1196 }
1197
1198 /// Audit a turn's cost on a provider/model route at its recorded time.
1199 ///
1200 /// This is the single implementation; `calculate_turn_cost_estimate_*` are thin
1201 /// projections of it, so no caller can build a total from one rule set while
1202 /// reporting completeness from another.
1203 #[must_use]
1204 pub fn audit_turn_cost_for_provider_on_endpoint_at(
1205 provider: ProviderKind,
1206 model: &str,
1207 endpoint_fingerprint: Option<&str>,
1208 usage: &Usage,
1209 recorded_at: DateTime<Utc>,
1210 ) -> TurnCostAudit {
1211 audit_turn_cost_for_provider_on_endpoint_for_identity_at(
1212 provider,
1213 None,
1214 model,
1215 endpoint_fingerprint,
1216 usage,
1217 recorded_at,
1218 true,
1219 None,
1220 )
1221 }
1222
1223 fn resolved_pricing_model(provider: ProviderKind, model: &str) -> Option<String> {
1224 let trimmed = model.trim();
1225 if trimmed.chars().any(char::is_control) {
1226 return None;
1227 }
1228 codewhale_config::route::resolve_model(provider, trimmed, None)
1229 .ok()
1230 .filter(|resolved| !resolved.is_auto)
1231 .map(|resolved| resolved.logical)
1232 }
1233
1234 /// Identity-aware provider audit for named compatible routes.
1235 ///
1236 /// `ProviderKind::Custom` is only a transport family, so it is never sufficient
1237 /// pricing provenance on its own. Baseten is the first reviewed compatible
1238 /// provider whose authenticated live catalog can price actual usage; every
1239 /// other custom identity stays unknown until it receives an equivalent
1240 /// provider/endpoint contract.
1241 #[must_use]
1242 fn audit_turn_cost_for_provider_on_endpoint_for_identity_at(
1243 provider: ProviderKind,
1244 provider_identity: Option<&str>,
1245 model: &str,
1246 endpoint_fingerprint: Option<&str>,
1247 usage: &Usage,
1248 recorded_at: DateTime<Utc>,
1249 allow_cloud_catalog: bool,
1250 frozen_cloud_pricing: Option<OfferingPricing>,
1251 ) -> TurnCostAudit {
1252 if !usage_cache_partition_is_consistent(usage) {
1253 return TurnCostAudit::unpriced(UnpricedReason::InconsistentUsage);
1254 }
1255 if provider == ProviderKind::OpenaiCodex {
1256 return TurnCostAudit::unpriced(UnpricedReason::AmbiguousBillingSurface);
1257 }
1258 if provider == ProviderKind::Custom {
1259 return TurnCostAudit::unpriced(UnpricedReason::UnknownBillingBasis);
1260 }
1261 if route_requires_billing_surface(provider, model) {
1262 return TurnCostAudit::unpriced(UnpricedReason::AmbiguousBillingSurface);
1263 }
1264 let normalized_model = model.trim();
1265 let model_lower = normalized_model.to_ascii_lowercase();
1266 let direct_deepseek = matches!(
1267 provider,
1268 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
1269 );
1270 let Some(canonical_model) = resolved_pricing_model(provider, normalized_model) else {
1271 return TurnCostAudit::unpriced(UnpricedReason::NoPricingRow);
1272 };
1273 let catalog_model = if direct_deepseek
1274 && matches!(model_lower.as_str(), "deepseek-chat" | "deepseek-reasoner")
1275 {
1276 let Ok(retirement) = DateTime::parse_from_rfc3339(DEEPSEEK_ALIAS_RETIREMENT_UTC) else {
1277 return TurnCostAudit::unpriced(UnpricedReason::NoPricingRow);
1278 };
1279 if recorded_at >= retirement.with_timezone(&Utc) {
1280 return TurnCostAudit::unpriced(UnpricedReason::RetiredAlias);
1281 }
1282 "deepseek-v4-flash".to_string()
1283 } else if direct_deepseek
1284 && matches!(
1285 model_lower.as_str(),
1286 "flash-vision" | "deepseek-v4flashvisionexp"
1287 )
1288 && recorded_at < deepseek_flash_effective_from()
1289 {
1290 "deepseek-v4-flash-vision-exp".to_string()
1291 } else {
1292 canonical_model
1293 };
1294
1295 if direct_openai_long_context_tier_is_unpriced(provider, &catalog_model, usage.input_tokens) {
1296 return TurnCostAudit::unpriced(UnpricedReason::UnrepresentedTier);
1297 }
1298
1299 // Direct DeepSeek pricing carries an authoritative CNY row and recorded-time
1300 // peak/off-peak tiers that a static catalog row cannot represent. These
1301 // exact first-party routes intentionally override the catalog; no other
1302 // provider/model text match is allowed to do so.
1303 if matches!(
1304 provider,
1305 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
1306 ) && catalog_model.eq_ignore_ascii_case("minimax-m3")
1307 {
1308 return hand_provider_audit(provider, &catalog_model, usage, recorded_at);
1309 }
1310
1311 if provider == ProviderKind::Xai && is_grok_tiered(&catalog_model) {
1312 return hand_provider_audit(provider, &catalog_model, usage, recorded_at);
1313 }
1314
1315 if direct_deepseek
1316 || (provider == ProviderKind::Anthropic
1317 && catalog_model.eq_ignore_ascii_case("claude-sonnet-5"))
1318 {
1319 return hand_provider_audit(provider, &catalog_model, usage, recorded_at);
1320 }
1321
1322 if let Some(pricing) = frozen_cloud_pricing {
1323 return audit_offering_pricing(pricing, usage);
1324 }
1325 let classes = token_usage_for_pricing(usage);
1326 // A live catalog row is only authoritative when it is fresh *and* was
1327 // fetched from the endpoint this turn was served on. When it is not, degrade
1328 // to the bundled published snapshot and receipt the defect; only if there is
1329 // no bundled row at all does the turn fail closed (#4318).
1330 let mut live_defect = None;
1331 let offering = match verified_catalog_offering(
1332 provider,
1333 provider_identity,
1334 &catalog_model,
1335 endpoint_fingerprint,
1336 recorded_at,
1337 allow_cloud_catalog,
1338 ) {
1339 VerifiedOffering::Usable(offering) => Some(offering),
1340 VerifiedOffering::DegradedToBundled { offering, defect } => {
1341 live_defect = Some(defect);
1342 Some(offering)
1343 }
1344 VerifiedOffering::Unusable(defect) => {
1345 live_defect = Some(defect);
1346 None
1347 }
1348 VerifiedOffering::FutureEffective => {
1349 return TurnCostAudit::unpriced(UnpricedReason::UnverifiedLivePricing);
1350 }
1351 VerifiedOffering::Absent => None,
1352 };
1353
1354 if let Some(audit) = offering
1355 .as_ref()
1356 .and_then(|offering| refused_catalog_pricing_audit(offering, usage))
1357 {
1358 return audit.with_live_defect(live_defect);
1359 }
1360
1361 if let Some(offering) = offering.as_ref()
1362 && let Some(pricing) =
1363 effective_offering_pricing(provider, &catalog_model, offering, &classes)
1364 {
1365 return audit_offering_pricing(pricing, usage).with_live_defect(live_defect);
1366 }
1367
1368 // A few first-party rows predate or intentionally omit a Models.dev entry
1369 // (for example OpenAI API `gpt-5-codex` and MiniMax `minimax-m2.7`).
1370 // Preserve only an explicit provider-owned allowlist here;
1371 // a costless foreign/catalog route must remain unpriced.
1372 let hand_row = provider_owned_hand_pricing_at(provider, &catalog_model, recorded_at);
1373
1374 // An unverifiable live row with no bundled fallback and no hand row is a
1375 // route CodeWhale cannot price truthfully. Say which, rather than reporting
1376 // the unverified rate or a bare "no pricing row".
1377 match (live_defect, hand_row) {
1378 (Some(defect), None) => TurnCostAudit::unverified_live(defect),
1379 // Concentrate publishes different upstream rates, and even a requested
1380 // provider/model can fail over. A slash is not a billing receipt. Keep
1381 // verified scoped offerings and operator overrides above authoritative;
1382 // absent those, do not inherit a model owner's or aggregate rate.
1383 // https://concentrate.ai/docs/api-reference/endpoint/auto-routing
1384 (None, None) if provider == ProviderKind::Concentrate => {
1385 TurnCostAudit::unpriced(UnpricedReason::RoutingDependentPrice)
1386 }
1387 (defect, hand_row) => hand_priced_audit(hand_row, usage).with_live_defect(defect),
1388 }
1389 }
1390
1391 /// Convert malformed catalog numerics, or a context tier this turn reached,
1392 /// into an explicit runtime audit reason.
1393 /// Keeping this distinct from the ordinary `None` projection prevents a bad
1394 /// published row from becoming indistinguishable from an absent price.
1395 fn refused_catalog_pricing_audit(
1396 offering: &codewhale_config::catalog::CatalogOffering,
1397 usage: &Usage,
1398 ) -> Option<TurnCostAudit> {
1399 let cost = offering.cost.as_ref()?;
1400 if !codewhale_config::pricing::catalog_cost_is_valid(cost) {
1401 return Some(TurnCostAudit::unpriced(UnpricedReason::InvalidPricingRow));
1402 }
1403 let pricing = OfferingPricing::from_catalog_offering(offering)?;
1404 matches!(
1405 pricing.quote_cost(&token_usage_for_pricing(usage)),
1406 Err(PricingQuoteError::UnsupportedTier)
1407 )
1408 .then(|| TurnCostAudit::unpriced(UnpricedReason::UnrepresentedTier))
1409 }
1410
1411 /// Outcome of checking a catalog row's pricing provenance against the route.
1412 enum VerifiedOffering {
1413 /// The row is authoritative as-is (bundled, user override, or a live row
1414 /// proven fresh and endpoint-matched).
1415 Usable(codewhale_config::catalog::CatalogOffering),
1416 /// The live row could not be verified, so the bundled published row is used
1417 /// instead. The defect is retained as the receipt for why.
1418 DegradedToBundled {
1419 offering: codewhale_config::catalog::CatalogOffering,
1420 defect: LivePricingDefect,
1421 },
1422 /// The live row could not be verified and no bundled row exists.
1423 Unusable(LivePricingDefect),
1424 /// The row claims it was fetched after this turn was dispatched. Clock
1425 /// saturation must never turn a future price into an age-zero price.
1426 FutureEffective,
1427 /// No catalog row for this provider/model at all.
1428 Absent,
1429 }
1430
1431 /// Resolve the catalog row to price against, refusing to treat an unverifiable
1432 /// live row as authoritative.
1433 ///
1434 /// `endpoint_fingerprint` is the non-secret SHA-256 digest of the base URL the turn
1435 /// was actually served on (see [`codewhale_config::catalog::base_url_fingerprint`]).
1436 /// Callers that do not know the endpoint pass `None`, which cannot *confirm* a
1437 /// live row — so those callers degrade to the bundled snapshot rather than
1438 /// billing against a rate whose endpoint scope is unproven.
1439 fn verified_catalog_offering(
1440 provider: ProviderKind,
1441 provider_identity: Option<&str>,
1442 catalog_model: &str,
1443 endpoint_fingerprint: Option<&str>,
1444 recorded_at: DateTime<Utc>,
1445 allow_cloud_catalog: bool,
1446 ) -> VerifiedOffering {
1447 let allows_bundled_fallback = !matches!(
1448 provider,
1449 ProviderKind::Custom
1450 | ProviderKind::OpenaiCodex
1451 | ProviderKind::Codewhale
1452 | ProviderKind::Concentrate
1453 | ProviderKind::Openrouter
1454 );
1455 let mut offering = match crate::provider_lake::catalog_offering_for_model_identity(
1456 provider,
1457 provider_identity,
1458 catalog_model,
1459 ) {
1460 Some(offering)
1461 if allows_bundled_fallback
1462 && offering.cost.is_none()
1463 && offering.cost_source.is_none() =>
1464 {
1465 crate::provider_lake::bundled_catalog_offering_for_model(provider, catalog_model)
1466 .unwrap_or(offering)
1467 }
1468 Some(offering) => offering,
1469 None if allows_bundled_fallback => {
1470 let Some(bundled) =
1471 crate::provider_lake::bundled_catalog_offering_for_model(provider, catalog_model)
1472 else {
1473 return VerifiedOffering::Absent;
1474 };
1475 bundled
1476 }
1477 None => return VerifiedOffering::Absent,
1478 };
1479 if allow_cloud_catalog
1480 && let codewhale_config::catalog::CatalogSource::CloudFacts {
1481 fetched_at,
1482 valid_until,
1483 ..
1484 } = offering.pricing_source()
1485 {
1486 let at = u64::try_from(recorded_at.timestamp()).unwrap_or(0);
1487 if *fetched_at > at {
1488 return VerifiedOffering::FutureEffective;
1489 }
1490 if valid_until.is_some_and(|expires| at > expires) {
1491 return crate::provider_lake::bundled_catalog_offering_for_model(
1492 provider,
1493 catalog_model,
1494 )
1495 .map(VerifiedOffering::Usable)
1496 .unwrap_or(VerifiedOffering::Absent);
1497 }
1498 }
1499 let cloud_price = matches!(
1500 offering.pricing_source(),
1501 codewhale_config::catalog::CatalogSource::CloudFacts { .. }
1502 );
1503 if cloud_price
1504 && (!allow_cloud_catalog
1505 || endpoint_fingerprint.is_some_and(|fingerprint| {
1506 codewhale_config::catalog::base_url_fingerprint(
1507 provider.provider().default_base_url(),
1508 ) != fingerprint
1509 }))
1510 {
1511 return crate::provider_lake::bundled_catalog_offering_for_model(provider, catalog_model)
1512 .map(VerifiedOffering::Usable)
1513 .unwrap_or(VerifiedOffering::Absent);
1514 }
1515 let models_dev_live_fetched_at = match offering.pricing_source() {
1516 codewhale_config::catalog::CatalogSource::Live { fetched_at, .. }
1517 if crate::provider_lake::live_catalog_origin(provider, catalog_model)
1518 == Some(crate::provider_lake::LiveSource::ModelsDev) =>
1519 {
1520 Some(*fetched_at)
1521 }
1522 _ => None,
1523 };
1524 if let Some(fetched_at) = models_dev_live_fetched_at {
1525 offering.cost_source =
1526 Some(codewhale_config::catalog::CatalogSource::ModelsDevLive { fetched_at });
1527 }
1528 let Some(pricing) = OfferingPricing::from_catalog_offering_at(
1529 &offering,
1530 u64::try_from(recorded_at.timestamp()).unwrap_or(0),
1531 ) else {
1532 // No priced row to verify; downstream treats this as unpriced.
1533 return VerifiedOffering::Usable(offering);
1534 };
1535 // `recorded_at` is the turn's own clock, which is the right reference for
1536 // "was this price current when the turn happened".
1537 let now_unix = u64::try_from(recorded_at.timestamp()).ok();
1538 if matches!(
1539 pricing.provenance,
1540 PricingProvenance::ProviderLive | PricingProvenance::ModelsDevLive
1541 ) && pricing
1542 .fetched_at
1543 .or(pricing.effective_at)
1544 .zip(now_unix)
1545 .is_some_and(|(effective_at, dispatched_at)| effective_at > dispatched_at)
1546 {
1547 return VerifiedOffering::FutureEffective;
1548 }
1549 let Some(defect) =
1550 pricing.live_pricing_defect(endpoint_fingerprint, now_unix, LIVE_PRICING_MAX_AGE_SECS)
1551 else {
1552 return VerifiedOffering::Usable(offering);
1553 };
1554 match crate::provider_lake::bundled_catalog_offering_for_model(provider, catalog_model) {
1555 Some(bundled) => VerifiedOffering::DegradedToBundled {
1556 offering: bundled,
1557 defect,
1558 },
1559 None => VerifiedOffering::Unusable(defect),
1560 }
1561 }
1562
1563 /// Project a hand-sourced provider row into an audit.
1564 ///
1565 /// A hand row always publishes input, cache-read, and output rates. Cache-write
1566 /// is the one class that can be genuinely absent: only providers that publish a
1567 /// write premium, or document that cache creation carries no separate charge,
1568 /// can price it. A turn that wrote to cache on a row with neither fact fails
1569 /// closed and names the class, rather than being billed at the input rate on the
1570 /// strength of an assumption (#4318).
1571 fn hand_priced_audit(pricing: Option<ModelPricing>, usage: &Usage) -> TurnCostAudit {
1572 let Some(pricing) = pricing else {
1573 return TurnCostAudit::unpriced(UnpricedReason::NoPricingRow);
1574 };
1575 audit_pricing_pair(
1576 currency_offering_pricing(pricing.usd, Currency::Usd),
1577 pricing
1578 .cny
1579 .map(|row| currency_offering_pricing(row, Currency::Cny)),
1580 usage,
1581 )
1582 }
1583
1584 fn audit_pricing_pair(
1585 primary: OfferingPricing,
1586 secondary: Option<OfferingPricing>,
1587 usage: &Usage,
1588 ) -> TurnCostAudit {
1589 let mut audit = audit_offering_pricing(primary, usage);
1590 if audit.estimate.is_none() {
1591 return audit;
1592 }
1593 if let Some(secondary) = secondary {
1594 let secondary = audit_offering_pricing(secondary, usage);
1595 let Some(cost) = secondary.estimate else {
1596 return secondary;
1597 };
1598 audit.estimate.as_mut().expect("priced primary").cny = cost.cny;
1599 audit.cny_priced = secondary.cny_priced;
1600 audit.exact_cny = secondary.exact_cny;
1601 }
1602 audit
1603 }
1604
1605 fn hand_provider_audit(
1606 provider: ProviderKind,
1607 model: &str,
1608 usage: &Usage,
1609 at: DateTime<Utc>,
1610 ) -> TurnCostAudit {
1611 provider_owned_hand_quote_rows(provider, model, at).map_or_else(
1612 || TurnCostAudit::unpriced(UnpricedReason::NoPricingRow),
1613 |(primary, secondary)| audit_pricing_pair(primary, secondary, usage),
1614 )
1615 }
1616
1617 /// Recorded-time variant with explicit billing-surface provenance.
1618 #[must_use]
1619 #[cfg(any(test, feature = "test-support"))]
1620 pub fn calculate_turn_cost_estimate_for_route_at(
1621 provider: ProviderKind,
1622 model: &str,
1623 billing_surface: Option<&str>,
1624 usage: &Usage,
1625 recorded_at: DateTime<Utc>,
1626 ) -> Option<CostEstimate> {
1627 audit_turn_cost_for_route_at(provider, model, billing_surface, usage, recorded_at).estimate
1628 }
1629
1630 /// Audit a turn's cost with endpoint-derived billing provenance.
1631 #[must_use]
1632 pub fn audit_turn_cost_for_route_at(
1633 provider: ProviderKind,
1634 model: &str,
1635 billing_surface: Option<&str>,
1636 usage: &Usage,
1637 recorded_at: DateTime<Utc>,
1638 ) -> TurnCostAudit {
1639 audit_turn_cost_for_route_on_endpoint_at(
1640 provider,
1641 model,
1642 billing_surface,
1643 None,
1644 usage,
1645 recorded_at,
1646 )
1647 }
1648
1649 /// Audit a turn's cost with both endpoint-derived billing provenance and the
1650 /// endpoint fingerprint needed to verify live catalog pricing.
1651 #[must_use]
1652 pub fn audit_turn_cost_for_route_on_endpoint_at(
1653 provider: ProviderKind,
1654 model: &str,
1655 billing_surface: Option<&str>,
1656 endpoint_fingerprint: Option<&str>,
1657 usage: &Usage,
1658 recorded_at: DateTime<Utc>,
1659 ) -> TurnCostAudit {
1660 audit_turn_cost_for_route_on_endpoint_for_identity_at(
1661 provider,
1662 None,
1663 model,
1664 billing_surface,
1665 endpoint_fingerprint,
1666 None,
1667 usage,
1668 recorded_at,
1669 )
1670 }
1671
1672 /// Identity-aware route audit for an immutable dispatch receipt.
1673 #[must_use]
1674 pub fn audit_turn_cost_for_route_on_endpoint_for_identity_at(
1675 provider: ProviderKind,
1676 provider_identity: Option<&str>,
1677 model: &str,
1678 billing_surface: Option<&str>,
1679 endpoint_fingerprint: Option<&str>,
1680 provider_live_pricing: Option<&crate::provider_catalog_live::ProviderLivePricingQuote>,
1681 usage: &Usage,
1682 recorded_at: DateTime<Utc>,
1683 ) -> TurnCostAudit {
1684 if matches!(
1685 endpoint_metering_for_billing_surface(billing_surface),
1686 EndpointMetering::ExactSubscription | EndpointMetering::LocalNoBill
1687 ) {
1688 return TurnCostAudit::unpriced(UnpricedReason::NotMoneyMetered);
1689 }
1690
1691 let frozen_pricing = match provider_live_pricing {
1692 Some(quote) => {
1693 let binding = provider_identity
1694 .zip(endpoint_fingerprint)
1695 .zip(u64::try_from(recorded_at.timestamp()).ok());
1696 let Some(((identity, fingerprint), at)) = binding else {
1697 return TurnCostAudit::unpriced(UnpricedReason::UnverifiedLivePricing);
1698 };
1699 let Some(pricing) = quote.pricing_for_route(provider, identity, model, fingerprint, at)
1700 else {
1701 return TurnCostAudit::unpriced(UnpricedReason::UnverifiedLivePricing);
1702 };
1703 let secondary =
1704 quote.secondary_pricing_for_route(provider, identity, model, fingerprint, at);
1705 Some((pricing, secondary))
1706 }
1707 None => None,
1708 };
1709 let declared = frozen_pricing
1710 .as_ref()
1711 .is_some_and(|(pricing, _)| pricing.provenance == PricingProvenance::UserOverride);
1712 let reviewed_custom_metered = reviewed_custom_route_is_metered(provider, endpoint_fingerprint);
1713 let reviewed_provider_live =
1714 reviewed_provider_live_route_is_metered(provider, provider_identity, endpoint_fingerprint);
1715 // An explicitly recorded surface is evidence. Exact non-metered surfaces
1716 // override provider guesses; an explicit unknown/unrecognized surface must
1717 // fail closed and may never fall through to a familiar model's hand row.
1718 match endpoint_metering_for_billing_surface(billing_surface) {
1719 EndpointMetering::ExactSubscription | EndpointMetering::LocalNoBill => {
1720 return TurnCostAudit::unpriced(UnpricedReason::NotMoneyMetered);
1721 }
1722 EndpointMetering::Unknown
1723 if billing_surface.is_some() && !reviewed_custom_metered && !declared =>
1724 {
1725 return TurnCostAudit::unpriced(UnpricedReason::UnknownBillingBasis);
1726 }
1727 EndpointMetering::Unknown | EndpointMetering::Money => {}
1728 }
1729 if !usage_cache_partition_is_consistent(usage) {
1730 return TurnCostAudit::unpriced(UnpricedReason::InconsistentUsage);
1731 }
1732 if declared && let Some((pricing, secondary)) = frozen_pricing.clone() {
1733 return audit_pricing_pair(pricing, secondary, usage);
1734 }
1735 if provider == ProviderKind::Stepfun {
1736 return match pricing_for_billing_surface(provider, model, billing_surface) {
1737 // Each model keeps its documented cache-write policy; unpublished
1738 // write rates fail closed instead of borrowing another model's rate.
1739 Some(pricing) => hand_priced_audit(Some(pricing), usage),
1740 // The surface classified as per-token but no rates exist for it, or
1741 // no surface was established at all.
1742 None => TurnCostAudit::unpriced(match billing_surface {
1743 Some(_) => UnpricedReason::UnpricedBillingSurface,
1744 None => UnpricedReason::AmbiguousBillingSurface,
1745 }),
1746 };
1747 }
1748 if stepfun_payg_pricing(model).is_some() {
1749 return TurnCostAudit::unpriced(UnpricedReason::AmbiguousBillingSurface);
1750 }
1751 // This is the *route* audit: the caller is asserting it knows which
1752 // endpoint served the turn. With no classification at all, nothing
1753 // distinguishes the provider's own official surface from a proxy, a
1754 // gateway, or a self-hosted clone speaking the same protocol — a provider
1755 // enum plus a familiar model id is not evidence of an official endpoint.
1756 // So the turn prices as unknown rather than at official rates.
1757 //
1758 // Callers that genuinely hold only a provider and a model use
1759 // `audit_turn_cost_for_provider_*`, which says so in its name and carries
1760 // its own weaker claim.
1761 if billing_surface.is_none() {
1762 return TurnCostAudit::unpriced(UnpricedReason::UnestablishedEndpoint);
1763 }
1764 if let Some((pricing, secondary)) = frozen_pricing {
1765 let catalog_model =
1766 resolved_pricing_model(provider, model).unwrap_or_else(|| model.trim().to_string());
1767 if direct_openai_long_context_tier_is_unpriced(provider, &catalog_model, usage.input_tokens)
1768 && pricing.context_tiers.is_empty()
1769 {
1770 return TurnCostAudit::unpriced(UnpricedReason::UnrepresentedTier);
1771 }
1772 return audit_pricing_pair(pricing, secondary, usage);
1773 }
1774 if reviewed_provider_live {
1775 return if provider == ProviderKind::Openrouter {
1776 audit_openrouter_immutable_pricing(model, usage, recorded_at)
1777 } else {
1778 TurnCostAudit::unpriced(UnpricedReason::UnverifiedLivePricing)
1779 };
1780 }
1781
1782 if provider == ProviderKind::Openrouter && provider_identity.is_some() {
1783 // A persisted built-in OpenRouter receipt that is missing the exact
1784 // official identity/endpoint binding (or its frozen quote) must not
1785 // fall through to the mutable process-wide provider lake.
1786 return TurnCostAudit::unpriced(UnpricedReason::UnverifiedLivePricing);
1787 }
1788 if provider == ProviderKind::Custom {
1789 return TurnCostAudit::unpriced(UnpricedReason::UnknownBillingBasis);
1790 }
1791 audit_turn_cost_for_provider_on_endpoint_for_identity_at(
1792 provider,
1793 provider_identity,
1794 model,
1795 endpoint_fingerprint,
1796 usage,
1797 recorded_at,
1798 false,
1799 None,
1800 )
1801 }
1802
1803 fn audit_offering_pricing(pricing: OfferingPricing, usage: &Usage) -> TurnCostAudit {
1804 if pricing.rate_withheld {
1805 return TurnCostAudit::unpriced(UnpricedReason::NoPricingRow);
1806 }
1807 let classes = token_usage_for_pricing(usage);
1808 let quote = match pricing.quote_cost(&classes) {
1809 Ok(quote) => quote,
1810 Err(PricingQuoteError::MissingRate(class)) => {
1811 let mut missing = pricing.unpriced_used_classes(&classes);
1812 if !missing.contains(&class) {
1813 missing.push(class);
1814 }
1815 return TurnCostAudit::missing_classes(pricing.provenance, missing);
1816 }
1817 Err(PricingQuoteError::MissingUsage(_)) => {
1818 return TurnCostAudit::unpriced(UnpricedReason::MissingUsageBreakdown);
1819 }
1820 Err(PricingQuoteError::UnsupportedTier) => {
1821 return TurnCostAudit::unpriced(UnpricedReason::UnrepresentedTier);
1822 }
1823 Err(PricingQuoteError::InvalidUsage) => {
1824 return TurnCostAudit::unpriced(UnpricedReason::InconsistentUsage);
1825 }
1826 Err(PricingQuoteError::InvalidRate) => {
1827 return TurnCostAudit::unpriced(UnpricedReason::InvalidPricingRow);
1828 }
1829 };
1830 let Ok(amount) = quote.amount.parse::<f64>() else {
1831 return TurnCostAudit::unpriced(UnpricedReason::InvalidPricingRow);
1832 };
1833 let (estimate, usd, cny) = match quote.currency {
1834 Currency::Usd => (CostEstimate::usd_only(amount), true, false),
1835 Currency::Cny => (
1836 CostEstimate {
1837 usd: 0.0,
1838 cny: amount,
1839 },
1840 false,
1841 true,
1842 ),
1843 Currency::Other(_) => return TurnCostAudit::unpriced(UnpricedReason::UnsupportedCurrency),
1844 };
1845 let mut audit = TurnCostAudit::priced(estimate, pricing.provenance, usd, cny);
1846 if usd {
1847 audit.exact_usd = Some(quote.amount);
1848 } else {
1849 audit.exact_cny = Some(quote.amount);
1850 }
1851 audit
1852 }
1853
1854 /// Price an exact official OpenRouter route without consulting mutable live
1855 /// catalog state. This is the no-quote application-dispatch fallback used when
1856 /// CodeWhale starts offline or the provider refresh has not completed yet.
1857 fn audit_openrouter_immutable_pricing(
1858 model: &str,
1859 usage: &Usage,
1860 recorded_at: DateTime<Utc>,
1861 ) -> TurnCostAudit {
1862 let Some(canonical_model) = resolved_pricing_model(ProviderKind::Openrouter, model) else {
1863 return TurnCostAudit::unpriced(UnpricedReason::NoPricingRow);
1864 };
1865 if let Some(offering) = crate::provider_lake::bundled_catalog_offering_for_model(
1866 ProviderKind::Openrouter,
1867 &canonical_model,
1868 ) {
1869 if let Some(audit) = refused_catalog_pricing_audit(&offering, usage) {
1870 return audit;
1871 }
1872 if let Some(pricing) = OfferingPricing::from_catalog_offering(&offering) {
1873 return audit_offering_pricing(pricing, usage);
1874 }
1875 }
1876
1877 hand_priced_audit(
1878 provider_owned_hand_pricing_at(ProviderKind::Openrouter, &canonical_model, recorded_at),
1879 usage,
1880 )
1881 }
1882
1883 /// Whether a named custom route has a reviewed per-token billing contract.
1884 ///
1885 /// Baseten is accepted only through the fingerprint of its documented Model
1886 /// APIs endpoint (#6289). The table name is irrelevant: a Baseten identity
1887 /// pointed at another host cannot become metered, and any table pointed at
1888 /// Baseten carries Baseten's billing contract. A priced `/models` row alone
1889 /// never mints metering.
1890 #[must_use]
1891 pub fn reviewed_custom_route_is_metered(
1892 provider: ProviderKind,
1893 endpoint_fingerprint: Option<&str>,
1894 ) -> bool {
1895 if provider != ProviderKind::Custom {
1896 return false;
1897 }
1898 endpoint_fingerprint.is_some_and(|fingerprint| {
1899 fingerprint
1900 == codewhale_config::catalog::base_url_fingerprint(
1901 codewhale_config::catalog::BASETEN_BASE_URL,
1902 )
1903 })
1904 }
1905
1906 /// Exact routes whose mutable provider-live rates must be frozen at the
1907 /// pre-permit application-dispatch boundary.
1908 ///
1909 /// OpenRouter is accepted only as the built-in identity on its official API;
1910 /// a custom table shadowing that name or an endpoint override is a different
1911 /// billing contract. Custom tables are metered only on Baseten's endpoint
1912 /// fingerprint and retain their exact, case-sensitive cache ownership.
1913 #[must_use]
1914 fn reviewed_provider_live_route_is_metered(
1915 provider: ProviderKind,
1916 provider_identity: Option<&str>,
1917 endpoint_fingerprint: Option<&str>,
1918 ) -> bool {
1919 match provider {
1920 ProviderKind::Openrouter => {
1921 provider_identity.map(str::trim) == Some(ProviderKind::Openrouter.as_str())
1922 && endpoint_fingerprint.is_some_and(|fingerprint| {
1923 fingerprint
1924 == codewhale_config::catalog::base_url_fingerprint(
1925 codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL,
1926 )
1927 })
1928 }
1929 ProviderKind::Custom => reviewed_custom_route_is_metered(provider, endpoint_fingerprint),
1930 _ => false,
1931 }
1932 }
1933
1934 /// Audit a turn against the route's billing presentation.
1935 ///
1936 /// The three non-metered presentations are **not** interchangeable, and
1937 /// collapsing them was the bug (#4318):
1938 ///
1939 /// - [`BillingPresentation::Subscription`] and [`BillingPresentation::Local`]
1940 /// are exact evidence that money is the wrong unit, so those turns are
1941 /// `NotMoneyMetered` and drop out of the coverage denominator.
1942 /// - [`BillingPresentation::Unknown`] is *not* such evidence. It means CodeWhale
1943 /// could not establish the basis, so the turn is `UnknownBillingBasis`: still
1944 /// unpriced, but counted as spend the total may be missing.
1945 ///
1946 /// [`BillingPresentation::Subscription`]: crate::route_billing::BillingPresentation::Subscription
1947 /// [`BillingPresentation::Local`]: crate::route_billing::BillingPresentation::Local
1948 /// [`BillingPresentation::Unknown`]: crate::route_billing::BillingPresentation::Unknown
1949 #[must_use]
1950 #[cfg(any(test, feature = "test-support"))]
1951 pub fn audit_turn_cost_for_route(
1952 provider: ProviderKind,
1953 model: &str,
1954 billing_surface: Option<&str>,
1955 usage: &Usage,
1956 recorded_at: DateTime<Utc>,
1957 billing: crate::route_billing::BillingPresentation,
1958 ) -> TurnCostAudit {
1959 audit_turn_cost_for_route_on_endpoint(
1960 provider,
1961 model,
1962 billing_surface,
1963 None,
1964 usage,
1965 recorded_at,
1966 billing,
1967 )
1968 }
1969
1970 /// [`audit_turn_cost_for_route`] plus the endpoint fingerprint that lets live
1971 /// catalog pricing be verified for this exact route.
1972 #[must_use]
1973 #[cfg(any(test, feature = "test-support"))]
1974 pub fn audit_turn_cost_for_route_on_endpoint(
1975 provider: ProviderKind,
1976 model: &str,
1977 billing_surface: Option<&str>,
1978 endpoint_fingerprint: Option<&str>,
1979 usage: &Usage,
1980 recorded_at: DateTime<Utc>,
1981 billing: crate::route_billing::BillingPresentation,
1982 ) -> TurnCostAudit {
1983 use crate::route_billing::BillingPresentation;
1984 match billing {
1985 BillingPresentation::Subscription(_) | BillingPresentation::Local => {
1986 return TurnCostAudit::unpriced(UnpricedReason::NotMoneyMetered);
1987 }
1988 BillingPresentation::Unknown => {
1989 return TurnCostAudit::unpriced(UnpricedReason::UnknownBillingBasis);
1990 }
1991 BillingPresentation::Metered => {}
1992 }
1993 // A metered presentation still has to survive the endpoint classification:
1994 // an endpoint that classifies as an exact subscription surface overrides a
1995 // metered guess, and an unclassifiable one fails closed.
1996 match endpoint_metering_for_billing_surface(billing_surface) {
1997 EndpointMetering::ExactSubscription | EndpointMetering::LocalNoBill => {
1998 return TurnCostAudit::unpriced(UnpricedReason::NotMoneyMetered);
1999 }
2000 // `Unknown` here is the common, benign case of a caller that has no
2001 // endpoint to classify; the provider/model path below still decides.
2002 EndpointMetering::Unknown if billing_surface.is_some() => {
2003 return TurnCostAudit::unpriced(UnpricedReason::UnknownBillingBasis);
2004 }
2005 EndpointMetering::Unknown | EndpointMetering::Money => {}
2006 }
2007 audit_turn_cost_for_route_on_endpoint_at(
2008 provider,
2009 model,
2010 billing_surface,
2011 endpoint_fingerprint,
2012 usage,
2013 recorded_at,
2014 )
2015 }
2016
2017 /// The offering's pricing row as it actually applies to this route.
2018 ///
2019 /// Two documented first-party routes publish no separate cache rate *because*
2020 /// cache tokens are billed at the plain input rate; that substitution happens
2021 /// here so cost estimation and the unpriced-class audit read the same row.
2022 fn effective_offering_pricing(
2023 provider: ProviderKind,
2024 model: &str,
2025 offering: &codewhale_config::catalog::CatalogOffering,
2026 classes: &TokenUsage,
2027 ) -> Option<OfferingPricing> {
2028 let mut pricing = OfferingPricing::from_catalog_offering(offering)?;
2029 let model_lower = model.trim().to_ascii_lowercase();
2030 let cache_uses_input_rate = matches!(
2031 (provider, model_lower.as_str()),
2032 (ProviderKind::Openai, "gpt-5.5-pro") | (ProviderKind::Arcee, "trinity-large-thinking")
2033 );
2034 if cache_uses_input_rate {
2035 if classes.cache_read > 0 && pricing.cache_read_per_million.is_none() {
2036 pricing.cache_read_per_million = pricing.input_per_million;
2037 }
2038 if classes.cache_write > 0 && pricing.cache_write_per_million.is_none() {
2039 pricing.cache_write_per_million = pricing.input_per_million;
2040 }
2041 for tier in &mut pricing.context_tiers {
2042 if classes.cache_read > 0 && tier.cost.cache_read.is_none() {
2043 tier.cost.cache_read = tier.cost.input;
2044 }
2045 if classes.cache_write > 0 && tier.cost.cache_write.is_none() {
2046 tier.cost.cache_write = tier.cost.input;
2047 }
2048 }
2049 }
2050 Some(pricing)
2051 }
2052
2053 /// Estimate usage only from the exact provider offering. Missing prices for a
2054 /// used token class fail closed, except on the two documented first-party
2055 /// routes where cache tokens are explicitly billed at the input rate.
2056 #[cfg(test)]
2057 fn catalog_cost_estimate_for_route(
2058 provider: ProviderKind,
2059 model: &str,
2060 offering: &codewhale_config::catalog::CatalogOffering,
2061 usage: &Usage,
2062 ) -> Option<CostEstimate> {
2063 let classes = token_usage_for_pricing(usage);
2064 let pricing = effective_offering_pricing(provider, model, offering, &classes)?;
2065
2066 let amount = pricing.estimate_cost(&classes)?;
2067 match pricing.currency {
2068 Currency::Usd => Some(CostEstimate::usd_only(amount)),
2069 Currency::Cny => Some(CostEstimate {
2070 usd: 0.0,
2071 cny: amount,
2072 }),
2073 Currency::Other(_) => None,
2074 }
2075 }
2076
2077 /// Project provider-normalized turn usage into canonical billable token
2078 /// classes for the shared config pricing layer (#2961 / #4318).
2079 ///
2080 /// `Usage::prompt_cache_miss_tokens` is billed as ordinary non-cached input.
2081 /// `Usage::prompt_cache_write_tokens` maps to `TokenUsage::cache_write` so
2082 /// providers that publish a write premium (Anthropic 1.25x–2x) are not
2083 /// undercounted.
2084 ///
2085 /// `Usage::reasoning_tokens` is deliberately **not** added to the billable
2086 /// output. Every provider CodeWhale normalizes reports reasoning as a *subset*
2087 /// of the completion count it already bills — OpenAI Responses nests
2088 /// `reasoning_tokens` under `output_tokens_details` while `output_tokens` is
2089 /// the total, and Chat Completions nests it under `completion_tokens_details`
2090 /// while `completion_tokens` is the total. Adding it charged reasoning turns
2091 /// twice for the same tokens (up to 2x on reasoning-heavy turns). It uses
2092 /// its own class when a rate is published, replacing that subset of output.
2093 #[must_use]
2094 pub fn token_usage_for_pricing(usage: &Usage) -> TokenUsage {
2095 let mut classes = request_token_usage_for_pricing(usage);
2096 classes.request_usages = usage
2097 .request_usages
2098 .iter()
2099 .take(1025)
2100 .map(|request| {
2101 let mut classes = request_token_usage_for_pricing(request);
2102 if !request.request_usages.is_empty() {
2103 classes
2104 .request_usages
2105 .push(request_token_usage_for_pricing(request));
2106 }
2107 classes
2108 })
2109 .collect();
2110 classes
2111 }
2112
2113 fn request_token_usage_for_pricing(usage: &Usage) -> TokenUsage {
2114 // `input_tokens` is the authoritative total. Even malformed provider
2115 // telemetry must never produce token classes whose sum exceeds it. The
2116 // audit path rejects contradictory partitions; this bounded projection
2117 // keeps token-only displays truthful while retaining deterministic class
2118 // priority (read, write, then miss/unclassified input).
2119 let total_input = usage.input_tokens;
2120 let cache_read = usage.prompt_cache_hit_tokens.unwrap_or(0).min(total_input);
2121 let after_read = total_input.saturating_sub(cache_read);
2122 let cache_write = usage.prompt_cache_write_tokens.unwrap_or(0).min(after_read);
2123 let after_write = after_read.saturating_sub(cache_write);
2124 let non_cached_reported = usage
2125 .prompt_cache_miss_tokens
2126 .unwrap_or(after_write)
2127 .min(after_write);
2128 let uncategorized_input = after_write.saturating_sub(non_cached_reported);
2129 let input = non_cached_reported.saturating_add(uncategorized_input);
2130 // Reasoning tokens are already inside `output_tokens`; see the doc comment.
2131 let output = usage.output_tokens;
2132 // Subset telemetry is clamped like the cache partition above: malformed
2133 // provider counts that exceed their parent total must never fail the
2134 // whole estimate closed or double-count.
2135 let reasoning = usage
2136 .reasoning_tokens
2137 .map(|tokens| u64::from(tokens.min(output)));
2138 let output_audio = usage.output_audio_tokens.map(|tokens| {
2139 let remaining = u64::from(output).saturating_sub(reasoning.unwrap_or(0));
2140 u64::from(tokens).min(remaining)
2141 });
2142 let input_audio = usage
2143 .input_audio_tokens
2144 .map(|tokens| u64::from(tokens).min(u64::from(input)));
2145
2146 TokenUsage {
2147 input: u64::from(input),
2148 output: u64::from(output),
2149 cache_read: u64::from(cache_read),
2150 cache_write: u64::from(cache_write),
2151
2152 reasoning,
2153 input_audio,
2154 output_audio,
2155
2156 request_usages: Vec::new(),
2157 }
2158 }
2159
2160 pub fn usage_cache_partition_is_consistent(usage: &Usage) -> bool {
2161 let reported = u64::from(usage.prompt_cache_hit_tokens.unwrap_or(0))
2162 + u64::from(usage.prompt_cache_miss_tokens.unwrap_or(0))
2163 + u64::from(usage.prompt_cache_write_tokens.unwrap_or(0));
2164 reported <= u64::from(usage.input_tokens)
2165 }
2166
2167 /// Estimate how much money was saved by serving `cache_hit_tokens` from the
2168 /// prefix cache instead of billing them at the cache-miss rate. Returns `None`
2169 /// when the model's pricing is unknown or the number of cache-hit tokens is
2170 /// zero (nothing to save).
2171 #[must_use]
2172 #[cfg(any(test, feature = "test-support"))]
2173 pub fn calculate_cache_savings(model: &str, cache_hit_tokens: u32) -> Option<CostEstimate> {
2174 if cache_hit_tokens == 0 {
2175 return None;
2176 }
2177 // M3's cache-read savings depend on whether total input crosses 512k;
2178 // this helper receives only cache-hit tokens, so an estimate would guess
2179 // the tier. The full turn-cost path has total input and remains precise.
2180 if is_minimax_m3(model) {
2181 return None;
2182 }
2183 let pricing = pricing_for_model(model)?;
2184 let tokens = cache_hit_tokens as f64 / 1_000_000.0;
2185 Some(CostEstimate {
2186 usd: tokens
2187 * (pricing.usd.input_cache_miss_per_million - pricing.usd.input_cache_hit_per_million),
2188 cny: pricing
2189 .cny
2190 .map(|pricing| {
2191 tokens
2192 * (pricing.input_cache_miss_per_million - pricing.input_cache_hit_per_million)
2193 })
2194 .unwrap_or(0.0),
2195 })
2196 }
2197
2198 /// The route's list price per million tokens, `in $X · out $Y`, when this
2199 /// provider/model pair has authoritative pricing without endpoint
2200 /// provenance. `None` otherwise — the price view omits the row rather than
2201 /// quoting a rate the session is not actually billed at.
2202 #[must_use]
2203 pub fn model_rate_label(
2204 provider: ProviderKind,
2205 model: &str,
2206 currency: CostCurrency,
2207 ) -> Option<String> {
2208 if !has_pricing_for_provider(provider, model) {
2209 return None;
2210 }
2211 let now = Utc::now();
2212 let catalog_model = resolved_pricing_model(provider, model)?;
2213 let format_hand = |pricing: ModelPricing| -> Option<String> {
2214 let rates = match currency {
2215 CostCurrency::Usd => pricing.usd,
2216 CostCurrency::Cny => pricing.cny?,
2217 };
2218 Some(format!(
2219 "in {} · out {}",
2220 format_cost_amount(rates.input_cache_miss_per_million, currency),
2221 format_cost_amount(rates.output_per_million, currency),
2222 ))
2223 };
2224 if hand_pricing_overrides_catalog(provider, &catalog_model)
2225 && let Some(pricing) = provider_owned_hand_pricing_at(provider, &catalog_model, now)
2226 {
2227 return format_hand(pricing);
2228 }
2229 if currency == CostCurrency::Usd
2230 && let VerifiedOffering::Usable(offering)
2231 | VerifiedOffering::DegradedToBundled { offering, .. } =
2232 verified_catalog_offering(provider, None, &catalog_model, None, now, true)
2233 && let Some(pricing) = OfferingPricing::from_catalog_offering_at(
2234 &offering,
2235 u64::try_from(now.timestamp()).unwrap_or(0),
2236 )
2237 && !pricing.rate_withheld
2238 && pricing.currency == Currency::Usd
2239 && let (Some(input), Some(output)) = (pricing.input_per_million, pricing.output_per_million)
2240 {
2241 return Some(format!(
2242 "in {} · out {}",
2243 format_cost_amount(input, currency),
2244 format_cost_amount(output, currency),
2245 ));
2246 }
2247 let pricing = provider_owned_hand_pricing_at(provider, &catalog_model, now)?;
2248 format_hand(pricing)
2249 }
2250
2251 /// Format a cost amount for compact display in the chosen currency.
2252 #[must_use]
2253 pub fn format_cost_amount(cost: f64, currency: CostCurrency) -> String {
2254 let symbol = currency.symbol();
2255 if cost == 0.0 {
2256 format!("{symbol}0.00")
2257 } else if cost > 0.0 && cost < 0.0001 {
2258 format!("<{symbol}0.0001")
2259 } else if cost < 0.01 {
2260 format!("{symbol}{cost:.4}")
2261 } else {
2262 format!("{symbol}{cost:.2}")
2263 }
2264 }
2265
2266 /// Format a dual-currency estimate using the selected display currency.
2267 #[must_use]
2268 pub fn format_cost_estimate(estimate: CostEstimate, currency: CostCurrency) -> String {
2269 format_cost_amount(estimate.amount(currency), currency)
2270 }
2271
2272 #[cfg(test)]
2273 mod default_coverage_tests;
2274
2275 #[cfg(test)]
2276 mod tests {
2277 use super::*;
2278 use chrono::TimeZone;
2279
2280 #[test]
2281 fn malformed_catalog_row_has_an_explicit_runtime_reason() {
2282 let offering = codewhale_config::catalog::CatalogOffering {
2283 provider: "openrouter".to_string(),
2284 wire_model_id: "openai/gpt-5.5".to_string(),
2285 cost: Some(codewhale_config::models_dev::ModelsDevCost {
2286 input: Some(f64::NAN),
2287 output: Some(30.0),
2288 cache_read: Some(0.05),
2289 cache_write: None,
2290 ..Default::default()
2291 }),
2292 ..Default::default()
2293 };
2294
2295 let audit = refused_catalog_pricing_audit(&offering, &Usage::default())
2296 .expect("malformed row must become an explicit failed-closed audit");
2297 assert!(!audit.is_priced());
2298 assert_eq!(
2299 audit.unpriced_reason,
2300 Some(UnpricedReason::InvalidPricingRow)
2301 );
2302 assert_eq!(
2303 audit.unpriced_reason.unwrap().label(),
2304 "invalid_pricing_row"
2305 );
2306 }
2307
2308 /// A hand-sourced row with **no published** cache-write rate must fail closed
2309 /// for a turn that wrote to cache, while a row whose provider *documents*
2310 /// that writes carry no separate charge prices it at the input rate.
2311 ///
2312 /// Both used to be `None` and both silently billed writes at the input rate,
2313 /// which invented a price for the first case (#4318).
2314 #[test]
2315 fn unpublished_cache_write_fails_closed_but_documented_same_rate_prices() {
2316 let write_heavy = Usage {
2317 input_tokens: 1_000_000,
2318 output_tokens: 0,
2319 prompt_cache_hit_tokens: Some(0),
2320 prompt_cache_miss_tokens: Some(900_000),
2321 prompt_cache_write_tokens: Some(100_000),
2322 ..Usage::default()
2323 };
2324 // Pinned off-peak (12:00 UTC) so the DeepSeek tier is deterministic.
2325 let now = Utc
2326 .with_ymd_and_hms(2026, 8, 17, 12, 0, 0)
2327 .single()
2328 .unwrap();
2329
2330 // DeepSeek documents that a cache miss is billed once and cached for
2331 // free, so the miss rate *is* the published write rate. The policy
2332 // carries the documentation receipt rather than being an assumption.
2333 let deepseek = pricing_for_model_at("deepseek-v4-flash", now).expect("Flash pricing");
2334 assert_eq!(
2335 deepseek.usd.cache_write,
2336 CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE)
2337 );
2338 let priced = audit_turn_cost_for_provider_at(
2339 ProviderKind::Deepseek,
2340 "deepseek-v4-flash",
2341 &write_heavy,
2342 now,
2343 );
2344 assert!(priced.is_priced(), "{priced:?}");
2345 // 900k miss + 100k write, both at the off-peak 0.22/M miss rate.
2346 let expected = (0.9 + 0.1) * 0.22;
2347 assert!(
2348 (priced.estimate.expect("priced").usd - expected).abs() < 1e-12,
2349 "{priced:?}"
2350 );
2351
2352 // StepFun's hand row publishes input/cache-read/output only. A write
2353 // turn is unpriced and names the class instead of borrowing the input
2354 // rate.
2355 let stepfun = pricing_for_billing_surface(
2356 ProviderKind::Stepfun,
2357 "step-3.7-flash",
2358 Some(STEPFUN_PAYG_BILLING_SURFACE),
2359 )
2360 .expect("StepFun PAYG row");
2361 assert_eq!(stepfun.usd.cache_write, CacheWritePolicy::Unpublished);
2362 let failed = audit_turn_cost_for_route_at(
2363 ProviderKind::Stepfun,
2364 "step-3.7-flash",
2365 Some(STEPFUN_PAYG_BILLING_SURFACE),
2366 &write_heavy,
2367 now,
2368 );
2369 assert!(!failed.is_priced(), "{failed:?}");
2370 assert_eq!(
2371 failed.unpriced_reason,
2372 Some(UnpricedReason::MissingClassPrice)
2373 );
2374 assert_eq!(failed.unpriced_classes, vec![TokenClass::CacheWrite]);
2375
2376 // The same route with no cache-write tokens prices normally, proving the
2377 // gap is class-scoped rather than route-scoped.
2378 let no_write = Usage {
2379 prompt_cache_write_tokens: None,
2380 ..write_heavy.clone()
2381 };
2382 assert!(
2383 audit_turn_cost_for_route_at(
2384 ProviderKind::Stepfun,
2385 "step-3.7-flash",
2386 Some(STEPFUN_PAYG_BILLING_SURFACE),
2387 &no_write,
2388 now,
2389 )
2390 .is_priced()
2391 );
2392 }
2393
2394 /// Every exact billing surface a route can carry must be understood, and
2395 /// anything unrecognized must fail closed as unknown rather than defaulting
2396 /// into per-token dollars (#4318).
2397 #[test]
2398 fn official_chatgpt_api_requires_the_exact_secure_base() {
2399 for endpoint in ["https://api.openai.com/v1", "https://api.openai.com/v1/"] {
2400 assert!(is_official_chatgpt_api(endpoint), "{endpoint}");
2401 }
2402 for endpoint in [
2403 "http://api.openai.com/v1",
2404 "https://api.openai.com:444/v1",
2405 "https://api.openai.com.example.net/v1",
2406 "https://api.openai.com/v1/responses",
2407 "https://api.openai.com/v1?route=plan",
2408 "https://api.openai.com/v1#plan",
2409 "https://user:secret@api.openai.com/v1",
2410 "https://chatgpt.com/backend-api",
2411 "",
2412 ] {
2413 assert!(!is_official_chatgpt_api(endpoint), "{endpoint}");
2414 }
2415 }
2416
2417 #[test]
2418 fn public_chatgpt_endpoint_does_not_prove_a_plan_without_grant_provenance() {
2419 assert_eq!(
2420 billing_surface_for_route(ProviderKind::OpenaiCodex, Some("https://api.openai.com/v1")),
2421 Some(UNCLASSIFIED_BILLING_SURFACE)
2422 );
2423 assert_eq!(
2424 billing_surface_for_route(ProviderKind::Openai, Some("https://api.openai.com/v1")),
2425 Some(FIRST_PARTY_PAYG_BILLING_SURFACE)
2426 );
2427 assert_eq!(
2428 billing_surface_for_route(
2429 ProviderKind::OpenaiCodex,
2430 Some("https://chatgpt.com/backend-api/codex")
2431 ),
2432 Some(OAUTH_SUBSCRIPTION_BILLING_SURFACE)
2433 );
2434 }
2435
2436 #[test]
2437 fn endpoint_classification_covers_every_exact_billing_surface() {
2438 for (provider, base_url, expected_surface, expected_metering) in [
2439 (
2440 ProviderKind::Zai,
2441 "https://api.z.ai/api/coding/paas/v4",
2442 ZAI_CODING_PLAN_BILLING_SURFACE,
2443 EndpointMetering::ExactSubscription,
2444 ),
2445 (
2446 ProviderKind::Zai,
2447 "https://api.z.ai/api/paas/v4",
2448 ZAI_PAYG_BILLING_SURFACE,
2449 EndpointMetering::Money,
2450 ),
2451 (
2452 ProviderKind::Moonshot,
2453 codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL,
2454 MOONSHOT_KIMI_CODE_BILLING_SURFACE,
2455 EndpointMetering::ExactSubscription,
2456 ),
2457 (
2458 ProviderKind::Moonshot,
2459 "https://api.moonshot.ai/v1",
2460 MOONSHOT_PAYG_BILLING_SURFACE,
2461 EndpointMetering::Money,
2462 ),
2463 (
2464 ProviderKind::XiaomiMimo,
2465 codewhale_runtime::config::XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL,
2466 XIAOMI_PAYG_BILLING_SURFACE,
2467 EndpointMetering::Money,
2468 ),
2469 (
2470 ProviderKind::XiaomiMimo,
2471 codewhale_config::descriptors::defaults::DEFAULT_XIAOMI_MIMO_BASE_URL,
2472 XIAOMI_TOKEN_PLAN_BILLING_SURFACE,
2473 EndpointMetering::ExactSubscription,
2474 ),
2475 (
2476 ProviderKind::Stepfun,
2477 "https://api.stepfun.ai/step_plan/v1",
2478 STEPFUN_PLAN_BILLING_SURFACE,
2479 EndpointMetering::ExactSubscription,
2480 ),
2481 (
2482 ProviderKind::Stepfun,
2483 "https://api.stepfun.ai/v1",
2484 STEPFUN_PAYG_BILLING_SURFACE,
2485 EndpointMetering::Money,
2486 ),
2487 (
2488 ProviderKind::Anthropic,
2489 "https://api.anthropic.com/v1",
2490 FIRST_PARTY_PAYG_BILLING_SURFACE,
2491 EndpointMetering::Money,
2492 ),
2493 (
2494 ProviderKind::Openrouter,
2495 "https://openrouter.ai/api/v1",
2496 AGGREGATOR_BILLING_SURFACE,
2497 EndpointMetering::Money,
2498 ),
2499 (
2500 ProviderKind::Orcarouter,
2501 "https://api.orcarouter.ai/v1",
2502 AGGREGATOR_BILLING_SURFACE,
2503 EndpointMetering::Money,
2504 ),
2505 ] {
2506 let surface = billing_surface_for_route(provider, Some(base_url));
2507 assert_eq!(surface, Some(expected_surface), "{provider:?} {base_url}");
2508 assert_eq!(
2509 endpoint_metering_for_billing_surface(surface),
2510 expected_metering,
2511 "{provider:?} {base_url}"
2512 );
2513 }
2514
2515 // Provider-intrinsic surfaces need no URL at all.
2516 for (provider, expected_surface, expected_metering) in [
2517 (
2518 ProviderKind::OpenaiCodex,
2519 UNCLASSIFIED_BILLING_SURFACE,
2520 EndpointMetering::Unknown,
2521 ),
2522 (
2523 ProviderKind::OpencodeGo,
2524 OAUTH_SUBSCRIPTION_BILLING_SURFACE,
2525 EndpointMetering::ExactSubscription,
2526 ),
2527 (
2528 ProviderKind::Ollama,
2529 LOCAL_BILLING_SURFACE,
2530 EndpointMetering::LocalNoBill,
2531 ),
2532 (
2533 ProviderKind::OllamaCloud,
2534 UNCLASSIFIED_BILLING_SURFACE,
2535 EndpointMetering::Unknown,
2536 ),
2537 (
2538 ProviderKind::Vllm,
2539 LOCAL_BILLING_SURFACE,
2540 EndpointMetering::LocalNoBill,
2541 ),
2542 // A named custom endpoint's pay mode is config, not URL shape.
2543 (
2544 ProviderKind::Custom,
2545 UNCLASSIFIED_BILLING_SURFACE,
2546 EndpointMetering::Unknown,
2547 ),
2548 ] {
2549 let surface = billing_surface_for_route(provider, None);
2550 assert_eq!(surface, Some(expected_surface), "{provider:?}");
2551 assert_eq!(
2552 endpoint_metering_for_billing_surface(surface),
2553 expected_metering,
2554 "{provider:?}"
2555 );
2556 }
2557
2558 // An unrecognized surface id — including one a newer build might write —
2559 // is never guessed into a known bucket.
2560 for unknown in [
2561 Some("some-future-surface"),
2562 Some(""),
2563 Some(" "),
2564 Some(UNCLASSIFIED_BILLING_SURFACE),
2565 None,
2566 ] {
2567 assert_eq!(
2568 endpoint_metering_for_billing_surface(unknown),
2569 EndpointMetering::Unknown,
2570 "{unknown:?}"
2571 );
2572 }
2573 }
2574
2575 /// An endpoint that was never established is not the official endpoint.
2576 ///
2577 /// The route audit used to fall through to the provider/model catalog when
2578 /// no billing surface was supplied, which meant a persisted or recorded row
2579 /// carrying nothing but `provider: "openai"` and a familiar model id got
2580 /// billed at OpenAI's published first-party rates — even though the turn
2581 /// could equally have been served by a proxy, a gateway, or a self-hosted
2582 /// clone speaking the same protocol. Absence of endpoint evidence is not
2583 /// evidence of the official endpoint.
2584 #[test]
2585 fn an_unestablished_endpoint_is_never_priced_as_the_official_one() {
2586 let usage = Usage {
2587 input_tokens: 10_000,
2588 output_tokens: 1_000,
2589 ..Usage::default()
2590 };
2591 let now = Utc::now();
2592 for (provider, model) in [
2593 (ProviderKind::Openai, "gpt-5.5"),
2594 (ProviderKind::Anthropic, "claude-haiku-4-5"),
2595 (ProviderKind::Deepseek, "deepseek-v4-flash"),
2596 (ProviderKind::Openrouter, "openai/gpt-5.5"),
2597 (ProviderKind::Moonshot, "kimi-k2.7-code"),
2598 ] {
2599 let audit = audit_turn_cost_for_route_at(provider, model, None, &usage, now);
2600 assert_eq!(
2601 audit.unpriced_reason,
2602 Some(UnpricedReason::UnestablishedEndpoint),
2603 "{provider:?}/{model}: {audit:?}"
2604 );
2605 assert!(!audit.is_priced(), "{provider:?}/{model}: {audit:?}");
2606 assert_eq!(audit.estimate, None, "{provider:?}/{model}");
2607 // An unknown route is still possibly-spent money, so it stays in
2608 // the coverage denominator rather than being excused like an OAuth
2609 // or local route.
2610 assert!(
2611 audit.counts_toward_money_coverage(),
2612 "{provider:?}/{model}: an unknown route must not leave money coverage"
2613 );
2614
2615 // The same route with its endpoint actually classified prices
2616 // normally: this is a fail-closed rule, not a refusal to price.
2617 // (OpenRouter is excluded here only because its aggregator surface
2618 // carries no bundled rate at all, which is a different gap.)
2619 if provider == ProviderKind::Openrouter {
2620 continue;
2621 }
2622 let classified = audit_turn_cost_for_route_at(
2623 provider,
2624 model,
2625 billing_surface_for_route(provider, Some(provider.provider().default_base_url())),
2626 &usage,
2627 now,
2628 );
2629 assert!(
2630 classified.is_priced(),
2631 "{provider:?}/{model} must price on its own official endpoint: {classified:?}"
2632 );
2633 }
2634
2635 // The distinction is preserved end to end: "no endpoint offered" and
2636 // "endpoint offered but unplaceable" are different findings, and
2637 // neither is a price.
2638 let unplaceable = audit_turn_cost_for_route_at(
2639 ProviderKind::Openai,
2640 "gpt-5.5",
2641 billing_surface_for_route(ProviderKind::Openai, Some("https://proxy.example/v1")),
2642 &usage,
2643 now,
2644 );
2645 assert_eq!(
2646 unplaceable.unpriced_reason,
2647 Some(UnpricedReason::UnknownBillingBasis)
2648 );
2649 }
2650
2651 #[test]
2652 fn builtin_provider_names_do_not_price_unofficial_proxy_endpoints() {
2653 let usage = Usage {
2654 input_tokens: 10_000,
2655 output_tokens: 1_000,
2656 ..Usage::default()
2657 };
2658 for (provider, model) in [
2659 (ProviderKind::Deepseek, "deepseek-v4-flash"),
2660 (ProviderKind::Openai, "gpt-5.5"),
2661 (ProviderKind::Anthropic, "claude-haiku-4-5"),
2662 (ProviderKind::Openrouter, "openai/gpt-5.5"),
2663 ] {
2664 let surface = billing_surface_for_route(provider, Some("https://proxy.example/v1"));
2665 assert_eq!(surface, Some(UNCLASSIFIED_BILLING_SURFACE), "{provider:?}");
2666 let audit = audit_turn_cost_for_route_at(provider, model, surface, &usage, Utc::now());
2667 assert_eq!(
2668 audit.unpriced_reason,
2669 Some(UnpricedReason::UnknownBillingBasis),
2670 "{provider:?}: {audit:?}"
2671 );
2672 assert!(!audit.is_priced(), "{provider:?}: {audit:?}");
2673 }
2674
2675 assert_eq!(
2676 billing_surface_for_route(
2677 ProviderKind::Moonshot,
2678 Some(codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL)
2679 ),
2680 Some(MOONSHOT_KIMI_CODE_BILLING_SURFACE)
2681 );
2682 for (provider, endpoint) in [
2683 (ProviderKind::Minimax, "https://api.minimax.io/v1"),
2684 (
2685 ProviderKind::MinimaxAnthropic,
2686 "https://api.minimax.io/anthropic",
2687 ),
2688 (
2689 ProviderKind::Minimax,
2690 "https://api.minimax.io/v1/token-plan",
2691 ),
2692 (
2693 ProviderKind::XiaomiMimo,
2694 "https://token-plan-proxy.example/v1",
2695 ),
2696 (
2697 ProviderKind::Zai,
2698 "https://api.z.ai/api/coding/something-else",
2699 ),
2700 ] {
2701 assert_eq!(
2702 billing_surface_for_route(provider, Some(endpoint)),
2703 Some(UNCLASSIFIED_BILLING_SURFACE),
2704 "{provider:?} {endpoint}"
2705 );
2706 }
2707 }
2708
2709 /// A route classified as an exact subscription surface is not money-metered
2710 /// even when the provider-level presentation guessed "metered", and it must
2711 /// never reach a per-token rate.
2712 #[test]
2713 fn exact_plan_surface_overrides_a_metered_presentation() {
2714 let usage = Usage {
2715 input_tokens: 100_000,
2716 output_tokens: 10_000,
2717 ..Usage::default()
2718 };
2719 let audit = audit_turn_cost_for_route(
2720 ProviderKind::Zai,
2721 "glm-5.2",
2722 Some(ZAI_CODING_PLAN_BILLING_SURFACE),
2723 &usage,
2724 Utc::now(),
2725 crate::route_billing::BillingPresentation::Metered,
2726 );
2727 assert!(!audit.is_priced(), "{audit:?}");
2728 assert_eq!(audit.unpriced_reason, Some(UnpricedReason::NotMoneyMetered));
2729 assert!(!audit.counts_toward_money_coverage());
2730
2731 // The same model on the per-token surface is money-metered, so it stays
2732 // in the coverage denominator whether or not a price is found.
2733 let payg = audit_turn_cost_for_route(
2734 ProviderKind::Zai,
2735 "glm-5.2",
2736 Some(ZAI_PAYG_BILLING_SURFACE),
2737 &usage,
2738 Utc::now(),
2739 crate::route_billing::BillingPresentation::Metered,
2740 );
2741 assert!(payg.counts_toward_money_coverage(), "{payg:?}");
2742 }
2743
2744 /// An unknown billing basis is *not* a subscription. It stays unpriced and
2745 /// stays inside the money-coverage denominator, so its spend is reported as
2746 /// missing rather than excused (#4318).
2747 #[test]
2748 fn unknown_billing_basis_is_not_excused_as_not_money_metered() {
2749 let usage = Usage {
2750 input_tokens: 10_000,
2751 output_tokens: 1_000,
2752 ..Usage::default()
2753 };
2754 let unknown = audit_turn_cost_for_route(
2755 ProviderKind::Anthropic,
2756 "claude-haiku-4-5",
2757 None,
2758 &usage,
2759 Utc::now(),
2760 crate::route_billing::BillingPresentation::Unknown,
2761 );
2762 assert!(!unknown.is_priced());
2763 assert_eq!(
2764 unknown.unpriced_reason,
2765 Some(UnpricedReason::UnknownBillingBasis)
2766 );
2767 assert!(unknown.counts_toward_money_coverage());
2768
2769 // Local and subscription presentations are exact, so they *are* excused.
2770 for billing in [
2771 crate::route_billing::BillingPresentation::Local,
2772 crate::route_billing::BillingPresentation::Subscription("plan"),
2773 ] {
2774 let audit = audit_turn_cost_for_route(
2775 ProviderKind::Anthropic,
2776 "claude-haiku-4-5",
2777 None,
2778 &usage,
2779 Utc::now(),
2780 billing,
2781 );
2782 assert_eq!(audit.unpriced_reason, Some(UnpricedReason::NotMoneyMetered));
2783 assert!(!audit.counts_toward_money_coverage());
2784 }
2785 }
2786
2787 #[test]
2788 fn audit_names_why_a_turn_is_missing_from_a_total() {
2789 let write_heavy = Usage {
2790 input_tokens: 1_000_000,
2791 output_tokens: 100_000,
2792 prompt_cache_hit_tokens: Some(200_000),
2793 prompt_cache_write_tokens: Some(100_000),
2794 ..Usage::default()
2795 };
2796
2797 // Anthropic publishes a cache-write rate: fully priced, provenance kept.
2798 let priced = audit_turn_cost_for_provider_at(
2799 ProviderKind::Anthropic,
2800 "claude-haiku-4-5",
2801 &write_heavy,
2802 Utc::now(),
2803 );
2804 assert!(priced.is_priced());
2805 assert_eq!(priced.unpriced_reason, None);
2806 assert!(priced.unpriced_classes.is_empty());
2807 assert!(priced.provenance.is_some());
2808
2809 // Moonshot does not: the turn fails closed and names the class.
2810 let missing = audit_turn_cost_for_provider_at(
2811 ProviderKind::Moonshot,
2812 "kimi-k2.7-code",
2813 &write_heavy,
2814 Utc::now(),
2815 );
2816 assert!(!missing.is_priced());
2817 assert_eq!(
2818 missing.unpriced_reason,
2819 Some(UnpricedReason::MissingClassPrice)
2820 );
2821 assert_eq!(missing.unpriced_classes, vec![TokenClass::CacheWrite]);
2822 // Dropping the write tokens makes the very same route priceable, which
2823 // proves the gap is class-scoped rather than route-scoped.
2824 let no_write = Usage {
2825 prompt_cache_write_tokens: None,
2826 ..write_heavy.clone()
2827 };
2828 assert!(
2829 audit_turn_cost_for_provider_at(
2830 ProviderKind::Moonshot,
2831 "kimi-k2.7-code",
2832 &no_write,
2833 Utc::now(),
2834 )
2835 .is_priced()
2836 );
2837
2838 // Subscription/OAuth and ambiguous-surface routes report their own
2839 // reasons rather than an absent price.
2840 assert_eq!(
2841 audit_turn_cost_for_provider_at(
2842 ProviderKind::OpenaiCodex,
2843 "gpt-5.5",
2844 &write_heavy,
2845 Utc::now(),
2846 )
2847 .unpriced_reason,
2848 Some(UnpricedReason::AmbiguousBillingSurface)
2849 );
2850 assert_eq!(
2851 audit_turn_cost_for_route_at(
2852 ProviderKind::Stepfun,
2853 DEFAULT_STEPFUN_MODEL,
2854 None,
2855 &write_heavy,
2856 Utc::now(),
2857 )
2858 .unpriced_reason,
2859 Some(UnpricedReason::AmbiguousBillingSurface)
2860 );
2861 assert_eq!(
2862 audit_turn_cost_for_provider_at(
2863 ProviderKind::Openai,
2864 "gpt-5.5",
2865 &Usage {
2866 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
2867 ..Usage::default()
2868 },
2869 Utc::now(),
2870 )
2871 .unpriced_reason,
2872 Some(UnpricedReason::UnrepresentedTier)
2873 );
2874 }
2875
2876 /// The audit and the estimator are the same computation, so every route
2877 /// must agree on whether it produced a number.
2878 #[test]
2879 fn audit_and_estimate_never_disagree() {
2880 let usage = Usage {
2881 input_tokens: 10_000,
2882 output_tokens: 1_000,
2883 prompt_cache_hit_tokens: Some(2_000),
2884 prompt_cache_write_tokens: Some(1_000),
2885 ..Usage::default()
2886 };
2887 let now = Utc::now();
2888 for (provider, model) in [
2889 (ProviderKind::Anthropic, "claude-haiku-4-5"),
2890 (ProviderKind::Anthropic, "claude-sonnet-5"),
2891 (ProviderKind::Moonshot, "kimi-k2.7-code"),
2892 (ProviderKind::Openai, "gpt-5.5"),
2893 (ProviderKind::OpenaiCodex, "gpt-5.5"),
2894 (ProviderKind::Deepseek, "deepseek-v4-pro"),
2895 (ProviderKind::Ollama, "gpt-5.5"),
2896 (ProviderKind::Stepfun, DEFAULT_STEPFUN_MODEL),
2897 ] {
2898 let audit = audit_turn_cost_for_route_at(provider, model, None, &usage, now);
2899 let estimate =
2900 calculate_turn_cost_estimate_for_route_at(provider, model, None, &usage, now);
2901 assert_eq!(audit.estimate, estimate, "{provider:?}/{model}");
2902 assert_eq!(
2903 audit.is_priced(),
2904 audit.unpriced_reason.is_none(),
2905 "{provider:?}/{model}"
2906 );
2907 }
2908 }
2909
2910 #[test]
2911 fn nvidia_nim_deepseek_model_does_not_use_deepseek_platform_pricing() {
2912 assert!(!has_pricing_for_model("deepseek-ai/deepseek-v4-pro"));
2913 }
2914
2915 #[test]
2916 fn stepfun_current_model_rates_require_payg_provenance() {
2917 for (model, cache, input, output) in [
2918 ("step-5-preview", 0.05, 1.00, 2.70),
2919 ("step-3.7-flash", 0.04, 0.20, 1.15),
2920 ("step-3.5-flash", 0.02, 0.10, 0.30),
2921 ("step-3.5-flash-2603", 0.02, 0.10, 0.30),
2922 ] {
2923 let price = pricing_for_billing_surface(
2924 ProviderKind::Stepfun,
2925 model,
2926 Some(STEPFUN_PAYG_BILLING_SURFACE),
2927 )
2928 .unwrap();
2929 assert_eq!(price.usd.input_cache_hit_per_million, cache);
2930 assert_eq!(price.usd.input_cache_miss_per_million, input);
2931 assert_eq!(price.usd.output_per_million, output);
2932 assert!(
2933 pricing_for_billing_surface(
2934 ProviderKind::Stepfun,
2935 model,
2936 Some(STEPFUN_PLAN_BILLING_SURFACE)
2937 )
2938 .is_none()
2939 );
2940 assert!(route_requires_billing_surface(ProviderKind::Custom, model));
2941 assert!(!has_pricing_for_provider(ProviderKind::Stepfun, model));
2942 }
2943 }
2944
2945 #[test]
2946 fn stepfun_billing_surface_keeps_payg_separate_from_step_plan() {
2947 for base_url in [
2948 "https://api.stepfun.ai",
2949 "https://api.stepfun.ai/",
2950 "https://api.stepfun.ai/v1",
2951 "https://API.STEPFUN.AI/v1/",
2952 ] {
2953 assert_eq!(
2954 billing_surface_for_route(ProviderKind::Stepfun, Some(base_url)),
2955 Some(STEPFUN_PAYG_BILLING_SURFACE),
2956 "{base_url}"
2957 );
2958 }
2959 for base_url in [
2960 "https://api.stepfun.ai/step_plan",
2961 "https://api.stepfun.ai/step_plan/v1/",
2962 "https://api.stepfun.com/step_plan/v1",
2963 ] {
2964 assert_eq!(
2965 billing_surface_for_route(ProviderKind::Stepfun, Some(base_url)),
2966 Some(STEPFUN_PLAN_BILLING_SURFACE),
2967 "{base_url}"
2968 );
2969 }
2970 // Endpoints CodeWhale cannot place now classify *positively* as
2971 // unclassified rather than returning `None`. Both fail closed
2972 // identically, but "we looked and could not place this" is a different
2973 // fact from "no endpoint was supplied", and the audit reports it as
2974 // such (#4318).
2975 for base_url in [
2976 "http://api.stepfun.ai/v1",
2977 "https://token@api.stepfun.ai/v1",
2978 "https://api.stepfun.ai/v1?account=other",
2979 "https://api.stepfun.ai/STEP_PLAN/v1",
2980 "https://stepfun.example/v1",
2981 ] {
2982 assert_eq!(
2983 billing_surface_for_route(ProviderKind::Stepfun, Some(base_url)),
2984 Some(UNCLASSIFIED_BILLING_SURFACE),
2985 "{base_url}"
2986 );
2987 assert_eq!(
2988 endpoint_metering_for_billing_surface(Some(UNCLASSIFIED_BILLING_SURFACE)),
2989 EndpointMetering::Unknown
2990 );
2991 }
2992 // A StepFun URL paired with the OpenRouter protocol is a foreign custom
2993 // endpoint, not proof of either provider's billing surface.
2994 assert_eq!(
2995 billing_surface_for_route(ProviderKind::Openrouter, Some(DEFAULT_STEPFUN_BASE_URL)),
2996 Some(UNCLASSIFIED_BILLING_SURFACE)
2997 );
2998 // No endpoint at all stays `None`.
2999 assert_eq!(
3000 billing_surface_for_route(ProviderKind::Stepfun, None),
3001 None,
3002 "an absent endpoint is not a classification"
3003 );
3004
3005 let usage = Usage {
3006 input_tokens: 1_000_000,
3007 output_tokens: 500_000,
3008 prompt_cache_hit_tokens: Some(250_000),
3009 ..Default::default()
3010 };
3011 let payg = calculate_turn_cost_estimate_for_billing_surface(
3012 ProviderKind::Stepfun,
3013 "step-3.7-flash",
3014 Some(STEPFUN_PAYG_BILLING_SURFACE),
3015 &usage,
3016 )
3017 .expect("standard StepFun API has an authoritative token price");
3018 assert!((payg.usd - 0.735).abs() < 1e-12);
3019 assert_eq!(payg.cny, 0.0);
3020
3021 // Provider/model-only legacy callers cannot distinguish PAYG from Step
3022 // Plan and must not add either route to spend or savings totals.
3023 assert!(
3024 calculate_turn_cost_estimate_for_provider(
3025 ProviderKind::Stepfun,
3026 "step-3.7-flash",
3027 &usage,
3028 )
3029 .is_none()
3030 );
3031 assert!(
3032 calculate_turn_cost_estimate_for_provider_at(
3033 ProviderKind::Stepfun,
3034 "step-3.7-flash",
3035 &usage,
3036 Utc::now(),
3037 )
3038 .is_none()
3039 );
3040 assert!(!has_pricing_for_provider(
3041 ProviderKind::Stepfun,
3042 "step-3.7-flash"
3043 ));
3044
3045 for surface in [None, Some(STEPFUN_PLAN_BILLING_SURFACE)] {
3046 assert!(
3047 calculate_turn_cost_estimate_for_billing_surface(
3048 ProviderKind::Stepfun,
3049 "step-3.7-flash",
3050 surface,
3051 &usage,
3052 )
3053 .is_none()
3054 );
3055 }
3056 assert!(
3057 calculate_turn_cost_estimate_for_billing_surface(
3058 ProviderKind::Stepfun,
3059 "step-unknown",
3060 Some(STEPFUN_PAYG_BILLING_SURFACE),
3061 &usage,
3062 )
3063 .is_none()
3064 );
3065 for provider in [
3066 ProviderKind::Openrouter,
3067 ProviderKind::Ollama,
3068 ProviderKind::Custom,
3069 ] {
3070 assert!(
3071 calculate_turn_cost_estimate_for_billing_surface(
3072 provider,
3073 "step-3.7-flash",
3074 Some(STEPFUN_PAYG_BILLING_SURFACE),
3075 &usage,
3076 )
3077 .is_none(),
3078 "{provider:?}"
3079 );
3080 assert!(
3081 calculate_turn_cost_estimate_for_provider(provider, "step-3.7-flash", &usage,)
3082 .is_none(),
3083 "{provider:?}"
3084 );
3085 assert!(
3086 calculate_turn_cost_estimate_for_provider_at(
3087 provider,
3088 "step-3.7-flash",
3089 &usage,
3090 Utc::now(),
3091 )
3092 .is_none(),
3093 "{provider:?}"
3094 );
3095 assert!(
3096 !has_pricing_for_provider(provider, "step-3.7-flash"),
3097 "{provider:?}"
3098 );
3099 }
3100
3101 let recorded = calculate_turn_cost_estimate_for_route_at(
3102 ProviderKind::Stepfun,
3103 "step-3.7-flash",
3104 Some(STEPFUN_PAYG_BILLING_SURFACE),
3105 &usage,
3106 Utc::now(),
3107 )
3108 .expect("recorded PAYG route retains provider-scoped pricing");
3109 assert_eq!(recorded, payg);
3110 }
3111
3112 #[test]
3113 fn catalog_sourced_models_have_usd_pricing() {
3114 for (model, input, output) in [
3115 ("minimax-m2.7", 0.3, 1.2),
3116 ("minimax/minimax-m2.7", 0.3, 1.2),
3117 ("step-3.7-flash", 0.2, 1.15),
3118 ("fugu-ultra-20260615", 5.0, 30.0),
3119 ("fugu-ultra", 5.0, 30.0),
3120 ] {
3121 let pricing = pricing_for_model_at(model, Utc::now()).expect(model);
3122 assert_eq!(pricing.usd.input_cache_miss_per_million, input, "{model}");
3123 assert_eq!(pricing.usd.output_per_million, output, "{model}");
3124 assert!(has_pricing_for_model(model));
3125 }
3126 }
3127
3128 #[test]
3129 fn trinity_mini_stays_unpriced_without_verified_provider_rates() {
3130 let usage = Usage {
3131 input_tokens: 1_000,
3132 output_tokens: 100,
3133 ..Usage::default()
3134 };
3135
3136 assert!(pricing_for_model_at("trinity-mini", Utc::now()).is_none());
3137 assert!(!has_pricing_for_model("trinity-mini"));
3138 assert!(!has_pricing_for_provider(
3139 ProviderKind::Arcee,
3140 "trinity-mini"
3141 ));
3142 assert!(
3143 calculate_turn_cost_estimate_for_provider(ProviderKind::Arcee, "trinity-mini", &usage,)
3144 .is_none()
3145 );
3146 }
3147
3148 #[test]
3149 fn minimax_m3_standard_pricing_tracks_the_512k_input_boundary() {
3150 for model in ["MiniMax-M3", "minimax/minimax-m3"] {
3151 for (input_tokens, cache_read, input, output) in
3152 [(512_000, 0.06, 0.30, 1.20), (512_001, 0.12, 0.60, 2.40)]
3153 {
3154 let usage = Usage {
3155 input_tokens,
3156 ..Usage::default()
3157 };
3158 let pricing = pricing_for_model_and_usage(model, &usage).expect("M3 pricing");
3159 assert_eq!(pricing.usd.input_cache_hit_per_million, cache_read);
3160 assert_eq!(pricing.usd.input_cache_miss_per_million, input);
3161 assert_eq!(pricing.usd.output_per_million, output);
3162 }
3163 assert!(calculate_cache_savings(model, 1).is_none());
3164 }
3165 }
3166
3167 #[test]
3168 fn grok_46_pricing_tracks_the_200k_prompt_boundary() {
3169 for (input_tokens, cache_read, input, output) in
3170 [(199_999, 0.50, 2.00, 6.00), (200_000, 1.00, 4.00, 12.00)]
3171 {
3172 let usage = Usage {
3173 input_tokens,
3174 ..Usage::default()
3175 };
3176 let pricing =
3177 pricing_for_model_and_usage("grok-4.6", &usage).expect("Grok 4.6 pricing");
3178 assert_eq!(pricing.usd.input_cache_hit_per_million, cache_read);
3179 assert_eq!(pricing.usd.input_cache_miss_per_million, input);
3180 assert_eq!(pricing.usd.output_per_million, output);
3181 }
3182 }
3183
3184 /// Published xAI rates per 1M tokens (cache-read, input, output) at the
3185 /// standard tier, verified 2026-08-17 on docs.x.ai/docs/models/grok-4.5
3186 /// and /grok-4.3; the pages' embedded price tables carry a `LongContext`
3187 /// column at exactly 2x for prompts past 200K.
3188 const GROK_4_5_USD_STANDARD: (f64, f64, f64) = (0.30, 2.00, 6.00);
3189 const GROK_4_5_USD_LONG_CONTEXT: (f64, f64, f64) = (0.60, 4.00, 12.00);
3190 const GROK_4_3_USD_STANDARD: (f64, f64, f64) = (0.20, 1.25, 2.50);
3191 const GROK_4_3_USD_LONG_CONTEXT: (f64, f64, f64) = (0.40, 2.50, 5.00);
3192
3193 #[test]
3194 fn grok_45_and_43_pricing_track_the_200k_prompt_boundary() {
3195 for (model, standard, long_context) in [
3196 ("grok-4.5", GROK_4_5_USD_STANDARD, GROK_4_5_USD_LONG_CONTEXT),
3197 ("grok-4.3", GROK_4_3_USD_STANDARD, GROK_4_3_USD_LONG_CONTEXT),
3198 ] {
3199 for (input_tokens, expected) in [(199_999, standard), (200_000, long_context)] {
3200 let usage = Usage {
3201 input_tokens,
3202 ..Usage::default()
3203 };
3204 let pricing = pricing_for_model_and_usage(model, &usage)
3205 .unwrap_or_else(|| panic!("{model} pricing"));
3206 assert_eq!(
3207 pricing.usd.input_cache_hit_per_million, expected.0,
3208 "{model} @ {input_tokens} cache-read"
3209 );
3210 assert_eq!(
3211 pricing.usd.input_cache_miss_per_million, expected.1,
3212 "{model} @ {input_tokens} input"
3213 );
3214 assert_eq!(
3215 pricing.usd.output_per_million, expected.2,
3216 "{model} @ {input_tokens} output"
3217 );
3218 assert!(pricing.cny.is_none());
3219 }
3220 // Metadata-only lookups report the standard tier.
3221 let metadata = pricing_for_model_at(model, Utc::now()).unwrap();
3222 assert_eq!(metadata.usd.input_cache_miss_per_million, standard.1);
3223 }
3224 }
3225
3226 #[test]
3227 fn direct_xai_grok_45_and_43_own_usage_tier_without_leaking_to_other_providers() {
3228 for (model, standard_input, long_input) in
3229 [("grok-4.5", 2.00, 4.00), ("grok-4.3", 1.25, 2.50)]
3230 {
3231 for (input_tokens, input_rate) in [(199_999, standard_input), (200_000, long_input)] {
3232 let usage = Usage {
3233 input_tokens,
3234 ..Usage::default()
3235 };
3236 let estimate = calculate_turn_cost_estimate_for_provider_at(
3237 ProviderKind::Xai,
3238 model,
3239 &usage,
3240 Utc::now(),
3241 )
3242 .unwrap_or_else(|| panic!("direct xAI {model} has tiered pricing"));
3243 let expected = f64::from(input_tokens) / 1_000_000.0 * input_rate;
3244 assert!(
3245 (estimate.usd - expected).abs() < 1e-12,
3246 "{model} @ {input_tokens}: {} != {expected}",
3247 estimate.usd
3248 );
3249 }
3250 assert!(
3251 provider_owned_hand_pricing_at(ProviderKind::Openrouter, model, Utc::now())
3252 .is_none(),
3253 "{model}: OpenRouter must not inherit xAI billing"
3254 );
3255 }
3256 }
3257
3258 #[test]
3259 fn direct_xai_grok_46_owns_usage_tier_without_leaking_to_other_providers() {
3260 for (input_tokens, input_rate) in [(199_999, 2.00), (200_000, 4.00)] {
3261 let usage = Usage {
3262 input_tokens,
3263 ..Usage::default()
3264 };
3265 let estimate = calculate_turn_cost_estimate_for_provider_at(
3266 ProviderKind::Xai,
3267 "grok-4.6",
3268 &usage,
3269 Utc::now(),
3270 )
3271 .expect("direct xAI route has authoritative tiered pricing");
3272 let expected = f64::from(input_tokens) / 1_000_000.0 * input_rate;
3273 assert!((estimate.usd - expected).abs() < 1e-12);
3274 }
3275
3276 assert!(
3277 provider_owned_hand_pricing_at(ProviderKind::Openrouter, "grok-4.6", Utc::now(),)
3278 .is_none()
3279 );
3280 }
3281
3282 #[test]
3283 fn provider_scoped_minimax_m3_keeps_usage_tiers_for_both_wire_protocols() {
3284 for provider in [ProviderKind::Minimax, ProviderKind::MinimaxAnthropic] {
3285 for (input_tokens, input_rate) in [(512_000, 0.30), (512_001, 0.60)] {
3286 let usage = Usage {
3287 input_tokens,
3288 ..Usage::default()
3289 };
3290 let estimate = calculate_turn_cost_estimate_for_provider_at(
3291 provider,
3292 "MiniMax-M3",
3293 &usage,
3294 Utc::now(),
3295 )
3296 .expect("direct MiniMax route has authoritative pricing");
3297 let expected = f64::from(input_tokens) / 1_000_000.0 * input_rate;
3298 assert!((estimate.usd - expected).abs() < 1e-12, "{provider:?}");
3299 }
3300 }
3301 }
3302
3303 #[test]
3304 fn direct_openai_long_context_estimates_fail_closed_above_272k() {
3305 for model in [
3306 "gpt-5.5",
3307 "gpt-5.6",
3308 "gpt-5.6-sol",
3309 "gpt-5.6-terra",
3310 "gpt-5.6-luna",
3311 ] {
3312 let at_boundary = Usage {
3313 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD,
3314 ..Usage::default()
3315 };
3316 let above_boundary = Usage {
3317 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3318 ..Usage::default()
3319 };
3320
3321 assert!(
3322 calculate_turn_cost_estimate_for_provider(
3323 ProviderKind::Openai,
3324 model,
3325 &at_boundary,
3326 )
3327 .is_some(),
3328 "{model} should retain its standard price at 272K"
3329 );
3330 assert!(
3331 calculate_turn_cost_estimate_for_provider(
3332 ProviderKind::Openai,
3333 model,
3334 &above_boundary,
3335 )
3336 .is_none(),
3337 "{model} must not report the lower static price above 272K"
3338 );
3339 }
3340 }
3341
3342 #[test]
3343 fn direct_openai_gpt54_family_is_guarded_even_without_a_bundled_catalog_row() {
3344 for model in ["gpt-5.4", "gpt-5.4-pro"] {
3345 assert!(!direct_openai_long_context_tier_is_unpriced(
3346 ProviderKind::Openai,
3347 model,
3348 OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD,
3349 ));
3350 assert!(direct_openai_long_context_tier_is_unpriced(
3351 ProviderKind::Openai,
3352 model,
3353 OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3354 ));
3355
3356 let above_boundary = Usage {
3357 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3358 ..Usage::default()
3359 };
3360 assert!(
3361 calculate_turn_cost_estimate_for_provider(
3362 ProviderKind::Openai,
3363 model,
3364 &above_boundary,
3365 )
3366 .is_none(),
3367 "{model} must remain unpriced if a live catalog row is available"
3368 );
3369 }
3370 }
3371
3372 #[test]
3373 fn openai_long_context_guard_is_exact_and_provider_scoped() {
3374 let input_tokens = OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1;
3375
3376 for provider in [
3377 ProviderKind::Openrouter,
3378 ProviderKind::OpenaiCodex,
3379 ProviderKind::Ollama,
3380 ProviderKind::Custom,
3381 ] {
3382 assert!(
3383 !direct_openai_long_context_tier_is_unpriced(provider, "gpt-5.5", input_tokens,),
3384 "{provider:?} must not inherit direct OpenAI tier handling"
3385 );
3386 }
3387 for model in [
3388 "gpt-5.4-mini",
3389 "gpt-5.4-nano",
3390 "gpt-5.5-pro",
3391 "gpt-5.5-pro-2026-04-23",
3392 "gpt-5.5-2026-04-23-extra",
3393 "openai/gpt-5.5",
3394 "gpt-5.6-sol-preview",
3395 ] {
3396 assert!(
3397 !direct_openai_long_context_tier_is_unpriced(
3398 ProviderKind::Openai,
3399 model,
3400 input_tokens,
3401 ),
3402 "non-documented id {model} must not be treated as an alias"
3403 );
3404 }
3405
3406 let usage = Usage {
3407 input_tokens,
3408 output_tokens: 1,
3409 ..Usage::default()
3410 };
3411 assert!(calculate_turn_cost_estimate_from_usage("gpt-5.5", &usage).is_some());
3412 assert!(
3413 calculate_turn_cost_estimate_for_provider(ProviderKind::OpenaiCodex, "gpt-5.5", &usage,)
3414 .is_none()
3415 );
3416 }
3417
3418 #[test]
3419 fn direct_openai_snapshots_use_the_same_strict_272k_boundary() {
3420 for snapshot in [
3421 "gpt-5.4-2026-03-05",
3422 "gpt-5.4-pro-2026-03-05",
3423 "gpt-5.5-2026-04-23",
3424 ] {
3425 assert!(!direct_openai_long_context_tier_is_unpriced(
3426 ProviderKind::Openai,
3427 snapshot,
3428 OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD,
3429 ));
3430 assert!(direct_openai_long_context_tier_is_unpriced(
3431 ProviderKind::Openai,
3432 snapshot,
3433 OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3434 ));
3435
3436 let above_boundary = Usage {
3437 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3438 ..Usage::default()
3439 };
3440 assert!(
3441 calculate_turn_cost_estimate_for_provider(
3442 ProviderKind::Openai,
3443 snapshot,
3444 &above_boundary,
3445 )
3446 .is_none(),
3447 "{snapshot} must not report the lower static price above 272K"
3448 );
3449 }
3450 }
3451
3452 #[test]
3453 fn direct_openai_long_context_guard_uses_total_input_with_mixed_cache_classes() {
3454 let at_boundary = Usage {
3455 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD,
3456 output_tokens: 1_000,
3457 prompt_cache_hit_tokens: Some(100_000),
3458 prompt_cache_miss_tokens: Some(100_000),
3459 prompt_cache_write_tokens: Some(72_000),
3460 ..Usage::default()
3461 };
3462 let above_boundary = Usage {
3463 input_tokens: OPENAI_LONG_CONTEXT_SURCHARGE_THRESHOLD + 1,
3464 prompt_cache_write_tokens: Some(72_001),
3465 ..at_boundary.clone()
3466 };
3467
3468 assert!(
3469 calculate_turn_cost_estimate_for_provider(
3470 ProviderKind::Openai,
3471 "gpt-5.6-sol",
3472 &at_boundary,
3473 )
3474 .is_some()
3475 );
3476 assert!(
3477 calculate_turn_cost_estimate_for_provider(
3478 ProviderKind::Openai,
3479 "gpt-5.6-sol",
3480 &above_boundary,
3481 )
3482 .is_none()
3483 );
3484 }
3485
3486 #[test]
3487 fn minimax_m2_7_preserves_cache_read_and_write_rates() {
3488 let pricing = pricing_for_model_at("MiniMax-M2.7", Utc::now()).expect("M2.7 pricing");
3489 assert_eq!(pricing.usd.input_cache_hit_per_million, 0.06);
3490 assert_eq!(pricing.usd.input_cache_miss_per_million, 0.30);
3491 assert_eq!(pricing.usd.output_per_million, 1.20);
3492 assert_eq!(pricing.usd.cache_write, CacheWritePolicy::Rate(0.375));
3493 }
3494
3495 /// The offline seed's price and the reviewed provider-owned table must
3496 /// agree wherever both price a row: the route audit reads a catalog rate
3497 /// before the hand table, so a disagreement silently changes the offline
3498 /// estimate (#6396). A deliberate difference belongs in
3499 /// `catalog_corrections.json`, which this reads through.
3500 #[test]
3501 fn bundled_seed_prices_agree_with_provider_owned_table() {
3502 let at = Utc.with_ymd_and_hms(2026, 9, 26, 12, 0, 0).unwrap();
3503 let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
3504 let mut checked = 0;
3505 let mut mismatches = Vec::new();
3506 for row in codewhale_config::catalog::bundled_catalog_offerings() {
3507 let Some(cost) = row.cost.as_ref() else {
3508 continue;
3509 };
3510 let Some(provider) = ProviderKind::parse(&row.provider) else {
3511 continue;
3512 };
3513 let Some(hand) = provider_owned_hand_pricing_at(provider, &row.wire_model_id, at)
3514 else {
3515 continue;
3516 };
3517 checked += 1;
3518 let usd = &hand.usd;
3519 let pairs = [
3520 ("input", cost.input, usd.input_cache_miss_per_million),
3521 ("output", cost.output, usd.output_per_million),
3522 (
3523 "cache_read",
3524 cost.cache_read,
3525 usd.input_cache_hit_per_million,
3526 ),
3527 ];
3528 for (field, seed, table) in pairs {
3529 if let Some(seed) = seed
3530 && !close(seed, table)
3531 {
3532 mismatches.push(format!(
3533 "{}/{} {field}: seed {seed} vs table {table}",
3534 row.provider, row.wire_model_id
3535 ));
3536 }
3537 }
3538 }
3539 assert!(
3540 checked > 0,
3541 "no bundled row has a provider-owned table price"
3542 );
3543 assert!(mismatches.is_empty(), "{mismatches:#?}");
3544 }
3545
3546 #[test]
3547 fn curated_usd_only_models_have_pricing_and_accrue_cost() {
3548 let usage = Usage {
3549 input_tokens: 1_000_000,
3550 output_tokens: 500_000,
3551 prompt_cache_hit_tokens: Some(250_000),
3552 prompt_cache_miss_tokens: Some(750_000),
3553 ..Default::default()
3554 };
3555 for (model, hit, miss, output) in [
3556 ("kimi-k2.6", 0.16, 0.95, 4.00),
3557 ("kimi-k2.7-code", 0.19, 0.95, 4.00),
3558 ("moonshotai/kimi-k2.7-code", 0.19, 0.95, 4.00),
3559 ("kimi-k2.7-code-highspeed", 0.38, 1.90, 8.00),
3560 ("moonshotai/kimi-k2.7-code-highspeed", 0.38, 1.90, 8.00),
3561 ("kimi-k3", 0.30, 3.00, 15.00),
3562 ("moonshotai/kimi-k3", 0.30, 3.00, 15.00),
3563 ("z-ai/glm-5.1", 0.26, 1.40, 4.40),
3564 ("glm-5.2", 0.26, 1.40, 4.40),
3565 ("z-ai/glm-5.2", 0.26, 1.40, 4.40),
3566 ("glm-5.3-flash", 0.03, 0.15, 0.50),
3567 ("z-ai/glm-5.3-flash", 0.03, 0.15, 0.50),
3568 ("glm-5-turbo", 0.24, 1.20, 4.00),
3569 ("z-ai/glm-5-turbo", 0.24, 1.20, 4.00),
3570 ("qwen/qwen3.6-plus", 0.325, 0.325, 1.95),
3571 ("qwen/qwen3.6-35b-a3b", 0.05, 0.14, 1.00),
3572 ("qwen/qwen3.6-27b", 0.15, 0.285, 2.40),
3573 // No published cache rate: cache-hit billed at the input rate.
3574 ("trinity-large-thinking", 0.25, 0.25, 0.80),
3575 ("nvidia/nemotron-3-ultra-550b-a55b", 0.10, 0.50, 2.20),
3576 ("claude-opus-4-8", 0.50, 5.00, 25.00),
3577 ("claude-opus-5", 0.50, 5.00, 25.00),
3578 ("claude-sonnet-4-6", 0.30, 3.00, 15.00),
3579 ("claude-haiku-4-5", 0.10, 1.00, 5.00),
3580 ("claude-fable-5", 1.00, 10.00, 50.00),
3581 ("gpt-5.5", 0.50, 5.00, 30.00),
3582 // GPT-5.5 Pro has no cached-input discount: cache-hit == input.
3583 ("gpt-5.5-pro", 30.00, 30.00, 180.00),
3584 ("gpt-5.6", 0.40, 4.00, 20.00),
3585 ("gpt-5.6-sol", 0.40, 4.00, 20.00),
3586 ("gpt-5.6-terra", 0.20, 2.00, 12.00),
3587 ("gpt-5.6-luna", 0.02, 0.20, 1.20),
3588 ("gpt-5-codex", 0.125, 1.25, 10.00),
3589 ("gpt-5.3-codex", 0.175, 1.75, 14.00),
3590 ("mistral-medium-latest", 0.15, 1.50, 7.50),
3591 ("mistral-medium-3-5", 0.15, 1.50, 7.50),
3592 ("mistral-large-latest", 0.05, 0.50, 1.50),
3593 ("mistral-large-2512", 0.05, 0.50, 1.50),
3594 ("mistral-small-latest", 0.015, 0.15, 0.60),
3595 ("mistral-small-2603", 0.015, 0.15, 0.60),
3596 ("mistral-code-latest", 0.03, 0.30, 0.90),
3597 ("codestral-latest", 0.03, 0.30, 0.90),
3598 ("qwen/qwen3.7-plus", 0.064, 0.32, 1.28),
3599 ("muse-spark-1.1", 0.15, 1.25, 4.25),
3600 ("muse-spark-1.2", 0.15, 1.25, 4.25),
3601 ("muse-spark-1.2-contributor", 0.002, 0.10, 0.20),
3602 ] {
3603 let pricing = pricing_for_model_at(model, Utc::now()).expect(model);
3604 assert_eq!(pricing.usd.input_cache_hit_per_million, hit);
3605 assert_eq!(pricing.usd.input_cache_miss_per_million, miss);
3606 assert_eq!(pricing.usd.output_per_million, output);
3607 assert!(pricing.cny.is_none());
3608 assert!(has_pricing_for_model(model));
3609
3610 let estimate = calculate_turn_cost_estimate_from_usage(model, &usage).expect(model);
3611 assert!(estimate.usd > 0.0, "expected positive USD for {model}");
3612 assert_eq!(estimate.cny, 0.0);
3613 }
3614
3615 // Anthropic / Qwen rows that publish a cache-write premium, and one row
3616 // (`gpt-5.5`) that publishes none — which is `Unpublished`, not a
3617 // licence to bill writes at the input rate (#4318).
3618 for (model, write) in [
3619 ("claude-opus-4-8", CacheWritePolicy::Rate(6.25)),
3620 ("claude-sonnet-4-6", CacheWritePolicy::Rate(3.75)),
3621 ("claude-haiku-4-5", CacheWritePolicy::Rate(1.25)),
3622 ("claude-fable-5", CacheWritePolicy::Rate(12.50)),
3623 ("qwen/qwen3.7-plus", CacheWritePolicy::Rate(0.40)),
3624 ("gpt-5.5", CacheWritePolicy::Unpublished),
3625 ] {
3626 let pricing = pricing_for_model_at(model, Utc::now()).expect(model);
3627 assert_eq!(
3628 pricing.usd.cache_write, write,
3629 "cache-write policy for {model}"
3630 );
3631 }
3632 }
3633
3634 #[test]
3635 fn glm_5_3_has_no_hardcoded_price() {
3636 // GLM-5.3's catalog metadata is inherited from GLM-5.2, but Z.ai has
3637 // published no GLM-5.3 rate. Inheriting the 5.2 price would invent one,
3638 // so every price surface must report *unknown*, never a number and
3639 // never $0. If Z.ai publishes rates, delete this test and add the real
3640 // row — do not "fix" it by copying 5.2's.
3641 for model in ["glm-5.3", "z-ai/glm-5.3"] {
3642 assert!(
3643 pricing_for_model_at(model, Utc::now()).is_none(),
3644 "{model} must have no price row until Z.ai publishes one"
3645 );
3646 assert!(!has_pricing_for_model(model), "{model} must be unpriced");
3647 assert!(
3648 calculate_turn_cost_estimate_from_usage(
3649 model,
3650 &Usage {
3651 input_tokens: 1_000_000,
3652 output_tokens: 500_000,
3653 ..Default::default()
3654 },
3655 )
3656 .is_none(),
3657 "{model} must not accrue an invented cost estimate"
3658 );
3659 }
3660 // The priced sibling it inherits capabilities from is unaffected.
3661 assert!(has_pricing_for_model("glm-5.2"));
3662 }
3663
3664 #[test]
3665 fn glm_5_4_has_no_hardcoded_price() {
3666 // GLM-5.4 ships on the GLM Coding Plan (credit multipliers) and its
3667 // pay-as-you-go Model API is not open yet (pending security
3668 // assessment), so no USD rate exists to stand behind. Every price
3669 // surface must report *unknown*, never a number and never $0. If Z.ai
3670 // publishes rates, delete this test and add the real row.
3671 for model in ["glm-5.4", "GLM-5.4", "z-ai/glm-5.4"] {
3672 assert!(
3673 pricing_for_model_at(model, Utc::now()).is_none(),
3674 "{model} must have no price row until Z.ai publishes one"
3675 );
3676 assert!(!has_pricing_for_model(model), "{model} must be unpriced");
3677 assert!(
3678 calculate_turn_cost_estimate_from_usage(
3679 model,
3680 &Usage {
3681 input_tokens: 1_000_000,
3682 output_tokens: 500_000,
3683 ..Default::default()
3684 },
3685 )
3686 .is_none(),
3687 "{model} must not accrue an invented cost estimate"
3688 );
3689 }
3690 }
3691
3692 #[test]
3693 fn cache_write_tokens_increase_anthropic_cost_estimate() {
3694 let with_write = Usage {
3695 input_tokens: 12_048,
3696 output_tokens: 1,
3697 prompt_cache_hit_tokens: Some(10_000),
3698 prompt_cache_miss_tokens: Some(3),
3699 prompt_cache_write_tokens: Some(2_045),
3700 ..Default::default()
3701 };
3702 let write_as_miss = Usage {
3703 input_tokens: 12_048,
3704 output_tokens: 1,
3705 prompt_cache_hit_tokens: Some(10_000),
3706 prompt_cache_miss_tokens: Some(2_048),
3707 prompt_cache_write_tokens: None,
3708 ..Default::default()
3709 };
3710
3711 let priced =
3712 calculate_turn_cost_estimate_from_usage("claude-fable-5", &with_write).expect("priced");
3713 let undercounted =
3714 calculate_turn_cost_estimate_from_usage("claude-fable-5", &write_as_miss)
3715 .expect("priced");
3716 // 2045 write @ 12.50 vs same tokens @ miss 10.00 → ~0.005 USD premium.
3717 assert!(
3718 priced.usd > undercounted.usd,
3719 "write premium should raise cost: priced={} undercounted={}",
3720 priced.usd,
3721 undercounted.usd
3722 );
3723 let expected_premium = (2_045.0 / 1_000_000.0) * (12.50 - 10.00);
3724 assert!(
3725 (priced.usd - undercounted.usd - expected_premium).abs() < 1e-9,
3726 "premium delta mismatch: {}",
3727 priced.usd - undercounted.usd
3728 );
3729 }
3730
3731 #[test]
3732 fn catalog_pricing_uses_its_cache_write_rate() {
3733 let offering = codewhale_config::catalog::CatalogOffering {
3734 provider: "anthropic".to_string(),
3735 wire_model_id: "catalog-priced-model".to_string(),
3736 endpoint_key: "chat".to_string(),
3737 cost: Some(codewhale_config::models_dev::ModelsDevCost {
3738 input: Some(10.0),
3739 output: Some(50.0),
3740 cache_read: Some(1.0),
3741 cache_write: Some(12.5),
3742 ..Default::default()
3743 }),
3744 ..Default::default()
3745 };
3746 let usage = Usage {
3747 input_tokens: 13,
3748 output_tokens: 5,
3749 prompt_cache_hit_tokens: Some(2),
3750 prompt_cache_miss_tokens: Some(3),
3751 prompt_cache_write_tokens: Some(8),
3752 ..Default::default()
3753 };
3754
3755 let estimate = catalog_cost_estimate_for_route(
3756 ProviderKind::Anthropic,
3757 "catalog-priced-model",
3758 &offering,
3759 &usage,
3760 )
3761 .expect("catalog cost estimate");
3762 assert!((estimate.usd - 0.000_382).abs() < 1e-15);
3763 assert_eq!(estimate.cny, 0.0);
3764 }
3765
3766 #[test]
3767 fn recorded_time_provider_cost_keeps_catalog_cache_write_tier() {
3768 let request = Usage {
3769 input_tokens: 100_000,
3770 output_tokens: 0,
3771 prompt_cache_hit_tokens: Some(0),
3772 prompt_cache_miss_tokens: Some(0),
3773 prompt_cache_write_tokens: Some(100_000),
3774 ..Default::default()
3775 };
3776 let usage = Usage {
3777 input_tokens: 1_000_000,
3778 output_tokens: 0,
3779 prompt_cache_hit_tokens: Some(0),
3780 prompt_cache_miss_tokens: Some(0),
3781 prompt_cache_write_tokens: Some(1_000_000),
3782 request_usages: vec![request; 10],
3783 ..Default::default()
3784 };
3785
3786 let estimate = calculate_turn_cost_estimate_for_provider_at(
3787 ProviderKind::Openrouter,
3788 "qwen/qwen3.7-plus",
3789 &usage,
3790 Utc::now(),
3791 )
3792 .expect("provider catalog write price");
3793
3794 assert!((estimate.usd - 0.40).abs() < f64::EPSILON);
3795 assert_eq!(estimate.cny, 0.0);
3796 }
3797
3798 #[test]
3799 fn recorded_time_provider_cost_rejects_foreign_model_ids() {
3800 let usage = Usage {
3801 input_tokens: 1_000,
3802 output_tokens: 100,
3803 ..Default::default()
3804 };
3805
3806 assert!(
3807 calculate_turn_cost_estimate_for_provider_at(
3808 ProviderKind::Ollama,
3809 "gpt-5.5",
3810 &usage,
3811 Utc::now(),
3812 )
3813 .is_none()
3814 );
3815 }
3816
3817 #[test]
3818 fn provider_cost_keeps_owned_hand_price_without_catalog_offering() {
3819 let usage = Usage {
3820 input_tokens: 1_000_000,
3821 output_tokens: 0,
3822 ..Default::default()
3823 };
3824 assert!(
3825 crate::provider_lake::catalog_offering_for_model(ProviderKind::Openai, "gpt-5-codex")
3826 .is_none(),
3827 "regression fixture must exercise the hand-price fallback"
3828 );
3829
3830 let estimate = calculate_turn_cost_estimate_for_provider_at(
3831 ProviderKind::Openai,
3832 "gpt-5-codex",
3833 &usage,
3834 Utc::now(),
3835 )
3836 .expect("OpenAI API owns the hand-priced model");
3837
3838 assert!((estimate.usd - 1.25).abs() < f64::EPSILON);
3839 assert_eq!(estimate.cny, 0.0);
3840 assert!(has_pricing_for_provider(
3841 ProviderKind::Openai,
3842 "gpt-5-codex"
3843 ));
3844 }
3845
3846 #[test]
3847 fn provider_price_does_not_invent_catalog_missing_cache_write_class() {
3848 let offering =
3849 crate::provider_lake::catalog_offering_for_model(ProviderKind::Openai, "gpt-5.5")
3850 .expect("bundled OpenAI route");
3851 let catalog_pricing =
3852 OfferingPricing::from_catalog_offering(&offering).expect("catalog pricing");
3853 assert!(catalog_pricing.cache_write_per_million.is_none());
3854 let usage = Usage {
3855 input_tokens: 250_000,
3856 output_tokens: 0,
3857 prompt_cache_miss_tokens: Some(0),
3858 prompt_cache_write_tokens: Some(250_000),
3859 ..Default::default()
3860 };
3861
3862 let audit =
3863 audit_turn_cost_for_provider_at(ProviderKind::Openai, "gpt-5.5", &usage, Utc::now());
3864
3865 assert!(audit.estimate.is_none());
3866 assert_eq!(
3867 audit.unpriced_reason,
3868 Some(UnpricedReason::MissingClassPrice)
3869 );
3870 assert_eq!(audit.unpriced_classes, vec![TokenClass::CacheWrite]);
3871 }
3872
3873 #[test]
3874 fn provider_cost_does_not_fabricate_price_for_costless_catalog_route() {
3875 let _live = crate::provider_lake::lock_live_snapshot();
3876 crate::provider_lake::clear_live_snapshot();
3877 let usage = Usage {
3878 input_tokens: 1_000_000,
3879 output_tokens: 0,
3880 ..Default::default()
3881 };
3882 let recorded_at = Utc::now();
3883
3884 for (provider, model) in [
3885 (ProviderKind::Zai, "GLM-5.3"),
3886 (ProviderKind::XiaomiMimo, "mimo-v2.6-pro"),
3887 (ProviderKind::ModelstudioTokenPlan, "qwen3.8-max"),
3888 ] {
3889 let offering =
3890 crate::provider_lake::bundled_catalog_offering_for_model(provider, model)
3891 .unwrap_or_else(|| panic!("missing bundled route: {provider:?}/{model}"));
3892 assert!(
3893 OfferingPricing::from_catalog_offering(&offering).is_none(),
3894 "{provider:?}/{model}"
3895 );
3896 assert!(
3897 calculate_turn_cost_estimate_for_provider_at(provider, model, &usage, recorded_at,)
3898 .is_none(),
3899 "{provider:?}/{model}"
3900 );
3901 assert!(
3902 calculate_turn_cost_estimate_for_provider(provider, model, &usage).is_none(),
3903 "{provider:?}/{model}"
3904 );
3905 assert!(
3906 !has_pricing_for_provider(provider, model),
3907 "{provider:?}/{model}"
3908 );
3909 }
3910
3911 crate::provider_lake::clear_live_snapshot();
3912 }
3913
3914 #[test]
3915 fn recorded_time_provider_cost_bounds_deepseek_compatibility_aliases() {
3916 let usage = Usage {
3917 input_tokens: 1_000,
3918 output_tokens: 100,
3919 ..Default::default()
3920 };
3921 let before_retirement: DateTime<Utc> =
3922 "2026-07-24T15:58:59Z".parse().expect("pre-retirement time");
3923 let at_retirement: DateTime<Utc> = DEEPSEEK_ALIAS_RETIREMENT_UTC
3924 .parse()
3925 .expect("retirement time");
3926
3927 assert!(
3928 calculate_turn_cost_estimate_for_provider_at(
3929 ProviderKind::Deepseek,
3930 "deepseek-chat",
3931 &usage,
3932 before_retirement,
3933 )
3934 .is_some()
3935 );
3936 assert!(
3937 calculate_turn_cost_estimate_for_provider_at(
3938 ProviderKind::Deepseek,
3939 "deepseek-reasoner",
3940 &usage,
3941 at_retirement,
3942 )
3943 .is_none()
3944 );
3945 }
3946
3947 #[test]
3948 fn deepseek_time_tier_names_the_window_for_tiered_models_only() {
3949 // Wednesday 2026-09-16: 02:00Z sits inside the 01:00-04:00 peak
3950 // window, 12:00Z outside every window.
3951 let peak = Utc.with_ymd_and_hms(2026, 9, 16, 2, 0, 0).unwrap();
3952 let off = Utc.with_ymd_and_hms(2026, 9, 16, 12, 0, 0).unwrap();
3953 // Saturday 02:00 Beijing time (Friday 18:00Z) bills off-peak even
3954 // inside a weekday peak hour.
3955 let weekend = Utc.with_ymd_and_hms(2026, 9, 18, 18, 0, 0).unwrap();
3956 for model in ["deepseek-v4-pro", "deepseek-v4-flash", "deepseek-flash"] {
3957 assert_eq!(deepseek_time_tier(model, peak), Some(true), "{model}");
3958 assert_eq!(deepseek_time_tier(model, off), Some(false), "{model}");
3959 assert_eq!(deepseek_time_tier(model, weekend), Some(false), "{model}");
3960 }
3961 assert_eq!(deepseek_time_tier(" DeepSeek-V4-Flash ", peak), Some(true));
3962 for flat in [
3963 "deepseek-chat",
3964 "deepseek-reasoner",
3965 "deepseek-ai/deepseek-v4-flash",
3966 "",
3967 ] {
3968 assert_eq!(deepseek_time_tier(flat, peak), None, "{flat}");
3969 }
3970 }
3971
3972 #[test]
3973 fn deepseek_pricing_requires_exact_ids_or_explicit_route_aliases() {
3974 let at = utc_hm(2, 0);
3975 let usage = Usage {
3976 input_tokens: 1_000,
3977 output_tokens: 100,
3978 ..Default::default()
3979 };
3980 let providers = [
3981 ProviderKind::Deepseek,
3982 ProviderKind::Deepseek,
3983 ProviderKind::DeepseekAnthropic,
3984 ];
3985
3986 for model in [
3987 "deepseek-v4.1-flash-expires-on-0910",
3988 "deepseek-v4.1-flash",
3989 "deepseek-v4.1-pro",
3990 "deepseek-v4-flash-vendor-preview",
3991 "vendor/deepseek-v4-pro-unverified",
3992 ] {
3993 assert!(pricing_for_model_at(model, at).is_none(), "{model}");
3994 for provider in providers {
3995 assert!(
3996 calculate_turn_cost_estimate_for_provider_at(provider, model, &usage, at)
3997 .is_none(),
3998 "{provider:?}/{model} must not inherit V4 rates"
3999 );
4000 }
4001 }
4002
4003 for (canonical, aliases) in [
4004 (
4005 "deepseek-v4-flash",
4006 ["flash", "deepseek-v4flash", "deepseek-ai/deepseek-v4flash"],
4007 ),
4008 (
4009 "deepseek-v4-pro",
4010 ["pro", "deepseek-v4pro", "deepseek/deepseek-v4-pro"],
4011 ),
4012 ] {
4013 let expected = cost_estimate_with_pricing(
4014 pricing_for_model_at(canonical, at).expect("canonical V4 pricing"),
4015 &usage,
4016 );
4017 for provider in providers {
4018 for model in std::iter::once(canonical).chain(aliases) {
4019 assert_eq!(
4020 calculate_turn_cost_estimate_for_provider_at(provider, model, &usage, at),
4021 Some(expected),
4022 "{provider:?}/{model} must preserve the canonical rate"
4023 );
4024 }
4025 }
4026 }
4027 }
4028
4029 #[test]
4030 fn token_usage_for_pricing_maps_cache_classes_without_double_billing_reasoning() {
4031 let usage = Usage {
4032 input_tokens: 1_000,
4033 output_tokens: 100,
4034 prompt_cache_hit_tokens: Some(250),
4035 prompt_cache_miss_tokens: Some(700),
4036 prompt_cache_write_tokens: Some(50),
4037 // Reasoning is a subset of the 100 reported output tokens, not an
4038 // extra 50 tokens of billable output.
4039 reasoning_tokens: Some(50),
4040 ..Default::default()
4041 };
4042
4043 assert_eq!(
4044 token_usage_for_pricing(&usage),
4045 TokenUsage {
4046 input: 700,
4047 output: 100,
4048 cache_read: 250,
4049 cache_write: 50,
4050
4051 reasoning: Some(50),
4052 input_audio: None,
4053 output_audio: None,
4054
4055 request_usages: Vec::new(),
4056 }
4057 );
4058
4059 // Informational reasoning telemetry must not move the billed output at
4060 // all: the same completion count costs the same with or without it.
4061 let without_reasoning = Usage {
4062 reasoning_tokens: None,
4063 ..usage.clone()
4064 };
4065 assert_eq!(
4066 token_usage_for_pricing(&usage).output,
4067 token_usage_for_pricing(&without_reasoning).output
4068 );
4069 assert_eq!(
4070 calculate_turn_cost_estimate_for_provider(
4071 ProviderKind::Anthropic,
4072 "claude-haiku-4-5",
4073 &usage,
4074 ),
4075 calculate_turn_cost_estimate_for_provider(
4076 ProviderKind::Anthropic,
4077 "claude-haiku-4-5",
4078 &without_reasoning,
4079 )
4080 );
4081 }
4082
4083 #[test]
4084 fn contradictory_cache_partition_is_bounded_and_fails_closed() {
4085 let usage = Usage {
4086 input_tokens: 100,
4087 output_tokens: 10,
4088 prompt_cache_hit_tokens: Some(80),
4089 prompt_cache_miss_tokens: Some(40),
4090 prompt_cache_write_tokens: Some(30),
4091 ..Usage::default()
4092 };
4093
4094 let classes = token_usage_for_pricing(&usage);
4095 assert_eq!(
4096 classes.input + classes.cache_read + classes.cache_write,
4097 u64::from(usage.input_tokens),
4098 "token projection may never exceed the provider's input total"
4099 );
4100 let audit = audit_turn_cost_for_provider_on_endpoint_at(
4101 ProviderKind::Deepseek,
4102 "deepseek-v4-flash",
4103 None,
4104 &usage,
4105 Utc::now(),
4106 );
4107 assert!(audit.estimate.is_none());
4108 assert_eq!(
4109 audit.unpriced_reason,
4110 Some(UnpricedReason::InconsistentUsage)
4111 );
4112
4113 let overflow_shape = Usage {
4114 input_tokens: u32::MAX,
4115 prompt_cache_hit_tokens: Some(u32::MAX),
4116 prompt_cache_miss_tokens: Some(1),
4117 ..Usage::default()
4118 };
4119 assert!(
4120 !usage_cache_partition_is_consistent(&overflow_shape),
4121 "consistency validation must not hide overflow via saturation"
4122 );
4123 }
4124
4125 #[test]
4126 fn openai_codex_gpt55_cost_is_unavailable_even_with_usage() {
4127 let usage = Usage {
4128 input_tokens: 1_000,
4129 output_tokens: 100,
4130 prompt_cache_hit_tokens: Some(250),
4131 prompt_cache_miss_tokens: Some(750),
4132 ..Default::default()
4133 };
4134
4135 assert!(calculate_turn_cost_estimate_from_usage("gpt-5.5", &usage).is_some());
4136 assert!(has_pricing_for_provider(ProviderKind::Openai, "gpt-5.5"));
4137 assert!(!has_pricing_for_provider(
4138 ProviderKind::OpenaiCodex,
4139 "gpt-5.5"
4140 ));
4141 assert!(
4142 calculate_turn_cost_estimate_for_provider(ProviderKind::OpenaiCodex, "gpt-5.5", &usage)
4143 .is_none()
4144 );
4145 }
4146
4147 #[test]
4148 fn subscription_route_does_not_inherit_same_models_api_price() {
4149 let usage = Usage {
4150 input_tokens: 1_000,
4151 output_tokens: 100,
4152 ..Default::default()
4153 };
4154 assert!(
4155 calculate_turn_cost_estimate_for_billing_surface(
4156 ProviderKind::Anthropic,
4157 "claude-sonnet-5",
4158 Some(FIRST_PARTY_PAYG_BILLING_SURFACE),
4159 &usage,
4160 )
4161 .is_some()
4162 );
4163 assert!(
4164 calculate_turn_cost_estimate_for_route(
4165 ProviderKind::Anthropic,
4166 "claude-sonnet-5",
4167 &usage,
4168 crate::route_billing::BillingPresentation::Subscription("Claude OAuth quota"),
4169 )
4170 .is_none()
4171 );
4172 }
4173
4174 #[test]
4175 fn token_usage_for_pricing_infers_missing_cache_miss_from_hit_source() {
4176 let usage = Usage {
4177 input_tokens: 1_000,
4178 output_tokens: 100,
4179 prompt_cache_hit_tokens: Some(250),
4180 prompt_cache_miss_tokens: None,
4181 ..Default::default()
4182 };
4183
4184 assert_eq!(
4185 token_usage_for_pricing(&usage),
4186 TokenUsage {
4187 input: 750,
4188 output: 100,
4189 cache_read: 250,
4190 cache_write: 0,
4191
4192 reasoning: None,
4193 input_audio: None,
4194 output_audio: None,
4195
4196 request_usages: Vec::new(),
4197 }
4198 );
4199 }
4200
4201 #[test]
4202 fn catalog_pricing_overrides_known_row_when_present() {
4203 for model in [
4204 "catalog-priced-model",
4205 "deepseek-v4.1-flash-expires-on-0910",
4206 ] {
4207 assert!(
4208 pricing_for_model_at(model, Utc::now()).is_none(),
4209 "private unknown rows never gain global prices"
4210 );
4211 }
4212 // Exact configured prices are tested through provider_lake + endpoint
4213 // identity above; the primitive helper cannot see those scoped declarations.
4214 }
4215
4216 /// Published Claude Sonnet 5 rates per 1M tokens (cache-hit, cache-miss,
4217 /// output, 5m cache-write), verified live on
4218 /// platform.claude.com/docs/en/about-claude/pricing on 2026-08-17: the
4219 /// $2/$10 launch rate is now standard and the 2026-09-01 increase to
4220 /// $3/$15 "will not occur".
4221 const CLAUDE_SONNET_5_USD: (f64, f64, f64, f64) = (0.20, 2.00, 10.00, 2.50);
4222
4223 fn assert_sonnet_5_standard_rate(at: DateTime<Utc>) {
4224 let pricing = pricing_for_model_at("claude-sonnet-5", at).unwrap();
4225 let (hit, miss, out, write) = CLAUDE_SONNET_5_USD;
4226 assert_eq!(pricing.usd.input_cache_hit_per_million, hit, "{at} hit");
4227 assert_eq!(pricing.usd.input_cache_miss_per_million, miss, "{at} miss");
4228 assert_eq!(pricing.usd.output_per_million, out, "{at} output");
4229 assert_eq!(
4230 pricing.usd.cache_write,
4231 CacheWritePolicy::Rate(write),
4232 "{at} write"
4233 );
4234 assert!(pricing.cny.is_none());
4235 }
4236
4237 #[test]
4238 fn sonnet_5_keeps_the_2_10_rate_before_the_former_2026_08_31_boundary() {
4239 assert_sonnet_5_standard_rate(
4240 Utc.with_ymd_and_hms(2026, 8, 31, 23, 59, 59)
4241 .single()
4242 .unwrap(),
4243 );
4244 assert!(has_pricing_for_model("claude-sonnet-5"));
4245 }
4246
4247 #[test]
4248 fn sonnet_5_does_not_flip_to_3_15_on_2026_09_01() {
4249 // Regression for the retired intro window: the scheduled increase was
4250 // cancelled upstream, so neither boundary minute nor any later time
4251 // may resurface 0.30 / 3.00 / 15.00 / 3.75.
4252 for at in [
4253 Utc.with_ymd_and_hms(2026, 9, 1, 0, 0, 0).single().unwrap(),
4254 Utc.with_ymd_and_hms(2027, 1, 1, 0, 0, 0).single().unwrap(),
4255 ] {
4256 assert_sonnet_5_standard_rate(at);
4257 let pricing = pricing_for_model_at("claude-sonnet-5", at).unwrap();
4258 assert_ne!(pricing.usd.input_cache_hit_per_million, 0.30);
4259 assert_ne!(pricing.usd.input_cache_miss_per_million, 3.00);
4260 assert_ne!(pricing.usd.output_per_million, 15.00);
4261 assert_ne!(pricing.usd.cache_write, CacheWritePolicy::Rate(3.75));
4262 }
4263 }
4264
4265 #[test]
4266 fn claude_opus_5_matches_published_first_party_card() {
4267 // https://platform.claude.com/docs/en/about-claude/pricing (2026-08-17):
4268 // $5 in / $25 out, cache read 0.50, 5m cache write 6.25.
4269 let pricing = pricing_for_model_at("claude-opus-5", Utc::now()).expect("Opus 5 pricing");
4270 assert_eq!(pricing.usd.input_cache_hit_per_million, 0.50);
4271 assert_eq!(pricing.usd.input_cache_miss_per_million, 5.00);
4272 assert_eq!(pricing.usd.output_per_million, 25.00);
4273 assert_eq!(pricing.usd.cache_write, CacheWritePolicy::Rate(6.25));
4274 assert!(pricing.cny.is_none());
4275 assert!(
4276 provider_owned_hand_pricing_at(ProviderKind::Anthropic, "claude-opus-5", Utc::now())
4277 .is_some(),
4278 "direct Anthropic owns the Opus 5 row"
4279 );
4280 assert!(
4281 provider_owned_hand_pricing_at(ProviderKind::Openrouter, "claude-opus-5", Utc::now())
4282 .is_none(),
4283 "an aggregator must not inherit the first-party Opus 5 row"
4284 );
4285 }
4286
4287 #[test]
4288 fn gpt_5_6_terra_and_luna_use_current_short_context_rates() {
4289 // https://developers.openai.com/api/docs/models/gpt-5.6-terra and
4290 // /gpt-5.6-luna (2026-08-17): Terra $2.00 / $0.20 / $12.00, Luna
4291 // $0.20 / $0.02 / $1.20 per 1M. The retired launch cards must not
4292 // resurface.
4293 for (model, hit, miss, out, stale) in [
4294 ("gpt-5.6-terra", 0.20, 2.00, 12.00, (0.25, 2.50, 15.00)),
4295 ("gpt-5.6-luna", 0.02, 0.20, 1.20, (0.10, 1.00, 6.00)),
4296 ] {
4297 let pricing = pricing_for_model_at(model, Utc::now()).expect(model);
4298 assert_eq!(pricing.usd.input_cache_hit_per_million, hit, "{model}");
4299 assert_eq!(pricing.usd.input_cache_miss_per_million, miss, "{model}");
4300 assert_eq!(pricing.usd.output_per_million, out, "{model}");
4301 assert_ne!(pricing.usd.input_cache_hit_per_million, stale.0);
4302 assert_ne!(pricing.usd.input_cache_miss_per_million, stale.1);
4303 assert_ne!(pricing.usd.output_per_million, stale.2);
4304 }
4305 }
4306
4307 #[test]
4308 fn moonshot_direct_kimi_k3_is_priced_but_membership_k3_is_not() {
4309 // https://platform.kimi.ai/docs/pricing/chat-k3 (2026-08-17):
4310 // cache-hit 0.30 / cache-miss 3.00 / output 15.00 per 1M.
4311 let now = Utc::now();
4312 let pricing = provider_owned_hand_pricing_at(ProviderKind::Moonshot, "kimi-k3", now)
4313 .expect("direct Moonshot owns the kimi-k3 row");
4314 assert_eq!(pricing.usd.input_cache_hit_per_million, 0.30);
4315 assert_eq!(pricing.usd.input_cache_miss_per_million, 3.00);
4316 assert_eq!(pricing.usd.output_per_million, 15.00);
4317 assert!(
4318 provider_owned_hand_pricing_at(ProviderKind::Moonshot, "k3", now).is_none(),
4319 "Kimi Code membership `k3` is quota billed"
4320 );
4321 assert!(pricing_for_model_at("k3", now).is_none());
4322 // Fireworks-hosted K3 keeps its own (still unpublished) rate card.
4323 assert!(
4324 provider_owned_hand_pricing_at(
4325 ProviderKind::Fireworks,
4326 "accounts/fireworks/models/kimi-k3",
4327 now
4328 )
4329 .is_none()
4330 );
4331 }
4332
4333 #[test]
4334 fn kimi_k2_7_code_highspeed_matches_published_rates() {
4335 // https://platform.kimi.ai/docs/pricing/chat-k27-code (2026-08-17).
4336 let now = Utc::now();
4337 let pricing =
4338 provider_owned_hand_pricing_at(ProviderKind::Moonshot, "kimi-k2.7-code-highspeed", now)
4339 .expect("direct Moonshot owns the K2.7 Code high-speed row");
4340 assert_eq!(pricing.usd.input_cache_hit_per_million, 0.38);
4341 assert_eq!(pricing.usd.input_cache_miss_per_million, 1.90);
4342 assert_eq!(pricing.usd.output_per_million, 8.00);
4343 // Exactly 2x the standard K2.7 Code card.
4344 let standard = pricing_for_model_at("kimi-k2.7-code", now).unwrap();
4345 assert!((standard.usd.input_cache_hit_per_million * 2.0 - 0.38).abs() < 1e-12);
4346 assert!((standard.usd.input_cache_miss_per_million * 2.0 - 1.90).abs() < 1e-12);
4347 assert!((standard.usd.output_per_million * 2.0 - 8.00).abs() < 1e-12);
4348 }
4349
4350 #[test]
4351 fn minimax_m2_7_highspeed_preserves_cache_read_and_write_rates() {
4352 // https://platform.minimax.io/docs/guides/pricing-paygo (2026-08-17):
4353 // $0.6 in / $2.4 out / $0.06 cache read / $0.375 cache write.
4354 for provider in [ProviderKind::Minimax, ProviderKind::MinimaxAnthropic] {
4355 let pricing =
4356 provider_owned_hand_pricing_at(provider, "MiniMax-M2.7-highspeed", Utc::now())
4357 .expect("direct MiniMax owns the M2.7 high-speed row");
4358 assert_eq!(
4359 pricing.usd.input_cache_hit_per_million, 0.06,
4360 "{provider:?}"
4361 );
4362 assert_eq!(
4363 pricing.usd.input_cache_miss_per_million, 0.60,
4364 "{provider:?}"
4365 );
4366 assert_eq!(pricing.usd.output_per_million, 2.40, "{provider:?}");
4367 assert_eq!(
4368 pricing.usd.cache_write,
4369 CacheWritePolicy::Rate(0.375),
4370 "{provider:?}"
4371 );
4372 }
4373 }
4374
4375 #[test]
4376 fn mistral_first_party_rows_match_published_table_and_stay_provider_owned() {
4377 // https://docs.mistral.ai/inference/pricing (2026-08-17): Medium 3.5
4378 // 1.5 / 0.15 / 7.5, Large 3 0.5 / 0.05 / 1.5, Small 4 0.15 / 0.015 /
4379 // 0.6, Codestral 0.3 / 0.03 / 0.9 (input / cached input / output).
4380 let now = Utc::now();
4381 for (model, hit, miss, out) in [
4382 ("mistral-medium-latest", 0.15, 1.50, 7.50),
4383 ("mistral-large-latest", 0.05, 0.50, 1.50),
4384 ("mistral-small-latest", 0.015, 0.15, 0.60),
4385 ("mistral-code-latest", 0.03, 0.30, 0.90),
4386 ] {
4387 let pricing = provider_owned_hand_pricing_at(ProviderKind::Mistral, model, now)
4388 .unwrap_or_else(|| panic!("direct Mistral owns {model}"));
4389 assert_eq!(pricing.usd.input_cache_hit_per_million, hit, "{model}");
4390 assert_eq!(pricing.usd.input_cache_miss_per_million, miss, "{model}");
4391 assert_eq!(pricing.usd.output_per_million, out, "{model}");
4392 // No published cache-write rate: unpriced, never assumed.
4393 assert_eq!(
4394 pricing.usd.cache_write,
4395 CacheWritePolicy::Unpublished,
4396 "{model}"
4397 );
4398 assert!(
4399 provider_owned_hand_pricing_at(ProviderKind::Openrouter, model, now).is_none(),
4400 "{model}: aggregators must not inherit first-party Mistral rates"
4401 );
4402 }
4403 }
4404
4405 /// Published DeepSeek V4 rates per 1M tokens (cache-hit, cache-miss,
4406 /// output), verified live on api-docs.deepseek.com/quick_start/pricing
4407 /// (and /zh-cn) on 2026-08-17. Off-peak is exactly half of peak.
4408 const DEEPSEEK_V4_FLASH_USD_OFF_PEAK: (f64, f64, f64) = (0.007, 0.22, 0.66);
4409 const DEEPSEEK_V4_FLASH_USD_PEAK: (f64, f64, f64) = (0.014, 0.44, 1.32);
4410 const DEEPSEEK_V4_FLASH_CNY_OFF_PEAK: (f64, f64, f64) = (0.05, 1.5, 4.5);
4411 const DEEPSEEK_V4_FLASH_CNY_PEAK: (f64, f64, f64) = (0.10, 3.0, 9.0);
4412 const DEEPSEEK_V4_PRO_USD_OFF_PEAK: (f64, f64, f64) = (0.022, 0.66, 1.98);
4413 const DEEPSEEK_V4_PRO_USD_PEAK: (f64, f64, f64) = (0.044, 1.32, 3.96);
4414 const DEEPSEEK_V4_PRO_CNY_OFF_PEAK: (f64, f64, f64) = (0.15, 4.5, 13.5);
4415 const DEEPSEEK_V4_PRO_CNY_PEAK: (f64, f64, f64) = (0.30, 9.0, 27.0);
4416
4417 fn assert_currency_rates(actual: &CurrencyPricing, expected: (f64, f64, f64), ctx: &str) {
4418 assert_eq!(
4419 actual.input_cache_hit_per_million, expected.0,
4420 "{ctx} cache-hit"
4421 );
4422 assert_eq!(
4423 actual.input_cache_miss_per_million, expected.1,
4424 "{ctx} cache-miss"
4425 );
4426 assert_eq!(actual.output_per_million, expected.2, "{ctx} output");
4427 assert_eq!(
4428 actual.cache_write,
4429 CacheWritePolicy::DocumentedAsInputRate(DEEPSEEK_CACHE_WRITE_IS_FREE),
4430 "{ctx} cache-write"
4431 );
4432 }
4433
4434 fn assert_deepseek_tier(model: &str, at: DateTime<Utc>, peak: bool) {
4435 let pricing = pricing_for_model_at(model, at).expect("DeepSeek V4 pricing");
4436 let (usd, cny) = match (model.contains("pro"), peak) {
4437 (true, true) => (DEEPSEEK_V4_PRO_USD_PEAK, DEEPSEEK_V4_PRO_CNY_PEAK),
4438 (true, false) => (DEEPSEEK_V4_PRO_USD_OFF_PEAK, DEEPSEEK_V4_PRO_CNY_OFF_PEAK),
4439 (false, true) => (DEEPSEEK_V4_FLASH_USD_PEAK, DEEPSEEK_V4_FLASH_CNY_PEAK),
4440 (false, false) => (
4441 DEEPSEEK_V4_FLASH_USD_OFF_PEAK,
4442 DEEPSEEK_V4_FLASH_CNY_OFF_PEAK,
4443 ),
4444 };
4445 let tier = if peak { "peak" } else { "off-peak" };
4446 assert_currency_rates(&pricing.usd, usd, &format!("{model} @ {at} USD {tier}"));
4447 let cny_pricing = pricing.cny.expect("DeepSeek pricing has CNY");
4448 assert_currency_rates(&cny_pricing, cny, &format!("{model} @ {at} CNY {tier}"));
4449 }
4450
4451 fn utc_hm(hour: u32, minute: u32) -> DateTime<Utc> {
4452 Utc.with_ymd_and_hms(2026, 8, 17, hour, minute, 59)
4453 .single()
4454 .unwrap()
4455 }
4456
4457 #[test]
4458 fn deepseek_v4_tiers_flip_at_each_published_utc_boundary() {
4459 // Peak windows are 01:00-04:00 and 06:00-10:00 UTC, half-open: the
4460 // start minute is peak, the end minute is off-peak.
4461 let boundaries = [
4462 (utc_hm(0, 59), false),
4463 (utc_hm(1, 0), true),
4464 (utc_hm(3, 59), true),
4465 (utc_hm(4, 0), false),
4466 (utc_hm(5, 59), false),
4467 (utc_hm(6, 0), true),
4468 (utc_hm(9, 59), true),
4469 (utc_hm(10, 0), false),
4470 ];
4471 for model in ["deepseek-v4-pro", "deepseek-v4-flash"] {
4472 for (at, peak) in boundaries {
4473 assert_deepseek_tier(model, at, peak);
4474 }
4475 }
4476 }
4477
4478 fn utc_ymd_h(year: i32, month: u32, day: u32, hour: u32) -> DateTime<Utc> {
4479 Utc.with_ymd_and_hms(year, month, day, hour, 0, 0)
4480 .single()
4481 .unwrap()
4482 }
4483
4484 #[test]
4485 fn deepseek_v4_bills_beijing_weekends_off_peak_from_the_published_date() {
4486 // 2026-08-22T16:00Z is 00:00 Beijing on Sunday 2026-08-23, when the rule
4487 // starts. Times are UTC; the Beijing day is in the comment.
4488 let cases = [
4489 (utc_ymd_h(2026, 8, 22, 6), true), // Sat 14:00 Beijing, rule not yet live
4490 (utc_ymd_h(2026, 8, 23, 1), false), // Sun 09:00 Beijing, first window it changes
4491 (utc_ymd_h(2026, 8, 23, 9), false), // Sun 17:00 Beijing
4492 (utc_ymd_h(2026, 8, 24, 1), true), // Mon 09:00 Beijing
4493 (utc_ymd_h(2026, 8, 28, 6), true), // Fri 14:00 Beijing
4494 (utc_ymd_h(2026, 8, 29, 6), false), // Sat 14:00 Beijing
4495 ];
4496 for (at, peak) in cases {
4497 assert_eq!(deepseek_is_peak(at), peak, "peak tier at {at}");
4498 for model in ["deepseek-v4-pro", "deepseek-v4-flash"] {
4499 assert_deepseek_tier(model, at, peak);
4500 }
4501 }
4502 }
4503
4504 #[test]
4505 fn deepseek_v4_pro_keeps_pro_rates_after_cancelled_retirement() {
4506 for day in [13, 14, 15, 21] {
4507 let at = utc_ymd_h(2026, 9, day, 12);
4508 let pro = pricing_for_model_at("deepseek-v4-pro", at).unwrap();
4509 let flash = pricing_for_model_at("deepseek-flash", at).unwrap();
4510 assert_eq!(pro.usd.output_per_million, 1.98);
4511 assert_ne!(pro.usd.output_per_million, flash.usd.output_per_million);
4512 }
4513 }
4514
4515 #[test]
4516 fn deepseek_v4_pro_off_peak_and_peak_rates_match_published_table() {
4517 assert_deepseek_tier("deepseek-v4-pro", utc_hm(12, 0), false);
4518 assert_deepseek_tier("deepseek-v4-pro", utc_hm(2, 0), true);
4519 // Regression for #267 / #2489: the retired flat promo rates must not
4520 // resurface in either tier.
4521 for at in [utc_hm(12, 0), utc_hm(2, 0)] {
4522 let pricing = pricing_for_model_at("deepseek-v4-pro", at).unwrap();
4523 assert_ne!(pricing.usd.input_cache_hit_per_million, 0.003625);
4524 assert_ne!(pricing.usd.input_cache_miss_per_million, 0.435);
4525 assert_ne!(pricing.usd.output_per_million, 0.87);
4526 }
4527 }
4528
4529 #[test]
4530 fn deepseek_v4_flash_off_peak_and_peak_rates_match_published_table() {
4531 assert_deepseek_tier("deepseek-v4-flash", utc_hm(12, 0), false);
4532 assert_deepseek_tier("deepseek-v4-flash", utc_hm(7, 0), true);
4533 for at in [utc_hm(12, 0), utc_hm(7, 0)] {
4534 let pricing = pricing_for_model_at("deepseek-v4-flash", at).unwrap();
4535 assert_ne!(pricing.usd.input_cache_hit_per_million, 0.0028);
4536 assert_ne!(pricing.usd.input_cache_miss_per_million, 0.14);
4537 assert_ne!(pricing.usd.output_per_million, 0.28);
4538 }
4539 }
4540
4541 #[test]
4542 fn deepseek_v4_off_peak_is_exactly_half_of_peak() {
4543 for model in ["deepseek-v4-pro", "deepseek-v4-flash"] {
4544 let off = pricing_for_model_at(model, utc_hm(12, 0)).unwrap();
4545 let peak = pricing_for_model_at(model, utc_hm(2, 0)).unwrap();
4546 for (o, p) in [
4547 (
4548 off.usd.input_cache_hit_per_million,
4549 peak.usd.input_cache_hit_per_million,
4550 ),
4551 (
4552 off.usd.input_cache_miss_per_million,
4553 peak.usd.input_cache_miss_per_million,
4554 ),
4555 (off.usd.output_per_million, peak.usd.output_per_million),
4556 ] {
4557 assert!((o * 2.0 - p).abs() < 1e-12, "{model}: {o} * 2 != {p}");
4558 }
4559 let (off_cny, peak_cny) = (off.cny.unwrap(), peak.cny.unwrap());
4560 for (o, p) in [
4561 (
4562 off_cny.input_cache_hit_per_million,
4563 peak_cny.input_cache_hit_per_million,
4564 ),
4565 (
4566 off_cny.input_cache_miss_per_million,
4567 peak_cny.input_cache_miss_per_million,
4568 ),
4569 (off_cny.output_per_million, peak_cny.output_per_million),
4570 ] {
4571 assert!((o * 2.0 - p).abs() < 1e-12, "{model}: CNY {o} * 2 != {p}");
4572 }
4573 }
4574 }
4575
4576 /// The route audit prices a DeepSeek turn at the tier of its RECORDED
4577 /// time, not the wall clock at audit time (same contract as Sonnet 5's
4578 /// recorded-time introductory window).
4579 #[test]
4580 fn deepseek_audit_uses_recorded_time_tier_not_now() {
4581 let usage = million_input_usage();
4582 for (provider, model) in [
4583 (ProviderKind::Deepseek, "deepseek-v4-flash"),
4584 (ProviderKind::Deepseek, "deepseek-v4-pro"),
4585 (ProviderKind::Deepseek, "deepseek-v4-flash"),
4586 (ProviderKind::DeepseekAnthropic, "deepseek-v4-pro"),
4587 ] {
4588 let off_peak_usd = if model.contains("pro") { 0.66 } else { 0.22 };
4589 let off_peak_cny = if model.contains("pro") { 4.5 } else { 1.5 };
4590 let off = audit_turn_cost_for_provider_at(provider, model, &usage, utc_hm(12, 0));
4591 assert!(off.is_priced(), "{provider:?}/{model}: {off:?}");
4592 let off_estimate = off.estimate.expect("priced");
4593 assert!(
4594 (off_estimate.usd - off_peak_usd).abs() < 1e-12,
4595 "{provider:?}/{model} off-peak: {}",
4596 off_estimate.usd
4597 );
4598 assert!(
4599 (off_estimate.cny - off_peak_cny).abs() < 1e-12,
4600 "{provider:?}/{model} off-peak CNY: {}",
4601 off_estimate.cny
4602 );
4603
4604 let peak = audit_turn_cost_for_provider_at(provider, model, &usage, utc_hm(2, 0));
4605 assert!(peak.is_priced(), "{provider:?}/{model}: {peak:?}");
4606 let peak_estimate = peak.estimate.expect("priced");
4607 assert!(
4608 (peak_estimate.usd - 2.0 * off_peak_usd).abs() < 1e-12,
4609 "{provider:?}/{model} peak: {}",
4610 peak_estimate.usd
4611 );
4612 assert!(
4613 (peak_estimate.cny - 2.0 * off_peak_cny).abs() < 1e-12,
4614 "{provider:?}/{model} peak CNY: {}",
4615 peak_estimate.cny
4616 );
4617 }
4618 }
4619
4620 #[test]
4621 fn fireworks_and_zen_flash_use_bundled_family_rates() {
4622 let now = Utc.with_ymd_and_hms(2026, 8, 14, 0, 0, 0).single().unwrap();
4623 let fireworks = provider_owned_hand_pricing_at(
4624 ProviderKind::Fireworks,
4625 "accounts/fireworks/models/deepseek-v4-flash",
4626 now,
4627 )
4628 .expect("Fireworks Flash should inherit the bundled DeepSeek family row");
4629 let zen =
4630 provider_owned_hand_pricing_at(ProviderKind::OpencodeZen, "deepseek-v4-flash", now)
4631 .expect("OpenCode Zen Flash should inherit the bundled DeepSeek family row");
4632 assert_eq!(fireworks.usd.output_per_million, zen.usd.output_per_million);
4633 assert!(
4634 provider_owned_hand_pricing_at(
4635 ProviderKind::Fireworks,
4636 "accounts/fireworks/models/kimi-k3",
4637 now,
4638 )
4639 .is_none(),
4640 "kimi-k3 has no published bundled rate; do not invent one"
4641 );
4642 }
4643
4644 #[test]
4645 fn xiaomi_mimo_token_plan_models_leave_cost_unknown() {
4646 let now = Utc.with_ymd_and_hms(2026, 6, 4, 0, 0, 0).single().unwrap();
4647
4648 for model in [
4649 "mimo-v2.5-pro",
4650 "mimo-v2.5-pro-ultraspeed",
4651 "mimo-v2.5",
4652 "xiaomi/mimo-v2.5",
4653 ] {
4654 assert!(pricing_for_model_at(model, now).is_none());
4655 assert!(!has_pricing_for_model(model));
4656 }
4657 }
4658
4659 #[test]
4660 fn cost_estimate_calculates_usd_and_cny() {
4661 let usage = Usage {
4662 input_tokens: 1_000_000,
4663 output_tokens: 500_000,
4664 ..Default::default()
4665 };
4666 // Off-peak (12:00 UTC): 1M input at 0.22 + 0.5M output at 0.66 USD;
4667 // 1.5 + 0.5 * 4.5 CNY.
4668 let off_peak = Utc
4669 .with_ymd_and_hms(2026, 8, 17, 12, 0, 0)
4670 .single()
4671 .unwrap();
4672 let pricing = pricing_for_model_at("deepseek-v4-flash", off_peak).expect("pricing");
4673 let estimate = cost_estimate_with_pricing(pricing, &usage);
4674 assert!((estimate.usd - 0.55).abs() < 1e-12, "{}", estimate.usd);
4675 assert!((estimate.cny - 3.75).abs() < 1e-12, "{}", estimate.cny);
4676
4677 // Peak (02:00 UTC) doubles both currencies.
4678 let peak = Utc.with_ymd_and_hms(2026, 8, 17, 2, 0, 0).single().unwrap();
4679 let pricing = pricing_for_model_at("deepseek-v4-flash", peak).expect("pricing");
4680 let estimate = cost_estimate_with_pricing(pricing, &usage);
4681 assert!((estimate.usd - 1.10).abs() < 1e-12, "{}", estimate.usd);
4682 assert!((estimate.cny - 7.5).abs() < 1e-12, "{}", estimate.cny);
4683 }
4684
4685 #[test]
4686 fn cost_currency_accepts_yuan_aliases() {
4687 assert_eq!(CostCurrency::from_setting("usd"), Some(CostCurrency::Usd));
4688 assert_eq!(CostCurrency::from_setting("yuan"), Some(CostCurrency::Cny));
4689 assert_eq!(CostCurrency::from_setting("rmb"), Some(CostCurrency::Cny));
4690 assert_eq!(CostCurrency::from_setting("cny"), Some(CostCurrency::Cny));
4691 assert_eq!(CostCurrency::from_setting("eur"), None);
4692 }
4693
4694 #[test]
4695 fn format_cost_amount_uses_selected_symbol() {
4696 assert_eq!(format_cost_amount(0.42, CostCurrency::Usd), "$0.42");
4697 assert_eq!(format_cost_amount(2.0, CostCurrency::Cny), "¥2.00");
4698 assert_eq!(format_cost_amount(0.0, CostCurrency::Usd), "$0.00");
4699 assert_eq!(format_cost_amount(0.00001, CostCurrency::Usd), "<$0.0001");
4700 }
4701
4702 #[test]
4703 fn format_cost_amount_precise_keeps_report_precision() {
4704 assert_eq!(
4705 codewhale_commands::diagnostics_reports::format_cost_amount_precise(
4706 0.1234,
4707 codewhale_command_contract::types::CommandCurrency::Usd
4708 ),
4709 "$0.1234"
4710 );
4711 assert_eq!(
4712 codewhale_commands::diagnostics_reports::format_cost_amount_precise(
4713 0.1234,
4714 codewhale_command_contract::types::CommandCurrency::Cny
4715 ),
4716 "¥0.1234"
4717 );
4718 assert_eq!(
4719 codewhale_commands::diagnostics_reports::format_cost_amount_precise(
4720 0.0,
4721 codewhale_command_contract::types::CommandCurrency::Usd
4722 ),
4723 "$0.0000"
4724 );
4725 assert_eq!(
4726 codewhale_commands::diagnostics_reports::format_cost_amount_precise(
4727 0.00001,
4728 codewhale_command_contract::types::CommandCurrency::Usd
4729 ),
4730 "<$0.0001"
4731 );
4732 }
4733
4734 #[test]
4735 fn accumulated_cost_stays_finite_and_nonnegative() {
4736 let saturated = CostEstimate {
4737 usd: f64::MAX,
4738 cny: 1.0,
4739 }
4740 .saturating_add(CostEstimate {
4741 usd: f64::MAX,
4742 cny: -1.0,
4743 });
4744 assert_eq!(saturated.usd, f64::MAX);
4745 assert_eq!(saturated.cny, 1.0);
4746 assert!(saturated.is_finite_nonnegative());
4747
4748 assert_eq!(
4749 CostEstimate {
4750 usd: f64::NAN,
4751 cny: f64::INFINITY,
4752 }
4753 .sanitized(),
4754 CostEstimate::default()
4755 );
4756 }
4757
4758 fn official_route_audit(provider: ProviderKind, model: &str, usage: &Usage) -> TurnCostAudit {
4759 let base = provider.provider().default_base_url();
4760 let at = Utc::now();
4761 let fingerprint = codewhale_config::catalog::base_url_fingerprint(base);
4762 let quote = crate::provider_catalog_live::fresh_dispatch_pricing_quote_at(
4763 provider,
4764 provider.as_str(),
4765 model,
4766 base,
4767 at.timestamp() as u64,
4768 );
4769 audit_turn_cost_for_route_on_endpoint_for_identity_at(
4770 provider,
4771 Some(provider.as_str()),
4772 model,
4773 billing_surface_for_route(provider, Some(base)),
4774 Some(&fingerprint),
4775 quote.as_ref(),
4776 usage,
4777 at,
4778 )
4779 }
4780
4781 fn million_input_usage() -> Usage {
4782 Usage {
4783 input_tokens: 1_000_000,
4784 output_tokens: 0,
4785 ..Usage::default()
4786 }
4787 }
4788
4789 /// #5241: Fireworks flash / pro and OpenCode Zen flash must leave
4790 /// `unverified_live_pricing` via provider-docs bundled rates when live
4791 /// control-plane / Models.dev pricing is not a usable rate source.
4792 #[test]
4793 fn hosted_flash_and_pro_routes_price_from_bundled_docs_rates() {
4794 let usage = million_input_usage();
4795 let now = Utc::now();
4796 let cases = [
4797 (
4798 ProviderKind::Fireworks,
4799 "accounts/fireworks/models/deepseek-v4-flash-0731",
4800 0.14,
4801 ),
4802 (
4803 ProviderKind::Fireworks,
4804 "accounts/fireworks/models/deepseek-v4-flash",
4805 0.14,
4806 ),
4807 (ProviderKind::Fireworks, "deepseek-v4-flash", 0.14),
4808 (
4809 ProviderKind::Fireworks,
4810 "accounts/fireworks/models/deepseek-v4-pro",
4811 1.74,
4812 ),
4813 (ProviderKind::OpencodeZen, "deepseek-v4-flash", 0.14),
4814 ];
4815 for (provider, model, expected_usd) in cases {
4816 let audit = official_route_audit(provider, model, &usage);
4817 assert!(
4818 audit.is_priced(),
4819 "{provider:?}/{model} must price on its official endpoint: {audit:?}"
4820 );
4821 assert_ne!(
4822 audit.unpriced_reason,
4823 Some(UnpricedReason::UnverifiedLivePricing),
4824 "{provider:?}/{model}"
4825 );
4826 assert_eq!(
4827 audit.provenance,
4828 Some(PricingProvenance::ProviderDocs),
4829 "{provider:?}/{model}"
4830 );
4831 let estimate = audit.estimate.expect("priced");
4832 assert!(
4833 (estimate.usd - expected_usd).abs() < 1e-12,
4834 "{provider:?}/{model}: {} != {expected_usd}",
4835 estimate.usd
4836 );
4837 assert_eq!(estimate.cny, 0.0, "{provider:?}/{model}");
4838
4839 let hand =
4840 provider_owned_hand_pricing_at(provider, model, now).expect("bundled fallback row");
4841 if model.contains("flash") {
4842 assert_eq!(hand.usd.input_cache_hit_per_million, 0.028);
4843 for first_party in [0.007, 0.014] {
4844 assert_ne!(
4845 hand.usd.input_cache_hit_per_million, first_party,
4846 "must not inherit first-party DeepSeek cache-hit"
4847 );
4848 }
4849 }
4850 }
4851
4852 let off_peak = Utc
4853 .with_ymd_and_hms(2026, 8, 17, 12, 0, 0)
4854 .single()
4855 .unwrap();
4856 let peak = Utc.with_ymd_and_hms(2026, 8, 17, 2, 0, 0).single().unwrap();
4857 assert_eq!(
4858 pricing_for_model_at("deepseek-v4-flash", off_peak)
4859 .expect("Flash pricing")
4860 .usd
4861 .input_cache_hit_per_million,
4862 0.007
4863 );
4864 assert_eq!(
4865 pricing_for_model_at("deepseek-v4-flash", peak)
4866 .expect("Flash pricing")
4867 .usd
4868 .input_cache_hit_per_million,
4869 0.014
4870 );
4871 }
4872
4873 #[test]
4874 fn models_dev_live_rates_price_the_published_estimate() {
4875 let _live = crate::provider_lake::lock_live_snapshot();
4876 crate::provider_lake::clear_live_snapshot();
4877 let now = Utc::now();
4878 let fetched_at = u64::try_from(now.timestamp()).expect("timestamp");
4879 crate::provider_lake::set_live_snapshot(
4880 codewhale_config::catalog::CatalogSnapshot {
4881 offerings: vec![codewhale_config::catalog::CatalogOffering {
4882 provider: "fireworks".to_string(),
4883 wire_model_id: "accounts/fireworks/models/deepseek-v4-flash-0731".to_string(),
4884 endpoint_key: "chat".to_string(),
4885 cost: Some(codewhale_config::models_dev::ModelsDevCost {
4886 input: Some(99.0),
4887 output: Some(199.0),
4888 cache_read: Some(9.0),
4889 cache_write: None,
4890 ..Default::default()
4891 }),
4892 source: codewhale_config::catalog::CatalogSource::Live {
4893 base_url_fingerprint: "models-dev-capabilities".to_string(),
4894 fetched_at,
4895 },
4896 ..Default::default()
4897 }],
4898 },
4899 crate::provider_lake::LiveSource::ModelsDev,
4900 );
4901
4902 let usage = million_input_usage();
4903 let audit = official_route_audit(
4904 ProviderKind::Fireworks,
4905 "accounts/fireworks/models/deepseek-v4-flash-0731",
4906 &usage,
4907 );
4908 crate::provider_lake::clear_live_snapshot();
4909
4910 assert!(audit.is_priced(), "{audit:?}");
4911 assert_ne!(
4912 audit.unpriced_reason,
4913 Some(UnpricedReason::UnverifiedLivePricing)
4914 );
4915 assert_eq!(audit.provenance, Some(PricingProvenance::ModelsDevLive));
4916 assert_eq!(audit.live_pricing_defect, None);
4917 let estimate = audit.estimate.expect("priced");
4918 assert!(
4919 (estimate.usd - 99.0).abs() < 1e-12,
4920 "live models.dev input rate must price the estimate: {}",
4921 estimate.usd
4922 );
4923 }
4924
4925 #[test]
4926 fn unverifiable_provider_live_rates_degrade_to_bundled_docs_with_defect() {
4927 let _live = crate::provider_lake::lock_live_snapshot();
4928 crate::provider_lake::clear_live_snapshot();
4929 let now = Utc::now();
4930 let fetched_at = u64::try_from(now.timestamp()).expect("timestamp");
4931 crate::provider_lake::set_live_snapshot(
4932 codewhale_config::catalog::CatalogSnapshot {
4933 offerings: vec![codewhale_config::catalog::CatalogOffering {
4934 provider: "opencode-zen".to_string(),
4935 wire_model_id: "deepseek-v4-flash".to_string(),
4936 endpoint_key: "chat".to_string(),
4937 cost: Some(codewhale_config::models_dev::ModelsDevCost {
4938 input: Some(99.0),
4939 output: Some(199.0),
4940 cache_read: Some(9.0),
4941 cache_write: None,
4942 ..Default::default()
4943 }),
4944 source: codewhale_config::catalog::CatalogSource::Live {
4945 base_url_fingerprint: "other-endpoint".to_string(),
4946 fetched_at,
4947 },
4948 ..Default::default()
4949 }],
4950 },
4951 crate::provider_lake::LiveSource::PerProvider,
4952 );
4953
4954 let usage = million_input_usage();
4955 let fingerprint = codewhale_config::catalog::base_url_fingerprint(
4956 ProviderKind::OpencodeZen.provider().default_base_url(),
4957 );
4958 let audit = audit_turn_cost_for_provider_on_endpoint_at(
4959 ProviderKind::OpencodeZen,
4960 "deepseek-v4-flash",
4961 Some(&fingerprint),
4962 &usage,
4963 now,
4964 );
4965 crate::provider_lake::clear_live_snapshot();
4966
4967 assert!(audit.is_priced(), "{audit:?}");
4968 assert_eq!(audit.provenance, Some(PricingProvenance::ProviderDocs));
4969 assert!(
4970 audit.live_pricing_defect.is_some(),
4971 "unverified provider-live must receipt a defect: {audit:?}"
4972 );
4973 let estimate = audit.estimate.expect("priced");
4974 assert!((estimate.usd - 0.14).abs() < 1e-12, "{}", estimate.usd);
4975 }
4976
4977 #[test]
4978 fn verified_provider_live_rates_win_over_bundled_docs() {
4979 let _live = crate::provider_lake::lock_live_snapshot();
4980 crate::provider_lake::clear_live_snapshot();
4981 let now = Utc::now();
4982 let fetched_at = u64::try_from(now.timestamp()).expect("timestamp");
4983 let fingerprint = codewhale_config::catalog::base_url_fingerprint(
4984 codewhale_config::descriptors::defaults::DEFAULT_FIREWORKS_BASE_URL,
4985 );
4986 crate::provider_lake::set_live_snapshot(
4987 codewhale_config::catalog::CatalogSnapshot {
4988 offerings: vec![codewhale_config::catalog::CatalogOffering {
4989 provider: "fireworks".to_string(),
4990 wire_model_id: "accounts/fireworks/models/kimi-k3".to_string(),
4991 endpoint_key: "chat".to_string(),
4992 cost: Some(codewhale_config::models_dev::ModelsDevCost {
4993 input: Some(9.0),
4994 output: Some(18.0),
4995 cache_read: Some(1.0),
4996 cache_write: None,
4997 ..Default::default()
4998 }),
4999 source: codewhale_config::catalog::CatalogSource::Live {
5000 base_url_fingerprint: fingerprint.clone(),
5001 fetched_at,
5002 },
5003 ..Default::default()
5004 }],
5005 },
5006 crate::provider_lake::LiveSource::PerProvider,
5007 );
5008
5009 let usage = million_input_usage();
5010 let audit = official_route_audit(
5011 ProviderKind::Fireworks,
5012 "accounts/fireworks/models/kimi-k3",
5013 &usage,
5014 );
5015 crate::provider_lake::clear_live_snapshot();
5016
5017 assert!(audit.is_priced(), "{audit:?}");
5018 assert_eq!(audit.provenance, Some(PricingProvenance::ProviderLive));
5019 assert_eq!(audit.live_pricing_defect, None);
5020 let estimate = audit.estimate.expect("priced");
5021 assert!(
5022 (estimate.usd - 9.0).abs() < 1e-12,
5023 "verified live must win: {}",
5024 estimate.usd
5025 );
5026 }
5027
5028 #[test]
5029 fn future_effective_provider_live_rate_is_not_treated_as_age_zero() {
5030 let _live = crate::provider_lake::lock_live_snapshot();
5031 crate::provider_lake::clear_live_snapshot();
5032 let dispatched_at = Utc::now();
5033 let future_fetched_at = u64::try_from(dispatched_at.timestamp())
5034 .expect("timestamp")
5035 .saturating_add(1);
5036 let fingerprint = codewhale_config::catalog::base_url_fingerprint(
5037 codewhale_config::descriptors::defaults::DEFAULT_FIREWORKS_BASE_URL,
5038 );
5039 crate::provider_lake::set_live_snapshot(
5040 codewhale_config::catalog::CatalogSnapshot {
5041 offerings: vec![codewhale_config::catalog::CatalogOffering {
5042 provider: "fireworks".to_string(),
5043 wire_model_id: "accounts/fireworks/models/future-price-only".to_string(),
5044 endpoint_key: "chat".to_string(),
5045 cost: Some(codewhale_config::models_dev::ModelsDevCost {
5046 input: Some(9.0),
5047 output: Some(18.0),
5048 cache_read: Some(1.0),
5049 cache_write: None,
5050 ..Default::default()
5051 }),
5052 source: codewhale_config::catalog::CatalogSource::Live {
5053 base_url_fingerprint: fingerprint.clone(),
5054 fetched_at: future_fetched_at,
5055 },
5056 ..Default::default()
5057 }],
5058 },
5059 crate::provider_lake::LiveSource::PerProvider,
5060 );
5061
5062 let audit = audit_turn_cost_for_provider_on_endpoint_at(
5063 ProviderKind::Fireworks,
5064 "accounts/fireworks/models/future-price-only",
5065 Some(&fingerprint),
5066 &million_input_usage(),
5067 dispatched_at,
5068 );
5069 crate::provider_lake::clear_live_snapshot();
5070
5071 assert!(
5072 !audit.is_priced(),
5073 "future price must fail closed: {audit:?}"
5074 );
5075 assert_eq!(
5076 audit.unpriced_reason,
5077 Some(UnpricedReason::UnverifiedLivePricing)
5078 );
5079 }
5080
5081 /// The fixture deliberately stamps `Live` rather than the `ModelsDevLive`
5082 /// the refresh now emits: this pins the *second*, independent check — the
5083 /// live partition the row sits in — which is what decides the price basis
5084 /// of a row mislabelled by an older publisher or a stale on-disk cache. Do
5085 /// not "correct" the source here; that would delete this belt's only
5086 /// coverage.
5087 #[test]
5088 fn models_dev_partition_live_rows_price_the_live_catalog_rate() {
5089 let _live = crate::provider_lake::lock_live_snapshot();
5090 crate::provider_lake::clear_live_snapshot();
5091 let now = Utc::now();
5092 let fetched_at = u64::try_from(now.timestamp()).expect("timestamp");
5093 crate::provider_lake::set_live_snapshot(
5094 codewhale_config::catalog::CatalogSnapshot {
5095 offerings: vec![codewhale_config::catalog::CatalogOffering {
5096 provider: "openai".to_string(),
5097 wire_model_id: "gpt-5.5".to_string(),
5098 endpoint_key: "chat".to_string(),
5099 cost: Some(codewhale_config::models_dev::ModelsDevCost {
5100 input: Some(99.0),
5101 output: Some(199.0),
5102 cache_read: Some(9.0),
5103 cache_write: None,
5104 ..Default::default()
5105 }),
5106 source: codewhale_config::catalog::CatalogSource::Live {
5107 base_url_fingerprint: "models-dev-capabilities".to_string(),
5108 fetched_at,
5109 },
5110 ..Default::default()
5111 }],
5112 },
5113 crate::provider_lake::LiveSource::ModelsDev,
5114 );
5115
5116 // Stay under the 272K long-context surcharge so this asserts the
5117 // catalog source, not the unrepresented-tier guard.
5118 let usage = Usage {
5119 input_tokens: 10_000,
5120 output_tokens: 0,
5121 ..Usage::default()
5122 };
5123 let audit = official_route_audit(ProviderKind::Openai, "gpt-5.5", &usage);
5124 crate::provider_lake::clear_live_snapshot();
5125
5126 assert!(audit.is_priced(), "{audit:?}");
5127 assert_eq!(audit.provenance, Some(PricingProvenance::ModelsDevLive));
5128 assert_eq!(audit.live_pricing_defect, None);
5129 let estimate = audit.estimate.expect("priced");
5130 assert!(
5131 (estimate.usd - 0.99).abs() < 1e-12,
5132 "the models.dev live rate must price the estimate: {}",
5133 estimate.usd
5134 );
5135 }
5136
5137 /// Concentrate publishes different upstream rates and can fail over even
5138 /// when a provider/model prefix is requested, so a requested model's own
5139 /// published rate is never inherited: without a verified scoped offering
5140 /// the route reports the explicit routing-dependent reason instead of
5141 /// dollars (#5976).
5142 #[test]
5143 fn concentrate_without_verified_scoped_pricing_reports_routing_dependent() {
5144 let _live = crate::provider_lake::lock_live_snapshot();
5145 crate::provider_lake::clear_live_snapshot();
5146 let usage = million_input_usage();
5147
5148 // deepseek-v4-pro is the model owner's own hand-priced row; a
5149 // Concentrate request for it must not inherit that rate.
5150 let audit = official_route_audit(ProviderKind::Concentrate, "deepseek-v4-pro", &usage);
5151 assert!(!audit.is_priced(), "{audit:?}");
5152 assert_eq!(
5153 audit.unpriced_reason,
5154 Some(UnpricedReason::RoutingDependentPrice),
5155 "{audit:?}"
5156 );
5157 assert!(!has_pricing_for_provider(
5158 ProviderKind::Concentrate,
5159 "deepseek-v4-pro"
5160 ));
5161 }
5162
5163 /// A fresh per-provider `/models` row fetched from the exact Concentrate
5164 /// endpoint is the scoped offering that *is* authoritative: with the
5165 /// endpoint fingerprint it prices at the scoped rate; without it the same
5166 /// row degrades to an unverified-live receipt rather than billing.
5167 #[test]
5168 fn concentrate_scoped_offering_prices_only_with_endpoint_provenance() {
5169 let _live = crate::provider_lake::lock_live_snapshot();
5170 crate::provider_lake::clear_live_snapshot();
5171 let now = Utc::now();
5172 let fetched_at = u64::try_from(now.timestamp()).expect("timestamp");
5173 let fingerprint = codewhale_config::catalog::base_url_fingerprint(
5174 codewhale_config::descriptors::defaults::DEFAULT_CONCENTRATE_BASE_URL,
5175 );
5176 crate::provider_lake::set_live_snapshot(
5177 codewhale_config::catalog::CatalogSnapshot {
5178 offerings: vec![codewhale_config::catalog::CatalogOffering {
5179 provider: "concentrate".to_string(),
5180 wire_model_id: "deepseek-v4-pro".to_string(),
5181 endpoint_key: "chat".to_string(),
5182 cost: Some(codewhale_config::models_dev::ModelsDevCost {
5183 input: Some(0.5),
5184 output: Some(1.5),
5185 cache_read: None,
5186 cache_write: None,
5187 ..Default::default()
5188 }),
5189 source: codewhale_config::catalog::CatalogSource::Live {
5190 base_url_fingerprint: fingerprint.clone(),
5191 fetched_at,
5192 },
5193 ..Default::default()
5194 }],
5195 },
5196 crate::provider_lake::LiveSource::PerProvider,
5197 );
5198
5199 let usage = million_input_usage();
5200 let surface = billing_surface_for_route(
5201 ProviderKind::Concentrate,
5202 Some(codewhale_config::descriptors::defaults::DEFAULT_CONCENTRATE_BASE_URL),
5203 );
5204 let scoped = audit_turn_cost_for_route_on_endpoint_at(
5205 ProviderKind::Concentrate,
5206 "deepseek-v4-pro",
5207 surface,
5208 Some(&fingerprint),
5209 &usage,
5210 now,
5211 );
5212 let unproven = audit_turn_cost_for_route_on_endpoint_at(
5213 ProviderKind::Concentrate,
5214 "deepseek-v4-pro",
5215 surface,
5216 None,
5217 &usage,
5218 now,
5219 );
5220 crate::provider_lake::clear_live_snapshot();
5221
5222 assert!(scoped.is_priced(), "{scoped:?}");
5223 assert_eq!(scoped.provenance, Some(PricingProvenance::ProviderLive));
5224 let estimate = scoped.estimate.expect("priced");
5225 assert!(
5226 (estimate.usd - 0.5).abs() < 1e-12,
5227 "scoped Concentrate rate must govern: {}",
5228 estimate.usd
5229 );
5230
5231 assert!(!unproven.is_priced(), "{unproven:?}");
5232 assert_eq!(
5233 unproven.unpriced_reason,
5234 Some(UnpricedReason::UnverifiedLivePricing),
5235 "{unproven:?}"
5236 );
5237 }
5238
5239 // ── BalanceResponse / BalanceInfo ──────────────────────────────
5240
5241 #[test]
5242 fn balance_response_deserializes_from_json() {
5243 let json = r#"{
5244 "is_available": true,
5245 "balance_infos": [
5246 {
5247 "currency": "CNY",
5248 "total_balance": "123.45",
5249 "topped_up_balance": "100.00",
5250 "granted_balance": "23.45"
5251 }
5252 ]
5253 }"#;
5254 let resp: BalanceResponse = serde_json::from_str(json).expect("valid JSON");
5255 assert!(resp.is_available);
5256 assert_eq!(resp.balance_infos.len(), 1);
5257 let info = &resp.balance_infos[0];
5258 assert_eq!(info.currency, "CNY");
5259 assert_eq!(info.total_balance, "123.45");
5260 assert_eq!(info.topped_up_balance, "100.00");
5261 assert_eq!(info.granted_balance, "23.45");
5262 }
5263
5264 #[test]
5265 fn balance_response_defaults_empty_balance_infos_when_unavailable() {
5266 let json = r#"{"is_available": false, "balance_infos": []}"#;
5267 let resp: BalanceResponse = serde_json::from_str(json).expect("valid JSON");
5268 assert!(!resp.is_available);
5269 assert!(resp.balance_infos.is_empty());
5270 }
5271
5272 #[test]
5273 fn balance_response_empty_list_is_valid() {
5274 let json = r#"{"is_available": true, "balance_infos": []}"#;
5275 let resp: BalanceResponse = serde_json::from_str(json).expect("valid JSON");
5276 assert!(resp.is_available);
5277 assert!(resp.balance_infos.is_empty());
5278 }
5279
5280 #[test]
5281 fn balance_info_chip_label_uses_currency_prefix() {
5282 let cny = BalanceInfo {
5283 currency: "CNY".to_string(),
5284 total_balance: "123.45".to_string(),
5285 ..BalanceInfo::default()
5286 };
5287 assert_eq!(cny.chip_label().as_deref(), Some("¥123.45"));
5288 let usd = BalanceInfo {
5289 currency: "USD".to_string(),
5290 total_balance: "12.50".to_string(),
5291 ..BalanceInfo::default()
5292 };
5293 assert_eq!(usd.chip_label().as_deref(), Some("$12.50"));
5294 assert_eq!(
5295 usd.report("OpenRouter"),
5296 "OpenRouter account balance: $12.50"
5297 );
5298 let deepseek = BalanceInfo {
5299 currency: "CNY".to_string(),
5300 total_balance: "123.45".to_string(),
5301 topped_up_balance: "100.00".to_string(),
5302 granted_balance: "23.45".to_string(),
5303 };
5304 assert_eq!(
5305 deepseek.report("DeepSeek"),
5306 "DeepSeek account balance: ¥123.45 (topped up 100.00, granted 23.45)"
5307 );
5308 }
5309
5310 struct CloudAuditReset;
5311 impl Drop for CloudAuditReset {
5312 fn drop(&mut self) {
5313 codewhale_config::cloud_facts::overlay::clear();
5314 crate::provider_lake::clear_live_snapshot();
5315 crate::provider_catalog_live::reset_cache_for_test();
5316 }
5317 }
5318
5319 fn publish_audit_facts(
5320 channel: &str,
5321 version: u64,
5322 models: Vec<codewhale_config::cloud_facts::ModelFact>,
5323 now: u64,
5324 ) {
5325 use codewhale_config::cloud_facts::{
5326 CloudFactsState, CloudFactsStatus, FactsOrigin, ScopedFacts, overlay,
5327 };
5328 let ticket = overlay::configure(true, channel).unwrap();
5329 assert!(overlay::publish(
5330 &ticket,
5331 Some(ScopedFacts {
5332 channel: channel.into(),
5333 facts_version: version,
5334 key_id: "cwf-test-only".into(),
5335 valid_until: Some(now + 600),
5336 models,
5337 ..Default::default()
5338 }),
5339 CloudFactsStatus {
5340 state: CloudFactsState::Verified {
5341 channel: channel.into(),
5342 facts_version: version,
5343 key_id: "cwf-test-only".into(),
5344 fetched_at: now,
5345 origin: FactsOrigin::LocalFile,
5346 stale: false,
5347 patches: 1,
5348 defaults: 0,
5349 announcements: 0
5350 },
5351 ..Default::default()
5352 }
5353 ));
5354 }
5355
5356 fn audit_price_patch(
5357 provider: ProviderKind,
5358 model: &str,
5359 input: f64,
5360 ) -> codewhale_config::cloud_facts::ModelFact {
5361 use codewhale_config::cloud_facts::{ModelFact, PricingFact};
5362 ModelFact {
5363 provider: provider.as_str().into(),
5364 id: model.into(),
5365 context_window: Some(1_000_000),
5366 pricing: Some(PricingFact {
5367 input_per_m: Some(input),
5368 output_per_m: Some(2.0),
5369 cache_read_per_m: Some(0.1),
5370 }),
5371 ..Default::default()
5372 }
5373 }
5374
5375 #[test]
5376 fn cloud_prices_require_dispatch_quotes_and_never_reprice_old_turns() {
5377 let _live = crate::provider_lake::lock_live_snapshot();
5378 let home = tempfile::tempdir().unwrap();
5379 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
5380 let _enabled = crate::test_support::EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS");
5381 let _reset = CloudAuditReset;
5382 codewhale_config::cloud_facts::overlay::clear();
5383 crate::provider_lake::clear_live_snapshot();
5384 crate::provider_catalog_live::reset_cache_for_test();
5385 let provider = ProviderKind::Openai;
5386 let model = "cloud-audit-fixture";
5387 let base = provider.provider().default_base_url();
5388 let fingerprint = codewhale_config::catalog::base_url_fingerprint(base);
5389 let now = Utc::now();
5390 let at = now.timestamp() as u64;
5391 let usage = Usage {
5392 input_tokens: 1_000_000,
5393 output_tokens: 0,
5394 ..Default::default()
5395 };
5396 let audit = |quote| {
5397 audit_turn_cost_for_route_on_endpoint_for_identity_at(
5398 provider,
5399 Some("openai"),
5400 model,
5401 billing_surface_for_route(provider, Some(base)),
5402 Some(&fingerprint),
5403 quote,
5404 &usage,
5405 now,
5406 )
5407 };
5408 let before = audit(None);
5409 publish_audit_facts(
5410 "pricing-retro-test",
5411 1,
5412 vec![audit_price_patch(provider, model, 1.0)],
5413 at,
5414 );
5415 assert_eq!(
5416 audit(None),
5417 before,
5418 "a newly installed catalog cannot price an old dispatch without a quote"
5419 );
5420 let estimate = audit_turn_cost_for_provider_on_endpoint_at(
5421 provider,
5422 model,
5423 Some(&fingerprint),
5424 &usage,
5425 now,
5426 );
5427 assert_eq!(estimate.provenance, Some(PricingProvenance::CloudFacts));
5428 assert_eq!(estimate.estimate.unwrap().usd, 1.0);
5429 let before_fetch = audit_turn_cost_for_provider_on_endpoint_at(
5430 provider,
5431 model,
5432 Some(&fingerprint),
5433 &usage,
5434 now - chrono::Duration::seconds(1),
5435 );
5436 assert_eq!(
5437 before_fetch.unpriced_reason,
5438 Some(UnpricedReason::UnverifiedLivePricing)
5439 );
5440 let quote = crate::provider_catalog_live::fresh_dispatch_pricing_quote_at(
5441 provider, "openai", model, base, at,
5442 )
5443 .unwrap();
5444 assert_eq!(audit(Some(&quote)).estimate.unwrap().usd, 1.0);
5445 publish_audit_facts(
5446 "pricing-retro-test",
5447 2,
5448 vec![audit_price_patch(provider, model, 9.0)],
5449 at,
5450 );
5451 assert_eq!(audit(Some(&quote)).estimate.unwrap().usd, 1.0);
5452 assert_eq!(audit(None), before);
5453 codewhale_config::cloud_facts::overlay::clear();
5454 assert_eq!(audit(Some(&quote)).estimate.unwrap().usd, 1.0);
5455 }
5456
5457 #[test]
5458 fn cloud_quote_keeps_provider_hand_tiers_and_recorded_time_authority() {
5459 let _live = crate::provider_lake::lock_live_snapshot();
5460 let home = tempfile::tempdir().unwrap();
5461 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
5462 let _enabled = crate::test_support::EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS");
5463 let _reset = CloudAuditReset;
5464 codewhale_config::cloud_facts::overlay::clear();
5465 crate::provider_lake::clear_live_snapshot();
5466 crate::provider_catalog_live::reset_cache_for_test();
5467 let now = Utc::now();
5468 let at = now.timestamp() as u64;
5469 let usage = Usage {
5470 input_tokens: 600_000,
5471 output_tokens: 1000,
5472 ..Default::default()
5473 };
5474 let routes = [
5475 (ProviderKind::Deepseek, "deepseek-v4-flash"),
5476 (ProviderKind::Anthropic, "claude-sonnet-5"),
5477 (ProviderKind::Minimax, "MiniMax-M3"),
5478 (ProviderKind::MinimaxAnthropic, "MiniMax-M3"),
5479 (ProviderKind::Xai, "grok-4.6"),
5480 ];
5481 let before: Vec<_> = routes
5482 .iter()
5483 .map(|(provider, model)| audit_turn_cost_for_provider_at(*provider, model, &usage, now))
5484 .collect();
5485 assert!(before.iter().all(TurnCostAudit::is_priced));
5486 publish_audit_facts(
5487 "pricing-hand-test",
5488 1,
5489 routes
5490 .iter()
5491 .map(|(provider, model)| audit_price_patch(*provider, model, 999.0))
5492 .collect(),
5493 at,
5494 );
5495 for ((provider, model), expected) in routes.into_iter().zip(before) {
5496 let base = provider.provider().default_base_url();
5497 let quote = crate::provider_catalog_live::fresh_dispatch_pricing_quote_at(
5498 provider,
5499 provider.as_str(),
5500 model,
5501 base,
5502 at,
5503 )
5504 .unwrap_or_else(|| {
5505 panic!(
5506 "cloud quote missing for {provider:?} identity={} model={model}",
5507 provider.as_str()
5508 )
5509 });
5510 // MiniMax shares these endpoints with subscription keys. Only a
5511 // saved PAYG mode supplies this receipt (as the client does); a
5512 // signed price cannot itself establish the account billing mode.
5513 let surface = if matches!(
5514 provider,
5515 ProviderKind::Minimax | ProviderKind::MinimaxAnthropic
5516 ) {
5517 let unknown = audit_turn_cost_for_route_on_endpoint_for_identity_at(
5518 provider,
5519 Some(provider.as_str()),
5520 model,
5521 billing_surface_for_route(provider, Some(base)),
5522 Some(&codewhale_config::catalog::base_url_fingerprint(base)),
5523 Some(&quote),
5524 &usage,
5525 now,
5526 );
5527 assert_eq!(
5528 unknown.unpriced_reason,
5529 Some(UnpricedReason::UnknownBillingBasis)
5530 );
5531 Some(MINIMAX_PAYG_BILLING_SURFACE)
5532 } else {
5533 billing_surface_for_route(provider, Some(base))
5534 };
5535 let actual = audit_turn_cost_for_route_on_endpoint_for_identity_at(
5536 provider,
5537 Some(provider.as_str()),
5538 model,
5539 surface,
5540 Some(&codewhale_config::catalog::base_url_fingerprint(base)),
5541 Some(&quote),
5542 &usage,
5543 now,
5544 );
5545 assert_eq!(actual, expected, "{provider:?}/{model}");
5546 }
5547 }
5548
5549 #[test]
5550 fn pricing_resolves_prefixed_route_models_and_refuses_auto_sentinel() {
5551 let now = Utc.with_ymd_and_hms(2026, 11, 17, 12, 0, 0).unwrap();
5552 let usage = Usage {
5553 input_tokens: 100_000,
5554 output_tokens: 10_000,
5555 ..Usage::default()
5556 };
5557 for (bare_id, prefixed_id, expected_usd, expected_label) in [
5558 (
5559 "gemini-4-hydrogen",
5560 "models/gemini-4-hydrogen",
5561 0.225,
5562 "in $1.50 · out $7.50",
5563 ),
5564 (
5565 "gemini-4-carbon",
5566 "models/gemini-4-carbon",
5567 0.30,
5568 "in $2.00 · out $10.00",
5569 ),
5570 ] {
5571 let bare = audit_turn_cost_for_provider_on_endpoint_for_identity_at(
5572 ProviderKind::Google,
5573 Some("google"),
5574 bare_id,
5575 None,
5576 &usage,
5577 now,
5578 false,
5579 None,
5580 );
5581 let prefixed = audit_turn_cost_for_provider_on_endpoint_for_identity_at(
5582 ProviderKind::Google,
5583 Some("google"),
5584 prefixed_id,
5585 None,
5586 &usage,
5587 now,
5588 false,
5589 None,
5590 );
5591 let estimate = bare.estimate.expect("google gemini-4 model must price");
5592 assert!(
5593 (estimate.usd - expected_usd).abs() < 1e-12,
5594 "{bare_id}: {bare:?}"
5595 );
5596 assert_eq!(prefixed, bare);
5597 assert_eq!(
5598 model_rate_label(ProviderKind::Google, bare_id, CostCurrency::Usd).as_deref(),
5599 Some(expected_label)
5600 );
5601 assert_eq!(
5602 model_rate_label(ProviderKind::Google, prefixed_id, CostCurrency::Usd).as_deref(),
5603 Some(expected_label)
5604 );
5605 assert_eq!(
5606 model_rate_label(ProviderKind::Google, bare_id, CostCurrency::Cny),
5607 None
5608 );
5609 }
5610
5611 let auto_audit = audit_turn_cost_for_provider_on_endpoint_for_identity_at(
5612 ProviderKind::Google,
5613 Some("google"),
5614 "auto",
5615 None,
5616 &usage,
5617 now,
5618 false,
5619 None,
5620 );
5621 assert_eq!(
5622 auto_audit.unpriced_reason,
5623 Some(UnpricedReason::NoPricingRow)
5624 );
5625 }
5626 }
5627
5627 lines RUST