| 1 | //! Provider/offering-scoped pricing projection with provenance (#3085). |
| 2 | //! |
| 3 | //! Network-free. Maps Models.dev offering `cost` (and live / user-override |
| 4 | //! rows) into pricing rows that carry explicit **provenance**, **currency**, and |
| 5 | //! **effective-at** metadata, plus a pure cost estimator over normalized token |
| 6 | //! usage. UI display (`CostDisplay`) and provider usage-payload parsing live |
| 7 | //! above this layer and are out of scope here. |
| 8 | //! |
| 9 | //! Boundary with the route layer: this models *pricing* — offering-owned, |
| 10 | //! per-token unit prices. The coarse route-facing meter shape already exists as |
| 11 | //! [`crate::route::PricingSku`] |
| 12 | //! (`Token` / `SubscriptionQuota` / `AccountCredits` / `LocalOrNotApplicable` / |
| 13 | //! `UnknownOrStale`); [`OfferingPricing::to_route_sku`] and |
| 14 | //! [`route_pricing_sku`] bridge to it. |
| 15 | //! |
| 16 | //! Honesty rule (#2608 / #3085): pricing is never assumed. A route with no |
| 17 | //! sourced price yields `None` here and `UnknownOrStale` at the route layer — |
| 18 | //! never a fabricated token price, and never an implicit "free" for |
| 19 | //! local/custom/subscription routes. |
| 20 | |
| 21 | use rust_decimal::Decimal; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | |
| 24 | use crate::catalog::{CatalogOffering, CatalogSource}; |
| 25 | use crate::models_dev::{ModelsDevCost, ModelsDevCostTier}; |
| 26 | use crate::route::PricingSku; |
| 27 | |
| 28 | /// Billing currency for a pricing row. Models.dev publishes USD per-million |
| 29 | /// costs; other currencies arrive via provider docs or user overrides. |
| 30 | #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] |
| 31 | #[serde(rename_all = "snake_case")] |
| 32 | pub enum Currency { |
| 33 | #[default] |
| 34 | Usd, |
| 35 | Cny, |
| 36 | /// An ISO-4217-style code CodeWhale does not special-case. |
| 37 | Other(String), |
| 38 | } |
| 39 | |
| 40 | /// Where a pricing row came from. Retained so the UI can show provenance and so |
| 41 | /// stale/unknown prices are never silently treated as authoritative. |
| 42 | #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] |
| 43 | #[serde(tag = "source", rename_all = "snake_case")] |
| 44 | pub enum PricingProvenance { |
| 45 | /// Published-price estimate from the offline Models.dev snapshot. |
| 46 | ModelsDevBundled, |
| 47 | ModelsDevLive, |
| 48 | /// From a provider live `/models` (or pricing) refresh — a rate the |
| 49 | /// provider itself published for one endpoint, not a catalog's report of it. |
| 50 | ProviderLive, |
| 51 | /// From provider documentation / a hand-sourced seed. Set only by callers |
| 52 | /// constructing rows directly; `from_catalog_offering` never produces this |
| 53 | /// (Models.dev-sourced rows map to `ModelsDevBundled`). |
| 54 | ProviderDocs, |
| 55 | /// User-supplied override (custom endpoint, enterprise terms, local route). |
| 56 | UserOverride, |
| 57 | /// No sourced price. |
| 58 | #[default] |
| 59 | Unknown, |
| 60 | /// From the Codewhale-owned signed/bundled catalog. |
| 61 | CodewhaleCatalog, |
| 62 | /// Verified signed cloud-facts price block; expiry is checked at projection. |
| 63 | CloudFacts, |
| 64 | } |
| 65 | |
| 66 | impl PricingProvenance { |
| 67 | /// Stable, non-localized identifier for logs and JSON. |
| 68 | #[must_use] |
| 69 | pub fn label(&self) -> &'static str { |
| 70 | match self { |
| 71 | Self::ModelsDevBundled => "models_dev_bundled", |
| 72 | Self::ModelsDevLive => "models_dev_live", |
| 73 | Self::ProviderLive => "provider_live", |
| 74 | Self::ProviderDocs => "provider_docs", |
| 75 | Self::UserOverride => "user_override", |
| 76 | Self::Unknown => "unknown", |
| 77 | Self::CodewhaleCatalog => "codewhale_catalog", |
| 78 | Self::CloudFacts => "cloud_facts", |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// Whether this provenance may be presented as an authoritative published |
| 83 | /// price without further freshness checks. |
| 84 | /// |
| 85 | /// [`Self::ProviderLive`] is deliberately excluded: a live row is only |
| 86 | /// authoritative while it is fresh *and* was fetched from the endpoint the |
| 87 | /// turn was actually served on. Callers must clear it through |
| 88 | /// [`OfferingPricing::live_pricing_defect`] first. |
| 89 | #[must_use] |
| 90 | pub fn is_authoritative_without_freshness_check(&self) -> bool { |
| 91 | matches!( |
| 92 | self, |
| 93 | Self::ModelsDevBundled |
| 94 | | Self::ProviderDocs |
| 95 | | Self::UserOverride |
| 96 | | Self::CodewhaleCatalog |
| 97 | ) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Default freshness window for a `ProviderLive` pricing row, in seconds. |
| 102 | /// |
| 103 | /// A provider `/models` refresh is a snapshot of a mutable price list. Past |
| 104 | /// this age CodeWhale stops calling the row authoritative rather than billing |
| 105 | /// against a rate the provider may have already changed. |
| 106 | pub const LIVE_PRICING_MAX_AGE_SECS: u64 = 24 * 60 * 60; |
| 107 | |
| 108 | /// Why a `ProviderLive` pricing row cannot be treated as authoritative. |
| 109 | /// |
| 110 | /// Each variant is a non-secret receipt: fingerprints are FNV digests of a |
| 111 | /// normalized base URL (see [`crate::catalog::base_url_fingerprint`]), never the |
| 112 | /// URL itself, so these can be logged and serialized freely. |
| 113 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 114 | #[serde(tag = "defect", rename_all = "snake_case")] |
| 115 | pub enum LivePricingDefect { |
| 116 | /// The row is older than the caller's freshness window. |
| 117 | Stale { age_secs: u64, max_age_secs: u64 }, |
| 118 | /// The row was fetched from a different endpoint than the turn was served |
| 119 | /// on, so it prices a different billing surface. |
| 120 | EndpointMismatch { |
| 121 | row_fingerprint: String, |
| 122 | route_fingerprint: String, |
| 123 | }, |
| 124 | /// The row claims live provenance but carries no endpoint fingerprint, so |
| 125 | /// it cannot be matched to the route that is being priced. |
| 126 | MissingEndpointFingerprint, |
| 127 | /// The row claims live provenance but carries no fetch timestamp, so its |
| 128 | /// age cannot be established. |
| 129 | MissingTimestamp, |
| 130 | /// The caller could not establish which endpoint the turn was served on, so |
| 131 | /// a live row cannot be confirmed to price that route. |
| 132 | UnknownRouteEndpoint, |
| 133 | } |
| 134 | |
| 135 | impl LivePricingDefect { |
| 136 | /// Stable, non-localized identifier for logs and JSON. |
| 137 | #[must_use] |
| 138 | pub fn label(&self) -> &'static str { |
| 139 | match self { |
| 140 | Self::Stale { .. } => "live_pricing_stale", |
| 141 | Self::EndpointMismatch { .. } => "live_pricing_endpoint_mismatch", |
| 142 | Self::MissingEndpointFingerprint => "live_pricing_missing_endpoint_fingerprint", |
| 143 | Self::MissingTimestamp => "live_pricing_missing_timestamp", |
| 144 | Self::UnknownRouteEndpoint => "live_pricing_unknown_route_endpoint", |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// Normalized token usage for a single turn, in canonical billable classes. |
| 150 | /// |
| 151 | /// Producing this from provider-specific usage payloads (Chat Completions, |
| 152 | /// Responses, Anthropic) is a separate concern; this layer only consumes it. |
| 153 | #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] |
| 154 | pub struct TokenUsage { |
| 155 | /// Non-cached input (prompt) tokens. |
| 156 | pub input: u64, |
| 157 | /// Total billable output (completion) tokens. |
| 158 | /// |
| 159 | /// Providers report reasoning tokens as a *subset* of the completion token |
| 160 | /// count (OpenAI `output_tokens_details.reasoning_tokens` ⊆ `output_tokens`, |
| 161 | /// Chat Completions `completion_tokens_details.reasoning_tokens` ⊆ |
| 162 | /// `completion_tokens`), so a normalizer must never add reasoning tokens on |
| 163 | /// top of this field — that double-bills every reasoning turn. |
| 164 | pub output: u64, |
| 165 | /// Cache-read (cache-hit) input tokens, billed at the cache-read rate. |
| 166 | pub cache_read: u64, |
| 167 | /// Cache-write (cache-creation) tokens, billed at the cache-write rate. |
| 168 | pub cache_write: u64, |
| 169 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 170 | pub reasoning: Option<u64>, |
| 171 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 172 | pub input_audio: Option<u64>, |
| 173 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 174 | pub output_audio: Option<u64>, |
| 175 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 176 | pub request_usages: Vec<TokenUsage>, |
| 177 | } |
| 178 | |
| 179 | /// A canonical billable token class. |
| 180 | /// |
| 181 | /// Used to report *which* class of a turn's usage lacked a published price, so |
| 182 | /// an unpriced turn can be audited instead of silently dropping out of a total. |
| 183 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 184 | #[serde(rename_all = "snake_case")] |
| 185 | pub enum TokenClass { |
| 186 | Input, |
| 187 | Output, |
| 188 | CacheRead, |
| 189 | CacheWrite, |
| 190 | Reasoning, |
| 191 | InputAudio, |
| 192 | OutputAudio, |
| 193 | } |
| 194 | |
| 195 | impl TokenClass { |
| 196 | /// Every class, in reporting order. |
| 197 | pub const ALL: [Self; 7] = [ |
| 198 | Self::Input, |
| 199 | Self::Output, |
| 200 | Self::CacheRead, |
| 201 | Self::CacheWrite, |
| 202 | Self::Reasoning, |
| 203 | Self::InputAudio, |
| 204 | Self::OutputAudio, |
| 205 | ]; |
| 206 | |
| 207 | /// Stable, non-localized identifier for logs and JSON. |
| 208 | #[must_use] |
| 209 | pub fn label(self) -> &'static str { |
| 210 | match self { |
| 211 | Self::Input => "input", |
| 212 | Self::Output => "output", |
| 213 | Self::CacheRead => "cache_read", |
| 214 | Self::CacheWrite => "cache_write", |
| 215 | Self::Reasoning => "reasoning", |
| 216 | Self::InputAudio => "input_audio", |
| 217 | Self::OutputAudio => "output_audio", |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// This class's token count within `usage`. |
| 222 | #[must_use] |
| 223 | pub fn tokens(self, usage: &TokenUsage) -> u64 { |
| 224 | match self { |
| 225 | Self::Input => usage.input, |
| 226 | Self::Output => usage.output, |
| 227 | Self::CacheRead => usage.cache_read, |
| 228 | Self::CacheWrite => usage.cache_write, |
| 229 | Self::Reasoning => usage.reasoning.unwrap_or(0), |
| 230 | Self::InputAudio => usage.input_audio.unwrap_or(0), |
| 231 | Self::OutputAudio => usage.output_audio.unwrap_or(0), |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// A provider/offering-scoped pricing row. |
| 237 | /// |
| 238 | /// Prices are per million tokens in [`Currency`]. Any field may be unknown |
| 239 | /// (`None`); [`OfferingPricing::estimate_cost`] refuses to invent a number for a |
| 240 | /// used class whose price is unknown. |
| 241 | #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] |
| 242 | pub struct OfferingPricing { |
| 243 | /// Provider id serving the offering. |
| 244 | pub provider: String, |
| 245 | /// Provider-owned wire id the price applies to. |
| 246 | pub wire_model_id: String, |
| 247 | /// Canonical model identity, when the offering carries one. |
| 248 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 249 | pub canonical_model: Option<String>, |
| 250 | /// Billing currency. |
| 251 | pub currency: Currency, |
| 252 | /// Input price per million tokens. |
| 253 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 254 | pub input_per_million: Option<f64>, |
| 255 | /// Output price per million tokens. |
| 256 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 257 | pub output_per_million: Option<f64>, |
| 258 | /// Cache-read price per million tokens. |
| 259 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 260 | pub cache_read_per_million: Option<f64>, |
| 261 | /// Cache-write price per million tokens. |
| 262 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 263 | pub cache_write_per_million: Option<f64>, |
| 264 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 265 | pub reasoning_per_million: Option<f64>, |
| 266 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 267 | pub input_audio_per_million: Option<f64>, |
| 268 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 269 | pub output_audio_per_million: Option<f64>, |
| 270 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 271 | pub context_tiers: Vec<ModelsDevCostTier>, |
| 272 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 273 | pub context_tiers_inclusive: bool, |
| 274 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 275 | pub rate_withheld: bool, |
| 276 | /// Where the price came from. |
| 277 | pub provenance: PricingProvenance, |
| 278 | /// Actual rate-effective time, when the source declares one. Old serialized |
| 279 | /// provider rows used this as a fetch time; `fetched_at` takes precedence. |
| 280 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 281 | pub effective_at: Option<u64>, |
| 282 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 283 | pub fetched_at: Option<u64>, |
| 284 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 285 | pub expires_at: Option<u64>, |
| 286 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 287 | pub upstream_last_updated: Option<String>, |
| 288 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 289 | pub source_ref: Option<String>, |
| 290 | /// Fingerprint of the base URL this price was fetched from, for |
| 291 | /// [`PricingProvenance::ProviderLive`] rows. |
| 292 | /// |
| 293 | /// This is the same non-secret SHA-256 digest the catalog cache scopes on |
| 294 | /// (see [`crate::catalog::base_url_fingerprint`]) — never the URL itself. |
| 295 | /// It exists so a live row can be proven to price the endpoint a turn was |
| 296 | /// actually served on; a row whose fingerprint does not match the route |
| 297 | /// is a different billing surface, not a fresher price for this one. |
| 298 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 299 | pub endpoint_fingerprint: Option<String>, |
| 300 | } |
| 301 | |
| 302 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 303 | pub struct QuotedCost { |
| 304 | pub amount: String, |
| 305 | pub currency: Currency, |
| 306 | } |
| 307 | |
| 308 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 309 | pub enum PricingQuoteError { |
| 310 | MissingRate(TokenClass), |
| 311 | MissingUsage(TokenClass), |
| 312 | InvalidUsage, |
| 313 | UnsupportedTier, |
| 314 | InvalidRate, |
| 315 | } |
| 316 | |
| 317 | impl OfferingPricing { |
| 318 | /// Derive a pricing row from a catalog offering's `cost`, when priced. |
| 319 | /// |
| 320 | /// Returns `None` when the offering carries no cost. An explicitly empty |
| 321 | /// cost object stays withheld, so another source cannot refill it. |
| 322 | /// |
| 323 | /// Models.dev `cost` values are USD per million tokens, so the currency is |
| 324 | /// [`Currency::Usd`]; provenance and `fetched_at` follow the offering's |
| 325 | /// [`CatalogSource`]. The upstream update date stays separate. |
| 326 | #[must_use] |
| 327 | pub fn from_catalog_offering(offering: &CatalogOffering) -> Option<Self> { |
| 328 | Self::from_catalog_offering_at(offering, crate::catalog::now_unix()) |
| 329 | } |
| 330 | |
| 331 | /// Project at the dispatch clock when freezing a quote. Cloud-facts source |
| 332 | /// validity is signed and cannot be extended by a later transport refresh. |
| 333 | #[must_use] |
| 334 | pub fn from_catalog_offering_at(offering: &CatalogOffering, now: u64) -> Option<Self> { |
| 335 | let source = offering.pricing_source(); |
| 336 | if let CatalogSource::CloudFacts { |
| 337 | fetched_at, |
| 338 | valid_until, |
| 339 | .. |
| 340 | } = source |
| 341 | && (*fetched_at > now || valid_until.is_some_and(|expires| now > expires)) |
| 342 | { |
| 343 | return None; |
| 344 | } |
| 345 | let cost = offering.cost.as_ref()?; |
| 346 | // A provider/catalog price is untrusted numeric input. Reject the |
| 347 | // entire row when any published class is NaN, infinite, or negative; |
| 348 | // accepting only the apparently valid fields would turn a malformed |
| 349 | // row into a silently incomplete (or negative) bill. |
| 350 | if !catalog_cost_is_valid(cost) { |
| 351 | return None; |
| 352 | } |
| 353 | let rate_withheld = cost.input.is_none() |
| 354 | && cost.output.is_none() |
| 355 | && cost.cache_read.is_none() |
| 356 | && cost.cache_write.is_none() |
| 357 | && cost.reasoning.is_none() |
| 358 | && cost.input_audio.is_none() |
| 359 | && cost.output_audio.is_none() |
| 360 | && cost.context_tiers().is_empty(); |
| 361 | Some(Self { |
| 362 | provider: offering.provider.clone(), |
| 363 | wire_model_id: offering.wire_model_id.clone(), |
| 364 | canonical_model: offering.canonical_model.clone(), |
| 365 | currency: Currency::Usd, |
| 366 | input_per_million: cost.input, |
| 367 | output_per_million: cost.output, |
| 368 | cache_read_per_million: cost.cache_read, |
| 369 | cache_write_per_million: cost.cache_write, |
| 370 | reasoning_per_million: cost.reasoning, |
| 371 | input_audio_per_million: cost.input_audio, |
| 372 | output_audio_per_million: cost.output_audio, |
| 373 | context_tiers: cost.context_tiers(), |
| 374 | context_tiers_inclusive: offering.provider == "xai", |
| 375 | rate_withheld, |
| 376 | provenance: provenance_from_source(source), |
| 377 | effective_at: None, |
| 378 | fetched_at: fetched_at_from_source(source), |
| 379 | expires_at: match source { |
| 380 | CatalogSource::CloudFacts { valid_until, .. } => *valid_until, |
| 381 | CatalogSource::Live { fetched_at, .. } |
| 382 | | CatalogSource::ModelsDevLive { fetched_at } => { |
| 383 | fetched_at.checked_add(LIVE_PRICING_MAX_AGE_SECS) |
| 384 | } |
| 385 | _ => None, |
| 386 | }, |
| 387 | upstream_last_updated: offering.last_updated.clone(), |
| 388 | source_ref: matches!( |
| 389 | source, |
| 390 | CatalogSource::Bundled | CatalogSource::ModelsDevLive { .. } |
| 391 | ) |
| 392 | .then(|| { |
| 393 | format!( |
| 394 | "https://models.dev/catalog.json#{}:{}", |
| 395 | offering.provider, offering.wire_model_id |
| 396 | ) |
| 397 | }), |
| 398 | endpoint_fingerprint: endpoint_fingerprint_from_source(source), |
| 399 | }) |
| 400 | } |
| 401 | |
| 402 | /// Whether any per-token price is known. |
| 403 | #[must_use] |
| 404 | pub fn has_any_price(&self) -> bool { |
| 405 | self.input_per_million.is_some() |
| 406 | || self.output_per_million.is_some() |
| 407 | || self.cache_read_per_million.is_some() |
| 408 | || self.cache_write_per_million.is_some() |
| 409 | || self.reasoning_per_million.is_some() |
| 410 | || self.input_audio_per_million.is_some() |
| 411 | || self.output_audio_per_million.is_some() |
| 412 | || !self.context_tiers.is_empty() |
| 413 | } |
| 414 | |
| 415 | /// Whether this price is older than `max_age_secs` at `now_unix`. |
| 416 | /// |
| 417 | /// Live rows age against their fetch clock. Declared effective dates do |
| 418 | /// not become fetch dates; explicit expiry applies to every source. |
| 419 | #[must_use] |
| 420 | pub fn is_stale(&self, now_unix: u64, max_age_secs: u64) -> bool { |
| 421 | self.expires_at.is_some_and(|expires| now_unix >= expires) |
| 422 | || (matches!( |
| 423 | self.provenance, |
| 424 | PricingProvenance::ModelsDevLive | PricingProvenance::ProviderLive |
| 425 | ) && self |
| 426 | .fetched_at |
| 427 | .or(self.effective_at) |
| 428 | .is_some_and(|time| time > now_unix || now_unix - time >= max_age_secs)) |
| 429 | } |
| 430 | |
| 431 | #[must_use] |
| 432 | pub fn status_label_at(&self, now: u64) -> &'static str { |
| 433 | if self.rate_withheld || !self.has_any_price() { |
| 434 | return "unavailable"; |
| 435 | } |
| 436 | if self.is_stale(now, LIVE_PRICING_MAX_AGE_SECS) { |
| 437 | return "stale"; |
| 438 | } |
| 439 | if matches!( |
| 440 | self.provenance, |
| 441 | PricingProvenance::ProviderLive | PricingProvenance::ModelsDevLive |
| 442 | ) && self |
| 443 | .live_pricing_defect( |
| 444 | self.endpoint_fingerprint.as_deref(), |
| 445 | Some(now), |
| 446 | LIVE_PRICING_MAX_AGE_SECS, |
| 447 | ) |
| 448 | .is_some() |
| 449 | { |
| 450 | return "unverified"; |
| 451 | } |
| 452 | match self.provenance { |
| 453 | PricingProvenance::Unknown => "unverified", |
| 454 | PricingProvenance::ModelsDevBundled | PricingProvenance::CodewhaleCatalog => { |
| 455 | "bundled_estimate" |
| 456 | } |
| 457 | PricingProvenance::ModelsDevLive | PricingProvenance::ProviderLive => "live_estimate", |
| 458 | PricingProvenance::ProviderDocs => "documented_estimate", |
| 459 | PricingProvenance::UserOverride => "operator_estimate", |
| 460 | PricingProvenance::CloudFacts => "verified_cloud_estimate", |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | /// Why this row cannot be trusted as an authoritative live price, if so. |
| 465 | /// |
| 466 | /// Returns `None` for rows that are not [`PricingProvenance::ProviderLive`] |
| 467 | /// (a bundled snapshot, a documented hand price, or a user override carries |
| 468 | /// no fetch clock to go stale against) and for live rows that are both |
| 469 | /// fresh and fingerprint-matched to `route_endpoint_fingerprint`. |
| 470 | /// |
| 471 | /// A live row with any defect must not be labelled `provider_live` nor used |
| 472 | /// as complete pricing: it is either older than `max_age_secs` or priced for |
| 473 | /// a different endpoint. Callers fail closed and receipt the returned |
| 474 | /// defect. `route_endpoint_fingerprint` of `None` means the caller could not |
| 475 | /// determine the endpoint at all, which is itself a defect — a live row can |
| 476 | /// never be *confirmed* to price an unknown route. |
| 477 | #[must_use] |
| 478 | pub fn live_pricing_defect( |
| 479 | &self, |
| 480 | route_endpoint_fingerprint: Option<&str>, |
| 481 | now_unix: Option<u64>, |
| 482 | max_age_secs: u64, |
| 483 | ) -> Option<LivePricingDefect> { |
| 484 | if !matches!( |
| 485 | self.provenance, |
| 486 | PricingProvenance::ProviderLive | PricingProvenance::ModelsDevLive |
| 487 | ) { |
| 488 | return None; |
| 489 | } |
| 490 | if self.provenance == PricingProvenance::ProviderLive { |
| 491 | let Some(row_fingerprint) = self.endpoint_fingerprint.as_deref() else { |
| 492 | return Some(LivePricingDefect::MissingEndpointFingerprint); |
| 493 | }; |
| 494 | let Some(route_fingerprint) = route_endpoint_fingerprint else { |
| 495 | return Some(LivePricingDefect::UnknownRouteEndpoint); |
| 496 | }; |
| 497 | if row_fingerprint != route_fingerprint { |
| 498 | return Some(LivePricingDefect::EndpointMismatch { |
| 499 | row_fingerprint: row_fingerprint.to_string(), |
| 500 | route_fingerprint: route_fingerprint.to_string(), |
| 501 | }); |
| 502 | } |
| 503 | } |
| 504 | let Some(fetched_at) = self.fetched_at.or(self.effective_at) else { |
| 505 | return Some(LivePricingDefect::MissingTimestamp); |
| 506 | }; |
| 507 | // Without a clock the age is unknowable, so the row stays unproven |
| 508 | // rather than being assumed fresh. |
| 509 | let Some(now_unix) = now_unix else { |
| 510 | return Some(LivePricingDefect::MissingTimestamp); |
| 511 | }; |
| 512 | let age_secs = now_unix.saturating_sub(fetched_at); |
| 513 | if fetched_at > now_unix |
| 514 | || age_secs >= max_age_secs |
| 515 | || self.expires_at.is_some_and(|expires| now_unix >= expires) |
| 516 | { |
| 517 | return Some(LivePricingDefect::Stale { |
| 518 | age_secs, |
| 519 | max_age_secs, |
| 520 | }); |
| 521 | } |
| 522 | None |
| 523 | } |
| 524 | |
| 525 | /// Classes this turn actually used that carry no published price. |
| 526 | /// |
| 527 | /// Non-empty means [`Self::estimate_cost`] fails closed for this usage; the |
| 528 | /// returned classes are exactly the reason why, so callers can report the |
| 529 | /// gap instead of presenting a silently under-counted total. |
| 530 | #[must_use] |
| 531 | pub fn unpriced_used_classes(&self, usage: &TokenUsage) -> Vec<TokenClass> { |
| 532 | if !usage.request_usages.is_empty() { |
| 533 | if usage.request_usages.len() > 1024 |
| 534 | || usage |
| 535 | .request_usages |
| 536 | .iter() |
| 537 | .any(|request| !request.request_usages.is_empty()) |
| 538 | { |
| 539 | return Vec::new(); |
| 540 | } |
| 541 | return usage |
| 542 | .request_usages |
| 543 | .iter() |
| 544 | .flat_map(|request| self.unpriced_used_classes(request)) |
| 545 | .collect::<std::collections::BTreeSet<_>>() |
| 546 | .into_iter() |
| 547 | .collect(); |
| 548 | } |
| 549 | let Ok((cost, billable)) = self.rates_and_usage(usage) else { |
| 550 | return Vec::new(); |
| 551 | }; |
| 552 | TokenClass::ALL |
| 553 | .into_iter() |
| 554 | .filter(|class| class.tokens(&billable) > 0 && rate_for_class(&cost, *class).is_none()) |
| 555 | .collect() |
| 556 | } |
| 557 | |
| 558 | fn rates_and_usage( |
| 559 | &self, |
| 560 | usage: &TokenUsage, |
| 561 | ) -> Result<(ModelsDevCost, TokenUsage), PricingQuoteError> { |
| 562 | let base = self.cost_structure(); |
| 563 | if !catalog_cost_is_valid(&base) { |
| 564 | return Err(PricingQuoteError::InvalidRate); |
| 565 | } |
| 566 | if self |
| 567 | .context_tiers |
| 568 | .iter() |
| 569 | .any(|tier| tier.tier.kind != "context" || !tier.cost.context_tiers().is_empty()) |
| 570 | { |
| 571 | return Err(PricingQuoteError::UnsupportedTier); |
| 572 | } |
| 573 | let total_input = usage |
| 574 | .input |
| 575 | .checked_add(usage.cache_read) |
| 576 | .and_then(|total| total.checked_add(usage.cache_write)) |
| 577 | .ok_or(PricingQuoteError::InvalidUsage)?; |
| 578 | let cost = self |
| 579 | .context_tiers |
| 580 | .iter() |
| 581 | .filter(|tier| { |
| 582 | if self.context_tiers_inclusive { |
| 583 | total_input >= tier.tier.size |
| 584 | } else { |
| 585 | total_input > tier.tier.size |
| 586 | } |
| 587 | }) |
| 588 | .max_by_key(|tier| tier.tier.size) |
| 589 | .map_or(base, |tier| tier.cost.clone()); |
| 590 | let mut billable = usage.clone(); |
| 591 | let reasoning = usage.reasoning.unwrap_or(0); |
| 592 | let audio_output = usage.output_audio.unwrap_or(0); |
| 593 | let audio_input = usage.input_audio.unwrap_or(0); |
| 594 | if reasoning |
| 595 | .checked_add(audio_output) |
| 596 | .is_none_or(|total| total > usage.output) |
| 597 | || audio_input > usage.input |
| 598 | { |
| 599 | return Err(PricingQuoteError::InvalidUsage); |
| 600 | } |
| 601 | if cost.reasoning.is_some() |
| 602 | && cost.reasoning != cost.output |
| 603 | && usage.reasoning.is_none() |
| 604 | && usage.output > 0 |
| 605 | { |
| 606 | return Err(PricingQuoteError::MissingUsage(TokenClass::Reasoning)); |
| 607 | } |
| 608 | if audio_input > 0 |
| 609 | && cost.input_audio != cost.input |
| 610 | && (usage.cache_read > 0 || usage.cache_write > 0) |
| 611 | { |
| 612 | return Err(PricingQuoteError::MissingUsage(TokenClass::InputAudio)); |
| 613 | } |
| 614 | billable.input = usage.input - audio_input; |
| 615 | billable.output = usage.output - audio_output; |
| 616 | if cost.reasoning.is_some() && usage.reasoning.is_some() { |
| 617 | billable.output -= reasoning; |
| 618 | } else { |
| 619 | billable.reasoning = None; |
| 620 | } |
| 621 | Ok((cost, billable)) |
| 622 | } |
| 623 | |
| 624 | #[must_use] |
| 625 | pub fn cost_structure(&self) -> ModelsDevCost { |
| 626 | ModelsDevCost { |
| 627 | input: self.input_per_million, |
| 628 | output: self.output_per_million, |
| 629 | cache_read: self.cache_read_per_million, |
| 630 | cache_write: self.cache_write_per_million, |
| 631 | reasoning: self.reasoning_per_million, |
| 632 | input_audio: self.input_audio_per_million, |
| 633 | output_audio: self.output_audio_per_million, |
| 634 | tiers: (!self.context_tiers.is_empty()).then(|| self.context_tiers.clone()), |
| 635 | context_over_200k: None, |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | pub fn quote_cost(&self, usage: &TokenUsage) -> Result<QuotedCost, PricingQuoteError> { |
| 640 | if self.rate_withheld { |
| 641 | return Err(PricingQuoteError::MissingRate(TokenClass::Input)); |
| 642 | } |
| 643 | if !usage.request_usages.is_empty() { |
| 644 | if usage.request_usages.len() > 1024 { |
| 645 | return Err(PricingQuoteError::InvalidUsage); |
| 646 | } |
| 647 | let mut aggregate = [0_u64; 4]; |
| 648 | let mut total = Decimal::ZERO; |
| 649 | for request in &usage.request_usages { |
| 650 | if !request.request_usages.is_empty() { |
| 651 | return Err(PricingQuoteError::InvalidUsage); |
| 652 | } |
| 653 | for (sum, count) in aggregate.iter_mut().zip([ |
| 654 | request.input, |
| 655 | request.output, |
| 656 | request.cache_read, |
| 657 | request.cache_write, |
| 658 | ]) { |
| 659 | *sum = sum |
| 660 | .checked_add(count) |
| 661 | .ok_or(PricingQuoteError::InvalidUsage)?; |
| 662 | } |
| 663 | let quote = self.quote_cost(request)?; |
| 664 | let amount = Decimal::from_str_exact("e.amount) |
| 665 | .map_err(|_| PricingQuoteError::InvalidRate)?; |
| 666 | total = add_decimal_exact(total, amount)?; |
| 667 | } |
| 668 | if aggregate |
| 669 | != [ |
| 670 | usage.input, |
| 671 | usage.output, |
| 672 | usage.cache_read, |
| 673 | usage.cache_write, |
| 674 | ] |
| 675 | { |
| 676 | return Err(PricingQuoteError::InvalidUsage); |
| 677 | } |
| 678 | return Ok(QuotedCost { |
| 679 | amount: total.normalize().to_string(), |
| 680 | currency: self.currency.clone(), |
| 681 | }); |
| 682 | } |
| 683 | let (cost, billable) = self.rates_and_usage(usage)?; |
| 684 | let mut total = Decimal::ZERO; |
| 685 | for class in TokenClass::ALL { |
| 686 | let tokens = class.tokens(&billable); |
| 687 | if tokens == 0 { |
| 688 | continue; |
| 689 | } |
| 690 | let rate = rate_for_class(&cost, class).ok_or(PricingQuoteError::MissingRate(class))?; |
| 691 | let rate = Decimal::from_str_exact(&rate.to_string()) |
| 692 | .map_err(|_| PricingQuoteError::InvalidRate)?; |
| 693 | let mut coefficient = rate |
| 694 | .mantissa() |
| 695 | .checked_mul(i128::from(tokens)) |
| 696 | .ok_or(PricingQuoteError::InvalidRate)?; |
| 697 | let mut scale = rate.scale() + 6; |
| 698 | while scale > 0 && coefficient % 10 == 0 { |
| 699 | coefficient /= 10; |
| 700 | scale -= 1; |
| 701 | } |
| 702 | let component = Decimal::try_from_i128_with_scale(coefficient, scale) |
| 703 | .map_err(|_| PricingQuoteError::InvalidRate)?; |
| 704 | total = add_decimal_exact(total, component)?; |
| 705 | } |
| 706 | Ok(QuotedCost { |
| 707 | amount: total.normalize().to_string(), |
| 708 | currency: self.currency.clone(), |
| 709 | }) |
| 710 | } |
| 711 | |
| 712 | /// Estimate in major currency units; floating point is a display projection |
| 713 | /// of the exact decimal quote, never a second calculation authority. |
| 714 | #[must_use] |
| 715 | pub fn estimate_cost(&self, usage: &TokenUsage) -> Option<f64> { |
| 716 | self.quote_cost(usage).ok()?.amount.parse().ok() |
| 717 | } |
| 718 | |
| 719 | /// Project to the coarse route-facing meter shape. |
| 720 | /// |
| 721 | /// Returns [`PricingSku::Token`] only when an input or output rate is known. |
| 722 | /// The route-layer `Token` shape carries only input/output rates, so a row |
| 723 | /// priced *only* on cache classes would become a `Token` with no visible |
| 724 | /// rates — misleading at the route layer. Such rows degrade to |
| 725 | /// [`PricingSku::UnknownOrStale`] here while their cache rates remain usable |
| 726 | /// through [`OfferingPricing::estimate_cost`]. |
| 727 | #[must_use] |
| 728 | pub fn to_route_sku(&self) -> PricingSku { |
| 729 | if self.input_per_million.is_none() && self.output_per_million.is_none() { |
| 730 | return PricingSku::UnknownOrStale; |
| 731 | } |
| 732 | PricingSku::Token { |
| 733 | input_per_mtok: self.input_per_million, |
| 734 | output_per_mtok: self.output_per_million, |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | /// The honest route-facing pricing meter for a catalog offering. |
| 740 | /// |
| 741 | /// An offering with a usable input/output rate becomes [`PricingSku::Token`]; |
| 742 | /// everything else — no cost, a cost object with no concrete price, or a |
| 743 | /// cache-only price — becomes [`PricingSku::UnknownOrStale`] rather than a |
| 744 | /// fabricated zero price. An explicit empty cost stays withheld; |
| 745 | /// `to_route_sku` keeps both it and a cache-only rate unknown. |
| 746 | #[must_use] |
| 747 | pub fn route_pricing_sku(offering: &CatalogOffering) -> PricingSku { |
| 748 | OfferingPricing::from_catalog_offering(offering) |
| 749 | .map_or(PricingSku::UnknownOrStale, |pricing| pricing.to_route_sku()) |
| 750 | } |
| 751 | |
| 752 | /// The honest route-facing pricing meter for a raw Models.dev `cost` block. |
| 753 | /// |
| 754 | /// Same honesty rule as [`route_pricing_sku`], but for callers that hold a |
| 755 | /// [`ModelsDevCost`] directly (the route-offering builders in |
| 756 | /// [`crate::models_dev`]) rather than a full [`CatalogOffering`]. An absent or |
| 757 | /// concretely-empty cost, or a cache-only cost, yields |
| 758 | /// [`PricingSku::UnknownOrStale`]; only a usable input/output rate yields |
| 759 | /// [`PricingSku::Token`]. |
| 760 | #[must_use] |
| 761 | pub(crate) fn route_pricing_sku_from_cost(cost: Option<&ModelsDevCost>) -> PricingSku { |
| 762 | let Some(cost) = cost else { |
| 763 | return PricingSku::UnknownOrStale; |
| 764 | }; |
| 765 | if !catalog_cost_is_valid(cost) { |
| 766 | return PricingSku::UnknownOrStale; |
| 767 | } |
| 768 | if cost.input.is_none() && cost.output.is_none() { |
| 769 | // No input/output rate: a cache-only or empty cost would render as a |
| 770 | // rate-less `Token` at the route layer, so it stays honestly unknown. |
| 771 | return PricingSku::UnknownOrStale; |
| 772 | } |
| 773 | PricingSku::Token { |
| 774 | input_per_mtok: cost.input, |
| 775 | output_per_mtok: cost.output, |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | /// Upper bound, per million tokens, on a price CodeWhale will treat as real. |
| 780 | /// |
| 781 | /// Published frontier rates are in the single-to-triple digits per million. |
| 782 | /// A value four orders of magnitude above that is not an expensive model, it is |
| 783 | /// a unit error — a per-token price parsed as per-million, or a minor-unit |
| 784 | /// integer (cents, fen) read as a major unit. Both mistakes bill the user |
| 785 | /// 10^6 or 10^2 times over, so the row is rejected rather than believed. |
| 786 | /// |
| 787 | /// The bound is deliberately generous: it exists to catch impossible |
| 788 | /// magnitudes, not to second-guess a provider's pricing. |
| 789 | pub const MAX_PLAUSIBLE_PRICE_PER_MILLION: f64 = 100_000.0; |
| 790 | |
| 791 | /// Whether every numeric field in a catalog price is finite, non-negative, and |
| 792 | /// of a plausible magnitude. |
| 793 | /// |
| 794 | /// Kept at the catalog boundary so every projection (routing SKU and runtime |
| 795 | /// cost audit) applies the same validation rule. Catalog prices are untrusted |
| 796 | /// numeric input: they arrive from a bundled snapshot, a live provider |
| 797 | /// `/models` response, or a user override file, and any of the three can carry |
| 798 | /// a malformed value. The whole row is rejected on a single bad field — |
| 799 | /// accepting the fields that happen to parse would turn a malformed row into a |
| 800 | /// silently under-counted bill, which is worse than no price at all. |
| 801 | #[must_use] |
| 802 | pub fn catalog_cost_is_valid(cost: &ModelsDevCost) -> bool { |
| 803 | cost.validate().is_ok() |
| 804 | && cost.tiers.as_ref().is_none_or(|tiers| tiers.len() <= 128) |
| 805 | && [ |
| 806 | cost.input, |
| 807 | cost.output, |
| 808 | cost.cache_read, |
| 809 | cost.cache_write, |
| 810 | cost.reasoning, |
| 811 | cost.input_audio, |
| 812 | cost.output_audio, |
| 813 | ] |
| 814 | .into_iter() |
| 815 | .flatten() |
| 816 | .all(|price| price.is_finite() && (0.0..=MAX_PLAUSIBLE_PRICE_PER_MILLION).contains(&price)) |
| 817 | && cost |
| 818 | .tiers |
| 819 | .iter() |
| 820 | .flatten() |
| 821 | .all(|tier| catalog_cost_is_valid(&tier.cost)) |
| 822 | && cost |
| 823 | .context_over_200k |
| 824 | .as_ref() |
| 825 | .is_none_or(|cost| catalog_cost_is_valid(cost)) |
| 826 | } |
| 827 | |
| 828 | fn add_decimal_exact(total: Decimal, component: Decimal) -> Result<Decimal, PricingQuoteError> { |
| 829 | let next = total |
| 830 | .checked_add(component) |
| 831 | .ok_or(PricingQuoteError::InvalidRate)?; |
| 832 | if next.checked_sub(total) != Some(component) { |
| 833 | return Err(PricingQuoteError::InvalidRate); |
| 834 | } |
| 835 | Ok(next) |
| 836 | } |
| 837 | |
| 838 | fn rate_for_class(cost: &ModelsDevCost, class: TokenClass) -> Option<f64> { |
| 839 | match class { |
| 840 | TokenClass::Input => cost.input, |
| 841 | TokenClass::Output => cost.output, |
| 842 | TokenClass::CacheRead => cost.cache_read, |
| 843 | TokenClass::CacheWrite => cost.cache_write, |
| 844 | TokenClass::Reasoning => cost.reasoning, |
| 845 | TokenClass::InputAudio => cost.input_audio, |
| 846 | TokenClass::OutputAudio => cost.output_audio, |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | fn provenance_from_source(source: &CatalogSource) -> PricingProvenance { |
| 851 | match source { |
| 852 | CatalogSource::CloudFacts { .. } => PricingProvenance::CloudFacts, |
| 853 | CatalogSource::Bundled => PricingProvenance::ModelsDevBundled, |
| 854 | CatalogSource::ModelsDevLive { .. } => PricingProvenance::ModelsDevLive, |
| 855 | CatalogSource::Live { .. } => PricingProvenance::ProviderLive, |
| 856 | CatalogSource::ConfigOverride | CatalogSource::UserOverride => { |
| 857 | PricingProvenance::UserOverride |
| 858 | } |
| 859 | CatalogSource::CodewhaleBundled { .. } => PricingProvenance::CodewhaleCatalog, |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | fn fetched_at_from_source(source: &CatalogSource) -> Option<u64> { |
| 864 | match source { |
| 865 | CatalogSource::Live { fetched_at, .. } |
| 866 | | CatalogSource::ModelsDevLive { fetched_at } |
| 867 | | CatalogSource::CloudFacts { fetched_at, .. } => Some(*fetched_at), |
| 868 | CatalogSource::Bundled |
| 869 | | CatalogSource::ConfigOverride |
| 870 | | CatalogSource::UserOverride |
| 871 | | CatalogSource::CodewhaleBundled { .. } => None, |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | fn endpoint_fingerprint_from_source(source: &CatalogSource) -> Option<String> { |
| 876 | match source { |
| 877 | CatalogSource::Live { |
| 878 | base_url_fingerprint, |
| 879 | .. |
| 880 | } => Some(base_url_fingerprint.clone()), |
| 881 | CatalogSource::Bundled |
| 882 | | CatalogSource::ModelsDevLive { .. } |
| 883 | | CatalogSource::ConfigOverride |
| 884 | | CatalogSource::UserOverride |
| 885 | | CatalogSource::CodewhaleBundled { .. } |
| 886 | | CatalogSource::CloudFacts { .. } => None, |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | /// Cost display currency. |
| 891 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 892 | pub enum CostCurrency { |
| 893 | Usd, |
| 894 | Cny, |
| 895 | } |
| 896 | |
| 897 | impl CostCurrency { |
| 898 | #[must_use] |
| 899 | pub fn from_setting(value: &str) -> Option<Self> { |
| 900 | match value.trim().to_ascii_lowercase().as_str() { |
| 901 | "usd" | "dollar" | "dollars" | "$" => Some(Self::Usd), |
| 902 | "cny" | "rmb" | "yuan" | "¥" => Some(Self::Cny), |
| 903 | _ => None, |
| 904 | } |
| 905 | } |
| 906 | |
| 907 | #[must_use] |
| 908 | pub fn symbol(self) -> &'static str { |
| 909 | match self { |
| 910 | Self::Usd => "$", |
| 911 | Self::Cny => "¥", |
| 912 | } |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | #[cfg(test)] |
| 917 | mod tests; |
| 918 |