| 1 | //! Usage projections and source attribution receipts. |
| 2 | |
| 3 | use codewhale_runtime::safe_label::{safe_receipt_field, sanitize_persisted_route_label}; |
| 4 | use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque}; |
| 5 | use std::sync::{Arc, Mutex, OnceLock}; |
| 6 | |
| 7 | use chrono::{DateTime, Utc}; |
| 8 | |
| 9 | use crate::pricing::{CostEstimate, TurnCostAudit}; |
| 10 | use crate::route_billing::BillingPresentation; |
| 11 | use codewhale_config::ProviderKind; |
| 12 | use codewhale_models::Usage; |
| 13 | |
| 14 | pub const MAX_USAGE_SOURCE_FINGERPRINTS: usize = 4_096; |
| 15 | |
| 16 | #[derive(Debug, Clone, Default)] |
| 17 | pub struct OrderedFingerprintSet { |
| 18 | order: VecDeque<String>, |
| 19 | index: HashSet<String>, |
| 20 | } |
| 21 | |
| 22 | impl OrderedFingerprintSet { |
| 23 | #[must_use] |
| 24 | pub fn new() -> Self { |
| 25 | Self::default() |
| 26 | } |
| 27 | |
| 28 | #[must_use] |
| 29 | pub fn len(&self) -> usize { |
| 30 | self.order.len() |
| 31 | } |
| 32 | |
| 33 | #[must_use] |
| 34 | pub fn is_empty(&self) -> bool { |
| 35 | self.order.is_empty() |
| 36 | } |
| 37 | |
| 38 | #[must_use] |
| 39 | pub fn contains(&self, value: &str) -> bool { |
| 40 | self.index.contains(value) |
| 41 | } |
| 42 | |
| 43 | pub fn insert(&mut self, value: String) -> bool { |
| 44 | if self.index.insert(value.clone()) { |
| 45 | self.order.push_back(value); |
| 46 | true |
| 47 | } else { |
| 48 | false |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn clear(&mut self) { |
| 53 | self.order.clear(); |
| 54 | self.index.clear(); |
| 55 | } |
| 56 | |
| 57 | pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, String> { |
| 58 | self.order.iter() |
| 59 | } |
| 60 | |
| 61 | pub fn compact_keeping_pinned( |
| 62 | &mut self, |
| 63 | cap: usize, |
| 64 | mut is_pinned: impl FnMut(&str) -> bool, |
| 65 | ) -> usize { |
| 66 | if self.order.len() <= cap { |
| 67 | return 0; |
| 68 | } |
| 69 | let excess = self.order.len() - cap; |
| 70 | let mut evicted = 0usize; |
| 71 | let mut retained = VecDeque::with_capacity(self.order.len().min(cap)); |
| 72 | while let Some(fingerprint) = self.order.pop_front() { |
| 73 | if evicted < excess && !is_pinned(&fingerprint) { |
| 74 | self.index.remove(&fingerprint); |
| 75 | evicted += 1; |
| 76 | } else { |
| 77 | retained.push_back(fingerprint); |
| 78 | } |
| 79 | } |
| 80 | self.order = retained; |
| 81 | evicted |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl PartialEq for OrderedFingerprintSet { |
| 86 | fn eq(&self, other: &Self) -> bool { |
| 87 | self.index == other.index |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl Eq for OrderedFingerprintSet {} |
| 92 | |
| 93 | impl Extend<String> for OrderedFingerprintSet { |
| 94 | fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) { |
| 95 | for item in iter { |
| 96 | self.insert(item); |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl FromIterator<String> for OrderedFingerprintSet { |
| 102 | fn from_iter<T: IntoIterator<Item = String>>(iter: T) -> Self { |
| 103 | let mut set = Self::new(); |
| 104 | set.extend(iter); |
| 105 | set |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | impl IntoIterator for OrderedFingerprintSet { |
| 110 | type Item = String; |
| 111 | type IntoIter = std::collections::vec_deque::IntoIter<String>; |
| 112 | |
| 113 | fn into_iter(self) -> Self::IntoIter { |
| 114 | self.order.into_iter() |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | impl<'a> IntoIterator for &'a OrderedFingerprintSet { |
| 119 | type Item = &'a String; |
| 120 | type IntoIter = std::collections::vec_deque::Iter<'a, String>; |
| 121 | |
| 122 | fn into_iter(self) -> Self::IntoIter { |
| 123 | self.order.iter() |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl<const N: usize> From<[String; N]> for OrderedFingerprintSet { |
| 128 | fn from(items: [String; N]) -> Self { |
| 129 | items.into_iter().collect() |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl From<BTreeSet<String>> for OrderedFingerprintSet { |
| 134 | fn from(items: BTreeSet<String>) -> Self { |
| 135 | items.into_iter().collect() |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | impl From<Vec<String>> for OrderedFingerprintSet { |
| 140 | fn from(items: Vec<String>) -> Self { |
| 141 | items.into_iter().collect() |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | impl serde::Serialize for OrderedFingerprintSet { |
| 146 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 147 | where |
| 148 | S: serde::Serializer, |
| 149 | { |
| 150 | self.order.serialize(serializer) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl<'de> serde::Deserialize<'de> for OrderedFingerprintSet { |
| 155 | fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 156 | where |
| 157 | D: serde::Deserializer<'de>, |
| 158 | { |
| 159 | let items = Vec::<String>::deserialize(deserializer)?; |
| 160 | Ok(Self::from(items)) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// Everything a drained background accrual needs to be explained. |
| 165 | /// |
| 166 | /// The money and the coverage/provenance that qualify it are drained together, |
| 167 | /// so `/cost` can never show a background subtotal whose completeness came from |
| 168 | /// a different observation. |
| 169 | #[derive(Debug, Clone, Default, PartialEq)] |
| 170 | pub struct PendingBackgroundCost { |
| 171 | /// Summed cost of the background turns that were priced. |
| 172 | pub estimate: CostEstimate, |
| 173 | /// Background turns that produced an authoritative price. |
| 174 | pub priced_turns: u32, |
| 175 | /// Background turns that were money-metered (or of unknown basis) but |
| 176 | /// produced no authoritative price, so their spend is missing. |
| 177 | pub unpriced_turns: u32, |
| 178 | /// Money-metered turns authoritatively priced in CNY. |
| 179 | pub cny_priced_turns: u32, |
| 180 | /// Money-metered turns missing authoritative CNY pricing. |
| 181 | pub cny_unpriced_turns: u32, |
| 182 | /// Stable reason labels for the unpriced turns. |
| 183 | pub unpriced_reasons: BTreeSet<&'static str>, |
| 184 | pub cny_unpriced_reasons: BTreeSet<&'static str>, |
| 185 | /// Token classes used on a background route that carry no published price. |
| 186 | pub unpriced_classes: BTreeSet<&'static str>, |
| 187 | /// Provenance labels of the pricing rows that were applied or attempted. |
| 188 | pub pricing_provenances: BTreeSet<&'static str>, |
| 189 | /// Live-pricing downgrade receipts, when a live catalog row could not be |
| 190 | /// verified for the endpoint that served the turn. |
| 191 | pub live_pricing_defects: BTreeSet<&'static str>, |
| 192 | /// Live pricing failed and no bundled row could price the turn. Kept |
| 193 | /// separate so `/cost` never claims a bundled fallback was used when the |
| 194 | /// result is actually unavailable. |
| 195 | pub live_pricing_unusable_defects: BTreeSet<&'static str>, |
| 196 | /// One redacted receipt per distinct background route that reported. |
| 197 | /// |
| 198 | /// See [`EffectiveRouteEnvelope::receipt`] for the exact contents; these carry |
| 199 | /// provider identity, endpoint *fingerprint*, billing surface, wire model, |
| 200 | /// and currency — never a URL, key, token, or filesystem path. |
| 201 | pub route_receipts: BTreeSet<String>, |
| 202 | /// Durable, redacted identities of provider responses folded into this |
| 203 | /// batch. These travel with the money so a session snapshot can make a |
| 204 | /// replay idempotent after reload. |
| 205 | pub usage_source_fingerprints: BTreeSet<String>, |
| 206 | pub pinned_usage_source_fingerprints: BTreeSet<String>, |
| 207 | /// Prompt-cache classes the background routes reported, through |
| 208 | /// [`crate::pricing::token_usage_for_pricing`] so they never exceed the |
| 209 | /// input they partition (#6565). `None` until a child reports cache |
| 210 | /// telemetry at all: no report is not a 0% hit rate. |
| 211 | pub cache_hit_tokens: Option<u64>, |
| 212 | pub cache_miss_tokens: Option<u64>, |
| 213 | pub cache_write_tokens: Option<u64>, |
| 214 | pub source_records: Vec<RuntimeUsageRecord>, |
| 215 | } |
| 216 | |
| 217 | /// Immutable, non-secret route evidence captured before a provider request. |
| 218 | /// It contains enough information to audit the eventual usage without reading |
| 219 | /// mutable parent/app config at completion time. |
| 220 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 221 | pub struct EffectiveRouteEnvelope { |
| 222 | pub provider: ProviderKind, |
| 223 | pub provider_identity: String, |
| 224 | pub model: String, |
| 225 | /// Requested OpenRouter upstream, frozen with the client that dispatched. |
| 226 | pub openrouter_vendor: Option<String>, |
| 227 | pub billing_surface: Option<String>, |
| 228 | pub endpoint_fingerprint: Option<String>, |
| 229 | /// Frozen provider-live or signed cloud rates captured from the exact catalog scope |
| 230 | /// at CodeWhale's pre-permit application-dispatch boundary. Legacy |
| 231 | /// receipts omit this and therefore cannot meter a reviewed custom route |
| 232 | /// retroactively. |
| 233 | pub provider_live_pricing: Option<crate::provider_catalog_live::ProviderLivePricingQuote>, |
| 234 | pub billing_mode: RouteBillingMode, |
| 235 | pub dispatched_at: DateTime<Utc>, |
| 236 | } |
| 237 | |
| 238 | #[derive(serde::Deserialize)] |
| 239 | struct EffectiveRouteEnvelopeWire { |
| 240 | provider: String, |
| 241 | provider_identity: String, |
| 242 | model: String, |
| 243 | /// Requested OpenRouter upstream, frozen with the client that dispatched. |
| 244 | #[serde(default)] |
| 245 | openrouter_vendor: Option<String>, |
| 246 | billing_surface: Option<String>, |
| 247 | endpoint_fingerprint: Option<String>, |
| 248 | /// Frozen provider-live or signed cloud rates captured from the exact catalog scope |
| 249 | /// at CodeWhale's pre-permit application-dispatch boundary. Legacy |
| 250 | /// receipts omit this and therefore cannot meter a reviewed custom route |
| 251 | /// retroactively. |
| 252 | #[serde( |
| 253 | default, |
| 254 | deserialize_with = "crate::provider_catalog_live::deserialize_optional_provider_live_pricing" |
| 255 | )] |
| 256 | provider_live_pricing: Option<crate::provider_catalog_live::ProviderLivePricingQuote>, |
| 257 | #[serde(default)] |
| 258 | billing_mode: RouteBillingMode, |
| 259 | dispatched_at: DateTime<Utc>, |
| 260 | } |
| 261 | |
| 262 | impl<'de> serde::Deserialize<'de> for EffectiveRouteEnvelope { |
| 263 | fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
| 264 | where |
| 265 | D: serde::Deserializer<'de>, |
| 266 | { |
| 267 | let wire = <EffectiveRouteEnvelopeWire as serde::Deserialize>::deserialize(deserializer)?; |
| 268 | let provider = codewhale_config::descriptors::kind_from_tui_wire_tag( |
| 269 | &wire.provider, |
| 270 | &wire.provider_identity, |
| 271 | ) |
| 272 | .ok_or_else(|| serde::de::Error::custom("contradictory usage provider identity"))?; |
| 273 | Ok(Self { |
| 274 | provider, |
| 275 | provider_identity: wire.provider_identity, |
| 276 | model: wire.model, |
| 277 | openrouter_vendor: wire.openrouter_vendor, |
| 278 | billing_surface: wire.billing_surface, |
| 279 | endpoint_fingerprint: wire.endpoint_fingerprint, |
| 280 | provider_live_pricing: wire.provider_live_pricing, |
| 281 | billing_mode: wire.billing_mode, |
| 282 | dispatched_at: wire.dispatched_at, |
| 283 | }) |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | impl serde::Serialize for EffectiveRouteEnvelope { |
| 288 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 289 | where |
| 290 | S: serde::Serializer, |
| 291 | { |
| 292 | use serde::ser::SerializeStruct as _; |
| 293 | |
| 294 | let route = self.sanitized_for_persistence(); |
| 295 | let mut state = serializer.serialize_struct( |
| 296 | "EffectiveRouteEnvelope", |
| 297 | 8 + usize::from(route.openrouter_vendor.is_some()), |
| 298 | )?; |
| 299 | let provider = codewhale_config::descriptors::tui_wire_tag_for_route( |
| 300 | route.provider, |
| 301 | &route.provider_identity, |
| 302 | ) |
| 303 | .ok_or_else(|| serde::ser::Error::custom("contradictory usage provider identity"))?; |
| 304 | state.serialize_field("provider", provider)?; |
| 305 | state.serialize_field("provider_identity", &route.provider_identity)?; |
| 306 | state.serialize_field("model", &route.model)?; |
| 307 | if let Some(vendor) = &route.openrouter_vendor { |
| 308 | state.serialize_field("openrouter_vendor", vendor)?; |
| 309 | } |
| 310 | state.serialize_field("billing_surface", &route.billing_surface)?; |
| 311 | state.serialize_field("endpoint_fingerprint", &route.endpoint_fingerprint)?; |
| 312 | state.serialize_field("provider_live_pricing", &route.provider_live_pricing)?; |
| 313 | state.serialize_field("billing_mode", &route.billing_mode)?; |
| 314 | state.serialize_field("dispatched_at", &route.dispatched_at)?; |
| 315 | state.end() |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | /// One provider usage payload paired with the immutable route that served it. |
| 320 | /// |
| 321 | /// Runtime hosts persist these for model calls made below the parent turn |
| 322 | /// (sub-agents, review/verify/RLM tools, and compaction). Keeping route and |
| 323 | /// usage together makes the record independently auditable and prevents a |
| 324 | /// later provider/model selection from changing its price. |
| 325 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 326 | pub struct EffectiveRouteUsage { |
| 327 | pub route: EffectiveRouteEnvelope, |
| 328 | pub usage: Usage, |
| 329 | } |
| 330 | |
| 331 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 332 | #[serde(rename_all = "snake_case")] |
| 333 | pub enum RouteBillingMode { |
| 334 | Metered, |
| 335 | Subscription, |
| 336 | Local, |
| 337 | #[default] |
| 338 | Unknown, |
| 339 | } |
| 340 | |
| 341 | impl From<BillingPresentation> for RouteBillingMode { |
| 342 | fn from(value: BillingPresentation) -> Self { |
| 343 | match value { |
| 344 | BillingPresentation::Metered => Self::Metered, |
| 345 | BillingPresentation::Subscription(_) => Self::Subscription, |
| 346 | BillingPresentation::Local => Self::Local, |
| 347 | BillingPresentation::Unknown => Self::Unknown, |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | impl EffectiveRouteEnvelope { |
| 353 | /// Provider-neutral observation. This never opens configuration or credentials. |
| 354 | #[must_use] |
| 355 | pub fn capture_observed( |
| 356 | provider: ProviderKind, |
| 357 | provider_identity: impl Into<String>, |
| 358 | model: impl Into<String>, |
| 359 | base_url: Option<&str>, |
| 360 | dispatched_at: DateTime<Utc>, |
| 361 | ) -> Self { |
| 362 | let key = provider_identity.into(); |
| 363 | Self::from_facts(None, (provider, &key), model, base_url, dispatched_at) |
| 364 | } |
| 365 | |
| 366 | #[cfg(any(test, feature = "test-support"))] |
| 367 | pub fn capture( |
| 368 | config: Option<&codewhale_runtime::config::Config>, |
| 369 | provider: ProviderKind, |
| 370 | provider_identity: impl Into<String>, |
| 371 | model: impl Into<String>, |
| 372 | base_url: Option<&str>, |
| 373 | dispatched_at: DateTime<Utc>, |
| 374 | ) -> Self { |
| 375 | let key = provider_identity.into(); |
| 376 | if let Some(config) = config |
| 377 | && let Ok(identity) = |
| 378 | config.resolve_persisted_provider_identity(Some(provider.as_str()), Some(&key)) |
| 379 | { |
| 380 | Self::from_admitted(Some(config), &identity, model, base_url, dispatched_at) |
| 381 | } else { |
| 382 | Self::capture_observed(provider, key, model, base_url, dispatched_at) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | #[must_use] |
| 387 | pub fn from_admitted( |
| 388 | config: Option<&codewhale_runtime::config::Config>, |
| 389 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 390 | model: impl Into<String>, |
| 391 | base_url: Option<&str>, |
| 392 | dispatched_at: DateTime<Utc>, |
| 393 | ) -> Self { |
| 394 | let admission = config |
| 395 | .filter(|config| config.verify_provider_identity(identity).is_ok()) |
| 396 | .map(|config| (config, identity)); |
| 397 | Self::from_facts( |
| 398 | admission, |
| 399 | (identity.provider, identity.key.as_str()), |
| 400 | model, |
| 401 | base_url, |
| 402 | dispatched_at, |
| 403 | ) |
| 404 | } |
| 405 | |
| 406 | fn from_facts( |
| 407 | admission: Option<( |
| 408 | &codewhale_runtime::config::Config, |
| 409 | &codewhale_runtime::config::ProviderIdentity, |
| 410 | )>, |
| 411 | facts: (ProviderKind, &str), |
| 412 | model: impl Into<String>, |
| 413 | base_url: Option<&str>, |
| 414 | dispatched_at: DateTime<Utc>, |
| 415 | ) -> Self { |
| 416 | let (provider, provider_identity) = facts; |
| 417 | let config = admission.map(|(config, _)| config); |
| 418 | let model = model.into(); |
| 419 | let billing = admission.map_or_else( |
| 420 | || crate::route_billing::for_endpoint_without_config(provider, base_url), |
| 421 | |(config, identity)| { |
| 422 | base_url.map_or_else( |
| 423 | || crate::route_billing::for_route(config, identity), |
| 424 | |endpoint| { |
| 425 | crate::route_billing::for_route_with_endpoint(config, identity, endpoint) |
| 426 | }, |
| 427 | ) |
| 428 | }, |
| 429 | ); |
| 430 | let endpoint_fingerprint = base_url.and_then(endpoint_fingerprint); |
| 431 | let provider_live_pricing = base_url.and_then(|base_url| { |
| 432 | u64::try_from(dispatched_at.timestamp()) |
| 433 | .ok() |
| 434 | .and_then(|at| { |
| 435 | crate::provider_catalog_live::declared_or_catalog_quote( |
| 436 | config.and_then(|config| { |
| 437 | crate::provider_catalog_live::configured_dispatch_pricing_quote_at( |
| 438 | config.custom_models.as_deref().unwrap_or_default(), |
| 439 | provider, |
| 440 | provider_identity, |
| 441 | &model, |
| 442 | base_url, |
| 443 | at, |
| 444 | ) |
| 445 | }), |
| 446 | || { |
| 447 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 448 | provider, |
| 449 | provider_identity, |
| 450 | &model, |
| 451 | base_url, |
| 452 | at, |
| 453 | ) |
| 454 | }, |
| 455 | ) |
| 456 | }) |
| 457 | }); |
| 458 | Self { |
| 459 | provider, |
| 460 | provider_identity: sanitize_persisted_route_label(provider_identity), |
| 461 | model: sanitize_persisted_route_label(&model), |
| 462 | openrouter_vendor: admission |
| 463 | .filter(|_| provider == ProviderKind::Openrouter) |
| 464 | .and_then(|(config, identity)| config.provider_config_for(identity)) |
| 465 | .and_then(|entry| entry.vendor.as_deref()) |
| 466 | .map(str::trim) |
| 467 | .filter(|vendor| !vendor.is_empty()) |
| 468 | .map(sanitize_persisted_route_label), |
| 469 | billing_surface: admission |
| 470 | .map_or_else( |
| 471 | || crate::pricing::billing_surface_for_route(provider, base_url), |
| 472 | |(config, identity)| { |
| 473 | crate::route_billing::billing_surface_for_dispatch( |
| 474 | Some(config), |
| 475 | identity, |
| 476 | base_url, |
| 477 | ) |
| 478 | }, |
| 479 | ) |
| 480 | .map(str::to_string), |
| 481 | endpoint_fingerprint, |
| 482 | provider_live_pricing, |
| 483 | billing_mode: billing.into(), |
| 484 | dispatched_at, |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | #[must_use] |
| 489 | pub fn audit_frozen(&self, usage: &Usage) -> TurnCostAudit { |
| 490 | let audit = self.audit(usage); |
| 491 | if self.provider_live_pricing.is_none() |
| 492 | && audit |
| 493 | .unpriced_reason |
| 494 | .is_none_or(|reason| reason.counts_toward_money_coverage()) |
| 495 | { |
| 496 | return TurnCostAudit::unpriced(crate::pricing::UnpricedReason::UnverifiedLivePricing); |
| 497 | } |
| 498 | audit |
| 499 | } |
| 500 | |
| 501 | pub fn audit(&self, usage: &Usage) -> TurnCostAudit { |
| 502 | let reviewed_custom_metered = crate::pricing::reviewed_custom_route_is_metered( |
| 503 | self.provider, |
| 504 | self.endpoint_fingerprint.as_deref(), |
| 505 | ); |
| 506 | let declared_quote = self.provider_live_pricing.as_ref().filter(|quote| { |
| 507 | quote.provenance == codewhale_config::pricing::PricingProvenance::UserOverride |
| 508 | && self |
| 509 | .endpoint_fingerprint |
| 510 | .as_deref() |
| 511 | .zip(u64::try_from(self.dispatched_at.timestamp()).ok()) |
| 512 | .is_some_and(|(fingerprint, at)| { |
| 513 | quote |
| 514 | .pricing_for_route( |
| 515 | self.provider, |
| 516 | &self.provider_identity, |
| 517 | &self.model, |
| 518 | fingerprint, |
| 519 | at, |
| 520 | ) |
| 521 | .is_some() |
| 522 | }) |
| 523 | }); |
| 524 | let declared_estimate = declared_quote.is_some(); |
| 525 | match self.billing_mode { |
| 526 | RouteBillingMode::Subscription | RouteBillingMode::Local => { |
| 527 | return TurnCostAudit::unpriced(crate::pricing::UnpricedReason::NotMoneyMetered); |
| 528 | } |
| 529 | RouteBillingMode::Unknown if !reviewed_custom_metered && !declared_estimate => { |
| 530 | return TurnCostAudit::unpriced( |
| 531 | crate::pricing::UnpricedReason::UnknownBillingBasis, |
| 532 | ); |
| 533 | } |
| 534 | RouteBillingMode::Metered | RouteBillingMode::Unknown => {} |
| 535 | } |
| 536 | // The OpenRouter model catalog does not identify a pinned upstream's |
| 537 | // price. An endpoint match alone must not promote that aggregate rate. |
| 538 | // An operator's own declared rate for this exact route is not the |
| 539 | // aggregate catalog, so it still prices the pinned turn. |
| 540 | if self.provider == ProviderKind::Openrouter |
| 541 | && self.openrouter_vendor.is_some() |
| 542 | && !declared_quote.is_some_and(|quote| quote.carries_rates()) |
| 543 | { |
| 544 | return TurnCostAudit::unpriced(crate::pricing::UnpricedReason::RoutingDependentPrice); |
| 545 | } |
| 546 | crate::pricing::audit_turn_cost_for_route_on_endpoint_for_identity_at( |
| 547 | self.provider, |
| 548 | Some(&self.provider_identity), |
| 549 | &self.model, |
| 550 | self.billing_surface.as_deref(), |
| 551 | self.endpoint_fingerprint.as_deref(), |
| 552 | self.provider_live_pricing.as_ref(), |
| 553 | usage, |
| 554 | self.dispatched_at, |
| 555 | ) |
| 556 | } |
| 557 | |
| 558 | #[must_use] |
| 559 | pub fn receipt(&self, audit: &TurnCostAudit) -> String { |
| 560 | let route = self.sanitized_for_persistence(); |
| 561 | let mut receipt = route_receipt( |
| 562 | route.provider, |
| 563 | Some(&route.provider_identity), |
| 564 | &route.model, |
| 565 | route.billing_surface.as_deref(), |
| 566 | route.endpoint_fingerprint.as_deref(), |
| 567 | route.billing_mode, |
| 568 | currency_tag(audit), |
| 569 | ); |
| 570 | if let Some(vendor) = route.openrouter_vendor.as_deref() { |
| 571 | receipt.push_str(" openrouter_vendor="); |
| 572 | receipt.push_str(&safe_receipt_field(vendor)); |
| 573 | } |
| 574 | receipt |
| 575 | } |
| 576 | |
| 577 | /// Redact filesystem-like labels before a route crosses a persistence or |
| 578 | /// metadata boundary. Ordinary provider model namespaces such as |
| 579 | /// `anthropic/claude-*` remain intact; absolute/local path forms do not. |
| 580 | #[must_use] |
| 581 | pub fn sanitized_for_persistence(&self) -> Self { |
| 582 | let mut route = self.clone(); |
| 583 | route.provider_identity = sanitize_persisted_route_label(&route.provider_identity); |
| 584 | route.model = sanitize_persisted_route_label(&route.model); |
| 585 | route.openrouter_vendor = route |
| 586 | .openrouter_vendor |
| 587 | .as_deref() |
| 588 | .map(sanitize_persisted_route_label); |
| 589 | route.billing_surface = route |
| 590 | .billing_surface |
| 591 | .as_deref() |
| 592 | .map(sanitize_persisted_route_label); |
| 593 | route.endpoint_fingerprint = |
| 594 | route |
| 595 | .endpoint_fingerprint |
| 596 | .as_deref() |
| 597 | .and_then(|fingerprint| { |
| 598 | let fingerprint = fingerprint.trim(); |
| 599 | (fingerprint.len() == 64 |
| 600 | && fingerprint.bytes().all(|byte| byte.is_ascii_hexdigit())) |
| 601 | .then(|| fingerprint.to_ascii_lowercase()) |
| 602 | }); |
| 603 | let quote_is_valid = route |
| 604 | .provider_live_pricing |
| 605 | .as_ref() |
| 606 | .zip(route.endpoint_fingerprint.as_deref()) |
| 607 | .and_then(|(quote, fingerprint)| { |
| 608 | u64::try_from(route.dispatched_at.timestamp()) |
| 609 | .ok() |
| 610 | .and_then(|dispatched_at_unix| { |
| 611 | quote.pricing_for_route( |
| 612 | route.provider, |
| 613 | &route.provider_identity, |
| 614 | &route.model, |
| 615 | fingerprint, |
| 616 | dispatched_at_unix, |
| 617 | ) |
| 618 | }) |
| 619 | }) |
| 620 | .is_some(); |
| 621 | if !quote_is_valid { |
| 622 | route.provider_live_pricing = None; |
| 623 | } |
| 624 | route |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | fn receipt_with_usage_classes(mut receipt: String, usage: &Usage) -> String { |
| 629 | let classes = crate::pricing::token_usage_for_pricing(usage); |
| 630 | if classes.cache_write > 0 { |
| 631 | receipt.push_str(" cache_write=yes"); |
| 632 | } |
| 633 | if usage.reasoning_tokens.unwrap_or(0) > 0 { |
| 634 | receipt.push_str(" reasoning=yes"); |
| 635 | } |
| 636 | receipt |
| 637 | } |
| 638 | |
| 639 | /// Canonical redacted route receipt for one exact usage payload. |
| 640 | #[must_use] |
| 641 | pub fn effective_route_usage_receipt( |
| 642 | route: &EffectiveRouteEnvelope, |
| 643 | audit: &TurnCostAudit, |
| 644 | usage: &Usage, |
| 645 | ) -> String { |
| 646 | receipt_with_usage_classes(route.receipt(audit), usage) |
| 647 | } |
| 648 | |
| 649 | /// Canonical `child_*` token and route metadata for tools that make their own |
| 650 | /// LLM calls (`review`, `verify`, and `rlm`). Keeping this next to the immutable |
| 651 | /// route envelope prevents the pure model types from depending on app config. |
| 652 | #[must_use] |
| 653 | pub fn child_usage_metadata_fields( |
| 654 | route: &EffectiveRouteEnvelope, |
| 655 | usage: &Usage, |
| 656 | ) -> serde_json::Map<String, serde_json::Value> { |
| 657 | let route = route.sanitized_for_persistence(); |
| 658 | let mut fields = serde_json::Map::new(); |
| 659 | fields.insert("child_provider".into(), serde_json::json!(route.provider)); |
| 660 | fields.insert( |
| 661 | "child_provider_identity".into(), |
| 662 | serde_json::json!(route.provider_identity), |
| 663 | ); |
| 664 | fields.insert("child_model".into(), serde_json::json!(route.model)); |
| 665 | fields.insert( |
| 666 | "child_openrouter_vendor".into(), |
| 667 | serde_json::json!(route.openrouter_vendor), |
| 668 | ); |
| 669 | fields.insert( |
| 670 | "child_billing_surface".into(), |
| 671 | serde_json::json!(route.billing_surface), |
| 672 | ); |
| 673 | fields.insert( |
| 674 | "child_endpoint_fingerprint".into(), |
| 675 | serde_json::json!(route.endpoint_fingerprint), |
| 676 | ); |
| 677 | fields.insert( |
| 678 | "child_provider_live_pricing".into(), |
| 679 | serde_json::json!(route.provider_live_pricing), |
| 680 | ); |
| 681 | fields.insert( |
| 682 | "child_billing_mode".into(), |
| 683 | serde_json::json!(route.billing_mode), |
| 684 | ); |
| 685 | fields.insert( |
| 686 | "child_dispatched_at".into(), |
| 687 | serde_json::json!(route.dispatched_at), |
| 688 | ); |
| 689 | fields.insert( |
| 690 | "child_input_tokens".into(), |
| 691 | serde_json::json!(usage.input_tokens), |
| 692 | ); |
| 693 | fields.insert( |
| 694 | "child_output_tokens".into(), |
| 695 | serde_json::json!(usage.output_tokens), |
| 696 | ); |
| 697 | fields.insert( |
| 698 | "child_prompt_cache_hit_tokens".into(), |
| 699 | serde_json::json!(usage.prompt_cache_hit_tokens), |
| 700 | ); |
| 701 | fields.insert( |
| 702 | "child_prompt_cache_miss_tokens".into(), |
| 703 | serde_json::json!(usage.prompt_cache_miss_tokens), |
| 704 | ); |
| 705 | fields.insert( |
| 706 | "child_prompt_cache_write_tokens".into(), |
| 707 | serde_json::json!(usage.prompt_cache_write_tokens), |
| 708 | ); |
| 709 | // Informational: reasoning tokens are already included in output tokens. |
| 710 | fields.insert( |
| 711 | "child_reasoning_tokens".into(), |
| 712 | serde_json::json!(usage.reasoning_tokens), |
| 713 | ); |
| 714 | fields.insert( |
| 715 | "child_reasoning_replay_tokens".into(), |
| 716 | serde_json::json!(usage.reasoning_replay_tokens), |
| 717 | ); |
| 718 | fields.insert( |
| 719 | "child_server_tool_use".into(), |
| 720 | serde_json::json!(usage.server_tool_use), |
| 721 | ); |
| 722 | fields.insert( |
| 723 | "child_input_audio_tokens".into(), |
| 724 | serde_json::json!(usage.input_audio_tokens), |
| 725 | ); |
| 726 | fields.insert( |
| 727 | "child_output_audio_tokens".into(), |
| 728 | serde_json::json!(usage.output_audio_tokens), |
| 729 | ); |
| 730 | fields.insert( |
| 731 | "child_safety_tokens".into(), |
| 732 | serde_json::json!(usage.safety_tokens), |
| 733 | ); |
| 734 | let requests = if usage.request_usages.len() > 1024 |
| 735 | || usage |
| 736 | .request_usages |
| 737 | .iter() |
| 738 | .any(|request| !request.request_usages.is_empty()) |
| 739 | { |
| 740 | vec![Usage::default(); 1025] |
| 741 | } else { |
| 742 | usage.request_usages.clone() |
| 743 | }; |
| 744 | fields.insert("child_request_usages".into(), serde_json::json!(requests)); |
| 745 | fields |
| 746 | } |
| 747 | |
| 748 | /// Merge canonical child usage into a tool metadata object. |
| 749 | pub fn attach_child_usage_metadata( |
| 750 | metadata: &mut serde_json::Value, |
| 751 | route: &EffectiveRouteEnvelope, |
| 752 | usage: &Usage, |
| 753 | ) { |
| 754 | if let Some(object) = metadata.as_object_mut() { |
| 755 | object.extend(child_usage_metadata_fields(route, usage)); |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | /// Maximum number of distinct routed-usage segments accepted from one tool |
| 760 | /// result. RLM reserves against the same bound before dispatch, so a valid |
| 761 | /// producer never has to discard a provider receipt after doing the work. |
| 762 | pub const MAX_CHILD_USAGE_RECORDS: usize = 64; |
| 763 | |
| 764 | const CHILD_USAGE_RECORDS_KEY: &str = "child_usage_records"; |
| 765 | const CHILD_DECISION_RECEIPTS_KEY: &str = "child_decision_receipts"; |
| 766 | const CHILD_USAGE_DROP_RECORDS_KEY: &str = "child_usage_drop_records"; |
| 767 | const CHILD_USAGE_DROPPED_RECORDS_KEY: &str = "child_usage_dropped_records"; |
| 768 | |
| 769 | /// Attach a bounded batch of routed child usage to tool metadata. |
| 770 | /// |
| 771 | /// The source identity is reduced to a one-way fingerprint before metadata |
| 772 | /// can enter a transcript. Routes pass through their persistence sanitizer, |
| 773 | /// so neither a raw response id nor an endpoint/credential can hitch a ride. |
| 774 | /// New consumers prefer this batch over the legacy single `child_*` fields. |
| 775 | /// Attach a bounded batch containing both exact usage receipts and exact |
| 776 | /// provider-success/missing-usage route receipts. |
| 777 | pub fn attach_child_usage_batch_metadata( |
| 778 | metadata: &mut serde_json::Value, |
| 779 | batch: &RuntimeUsageBatch, |
| 780 | ) { |
| 781 | let Some(object) = metadata.as_object_mut() else { |
| 782 | return; |
| 783 | }; |
| 784 | object.insert( |
| 785 | CHILD_DECISION_RECEIPTS_KEY.into(), |
| 786 | serde_json::json!( |
| 787 | batch |
| 788 | .decisions |
| 789 | .iter() |
| 790 | .filter(|receipt| receipt.is_bounded()) |
| 791 | .take(MAX_CHILD_USAGE_RECORDS) |
| 792 | .map(RuntimeDecisionReceipt::sanitized) |
| 793 | .collect::<Vec<_>>() |
| 794 | ), |
| 795 | ); |
| 796 | let retained_records = batch |
| 797 | .records |
| 798 | .iter() |
| 799 | .take(MAX_CHILD_USAGE_RECORDS) |
| 800 | .map(|record| { |
| 801 | serde_json::json!({ |
| 802 | "source_id": format!( |
| 803 | "routed:{}", |
| 804 | usage_source_fingerprint(&record.source_id) |
| 805 | ), |
| 806 | "route": record.usage.route.sanitized_for_persistence(), |
| 807 | "usage": record.usage.usage, |
| 808 | "settlement": record.settlement, |
| 809 | }) |
| 810 | }) |
| 811 | .collect::<Vec<_>>(); |
| 812 | let remaining = MAX_CHILD_USAGE_RECORDS.saturating_sub(retained_records.len()); |
| 813 | let retained_drops = batch |
| 814 | .drop_records |
| 815 | .iter() |
| 816 | .take(remaining) |
| 817 | .map(|record| RuntimeUsageDropRecord { |
| 818 | reason: record.reason, |
| 819 | source_id: format!("routed:{}", usage_source_fingerprint(&record.source_id)), |
| 820 | route: record.route.sanitized_for_persistence(), |
| 821 | }) |
| 822 | .collect::<Vec<_>>(); |
| 823 | object.insert( |
| 824 | CHILD_USAGE_RECORDS_KEY.into(), |
| 825 | serde_json::json!(retained_records), |
| 826 | ); |
| 827 | object.insert( |
| 828 | CHILD_USAGE_DROP_RECORDS_KEY.into(), |
| 829 | serde_json::json!(retained_drops), |
| 830 | ); |
| 831 | let usage_overflow = batch.records.len().saturating_sub(MAX_CHILD_USAGE_RECORDS); |
| 832 | let decision_overflow = batch |
| 833 | .decisions |
| 834 | .len() |
| 835 | .saturating_sub(MAX_CHILD_USAGE_RECORDS) |
| 836 | .saturating_add( |
| 837 | batch |
| 838 | .decisions |
| 839 | .iter() |
| 840 | .take(MAX_CHILD_USAGE_RECORDS) |
| 841 | .filter(|r| !r.is_bounded()) |
| 842 | .count(), |
| 843 | ); |
| 844 | let dropped_records = batch |
| 845 | .dropped_records |
| 846 | .max(u64::try_from(batch.drop_records.len()).unwrap_or(u64::MAX)) |
| 847 | .saturating_add(u64::try_from(usage_overflow).unwrap_or(u64::MAX)) |
| 848 | .saturating_add(u64::try_from(decision_overflow).unwrap_or(u64::MAX)); |
| 849 | if dropped_records > 0 { |
| 850 | object.insert( |
| 851 | CHILD_USAGE_DROPPED_RECORDS_KEY.into(), |
| 852 | serde_json::json!(dropped_records), |
| 853 | ); |
| 854 | } else { |
| 855 | object.remove(CHILD_USAGE_DROPPED_RECORDS_KEY); |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | /// Parse the preferred routed child-usage batch. |
| 860 | /// |
| 861 | /// `None` means the batch key was absent and callers may use the legacy |
| 862 | /// single-record parser. Once the key is present, malformed/overflow entries |
| 863 | /// are represented by `dropped_records` instead of falling back and risking a |
| 864 | /// partial subtotal being presented as complete. |
| 865 | #[must_use] |
| 866 | pub fn child_usage_records_from_metadata( |
| 867 | metadata: &serde_json::Value, |
| 868 | ) -> Option<RuntimeUsageBatch> { |
| 869 | let value = metadata.get(CHILD_USAGE_RECORDS_KEY)?; |
| 870 | let drop_values = metadata |
| 871 | .get(CHILD_USAGE_DROP_RECORDS_KEY) |
| 872 | .and_then(serde_json::Value::as_array) |
| 873 | .map(Vec::as_slice) |
| 874 | .unwrap_or_default(); |
| 875 | let declared_dropped = metadata |
| 876 | .get(CHILD_USAGE_DROPPED_RECORDS_KEY) |
| 877 | .and_then(serde_json::Value::as_u64) |
| 878 | .unwrap_or(0); |
| 879 | let Some(values) = value.as_array() else { |
| 880 | return Some(RuntimeUsageBatch { |
| 881 | decisions: Vec::new(), |
| 882 | records: Vec::new(), |
| 883 | drop_records: Vec::new(), |
| 884 | dropped_records: declared_dropped.saturating_add(1), |
| 885 | }); |
| 886 | }; |
| 887 | |
| 888 | let overflow = values.len().saturating_sub(MAX_CHILD_USAGE_RECORDS); |
| 889 | let mut batch = RuntimeUsageBatch { |
| 890 | decisions: Vec::new(), |
| 891 | records: Vec::with_capacity(values.len().min(MAX_CHILD_USAGE_RECORDS)), |
| 892 | drop_records: Vec::with_capacity(drop_values.len().min(MAX_CHILD_USAGE_RECORDS)), |
| 893 | dropped_records: declared_dropped |
| 894 | .max(u64::try_from(drop_values.len()).unwrap_or(u64::MAX)) |
| 895 | .saturating_add(u64::try_from(overflow).unwrap_or(u64::MAX)), |
| 896 | }; |
| 897 | for value in values.iter().take(MAX_CHILD_USAGE_RECORDS) { |
| 898 | let parsed = (|| { |
| 899 | let source_id = value.get("source_id")?.as_str()?; |
| 900 | let route = |
| 901 | serde_json::from_value::<EffectiveRouteEnvelope>(value.get("route")?.clone()) |
| 902 | .ok()? |
| 903 | .sanitized_for_persistence(); |
| 904 | let usage = serde_json::from_value::<Usage>(value.get("usage")?.clone()).ok()?; |
| 905 | let mut record = RuntimeUsageRecord::legacy( |
| 906 | usage_source_fingerprint(source_id), |
| 907 | EffectiveRouteUsage { route, usage }, |
| 908 | ); |
| 909 | record.settlement = value |
| 910 | .get("settlement") |
| 911 | .filter(|value| !value.is_null()) |
| 912 | .map(|value| serde_json::from_value::<UsageSourceRevision>(value.clone())) |
| 913 | .transpose() |
| 914 | .ok()?; |
| 915 | record.validate().ok()?; |
| 916 | Some(record) |
| 917 | })(); |
| 918 | if let Some(record) = parsed { |
| 919 | batch.records.push(record); |
| 920 | } else { |
| 921 | batch.dropped_records = batch.dropped_records.saturating_add(1); |
| 922 | } |
| 923 | } |
| 924 | let remaining = MAX_CHILD_USAGE_RECORDS.saturating_sub(batch.records.len()); |
| 925 | for value in drop_values.iter().take(remaining) { |
| 926 | let parsed = (|| { |
| 927 | let source_id = value.get("source_id")?.as_str()?; |
| 928 | let route = |
| 929 | serde_json::from_value::<EffectiveRouteEnvelope>(value.get("route")?.clone()) |
| 930 | .ok()? |
| 931 | .sanitized_for_persistence(); |
| 932 | Some(RuntimeUsageDropRecord { |
| 933 | reason: value |
| 934 | .get("reason") |
| 935 | .map(|value| serde_json::from_value(value.clone())) |
| 936 | .transpose() |
| 937 | .ok()? |
| 938 | .unwrap_or_default(), |
| 939 | source_id: usage_source_fingerprint(source_id), |
| 940 | route, |
| 941 | }) |
| 942 | })(); |
| 943 | if let Some(record) = parsed { |
| 944 | batch.drop_records.push(record); |
| 945 | } |
| 946 | // Every declared drop slot already contributes to dropped_records, |
| 947 | // including malformed entries; do not count the same gap twice. |
| 948 | } |
| 949 | if let Some(decisions) = metadata.get(CHILD_DECISION_RECEIPTS_KEY) { |
| 950 | if let Some(values) = decisions.as_array() { |
| 951 | for value in values.iter().take(MAX_CHILD_USAGE_RECORDS) { |
| 952 | let bounded = serde_json::to_vec(value).is_ok_and(|bytes| bytes.len() <= 8 * 1024); |
| 953 | let parsed = bounded |
| 954 | .then(|| serde_json::from_value::<RuntimeDecisionReceipt>(value.clone()).ok()) |
| 955 | .flatten(); |
| 956 | if let Some(receipt) = parsed.filter(RuntimeDecisionReceipt::is_bounded) { |
| 957 | batch.decisions.push(receipt.sanitized()); |
| 958 | } else { |
| 959 | batch.dropped_records = batch.dropped_records.saturating_add(1); |
| 960 | } |
| 961 | } |
| 962 | batch.dropped_records = batch.dropped_records.saturating_add( |
| 963 | u64::try_from(values.len().saturating_sub(MAX_CHILD_USAGE_RECORDS)) |
| 964 | .unwrap_or(u64::MAX), |
| 965 | ); |
| 966 | } else { |
| 967 | batch.dropped_records = batch.dropped_records.saturating_add(1); |
| 968 | } |
| 969 | } |
| 970 | Some(batch) |
| 971 | } |
| 972 | |
| 973 | /// Rehydrate the immutable route envelope emitted with child usage. Legacy or |
| 974 | /// incomplete metadata becomes an explicitly unknown route and never borrows |
| 975 | /// mutable parent-session facts. |
| 976 | #[must_use] |
| 977 | pub fn child_route_envelope_from_metadata( |
| 978 | metadata: &serde_json::Value, |
| 979 | ) -> Option<EffectiveRouteEnvelope> { |
| 980 | let model = metadata.get("child_model")?.as_str()?.to_string(); |
| 981 | let provider = metadata |
| 982 | .get("child_provider") |
| 983 | .cloned() |
| 984 | .and_then(|value| serde_json::from_value(value).ok()); |
| 985 | let provider_identity = metadata |
| 986 | .get("child_provider_identity") |
| 987 | .and_then(serde_json::Value::as_str) |
| 988 | .map(str::to_string); |
| 989 | let billing_mode = metadata |
| 990 | .get("child_billing_mode") |
| 991 | .cloned() |
| 992 | .and_then(|value| serde_json::from_value(value).ok()); |
| 993 | let dispatched_at = metadata |
| 994 | .get("child_dispatched_at") |
| 995 | .cloned() |
| 996 | .and_then(|value| serde_json::from_value(value).ok()); |
| 997 | |
| 998 | let complete = provider.is_some() |
| 999 | && provider_identity.is_some() |
| 1000 | && billing_mode.is_some() |
| 1001 | && dispatched_at.is_some(); |
| 1002 | Some( |
| 1003 | EffectiveRouteEnvelope { |
| 1004 | provider: provider.unwrap_or(ProviderKind::Custom), |
| 1005 | provider_identity: provider_identity.unwrap_or_else(|| "legacy-unreported".to_string()), |
| 1006 | model, |
| 1007 | openrouter_vendor: metadata |
| 1008 | .get("child_openrouter_vendor") |
| 1009 | .and_then(serde_json::Value::as_str) |
| 1010 | .map(str::to_string), |
| 1011 | billing_surface: metadata |
| 1012 | .get("child_billing_surface") |
| 1013 | .and_then(serde_json::Value::as_str) |
| 1014 | .map(str::to_string), |
| 1015 | endpoint_fingerprint: metadata |
| 1016 | .get("child_endpoint_fingerprint") |
| 1017 | .and_then(serde_json::Value::as_str) |
| 1018 | .map(str::to_string), |
| 1019 | provider_live_pricing: metadata |
| 1020 | .get("child_provider_live_pricing") |
| 1021 | .cloned() |
| 1022 | .and_then(|value| serde_json::from_value(value).ok()), |
| 1023 | billing_mode: billing_mode |
| 1024 | .filter(|_| complete) |
| 1025 | .unwrap_or(RouteBillingMode::Unknown), |
| 1026 | dispatched_at: dispatched_at.unwrap_or_else(|| { |
| 1027 | DateTime::<Utc>::from_timestamp(0, 0).expect("Unix epoch is representable") |
| 1028 | }), |
| 1029 | } |
| 1030 | .sanitized_for_persistence(), |
| 1031 | ) |
| 1032 | } |
| 1033 | |
| 1034 | /// Rehydrate the complete child usage payload emitted by |
| 1035 | /// [`attach_child_usage_metadata`]. The presence of a canonical child token |
| 1036 | /// field is significant even when every value is zero: a zero-usage provider |
| 1037 | /// call still needs a route receipt and coverage classification. |
| 1038 | #[must_use] |
| 1039 | pub fn child_usage_from_metadata(metadata: &serde_json::Value) -> Option<Usage> { |
| 1040 | const TOKEN_FIELDS: &[&str] = &[ |
| 1041 | "child_input_tokens", |
| 1042 | "child_output_tokens", |
| 1043 | "child_prompt_cache_hit_tokens", |
| 1044 | "child_prompt_cache_miss_tokens", |
| 1045 | "child_prompt_cache_write_tokens", |
| 1046 | "child_reasoning_tokens", |
| 1047 | "child_reasoning_replay_tokens", |
| 1048 | "child_input_audio_tokens", |
| 1049 | "child_output_audio_tokens", |
| 1050 | "child_request_usages", |
| 1051 | ]; |
| 1052 | if !TOKEN_FIELDS |
| 1053 | .iter() |
| 1054 | .any(|field| metadata.get(field).is_some()) |
| 1055 | { |
| 1056 | return None; |
| 1057 | } |
| 1058 | |
| 1059 | fn u32_field(metadata: &serde_json::Value, field: &str) -> Option<u32> { |
| 1060 | metadata |
| 1061 | .get(field) |
| 1062 | .and_then(serde_json::Value::as_u64) |
| 1063 | .map(|value| u32::try_from(value).unwrap_or(u32::MAX)) |
| 1064 | } |
| 1065 | |
| 1066 | let invalid_requests = || vec![Usage::default(); 1025]; |
| 1067 | let token_value = |value: &serde_json::Value| { |
| 1068 | value.is_null() |
| 1069 | || value |
| 1070 | .as_u64() |
| 1071 | .is_some_and(|value| u32::try_from(value).is_ok()) |
| 1072 | }; |
| 1073 | let flat_request = |request: &serde_json::Value| { |
| 1074 | request.as_object().is_some_and(|fields| { |
| 1075 | ["input_tokens", "output_tokens"].iter().all(|field| { |
| 1076 | fields |
| 1077 | .get(*field) |
| 1078 | .is_some_and(|value| value.as_u64().is_some()) |
| 1079 | }) && fields.iter().all(|(key, value)| match key.as_str() { |
| 1080 | "input_tokens" |
| 1081 | | "output_tokens" |
| 1082 | | "prompt_cache_hit_tokens" |
| 1083 | | "prompt_cache_miss_tokens" |
| 1084 | | "prompt_cache_write_tokens" |
| 1085 | | "reasoning_tokens" |
| 1086 | | "reasoning_replay_tokens" |
| 1087 | | "input_audio_tokens" |
| 1088 | | "output_audio_tokens" |
| 1089 | | "safety_tokens" => token_value(value), |
| 1090 | "request_usages" => value.as_array().is_some_and(|nested| nested.is_empty()), |
| 1091 | "server_tool_use" => { |
| 1092 | value.is_null() |
| 1093 | || value.as_object().is_some_and(|tools| { |
| 1094 | tools.iter().all(|(key, value)| { |
| 1095 | matches!( |
| 1096 | key.as_str(), |
| 1097 | "code_execution_requests" |
| 1098 | | "tool_search_requests" |
| 1099 | | "web_search_requests" |
| 1100 | | "web_fetch_requests" |
| 1101 | | "tool_search" |
| 1102 | | "tool_fetch" |
| 1103 | | "tool_image_search" |
| 1104 | ) && token_value(value) |
| 1105 | }) |
| 1106 | }) |
| 1107 | } |
| 1108 | _ => false, |
| 1109 | }) |
| 1110 | }) |
| 1111 | }; |
| 1112 | let request_usages = match metadata.get("child_request_usages") { |
| 1113 | None => Vec::new(), |
| 1114 | Some(serde_json::Value::Array(requests)) |
| 1115 | if requests.len() <= 1024 && requests.iter().all(flat_request) => |
| 1116 | { |
| 1117 | serde_json::from_value(serde_json::Value::Array(requests.clone())) |
| 1118 | .unwrap_or_else(|_| invalid_requests()) |
| 1119 | } |
| 1120 | Some(_) => invalid_requests(), |
| 1121 | }; |
| 1122 | Some(Usage { |
| 1123 | input_tokens: u32_field(metadata, "child_input_tokens").unwrap_or(0), |
| 1124 | output_tokens: u32_field(metadata, "child_output_tokens").unwrap_or(0), |
| 1125 | prompt_cache_hit_tokens: u32_field(metadata, "child_prompt_cache_hit_tokens"), |
| 1126 | prompt_cache_miss_tokens: u32_field(metadata, "child_prompt_cache_miss_tokens"), |
| 1127 | prompt_cache_write_tokens: u32_field(metadata, "child_prompt_cache_write_tokens"), |
| 1128 | reasoning_tokens: u32_field(metadata, "child_reasoning_tokens"), |
| 1129 | reasoning_replay_tokens: u32_field(metadata, "child_reasoning_replay_tokens"), |
| 1130 | server_tool_use: metadata |
| 1131 | .get("child_server_tool_use") |
| 1132 | .cloned() |
| 1133 | .and_then(|value| serde_json::from_value(value).ok()), |
| 1134 | |
| 1135 | input_audio_tokens: u32_field(metadata, "child_input_audio_tokens"), |
| 1136 | output_audio_tokens: u32_field(metadata, "child_output_audio_tokens"), |
| 1137 | safety_tokens: u32_field(metadata, "child_safety_tokens"), |
| 1138 | request_usages, |
| 1139 | }) |
| 1140 | } |
| 1141 | |
| 1142 | impl PendingBackgroundCost { |
| 1143 | /// Whether anything at all was accrued. |
| 1144 | /// |
| 1145 | /// Compared against `Default` rather than checking a subset of fields, so a |
| 1146 | /// field added later cannot be silently left out of the emptiness test. |
| 1147 | #[must_use] |
| 1148 | pub fn is_empty(&self) -> bool { |
| 1149 | *self == Self::default() |
| 1150 | } |
| 1151 | } |
| 1152 | |
| 1153 | #[derive(Default)] |
| 1154 | struct ScopedPendingBackgroundCost { |
| 1155 | generation: u64, |
| 1156 | pending: PendingBackgroundCost, |
| 1157 | seen_usage_source_fingerprints: OrderedFingerprintSet, |
| 1158 | retired_usage_sources: OrderedFingerprintSet, |
| 1159 | pinned_usage_source_fingerprints: HashSet<String>, |
| 1160 | source_records: BTreeMap<String, RuntimeUsageRecord>, |
| 1161 | } |
| 1162 | |
| 1163 | impl ScopedPendingBackgroundCost { |
| 1164 | fn compact_fingerprints(&mut self) { |
| 1165 | let source_records = &self.source_records; |
| 1166 | let pinned = &self.pinned_usage_source_fingerprints; |
| 1167 | self.seen_usage_source_fingerprints |
| 1168 | .compact_keeping_pinned(MAX_USAGE_SOURCE_FINGERPRINTS, |fp| { |
| 1169 | source_records.contains_key(fp) || pinned.contains(fp) |
| 1170 | }); |
| 1171 | self.retired_usage_sources |
| 1172 | .compact_keeping_pinned(MAX_USAGE_SOURCE_FINGERPRINTS, |fp| pinned.contains(fp)); |
| 1173 | } |
| 1174 | } |
| 1175 | |
| 1176 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1177 | pub struct CostScopeToken(u64); |
| 1178 | |
| 1179 | pub type RuntimeDecisionSink = Arc<dyn Fn(RuntimeDecisionReceipt) -> bool + Send + Sync>; |
| 1180 | pub type RuntimeUsageSink = Arc<dyn Fn(RuntimeUsageRecord) -> bool + Send + Sync>; |
| 1181 | pub type RuntimeDropSink = Arc<dyn Fn(RuntimeUsageDropRecord) -> bool + Send + Sync>; |
| 1182 | |
| 1183 | #[derive(Clone)] |
| 1184 | pub struct NativeUsageOrigin { |
| 1185 | scope: CostScopeToken, |
| 1186 | #[cfg(any(test, feature = "test-support"))] |
| 1187 | test_origin: std::thread::ThreadId, |
| 1188 | destination: NativeUsageDestination, |
| 1189 | } |
| 1190 | |
| 1191 | #[derive(Clone)] |
| 1192 | enum NativeUsageDestination { |
| 1193 | Session { |
| 1194 | sessions_dir: std::path::PathBuf, |
| 1195 | session_id: String, |
| 1196 | operation_id: String, |
| 1197 | }, |
| 1198 | Runtime { |
| 1199 | owner: String, |
| 1200 | sink: RuntimeUsageSink, |
| 1201 | drop_sink: Option<RuntimeDropSink>, |
| 1202 | decision_sink: Option<RuntimeDecisionSink>, |
| 1203 | }, |
| 1204 | } |
| 1205 | |
| 1206 | impl std::fmt::Debug for NativeUsageOrigin { |
| 1207 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1208 | formatter |
| 1209 | .debug_struct("NativeUsageOrigin") |
| 1210 | .field("scope", &self.scope) |
| 1211 | .finish_non_exhaustive() |
| 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | static WARNED_USAGE_PERSISTENCE_FAILURES: OnceLock<Mutex<HashSet<String>>> = OnceLock::new(); |
| 1216 | |
| 1217 | fn should_warn_usage_persistence_failure(session_id: &str, error: &std::io::Error) -> bool { |
| 1218 | let mut warned = WARNED_USAGE_PERSISTENCE_FAILURES |
| 1219 | .get_or_init(|| Mutex::new(HashSet::new())) |
| 1220 | .lock() |
| 1221 | .unwrap_or_else(|e| e.into_inner()); |
| 1222 | if warned.len() >= 256 { |
| 1223 | warned.clear(); |
| 1224 | } |
| 1225 | warned.insert(format!("{session_id}:{:?}", error.kind())) |
| 1226 | } |
| 1227 | |
| 1228 | impl NativeUsageOrigin { |
| 1229 | pub(crate) fn session_id(&self) -> Option<&str> { |
| 1230 | match &self.destination { |
| 1231 | NativeUsageDestination::Session { session_id, .. } => Some(session_id), |
| 1232 | NativeUsageDestination::Runtime { .. } => None, |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | pub(crate) fn scope(&self) -> CostScopeToken { |
| 1237 | self.scope |
| 1238 | } |
| 1239 | |
| 1240 | pub(crate) fn session( |
| 1241 | scope: CostScopeToken, |
| 1242 | sessions_dir: std::path::PathBuf, |
| 1243 | session_id: String, |
| 1244 | ) -> Self { |
| 1245 | Self { |
| 1246 | scope, |
| 1247 | #[cfg(any(test, feature = "test-support"))] |
| 1248 | test_origin: test_cost_scope_id(), |
| 1249 | destination: NativeUsageDestination::Session { |
| 1250 | sessions_dir, |
| 1251 | session_id, |
| 1252 | operation_id: uuid::Uuid::new_v4().to_string(), |
| 1253 | }, |
| 1254 | } |
| 1255 | } |
| 1256 | |
| 1257 | pub(crate) fn captured_runtime( |
| 1258 | scope: CostScopeToken, |
| 1259 | owner: String, |
| 1260 | sink: RuntimeUsageSink, |
| 1261 | ) -> Self { |
| 1262 | Self::captured_runtime_with_sinks(scope, owner, sink, None, None) |
| 1263 | } |
| 1264 | |
| 1265 | pub(crate) fn captured_runtime_with_sinks( |
| 1266 | scope: CostScopeToken, |
| 1267 | owner: String, |
| 1268 | sink: RuntimeUsageSink, |
| 1269 | drop_sink: Option<RuntimeDropSink>, |
| 1270 | decision_sink: Option<RuntimeDecisionSink>, |
| 1271 | ) -> Self { |
| 1272 | Self { |
| 1273 | scope, |
| 1274 | #[cfg(any(test, feature = "test-support"))] |
| 1275 | test_origin: test_cost_scope_id(), |
| 1276 | destination: NativeUsageDestination::Runtime { |
| 1277 | owner, |
| 1278 | sink, |
| 1279 | drop_sink, |
| 1280 | decision_sink, |
| 1281 | }, |
| 1282 | } |
| 1283 | } |
| 1284 | |
| 1285 | pub(crate) fn publish(&self, record: &RuntimeUsageRecord) { |
| 1286 | #[cfg(any(test, feature = "test-support"))] |
| 1287 | let _origin = bind_test_cost_scope(self.test_origin); |
| 1288 | match &self.destination { |
| 1289 | NativeUsageDestination::Session { |
| 1290 | sessions_dir, |
| 1291 | session_id, |
| 1292 | operation_id, |
| 1293 | } => { |
| 1294 | if let Err(error) = crate::session_manager::SessionManager::new( |
| 1295 | sessions_dir.clone(), |
| 1296 | ) |
| 1297 | .and_then(|manager| { |
| 1298 | crate::usage_persistence::report_runtime_usage_record_for_origin_with_manager( |
| 1299 | self.scope, |
| 1300 | session_id, |
| 1301 | operation_id, |
| 1302 | record, |
| 1303 | &manager, |
| 1304 | ) |
| 1305 | }) { |
| 1306 | if should_warn_usage_persistence_failure(session_id, &error) { |
| 1307 | tracing::warn!(%error, session_id = %session_id, "usage persistence failed; continuing with unknown cost"); |
| 1308 | } else { |
| 1309 | tracing::debug!(%error, session_id = %session_id, "usage persistence failed again; continuing with unknown cost"); |
| 1310 | } |
| 1311 | } |
| 1312 | } |
| 1313 | NativeUsageDestination::Runtime { owner, sink, .. } => { |
| 1314 | if !sink(record.clone()) { |
| 1315 | tracing::warn!( |
| 1316 | owner = %owner, |
| 1317 | "captured usage receipt was not persisted; continuing" |
| 1318 | ); |
| 1319 | } |
| 1320 | } |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | pub(crate) fn publish_drop(&self, record: &RuntimeUsageDropRecord) { |
| 1325 | #[cfg(any(test, feature = "test-support"))] |
| 1326 | let _origin = bind_test_cost_scope(self.test_origin); |
| 1327 | match &self.destination { |
| 1328 | NativeUsageDestination::Session { |
| 1329 | sessions_dir, |
| 1330 | session_id, |
| 1331 | operation_id, |
| 1332 | } => { |
| 1333 | let ok = crate::session_manager::SessionManager::new(sessions_dir.clone()) |
| 1334 | .is_ok_and(|manager| { |
| 1335 | crate::usage_persistence::report_missing_usage_for_interactive_origin_with_manager( |
| 1336 | self.scope, |
| 1337 | session_id, |
| 1338 | operation_id, |
| 1339 | &record.source_id, |
| 1340 | &record.route, |
| 1341 | record.reason, |
| 1342 | &manager, |
| 1343 | ) |
| 1344 | }); |
| 1345 | if !ok { |
| 1346 | tracing::warn!(session_id = %session_id, "missing-usage receipt was not persisted; continuing"); |
| 1347 | } |
| 1348 | } |
| 1349 | NativeUsageDestination::Runtime { |
| 1350 | owner, |
| 1351 | sink, |
| 1352 | drop_sink, |
| 1353 | .. |
| 1354 | } => { |
| 1355 | let ok = if let Some(drop_sink) = drop_sink { |
| 1356 | drop_sink(record.clone()) |
| 1357 | } else { |
| 1358 | sink(record.as_usage_record()) |
| 1359 | }; |
| 1360 | if !ok { |
| 1361 | tracing::warn!(owner = %owner, "runtime drop receipt was not persisted; continuing"); |
| 1362 | } |
| 1363 | } |
| 1364 | } |
| 1365 | } |
| 1366 | |
| 1367 | pub(crate) fn publish_decision(&self, receipt: &RuntimeDecisionReceipt) { |
| 1368 | #[cfg(any(test, feature = "test-support"))] |
| 1369 | let _origin = bind_test_cost_scope(self.test_origin); |
| 1370 | match &self.destination { |
| 1371 | NativeUsageDestination::Session { |
| 1372 | sessions_dir, |
| 1373 | session_id, |
| 1374 | operation_id, |
| 1375 | } => { |
| 1376 | if let Ok(manager) = |
| 1377 | crate::session_manager::SessionManager::new(sessions_dir.clone()) |
| 1378 | && manager |
| 1379 | .persist_late_decision_receipt(session_id, operation_id, receipt) |
| 1380 | .unwrap_or(false) |
| 1381 | { |
| 1382 | let _ = manager.with_live_session_origin(session_id, || { |
| 1383 | report_interactive_decision(self.scope, receipt); |
| 1384 | true |
| 1385 | }); |
| 1386 | } |
| 1387 | } |
| 1388 | NativeUsageDestination::Runtime { |
| 1389 | owner, |
| 1390 | decision_sink, |
| 1391 | .. |
| 1392 | } => { |
| 1393 | if let Some(decision_sink) = decision_sink |
| 1394 | && !decision_sink(receipt.clone()) |
| 1395 | { |
| 1396 | tracing::warn!(owner = %owner, "runtime decision receipt was not persisted; continuing"); |
| 1397 | } |
| 1398 | } |
| 1399 | } |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | #[cfg(not(any(test, feature = "test-support")))] |
| 1404 | static PENDING: OnceLock<Mutex<ScopedPendingBackgroundCost>> = OnceLock::new(); |
| 1405 | |
| 1406 | #[cfg(any(test, feature = "test-support"))] |
| 1407 | static TEST_PENDING: OnceLock< |
| 1408 | Mutex<std::collections::HashMap<std::thread::ThreadId, ScopedPendingBackgroundCost>>, |
| 1409 | > = OnceLock::new(); |
| 1410 | |
| 1411 | fn with_pending_state_mut<R>(f: impl FnOnce(&mut ScopedPendingBackgroundCost) -> R) -> R { |
| 1412 | #[cfg(not(any(test, feature = "test-support")))] |
| 1413 | { |
| 1414 | let mut pending = PENDING |
| 1415 | .get_or_init(|| Mutex::new(ScopedPendingBackgroundCost::default())) |
| 1416 | .lock() |
| 1417 | .unwrap_or_else(|e| e.into_inner()); |
| 1418 | f(&mut pending) |
| 1419 | } |
| 1420 | #[cfg(any(test, feature = "test-support"))] |
| 1421 | { |
| 1422 | let mut by_thread = TEST_PENDING |
| 1423 | .get_or_init(|| Mutex::new(std::collections::HashMap::new())) |
| 1424 | .lock() |
| 1425 | .unwrap_or_else(|e| e.into_inner()); |
| 1426 | f(by_thread.entry(test_cost_scope_id()).or_default()) |
| 1427 | } |
| 1428 | } |
| 1429 | |
| 1430 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 1431 | pub struct RuntimeUsageBatch { |
| 1432 | pub decisions: Vec<RuntimeDecisionReceipt>, |
| 1433 | pub records: Vec<RuntimeUsageRecord>, |
| 1434 | pub drop_records: Vec<RuntimeUsageDropRecord>, |
| 1435 | pub dropped_records: u64, |
| 1436 | } |
| 1437 | |
| 1438 | #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] |
| 1439 | pub struct RuntimeUsageRecord { |
| 1440 | pub source_id: String, |
| 1441 | pub usage: EffectiveRouteUsage, |
| 1442 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1443 | pub settlement: Option<UsageSourceRevision>, |
| 1444 | } |
| 1445 | |
| 1446 | impl PartialEq for RuntimeUsageRecord { |
| 1447 | fn eq(&self, other: &Self) -> bool { |
| 1448 | usage_source_fingerprint(&self.source_id) == usage_source_fingerprint(&other.source_id) |
| 1449 | && self.usage == other.usage |
| 1450 | && self.settlement == other.settlement |
| 1451 | } |
| 1452 | } |
| 1453 | impl Eq for RuntimeUsageRecord {} |
| 1454 | |
| 1455 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 1456 | #[serde(rename_all = "snake_case")] |
| 1457 | pub enum UsageSpendOwner { |
| 1458 | Primary, |
| 1459 | Auxiliary, |
| 1460 | } |
| 1461 | |
| 1462 | fn normalized_usage_missing_reason( |
| 1463 | coverage: crate::llm_client::ProviderUsageCoverage, |
| 1464 | reason: Option<RuntimeUsageMissingReason>, |
| 1465 | ) -> Option<RuntimeUsageMissingReason> { |
| 1466 | match coverage { |
| 1467 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1468 | | crate::llm_client::ProviderUsageCoverage::Incomplete => Some(reason.unwrap_or_default()), |
| 1469 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1470 | | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 1471 | | crate::llm_client::ProviderUsageCoverage::Rejected => None, |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 1476 | #[serde(from = "UsageSourceRevisionSerde")] |
| 1477 | pub struct UsageSourceRevision { |
| 1478 | lineage: String, |
| 1479 | revision: u64, |
| 1480 | previous_sha256: Option<String>, |
| 1481 | pub owner: UsageSpendOwner, |
| 1482 | pub coverage: crate::llm_client::ProviderUsageCoverage, |
| 1483 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1484 | pub reason: Option<RuntimeUsageMissingReason>, |
| 1485 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1486 | pub physical_requests: Vec<crate::llm_client::OutboundTransmissionObservation>, |
| 1487 | #[serde(default)] |
| 1488 | pub physical_requests_dropped: u64, |
| 1489 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 1490 | reservation: bool, |
| 1491 | } |
| 1492 | |
| 1493 | #[derive(serde::Deserialize)] |
| 1494 | struct UsageSourceRevisionSerde { |
| 1495 | lineage: String, |
| 1496 | revision: u64, |
| 1497 | previous_sha256: Option<String>, |
| 1498 | owner: UsageSpendOwner, |
| 1499 | coverage: crate::llm_client::ProviderUsageCoverage, |
| 1500 | #[serde(default)] |
| 1501 | reason: Option<RuntimeUsageMissingReason>, |
| 1502 | #[serde(default)] |
| 1503 | physical_requests: Vec<crate::llm_client::OutboundTransmissionObservation>, |
| 1504 | #[serde(default)] |
| 1505 | physical_requests_dropped: u64, |
| 1506 | #[serde(default)] |
| 1507 | reservation: bool, |
| 1508 | } |
| 1509 | |
| 1510 | impl From<UsageSourceRevisionSerde> for UsageSourceRevision { |
| 1511 | fn from(raw: UsageSourceRevisionSerde) -> Self { |
| 1512 | let reason = normalized_usage_missing_reason(raw.coverage, raw.reason); |
| 1513 | Self { |
| 1514 | lineage: raw.lineage, |
| 1515 | revision: raw.revision, |
| 1516 | previous_sha256: raw.previous_sha256, |
| 1517 | owner: raw.owner, |
| 1518 | coverage: raw.coverage, |
| 1519 | reason, |
| 1520 | physical_requests: raw.physical_requests, |
| 1521 | physical_requests_dropped: raw.physical_requests_dropped, |
| 1522 | reservation: raw.reservation, |
| 1523 | } |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | impl UsageSourceRevision { |
| 1528 | pub fn lineage(&self) -> &str { |
| 1529 | &self.lineage |
| 1530 | } |
| 1531 | |
| 1532 | pub fn revision(&self) -> u64 { |
| 1533 | self.revision |
| 1534 | } |
| 1535 | |
| 1536 | pub fn is_reservation(&self) -> bool { |
| 1537 | self.reservation |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | #[derive(Debug, Clone)] |
| 1542 | pub struct NativeUsageSource { |
| 1543 | source_id: String, |
| 1544 | lineage: String, |
| 1545 | owner: UsageSpendOwner, |
| 1546 | origin: Option<NativeUsageOrigin>, |
| 1547 | wire: crate::llm_client::OutboundWireObservations, |
| 1548 | last_record: Arc<Mutex<Option<RuntimeUsageRecord>>>, |
| 1549 | } |
| 1550 | |
| 1551 | impl NativeUsageSource { |
| 1552 | pub fn capture(source_id: impl Into<String>, owner: UsageSpendOwner) -> Self { |
| 1553 | Self::capture_with_origin(source_id, owner, None) |
| 1554 | } |
| 1555 | |
| 1556 | pub fn capture_with_origin( |
| 1557 | source_id: impl Into<String>, |
| 1558 | owner: UsageSpendOwner, |
| 1559 | origin: Option<NativeUsageOrigin>, |
| 1560 | ) -> Self { |
| 1561 | let source_id = source_id.into(); |
| 1562 | let source_id = if source_id.trim().is_empty() { |
| 1563 | uuid::Uuid::new_v4().to_string() |
| 1564 | } else { |
| 1565 | source_id |
| 1566 | }; |
| 1567 | let wire = crate::llm_client::OutboundWireObservations::default(); |
| 1568 | Self { |
| 1569 | source_id, |
| 1570 | lineage: uuid::Uuid::new_v4().to_string(), |
| 1571 | owner, |
| 1572 | origin, |
| 1573 | wire, |
| 1574 | last_record: Arc::new(Mutex::new(None)), |
| 1575 | } |
| 1576 | } |
| 1577 | |
| 1578 | pub fn origin(&self) -> Option<&NativeUsageOrigin> { |
| 1579 | self.origin.as_ref() |
| 1580 | } |
| 1581 | |
| 1582 | pub fn observation(&self) -> crate::llm_client::RequestRetryObservation { |
| 1583 | let mut obs = |
| 1584 | crate::llm_client::RequestRetryObservation::for_auxiliary_request(self.source_id()); |
| 1585 | obs.wire_observations = self.wire.clone(); |
| 1586 | obs |
| 1587 | } |
| 1588 | |
| 1589 | pub(crate) fn observed_wire(&self) -> crate::llm_client::OutboundWireObservationBatch { |
| 1590 | self.wire.snapshot() |
| 1591 | } |
| 1592 | |
| 1593 | pub fn source_id(&self) -> String { |
| 1594 | self.source_id.clone() |
| 1595 | } |
| 1596 | |
| 1597 | pub fn prepare_record( |
| 1598 | &self, |
| 1599 | route: &EffectiveRouteEnvelope, |
| 1600 | usage: &Usage, |
| 1601 | coverage: crate::llm_client::ProviderUsageCoverage, |
| 1602 | reason: RuntimeUsageMissingReason, |
| 1603 | wire: &crate::llm_client::OutboundWireObservationBatch, |
| 1604 | ) -> RuntimeUsageRecord { |
| 1605 | let reason = normalized_usage_missing_reason(coverage, Some(reason)); |
| 1606 | let effective = EffectiveRouteUsage { |
| 1607 | route: route.sanitized_for_persistence(), |
| 1608 | usage: usage.clone(), |
| 1609 | }; |
| 1610 | let dropped_extra = |
| 1611 | u64::try_from(wire.transmissions.len().saturating_sub(32)).unwrap_or(u64::MAX); |
| 1612 | let physical_requests: Vec<_> = wire |
| 1613 | .transmissions |
| 1614 | .iter() |
| 1615 | .take(32) |
| 1616 | .cloned() |
| 1617 | .map(|mut attempt| { |
| 1618 | attempt.source_id = usage_source_fingerprint(&attempt.source_id); |
| 1619 | attempt |
| 1620 | }) |
| 1621 | .collect(); |
| 1622 | let physical_requests_dropped = wire.transmissions_dropped.saturating_add(dropped_extra); |
| 1623 | let mut last = self |
| 1624 | .last_record |
| 1625 | .lock() |
| 1626 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 1627 | let (revision, previous_sha256, lineage) = match last.as_ref() { |
| 1628 | Some(prior) if prior.usage.route == effective.route => { |
| 1629 | if prior.usage == effective |
| 1630 | && prior.settlement.as_ref().is_some_and(|r| { |
| 1631 | r.coverage == coverage |
| 1632 | && r.reason == reason |
| 1633 | && r.physical_requests == physical_requests |
| 1634 | && r.physical_requests_dropped == physical_requests_dropped |
| 1635 | }) |
| 1636 | { |
| 1637 | return prior.clone(); |
| 1638 | } |
| 1639 | let prev_rev = prior.settlement.as_ref().map_or(0, |r| r.revision); |
| 1640 | ( |
| 1641 | prev_rev.saturating_add(1), |
| 1642 | prior.digest().ok(), |
| 1643 | prior |
| 1644 | .settlement |
| 1645 | .as_ref() |
| 1646 | .map_or_else(|| self.lineage.clone(), |r| r.lineage.clone()), |
| 1647 | ) |
| 1648 | } |
| 1649 | _ => (1, None, uuid::Uuid::new_v4().to_string()), |
| 1650 | }; |
| 1651 | let record = RuntimeUsageRecord { |
| 1652 | source_id: self.source_id.clone(), |
| 1653 | usage: effective, |
| 1654 | settlement: Some(UsageSourceRevision { |
| 1655 | lineage, |
| 1656 | revision, |
| 1657 | previous_sha256, |
| 1658 | owner: self.owner, |
| 1659 | coverage, |
| 1660 | reason, |
| 1661 | physical_requests, |
| 1662 | physical_requests_dropped, |
| 1663 | reservation: false, |
| 1664 | }), |
| 1665 | }; |
| 1666 | *last = Some(record.clone()); |
| 1667 | record |
| 1668 | } |
| 1669 | |
| 1670 | pub fn prepare( |
| 1671 | &self, |
| 1672 | route: &EffectiveRouteEnvelope, |
| 1673 | usage: &Usage, |
| 1674 | coverage: crate::llm_client::ProviderUsageCoverage, |
| 1675 | reason: RuntimeUsageMissingReason, |
| 1676 | ) -> RuntimeUsageRecord { |
| 1677 | self.prepare_record( |
| 1678 | route, |
| 1679 | usage, |
| 1680 | coverage, |
| 1681 | reason, |
| 1682 | &crate::llm_client::OutboundWireObservationBatch::default(), |
| 1683 | ) |
| 1684 | } |
| 1685 | |
| 1686 | pub fn response_record( |
| 1687 | &self, |
| 1688 | route: &EffectiveRouteEnvelope, |
| 1689 | response: &anyhow::Result<codewhale_models::MessageResponse>, |
| 1690 | wire: &crate::llm_client::OutboundWireObservationBatch, |
| 1691 | ) -> RuntimeUsageRecord { |
| 1692 | let empty = Usage::default(); |
| 1693 | let usage = response |
| 1694 | .as_ref() |
| 1695 | .map(|response| &response.usage) |
| 1696 | .unwrap_or(&empty); |
| 1697 | let reported = usage != ∅ |
| 1698 | let coverage = if wire.last_transmission.is_some() { |
| 1699 | wire.usage_coverage(reported, response.is_ok()) |
| 1700 | } else { |
| 1701 | match response { |
| 1702 | Ok(_) if reported => crate::llm_client::ProviderUsageCoverage::Reported, |
| 1703 | Ok(_) => crate::llm_client::ProviderUsageCoverage::Missing, |
| 1704 | Err(error) => match error |
| 1705 | .downcast_ref::<crate::llm_client::LlmError>() |
| 1706 | .map(crate::llm_client::LlmError::transmission) |
| 1707 | { |
| 1708 | Some(crate::llm_client::RequestTransmission::NotDispatched) => { |
| 1709 | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 1710 | } |
| 1711 | Some(crate::llm_client::RequestTransmission::Rejected) => { |
| 1712 | crate::llm_client::ProviderUsageCoverage::Rejected |
| 1713 | } |
| 1714 | _ => crate::llm_client::ProviderUsageCoverage::Missing, |
| 1715 | }, |
| 1716 | } |
| 1717 | }; |
| 1718 | self.prepare_record( |
| 1719 | route, |
| 1720 | usage, |
| 1721 | coverage, |
| 1722 | if response.is_ok() { |
| 1723 | RuntimeUsageMissingReason::SuccessWithoutUsage |
| 1724 | } else { |
| 1725 | RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 1726 | }, |
| 1727 | wire, |
| 1728 | ) |
| 1729 | } |
| 1730 | |
| 1731 | pub fn reported(&self, route: &EffectiveRouteEnvelope, usage: &Usage) -> RuntimeUsageRecord { |
| 1732 | self.prepare( |
| 1733 | route, |
| 1734 | usage, |
| 1735 | if usage == &Usage::default() { |
| 1736 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1737 | } else { |
| 1738 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1739 | }, |
| 1740 | RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 1741 | ) |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | impl RuntimeUsageRecord { |
| 1746 | pub fn legacy(source_id: impl Into<String>, usage: EffectiveRouteUsage) -> Self { |
| 1747 | Self { |
| 1748 | source_id: source_id.into(), |
| 1749 | usage, |
| 1750 | settlement: None, |
| 1751 | } |
| 1752 | } |
| 1753 | |
| 1754 | pub fn persisted(&self) -> Self { |
| 1755 | let mut record = self.clone(); |
| 1756 | record.source_id = usage_source_fingerprint(&record.source_id); |
| 1757 | record.usage.route = record.usage.route.sanitized_for_persistence(); |
| 1758 | if let Some(revision) = record.settlement.as_mut() { |
| 1759 | revision.reason = normalized_usage_missing_reason(revision.coverage, revision.reason); |
| 1760 | } |
| 1761 | record |
| 1762 | } |
| 1763 | |
| 1764 | pub fn digest(&self) -> std::io::Result<String> { |
| 1765 | use sha2::Digest as _; |
| 1766 | let bytes = serde_json::to_vec(&self.persisted()).map_err(std::io::Error::other)?; |
| 1767 | Ok(codewhale_runtime::hashing::hex_bytes(sha2::Sha256::digest( |
| 1768 | bytes, |
| 1769 | ))) |
| 1770 | } |
| 1771 | |
| 1772 | pub fn validate(&self) -> std::io::Result<()> { |
| 1773 | if self.source_id.trim().is_empty() { |
| 1774 | return Err(std::io::Error::new( |
| 1775 | std::io::ErrorKind::InvalidData, |
| 1776 | "usage source identity is empty", |
| 1777 | )); |
| 1778 | } |
| 1779 | if let Some(revision) = self.settlement.as_ref() { |
| 1780 | if matches!( |
| 1781 | revision.coverage, |
| 1782 | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 1783 | | crate::llm_client::ProviderUsageCoverage::Rejected |
| 1784 | ) && self.usage.usage != Usage::default() |
| 1785 | { |
| 1786 | return Err(std::io::Error::new( |
| 1787 | std::io::ErrorKind::InvalidData, |
| 1788 | "a refused request cannot claim a token receipt", |
| 1789 | )); |
| 1790 | } |
| 1791 | if revision.physical_requests.len() > 32 |
| 1792 | || uuid::Uuid::parse_str(&revision.lineage).is_err() |
| 1793 | || revision.revision == 0 |
| 1794 | || (revision.revision == 1) != revision.previous_sha256.is_none() |
| 1795 | || revision.previous_sha256.as_ref().is_some_and(|hash| { |
| 1796 | hash.len() != 64 |
| 1797 | || !hash |
| 1798 | .bytes() |
| 1799 | .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) |
| 1800 | }) |
| 1801 | { |
| 1802 | return Err(std::io::Error::new( |
| 1803 | std::io::ErrorKind::InvalidData, |
| 1804 | "invalid usage source revision", |
| 1805 | )); |
| 1806 | } |
| 1807 | } |
| 1808 | Ok(()) |
| 1809 | } |
| 1810 | |
| 1811 | pub fn route_conflicts_with(&self, previous: Option<&Self>) -> bool { |
| 1812 | previous.is_some_and(|old| { |
| 1813 | usage_source_fingerprint(&old.source_id) == usage_source_fingerprint(&self.source_id) |
| 1814 | && old.usage.route != self.usage.route |
| 1815 | }) |
| 1816 | } |
| 1817 | |
| 1818 | pub fn follows_inherited(&self, inherited: &Self) -> bool { |
| 1819 | usage_source_fingerprint(&self.source_id) == usage_source_fingerprint(&inherited.source_id) |
| 1820 | && !self.route_conflicts_with(Some(inherited)) |
| 1821 | && self.settlement.as_ref().map(|r| r.owner) |
| 1822 | == inherited.settlement.as_ref().map(|r| r.owner) |
| 1823 | && self |
| 1824 | .settlement |
| 1825 | .as_ref() |
| 1826 | .map_or(0, UsageSourceRevision::revision) |
| 1827 | >= inherited |
| 1828 | .settlement |
| 1829 | .as_ref() |
| 1830 | .map_or(0, UsageSourceRevision::revision) |
| 1831 | } |
| 1832 | |
| 1833 | pub fn supersedes(&self, previous: Option<&Self>) -> bool { |
| 1834 | if self.source_id.trim().is_empty() { |
| 1835 | return false; |
| 1836 | } |
| 1837 | let Some(old) = previous else { |
| 1838 | return true; |
| 1839 | }; |
| 1840 | if usage_source_fingerprint(&old.source_id) != usage_source_fingerprint(&self.source_id) |
| 1841 | || old == self |
| 1842 | || old.usage.route != self.usage.route |
| 1843 | { |
| 1844 | return false; |
| 1845 | } |
| 1846 | let old_final = old.settlement.as_ref().is_some_and(|r| { |
| 1847 | matches!( |
| 1848 | r.coverage, |
| 1849 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1850 | | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 1851 | | crate::llm_client::ProviderUsageCoverage::Rejected |
| 1852 | ) |
| 1853 | }) || (old.settlement.is_none() && old.usage.usage != Usage::default()); |
| 1854 | if old_final { |
| 1855 | return false; |
| 1856 | } |
| 1857 | if self.usage.usage != Usage::default() { |
| 1858 | return true; |
| 1859 | } |
| 1860 | let old_rev = old.settlement.as_ref().map_or(0, |r| r.revision); |
| 1861 | let new_rev = self.settlement.as_ref().map_or(0, |r| r.revision); |
| 1862 | new_rev > old_rev |
| 1863 | } |
| 1864 | } |
| 1865 | |
| 1866 | #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] |
| 1867 | pub struct UsageSourceContribution { |
| 1868 | pub record: RuntimeUsageRecord, |
| 1869 | pub usd: f64, |
| 1870 | pub cny: f64, |
| 1871 | pub priced: u32, |
| 1872 | pub unpriced: u32, |
| 1873 | pub cny_priced: u32, |
| 1874 | pub cny_unpriced: u32, |
| 1875 | } |
| 1876 | |
| 1877 | impl UsageSourceContribution { |
| 1878 | pub fn for_record(record: &RuntimeUsageRecord) -> Self { |
| 1879 | let audit = record.usage.route.audit_frozen(&record.usage.usage); |
| 1880 | let non_billable = record.settlement.as_ref().is_some_and(|revision| { |
| 1881 | matches!( |
| 1882 | revision.coverage, |
| 1883 | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 1884 | | crate::llm_client::ProviderUsageCoverage::Rejected |
| 1885 | ) |
| 1886 | }); |
| 1887 | let reported = record.settlement.as_ref().map_or_else( |
| 1888 | || record.usage.usage != Usage::default(), |
| 1889 | |revision| { |
| 1890 | matches!( |
| 1891 | revision.coverage, |
| 1892 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1893 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 1894 | ) |
| 1895 | }, |
| 1896 | ); |
| 1897 | let metered = audit |
| 1898 | .unpriced_reason |
| 1899 | .is_none_or(|reason| reason.counts_toward_money_coverage()); |
| 1900 | let incomplete = !non_billable |
| 1901 | && record.settlement.as_ref().is_some_and(|revision| { |
| 1902 | matches!( |
| 1903 | revision.coverage, |
| 1904 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1905 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 1906 | ) |
| 1907 | }); |
| 1908 | let estimate = audit |
| 1909 | .estimate |
| 1910 | .filter(|_| reported && !non_billable) |
| 1911 | .unwrap_or_default() |
| 1912 | .sanitized(); |
| 1913 | Self { |
| 1914 | record: record.persisted(), |
| 1915 | usd: estimate.usd, |
| 1916 | cny: estimate.cny, |
| 1917 | priced: u32::from(reported && !non_billable && audit.usd_priced), |
| 1918 | unpriced: u32::from( |
| 1919 | !non_billable && metered && (!reported || !audit.usd_priced || incomplete), |
| 1920 | ), |
| 1921 | cny_priced: u32::from(reported && !non_billable && audit.cny_priced), |
| 1922 | cny_unpriced: u32::from( |
| 1923 | !non_billable && metered && (!reported || !audit.cny_priced || incomplete), |
| 1924 | ), |
| 1925 | } |
| 1926 | } |
| 1927 | |
| 1928 | pub fn validate(&self) -> std::io::Result<()> { |
| 1929 | self.record.validate()?; |
| 1930 | if !self.usd.is_finite() |
| 1931 | || !self.cny.is_finite() |
| 1932 | || self.usd < 0.0 |
| 1933 | || self.cny < 0.0 |
| 1934 | || *self != Self::for_record(&self.record) |
| 1935 | { |
| 1936 | return Err(std::io::Error::new( |
| 1937 | std::io::ErrorKind::InvalidData, |
| 1938 | "persisted usage contribution does not match its frozen receipt", |
| 1939 | )); |
| 1940 | } |
| 1941 | Ok(()) |
| 1942 | } |
| 1943 | |
| 1944 | pub fn owner(&self) -> UsageSpendOwner { |
| 1945 | self.record |
| 1946 | .settlement |
| 1947 | .as_ref() |
| 1948 | .map_or(UsageSpendOwner::Auxiliary, |revision| revision.owner) |
| 1949 | } |
| 1950 | |
| 1951 | pub fn total_tokens(&self) -> u64 { |
| 1952 | u64::from(self.record.usage.usage.input_tokens) |
| 1953 | .saturating_add(u64::from(self.record.usage.usage.output_tokens)) |
| 1954 | } |
| 1955 | } |
| 1956 | |
| 1957 | /// One provider-success response that omitted usage metadata. |
| 1958 | /// |
| 1959 | /// The frozen route is required to distinguish money-metered calls from |
| 1960 | /// subscription/local calls without consulting mutable completion-time config. |
| 1961 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 1962 | pub struct RuntimeUsageDropRecord { |
| 1963 | #[serde(default, skip_serializing_if = "RuntimeUsageMissingReason::is_success")] |
| 1964 | pub reason: RuntimeUsageMissingReason, |
| 1965 | pub source_id: String, |
| 1966 | pub route: EffectiveRouteEnvelope, |
| 1967 | } |
| 1968 | |
| 1969 | /// Why this dispatched request has no usable usage receipt. Legacy bytes |
| 1970 | /// mean a successful response omitted usage, never an inferred failure charge. |
| 1971 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 1972 | #[serde(rename_all = "snake_case")] |
| 1973 | pub enum RuntimeUsageMissingReason { |
| 1974 | #[default] |
| 1975 | SuccessWithoutUsage, |
| 1976 | RequestOutcomeUnknown, |
| 1977 | } |
| 1978 | impl RuntimeUsageMissingReason { |
| 1979 | pub fn is_success(&self) -> bool { |
| 1980 | *self == Self::SuccessWithoutUsage |
| 1981 | } |
| 1982 | pub fn label(self) -> &'static str { |
| 1983 | match self { |
| 1984 | Self::SuccessWithoutUsage => "provider_success_missing_usage", |
| 1985 | Self::RequestOutcomeUnknown => "request_outcome_unknown", |
| 1986 | } |
| 1987 | } |
| 1988 | } |
| 1989 | impl RuntimeUsageDropRecord { |
| 1990 | pub fn as_usage_record(&self) -> RuntimeUsageRecord { |
| 1991 | RuntimeUsageRecord { |
| 1992 | source_id: self.source_id.clone(), |
| 1993 | usage: EffectiveRouteUsage { |
| 1994 | route: self.route.sanitized_for_persistence(), |
| 1995 | usage: Usage::default(), |
| 1996 | }, |
| 1997 | settlement: Some(UsageSourceRevision { |
| 1998 | lineage: uuid::Uuid::new_v4().to_string(), |
| 1999 | revision: 1, |
| 2000 | previous_sha256: None, |
| 2001 | owner: UsageSpendOwner::Auxiliary, |
| 2002 | coverage: crate::llm_client::ProviderUsageCoverage::Missing, |
| 2003 | reason: Some(self.reason), |
| 2004 | physical_requests: Vec::new(), |
| 2005 | physical_requests_dropped: 0, |
| 2006 | reservation: false, |
| 2007 | }), |
| 2008 | } |
| 2009 | } |
| 2010 | } |
| 2011 | /// Provider decision evidence attached to the existing origin-turn ledger. |
| 2012 | /// It is diagnostic evidence, never an instruction to change the model route. |
| 2013 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 2014 | pub struct RuntimeDecisionReceipt { |
| 2015 | pub source_id: String, |
| 2016 | pub route: EffectiveRouteEnvelope, |
| 2017 | pub usage: Option<Usage>, |
| 2018 | #[serde(default)] |
| 2019 | pub usage_complete: bool, |
| 2020 | pub shadow: bool, |
| 2021 | pub valid_answers: bool, |
| 2022 | pub evidence: codewhale_models::auto_route_evidence::AutoRouteDecisionEvidence, |
| 2023 | } |
| 2024 | |
| 2025 | impl RuntimeDecisionReceipt { |
| 2026 | pub fn is_bounded(&self) -> bool { |
| 2027 | !self.source_id.trim().is_empty() |
| 2028 | && self.source_id.len() <= 128 |
| 2029 | && self.evidence.choice.len() <= 128 |
| 2030 | && self.evidence.probabilities_bp.len() <= 64 |
| 2031 | && self |
| 2032 | .evidence |
| 2033 | .probabilities_bp |
| 2034 | .iter() |
| 2035 | .all(|(key, value)| key.len() <= 128 && *value <= 10_000) |
| 2036 | && self.evidence.confidence_bp <= 10_000 |
| 2037 | && self.evidence.min_confidence_bp <= 10_000 |
| 2038 | && self |
| 2039 | .evidence |
| 2040 | .thinking |
| 2041 | .as_ref() |
| 2042 | .is_none_or(|v| v.len() <= 128) |
| 2043 | && self |
| 2044 | .evidence |
| 2045 | .response_model |
| 2046 | .as_ref() |
| 2047 | .is_none_or(|v| v.len() <= 128) |
| 2048 | && self |
| 2049 | .evidence |
| 2050 | .provider_reported_cost_usd |
| 2051 | .as_ref() |
| 2052 | .is_none_or(|v| { |
| 2053 | v.len() <= 128 |
| 2054 | && v.parse::<f64>() |
| 2055 | .is_ok_and(|cost| cost.is_finite() && cost >= 0.0) |
| 2056 | }) |
| 2057 | && serde_json::to_vec(self).is_ok_and(|bytes| bytes.len() <= 8 * 1024) |
| 2058 | } |
| 2059 | |
| 2060 | pub fn sanitized(&self) -> Self { |
| 2061 | let mut receipt = self.clone(); |
| 2062 | receipt.source_id = usage_source_fingerprint(&receipt.source_id); |
| 2063 | receipt.route = receipt.route.sanitized_for_persistence(); |
| 2064 | receipt.evidence.choice = sanitize_persisted_route_label(&receipt.evidence.choice); |
| 2065 | receipt.evidence.thinking = receipt |
| 2066 | .evidence |
| 2067 | .thinking |
| 2068 | .as_deref() |
| 2069 | .map(sanitize_persisted_route_label); |
| 2070 | receipt.evidence.response_model = receipt |
| 2071 | .evidence |
| 2072 | .response_model |
| 2073 | .as_deref() |
| 2074 | .map(sanitize_persisted_route_label); |
| 2075 | receipt.evidence.probabilities_bp = receipt |
| 2076 | .evidence |
| 2077 | .probabilities_bp |
| 2078 | .into_iter() |
| 2079 | .map(|(key, value)| (sanitize_persisted_route_label(&key), value)) |
| 2080 | .collect(); |
| 2081 | receipt |
| 2082 | } |
| 2083 | |
| 2084 | pub fn diagnostic_receipt(&self) -> String { |
| 2085 | // Reuse cost_status's persisted diagnostic receipt surface. No prompt, |
| 2086 | // response id, URL, auth header or unoffered choice enters this string. |
| 2087 | format!( |
| 2088 | "decision:{}", |
| 2089 | serde_json::to_string(&self.sanitized()).unwrap_or_default() |
| 2090 | ) |
| 2091 | } |
| 2092 | } |
| 2093 | |
| 2094 | pub type RuntimeUsageDropSink = Arc<dyn Fn(RuntimeUsageDropRecord) -> bool + Send + Sync>; |
| 2095 | |
| 2096 | #[cfg(any(test, feature = "test-support"))] |
| 2097 | pub fn decision_receipt_fixture(source_id: &str) -> RuntimeDecisionReceipt { |
| 2098 | let mut route = EffectiveRouteEnvelope::capture( |
| 2099 | None, |
| 2100 | codewhale_config::ProviderKind::Custom, |
| 2101 | "typesafe", |
| 2102 | "jev-latest", |
| 2103 | Some("https://api.typesafe.ai/v1"), |
| 2104 | Utc::now(), |
| 2105 | ); |
| 2106 | route.billing_mode = RouteBillingMode::Unknown; |
| 2107 | RuntimeDecisionReceipt { |
| 2108 | source_id: source_id.to_string(), |
| 2109 | route, |
| 2110 | usage: Some(Usage { |
| 2111 | input_tokens: 9, |
| 2112 | output_tokens: 4, |
| 2113 | ..Default::default() |
| 2114 | }), |
| 2115 | usage_complete: true, |
| 2116 | shadow: true, |
| 2117 | valid_answers: false, |
| 2118 | evidence: codewhale_models::auto_route_evidence::AutoRouteDecisionEvidence { |
| 2119 | choice: "invalid".to_string(), |
| 2120 | probabilities_bp: Default::default(), |
| 2121 | confidence_bp: 0, |
| 2122 | min_confidence_bp: 5_000, |
| 2123 | abstained_questions: Vec::new(), |
| 2124 | cost_saving_kept_fast: false, |
| 2125 | thinking: None, |
| 2126 | provider_reported_cost_usd: Some("0.000012054".to_string()), |
| 2127 | latency_ms: 12, |
| 2128 | response_model: Some("jev-latest".to_string()), |
| 2129 | }, |
| 2130 | } |
| 2131 | } |
| 2132 | |
| 2133 | const MAX_RUNTIME_USAGE_RECORDS_PER_OWNER: usize = 256; |
| 2134 | |
| 2135 | pub fn report_interactive_decision(scope: CostScopeToken, receipt: &RuntimeDecisionReceipt) { |
| 2136 | if !receipt.is_bounded() { |
| 2137 | return; |
| 2138 | } |
| 2139 | with_pending_state_mut(|state| { |
| 2140 | if state.generation == scope.0 { |
| 2141 | if state |
| 2142 | .pending |
| 2143 | .route_receipts |
| 2144 | .iter() |
| 2145 | .filter(|v| v.starts_with("decision:")) |
| 2146 | .count() |
| 2147 | < MAX_RUNTIME_USAGE_RECORDS_PER_OWNER |
| 2148 | { |
| 2149 | state |
| 2150 | .pending |
| 2151 | .route_receipts |
| 2152 | .insert(receipt.diagnostic_receipt()); |
| 2153 | } else { |
| 2154 | state |
| 2155 | .pending |
| 2156 | .route_receipts |
| 2157 | .insert("decision:diagnostic_receipt_bound_reached".to_string()); |
| 2158 | } |
| 2159 | } |
| 2160 | }); |
| 2161 | } |
| 2162 | |
| 2163 | #[must_use] |
| 2164 | pub fn usage_source_fingerprint(source_id: &str) -> String { |
| 2165 | let source_id = source_id.trim(); |
| 2166 | let fingerprint = source_id.strip_prefix("routed:").unwrap_or(source_id); |
| 2167 | if fingerprint.len() == 64 && fingerprint.bytes().all(|byte| byte.is_ascii_hexdigit()) { |
| 2168 | return fingerprint.to_ascii_lowercase(); |
| 2169 | } |
| 2170 | codewhale_config::catalog::base_url_fingerprint(source_id) |
| 2171 | } |
| 2172 | |
| 2173 | #[cfg(any(test, feature = "test-support"))] |
| 2174 | thread_local! { |
| 2175 | static TEST_COST_ORIGIN: std::cell::Cell<Option<std::thread::ThreadId>> = const { std::cell::Cell::new(None) }; |
| 2176 | } |
| 2177 | |
| 2178 | #[cfg(any(test, feature = "test-support"))] |
| 2179 | pub fn test_cost_scope_id() -> std::thread::ThreadId { |
| 2180 | TEST_COST_ORIGIN |
| 2181 | .with(|scope| scope.get()) |
| 2182 | .unwrap_or_else(|| std::thread::current().id()) |
| 2183 | } |
| 2184 | |
| 2185 | #[cfg(any(test, feature = "test-support"))] |
| 2186 | pub struct TestCostScopeBinding(Option<std::thread::ThreadId>); |
| 2187 | |
| 2188 | #[cfg(any(test, feature = "test-support"))] |
| 2189 | pub fn bind_test_cost_scope(origin: std::thread::ThreadId) -> TestCostScopeBinding { |
| 2190 | TestCostScopeBinding(TEST_COST_ORIGIN.with(|scope| scope.replace(Some(origin)))) |
| 2191 | } |
| 2192 | |
| 2193 | #[cfg(any(test, feature = "test-support"))] |
| 2194 | impl Drop for TestCostScopeBinding { |
| 2195 | fn drop(&mut self) { |
| 2196 | TEST_COST_ORIGIN.with(|scope| scope.set(self.0)); |
| 2197 | } |
| 2198 | } |
| 2199 | |
| 2200 | /// Capture the current session/run generation before starting a background |
| 2201 | /// provider request. The same token must be supplied when its usage returns. |
| 2202 | #[must_use] |
| 2203 | pub fn scope_token() -> CostScopeToken { |
| 2204 | with_pending_state_mut(|state| CostScopeToken(state.generation)) |
| 2205 | } |
| 2206 | |
| 2207 | pub fn close_current_scope() -> PendingBackgroundCost { |
| 2208 | with_pending_state_mut(|state| { |
| 2209 | let pending = std::mem::take(&mut state.pending); |
| 2210 | state.generation = state.generation.wrapping_add(1); |
| 2211 | state.seen_usage_source_fingerprints.clear(); |
| 2212 | state.retired_usage_sources.clear(); |
| 2213 | state.pinned_usage_source_fingerprints.clear(); |
| 2214 | state.source_records.clear(); |
| 2215 | pending |
| 2216 | }) |
| 2217 | } |
| 2218 | |
| 2219 | pub fn restore_usage_source_fingerprints(fingerprints: impl IntoIterator<Item = String>) { |
| 2220 | with_pending_state_mut(|state| { |
| 2221 | state.seen_usage_source_fingerprints = fingerprints.into_iter().collect(); |
| 2222 | state.retired_usage_sources.clear(); |
| 2223 | state.pinned_usage_source_fingerprints.clear(); |
| 2224 | state.compact_fingerprints(); |
| 2225 | }) |
| 2226 | } |
| 2227 | |
| 2228 | pub fn restore_accounted_usage_sources( |
| 2229 | sources: &BTreeMap<String, UsageSourceContribution>, |
| 2230 | fingerprints: &OrderedFingerprintSet, |
| 2231 | ) { |
| 2232 | restore_accounted_usage_sources_with_pins(sources, fingerprints, &HashSet::new()); |
| 2233 | } |
| 2234 | |
| 2235 | pub fn restore_accounted_usage_sources_with_pins( |
| 2236 | sources: &BTreeMap<String, UsageSourceContribution>, |
| 2237 | fingerprints: &OrderedFingerprintSet, |
| 2238 | pinned: &HashSet<String>, |
| 2239 | ) { |
| 2240 | with_pending_state_mut(|state| { |
| 2241 | state.source_records = sources |
| 2242 | .iter() |
| 2243 | .map(|(key, value)| (key.clone(), value.record.persisted())) |
| 2244 | .collect(); |
| 2245 | state.seen_usage_source_fingerprints = fingerprints.clone(); |
| 2246 | state.retired_usage_sources.clear(); |
| 2247 | state.pinned_usage_source_fingerprints = pinned.clone(); |
| 2248 | state.compact_fingerprints(); |
| 2249 | }); |
| 2250 | } |
| 2251 | |
| 2252 | pub fn pin_usage_source_fingerprint(scope: CostScopeToken, source_id: &str) { |
| 2253 | with_pending_state_mut(|state| { |
| 2254 | if state.generation == scope.0 { |
| 2255 | let fingerprint = usage_source_fingerprint(source_id); |
| 2256 | if state |
| 2257 | .pending |
| 2258 | .usage_source_fingerprints |
| 2259 | .contains(&fingerprint) |
| 2260 | { |
| 2261 | state |
| 2262 | .pending |
| 2263 | .pinned_usage_source_fingerprints |
| 2264 | .insert(fingerprint.clone()); |
| 2265 | } |
| 2266 | state.pinned_usage_source_fingerprints.insert(fingerprint); |
| 2267 | } |
| 2268 | }); |
| 2269 | } |
| 2270 | |
| 2271 | pub fn mark_retired_usage_source(scope: CostScopeToken, source_id: &str) { |
| 2272 | with_pending_state_mut(|state| { |
| 2273 | if state.generation == scope.0 { |
| 2274 | let fingerprint = usage_source_fingerprint(source_id); |
| 2275 | state |
| 2276 | .seen_usage_source_fingerprints |
| 2277 | .insert(fingerprint.clone()); |
| 2278 | state.retired_usage_sources.insert(fingerprint); |
| 2279 | state.compact_fingerprints(); |
| 2280 | } |
| 2281 | }); |
| 2282 | } |
| 2283 | |
| 2284 | #[must_use] |
| 2285 | pub fn is_usage_source_retired(scope: CostScopeToken, source_id: &str) -> bool { |
| 2286 | let fingerprint = usage_source_fingerprint(source_id); |
| 2287 | with_pending_state_mut(|state| { |
| 2288 | state.generation == scope.0 && state.retired_usage_sources.contains(&fingerprint) |
| 2289 | }) |
| 2290 | } |
| 2291 | |
| 2292 | #[must_use] |
| 2293 | pub fn usage_source_seen(source_id: &str) -> bool { |
| 2294 | let fingerprint = usage_source_fingerprint(source_id); |
| 2295 | with_pending_state_mut(|state| { |
| 2296 | state.seen_usage_source_fingerprints.contains(&fingerprint) |
| 2297 | || state.source_records.contains_key(&fingerprint) |
| 2298 | }) |
| 2299 | } |
| 2300 | |
| 2301 | /// The non-secret identity of a background LLM call's route. |
| 2302 | /// |
| 2303 | /// Background helpers run off a bare client with no app `Config`, so they cannot |
| 2304 | /// resolve credential-derived billing. They *can* report what they actually know |
| 2305 | /// — which provider, which configured route, which wire model, which endpoint — |
| 2306 | /// and this type carries exactly that, so the pricing decision is made from |
| 2307 | /// evidence instead of from a provider name. |
| 2308 | #[derive(Debug, Clone, Copy)] |
| 2309 | #[cfg(any(test, feature = "test-support"))] |
| 2310 | pub struct BackgroundRoute<'a> { |
| 2311 | /// Provider kind serving the call. |
| 2312 | pub provider: ProviderKind, |
| 2313 | /// Configured route identity (the `[providers.<name>]` key), when the |
| 2314 | /// caller has one. This is a user-chosen label, not a credential. |
| 2315 | pub provider_identity: Option<&'a str>, |
| 2316 | /// Wire model id as sent on the request. |
| 2317 | pub wire_model: &'a str, |
| 2318 | /// Concrete base URL the request went to, when the client exposes one. |
| 2319 | /// |
| 2320 | /// Only ever used to derive a billing-surface classification and a |
| 2321 | /// SHA-256 fingerprint; the URL itself never leaves this struct. |
| 2322 | pub base_url: Option<&'a str>, |
| 2323 | } |
| 2324 | |
| 2325 | #[cfg(any(test, feature = "test-support"))] |
| 2326 | impl<'a> BackgroundRoute<'a> { |
| 2327 | /// A route with no endpoint information. |
| 2328 | #[must_use] |
| 2329 | pub fn new(provider: ProviderKind, wire_model: &'a str) -> Self { |
| 2330 | Self { |
| 2331 | provider, |
| 2332 | provider_identity: None, |
| 2333 | wire_model, |
| 2334 | base_url: None, |
| 2335 | } |
| 2336 | } |
| 2337 | |
| 2338 | #[must_use] |
| 2339 | pub fn with_base_url(mut self, base_url: Option<&'a str>) -> Self { |
| 2340 | self.base_url = base_url; |
| 2341 | self |
| 2342 | } |
| 2343 | |
| 2344 | /// Non-secret billing-surface classification for this endpoint. |
| 2345 | #[must_use] |
| 2346 | pub fn billing_surface(&self) -> Option<&'static str> { |
| 2347 | crate::pricing::billing_surface_for_route(self.provider, self.base_url) |
| 2348 | } |
| 2349 | |
| 2350 | /// SHA-256 fingerprint of the normalized base URL, or `None` when unknown. |
| 2351 | /// |
| 2352 | /// This is the same digest the catalog scopes live rows on, so a live |
| 2353 | /// pricing row can be proven to price *this* endpoint. |
| 2354 | #[must_use] |
| 2355 | pub fn endpoint_fingerprint(&self) -> Option<String> { |
| 2356 | self.base_url.and_then(endpoint_fingerprint) |
| 2357 | } |
| 2358 | |
| 2359 | /// Billing presentation derivable without app config. |
| 2360 | #[must_use] |
| 2361 | pub fn billing(&self) -> BillingPresentation { |
| 2362 | crate::route_billing::for_endpoint_without_config(self.provider, self.base_url) |
| 2363 | } |
| 2364 | |
| 2365 | /// A redacted, stable receipt describing this route. |
| 2366 | #[must_use] |
| 2367 | pub fn receipt(&self, currency: &str) -> String { |
| 2368 | route_receipt( |
| 2369 | self.provider, |
| 2370 | self.provider_identity, |
| 2371 | self.wire_model, |
| 2372 | self.billing_surface(), |
| 2373 | self.endpoint_fingerprint().as_deref(), |
| 2374 | self.billing().into(), |
| 2375 | currency, |
| 2376 | ) |
| 2377 | } |
| 2378 | } |
| 2379 | |
| 2380 | /// Format one redacted route receipt. |
| 2381 | /// |
| 2382 | /// Contains only: provider kind, configured route label, wire model, |
| 2383 | /// billing-surface classification, endpoint fingerprint, billing mode, and the currency the |
| 2384 | /// estimate is denominated in. It deliberately contains no URL, no credential, |
| 2385 | /// and no filesystem path, so it is safe to persist into a saved session and to |
| 2386 | /// log. This is the single formatter, so the foreground turn path and the |
| 2387 | /// background pool cannot describe the same route two different ways. |
| 2388 | #[must_use] |
| 2389 | pub fn route_receipt( |
| 2390 | provider: ProviderKind, |
| 2391 | provider_identity: Option<&str>, |
| 2392 | wire_model: &str, |
| 2393 | billing_surface: Option<&str>, |
| 2394 | endpoint_fingerprint: Option<&str>, |
| 2395 | billing_mode: RouteBillingMode, |
| 2396 | currency: &str, |
| 2397 | ) -> String { |
| 2398 | format!( |
| 2399 | "provider={} identity={} model={} surface={} endpoint_fp={} billing_mode={} currency={currency}", |
| 2400 | provider.as_str(), |
| 2401 | safe_receipt_field(provider_identity.unwrap_or("-")), |
| 2402 | safe_receipt_field(wire_model), |
| 2403 | safe_receipt_field(billing_surface.unwrap_or("unreported")), |
| 2404 | safe_receipt_field(endpoint_fingerprint.unwrap_or("unreported")), |
| 2405 | match billing_mode { |
| 2406 | RouteBillingMode::Metered => "metered", |
| 2407 | RouteBillingMode::Subscription => "subscription", |
| 2408 | RouteBillingMode::Local => "local", |
| 2409 | RouteBillingMode::Unknown => "unknown", |
| 2410 | }, |
| 2411 | ) |
| 2412 | } |
| 2413 | |
| 2414 | /// Validate and canonicalize an endpoint before producing the cryptographic |
| 2415 | /// fingerprint persisted in a receipt. Secret-bearing/malformed URLs receive |
| 2416 | /// no fingerprint at all; userinfo, query strings, and fragments are never fed |
| 2417 | /// to the hash function. |
| 2418 | #[must_use] |
| 2419 | pub fn endpoint_fingerprint(base_url: &str) -> Option<String> { |
| 2420 | let mut parsed = reqwest::Url::parse(base_url.trim()).ok()?; |
| 2421 | if !matches!(parsed.scheme(), "http" | "https") |
| 2422 | || !parsed.username().is_empty() |
| 2423 | || parsed.password().is_some() |
| 2424 | || parsed.query().is_some() |
| 2425 | || parsed.fragment().is_some() |
| 2426 | || parsed.host_str().is_none() |
| 2427 | { |
| 2428 | return None; |
| 2429 | } |
| 2430 | parsed.set_query(None); |
| 2431 | parsed.set_fragment(None); |
| 2432 | let canonical = parsed.as_str().trim_end_matches('/'); |
| 2433 | Some(codewhale_config::catalog::base_url_fingerprint(canonical)) |
| 2434 | } |
| 2435 | |
| 2436 | /// Currency tag for a receipt, derived from authoritative currency coverage — |
| 2437 | /// not from a positive amount, because a zero-usage priced turn is still a |
| 2438 | /// valid zero in its published currency. |
| 2439 | #[must_use] |
| 2440 | pub fn currency_tag(audit: &TurnCostAudit) -> &'static str { |
| 2441 | match (audit.usd_priced, audit.cny_priced) { |
| 2442 | (true, true) => "usd+cny", |
| 2443 | (true, false) => "usd", |
| 2444 | (false, true) => "cny", |
| 2445 | (false, false) => "unpriced", |
| 2446 | } |
| 2447 | } |
| 2448 | |
| 2449 | /// Background callers report their LLM usage here. |
| 2450 | /// |
| 2451 | /// The route is priced through the same [`crate::pricing::audit_turn_cost_for_route_on_endpoint`] |
| 2452 | /// the foreground turn path uses, so a background turn cannot be counted under |
| 2453 | /// different rules than a parent turn. Adds no money when the route is exactly |
| 2454 | /// non-metered (a local runtime, an OAuth broker, a named plan endpoint), and |
| 2455 | /// counts the turn as *missing spend* whenever it is money-metered or of unknown |
| 2456 | /// basis but could not be priced — an unknown basis is never waved through as a |
| 2457 | /// subscription (#4318). |
| 2458 | #[cfg(any(test, feature = "test-support"))] |
| 2459 | pub fn report(scope: CostScopeToken, route: &BackgroundRoute<'_>, usage: &Usage) { |
| 2460 | let billing_surface = route.billing_surface(); |
| 2461 | let fingerprint = route.endpoint_fingerprint(); |
| 2462 | let audit = crate::pricing::audit_turn_cost_for_route_on_endpoint( |
| 2463 | route.provider, |
| 2464 | route.wire_model, |
| 2465 | billing_surface, |
| 2466 | fingerprint.as_deref(), |
| 2467 | usage, |
| 2468 | chrono::Utc::now(), |
| 2469 | route.billing(), |
| 2470 | ); |
| 2471 | record(scope, route.receipt(currency_tag(&audit)), &audit, usage); |
| 2472 | } |
| 2473 | |
| 2474 | pub(crate) fn unknown_cost_record( |
| 2475 | source_id: impl Into<String>, |
| 2476 | route: &EffectiveRouteEnvelope, |
| 2477 | usage: Usage, |
| 2478 | ) -> RuntimeUsageRecord { |
| 2479 | let mut route = route.sanitized_for_persistence(); |
| 2480 | if !matches!( |
| 2481 | route.billing_mode, |
| 2482 | RouteBillingMode::Subscription | RouteBillingMode::Local |
| 2483 | ) { |
| 2484 | route.billing_mode = RouteBillingMode::Unknown; |
| 2485 | } |
| 2486 | route.provider_live_pricing = None; |
| 2487 | let coverage = if usage == Usage::default() { |
| 2488 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2489 | } else { |
| 2490 | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 2491 | }; |
| 2492 | RuntimeUsageRecord { |
| 2493 | source_id: source_id.into(), |
| 2494 | usage: EffectiveRouteUsage { route, usage }, |
| 2495 | settlement: Some(UsageSourceRevision { |
| 2496 | lineage: uuid::Uuid::new_v4().to_string(), |
| 2497 | revision: 1, |
| 2498 | previous_sha256: None, |
| 2499 | owner: UsageSpendOwner::Auxiliary, |
| 2500 | coverage, |
| 2501 | reason: Some(RuntimeUsageMissingReason::RequestOutcomeUnknown), |
| 2502 | physical_requests: Vec::new(), |
| 2503 | physical_requests_dropped: 0, |
| 2504 | reservation: false, |
| 2505 | }), |
| 2506 | } |
| 2507 | } |
| 2508 | |
| 2509 | pub fn record_runtime_usage( |
| 2510 | scope: CostScopeToken, |
| 2511 | origin: Option<&NativeUsageOrigin>, |
| 2512 | record: &RuntimeUsageRecord, |
| 2513 | ) { |
| 2514 | if let Some(origin) = origin { |
| 2515 | origin.publish(record); |
| 2516 | } else { |
| 2517 | let _ = record_interactive_runtime_usage(scope, record.clone()); |
| 2518 | } |
| 2519 | } |
| 2520 | |
| 2521 | #[cfg(test)] |
| 2522 | tokio::task_local! { |
| 2523 | static TEST_RUNTIME_USAGE_ERROR: &'static str; |
| 2524 | } |
| 2525 | |
| 2526 | #[cfg(test)] |
| 2527 | pub(crate) async fn with_test_runtime_usage_error<F, T>(message: &'static str, fut: F) -> T |
| 2528 | where |
| 2529 | F: std::future::Future<Output = T>, |
| 2530 | { |
| 2531 | TEST_RUNTIME_USAGE_ERROR.scope(message, fut).await |
| 2532 | } |
| 2533 | |
| 2534 | pub async fn try_record_runtime_usage_async( |
| 2535 | scope: CostScopeToken, |
| 2536 | origin: Option<&NativeUsageOrigin>, |
| 2537 | record: &RuntimeUsageRecord, |
| 2538 | ) -> anyhow::Result<()> { |
| 2539 | #[cfg(test)] |
| 2540 | if let Ok(message) = TEST_RUNTIME_USAGE_ERROR.try_with(|message| *message) { |
| 2541 | anyhow::bail!("{message}"); |
| 2542 | } |
| 2543 | let origin = origin.cloned(); |
| 2544 | let record = record.clone(); |
| 2545 | #[cfg(any(test, feature = "test-support"))] |
| 2546 | let test_origin = test_cost_scope_id(); |
| 2547 | codewhale_runtime::runtime_control::owner_work(move || { |
| 2548 | #[cfg(any(test, feature = "test-support"))] |
| 2549 | let _binding = bind_test_cost_scope(test_origin); |
| 2550 | record_runtime_usage(scope, origin.as_ref(), &record); |
| 2551 | Ok(()) |
| 2552 | }) |
| 2553 | .await |
| 2554 | } |
| 2555 | |
| 2556 | pub async fn record_runtime_usage_async( |
| 2557 | scope: CostScopeToken, |
| 2558 | origin: Option<&NativeUsageOrigin>, |
| 2559 | record: &RuntimeUsageRecord, |
| 2560 | ) { |
| 2561 | if let Err(error) = try_record_runtime_usage_async(scope, origin, record).await { |
| 2562 | tracing::warn!(%error, "runtime usage settlement failed"); |
| 2563 | } |
| 2564 | } |
| 2565 | |
| 2566 | pub fn report_missing_runtime_usage( |
| 2567 | scope: CostScopeToken, |
| 2568 | origin: Option<&NativeUsageOrigin>, |
| 2569 | source_id: &str, |
| 2570 | route: &EffectiveRouteEnvelope, |
| 2571 | reason: RuntimeUsageMissingReason, |
| 2572 | ) { |
| 2573 | let drop = RuntimeUsageDropRecord { |
| 2574 | reason, |
| 2575 | source_id: source_id.to_string(), |
| 2576 | route: route.sanitized_for_persistence(), |
| 2577 | }; |
| 2578 | if let Some(origin) = origin { |
| 2579 | origin.publish_drop(&drop); |
| 2580 | } else { |
| 2581 | let _ = record_interactive_runtime_usage_drop(scope, drop); |
| 2582 | } |
| 2583 | } |
| 2584 | |
| 2585 | pub fn record_runtime_usage_batch( |
| 2586 | scope: CostScopeToken, |
| 2587 | origin: Option<&NativeUsageOrigin>, |
| 2588 | batch: &RuntimeUsageBatch, |
| 2589 | ) { |
| 2590 | if let Some(origin) = origin { |
| 2591 | for receipt in &batch.decisions { |
| 2592 | origin.publish_decision(receipt); |
| 2593 | } |
| 2594 | for record in &batch.records { |
| 2595 | origin.publish(record); |
| 2596 | } |
| 2597 | for drop in &batch.drop_records { |
| 2598 | origin.publish_drop(drop); |
| 2599 | } |
| 2600 | return; |
| 2601 | } |
| 2602 | for receipt in &batch.decisions { |
| 2603 | report_interactive_decision(scope, receipt); |
| 2604 | } |
| 2605 | for record in &batch.records { |
| 2606 | let _ = record_interactive_runtime_usage(scope, record.clone()); |
| 2607 | } |
| 2608 | for drop in &batch.drop_records { |
| 2609 | let _ = record_interactive_runtime_usage_drop(scope, drop.clone()); |
| 2610 | } |
| 2611 | let residual = batch |
| 2612 | .dropped_records |
| 2613 | .saturating_sub(u64::try_from(batch.drop_records.len()).unwrap_or(u64::MAX)); |
| 2614 | if residual == 0 { |
| 2615 | return; |
| 2616 | } |
| 2617 | let mut identities = batch |
| 2618 | .records |
| 2619 | .iter() |
| 2620 | .map(|record| usage_source_fingerprint(&record.source_id)) |
| 2621 | .chain( |
| 2622 | batch |
| 2623 | .drop_records |
| 2624 | .iter() |
| 2625 | .map(|record| usage_source_fingerprint(&record.source_id)), |
| 2626 | ) |
| 2627 | .take(MAX_RUNTIME_USAGE_RECORDS_PER_OWNER) |
| 2628 | .collect::<Vec<_>>(); |
| 2629 | identities.sort_unstable(); |
| 2630 | let residual_source = format!( |
| 2631 | "runtime-usage-batch-residual:{}", |
| 2632 | usage_source_fingerprint(&format!( |
| 2633 | "{}:{}:{}:{}", |
| 2634 | batch.records.len(), |
| 2635 | batch.drop_records.len(), |
| 2636 | batch.dropped_records, |
| 2637 | identities.join(":") |
| 2638 | )) |
| 2639 | ); |
| 2640 | let _ = record_interactive_runtime_usage_drop_count(scope, &residual_source, residual); |
| 2641 | } |
| 2642 | |
| 2643 | #[must_use] |
| 2644 | pub fn background_cost_for_runtime_usage(record: &RuntimeUsageRecord) -> PendingBackgroundCost { |
| 2645 | if record.settlement.is_some() { |
| 2646 | let mut pending = PendingBackgroundCost::default(); |
| 2647 | pending |
| 2648 | .usage_source_fingerprints |
| 2649 | .insert(usage_source_fingerprint(&record.source_id)); |
| 2650 | pending.source_records.push(record.clone()); |
| 2651 | return pending; |
| 2652 | } |
| 2653 | if record.usage.usage == Usage::default() { |
| 2654 | return background_cost_for_runtime_drop(&RuntimeUsageDropRecord { |
| 2655 | reason: RuntimeUsageMissingReason::default(), |
| 2656 | source_id: record.source_id.clone(), |
| 2657 | route: record.usage.route.clone(), |
| 2658 | }); |
| 2659 | } |
| 2660 | let mut pending = PendingBackgroundCost::default(); |
| 2661 | let fingerprint = usage_source_fingerprint(&record.source_id); |
| 2662 | let audit = record.usage.route.audit_frozen(&record.usage.usage); |
| 2663 | let receipt = record.usage.route.receipt(&audit); |
| 2664 | pending.usage_source_fingerprints.insert(fingerprint); |
| 2665 | fold_audit_into_pending(&mut pending, receipt, &audit, &record.usage.usage); |
| 2666 | pending |
| 2667 | } |
| 2668 | |
| 2669 | #[must_use] |
| 2670 | pub fn background_cost_for_runtime_drop(record: &RuntimeUsageDropRecord) -> PendingBackgroundCost { |
| 2671 | let mut pending = PendingBackgroundCost::default(); |
| 2672 | pending |
| 2673 | .usage_source_fingerprints |
| 2674 | .insert(usage_source_fingerprint(&record.source_id)); |
| 2675 | pending.source_records.push(record.as_usage_record()); |
| 2676 | pending |
| 2677 | } |
| 2678 | |
| 2679 | pub fn prune_settled_missing_reasons( |
| 2680 | accounted: &BTreeMap<String, UsageSourceContribution>, |
| 2681 | unpriced: u32, |
| 2682 | cny_unpriced: u32, |
| 2683 | reasons: &mut BTreeSet<String>, |
| 2684 | cny_reasons: &mut BTreeSet<String>, |
| 2685 | ) { |
| 2686 | for reason in [ |
| 2687 | RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 2688 | RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 2689 | ] { |
| 2690 | let has_usd_reason = accounted.values().any(|entry| { |
| 2691 | entry.unpriced > 0 |
| 2692 | && entry.record.settlement.as_ref().is_some_and(|revision| { |
| 2693 | matches!( |
| 2694 | revision.coverage, |
| 2695 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2696 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 2697 | ) && revision.reason.unwrap_or_default() == reason |
| 2698 | }) |
| 2699 | }); |
| 2700 | if unpriced == 0 || !has_usd_reason { |
| 2701 | reasons.remove(reason.label()); |
| 2702 | } |
| 2703 | let has_cny_reason = accounted.values().any(|entry| { |
| 2704 | entry.cny_unpriced > 0 |
| 2705 | && entry.record.settlement.as_ref().is_some_and(|revision| { |
| 2706 | matches!( |
| 2707 | revision.coverage, |
| 2708 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2709 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 2710 | ) && revision.reason.unwrap_or_default() == reason |
| 2711 | }) |
| 2712 | }); |
| 2713 | if cny_unpriced == 0 || !has_cny_reason { |
| 2714 | cny_reasons.remove(reason.label()); |
| 2715 | } |
| 2716 | } |
| 2717 | reasons.remove(crate::pricing::UnpricedReason::RequestInProgress.label()); |
| 2718 | cny_reasons.remove(crate::pricing::UnpricedReason::RequestInProgress.label()); |
| 2719 | } |
| 2720 | |
| 2721 | #[cfg(any(test, feature = "test-support"))] |
| 2722 | fn record(scope: CostScopeToken, route_receipt: String, audit: &TurnCostAudit, usage: &Usage) { |
| 2723 | with_pending_state_mut(|state| { |
| 2724 | if state.generation != scope.0 { |
| 2725 | return; |
| 2726 | } |
| 2727 | fold_audit_into_pending(&mut state.pending, route_receipt, audit, usage); |
| 2728 | }); |
| 2729 | } |
| 2730 | |
| 2731 | pub fn record_interactive_runtime_usage(scope: CostScopeToken, record: RuntimeUsageRecord) -> bool { |
| 2732 | record_interactive_runtime_usage_inner(scope, record, false) |
| 2733 | } |
| 2734 | |
| 2735 | pub fn record_interactive_runtime_usage_pinned( |
| 2736 | scope: CostScopeToken, |
| 2737 | record: RuntimeUsageRecord, |
| 2738 | ) -> bool { |
| 2739 | record_interactive_runtime_usage_inner(scope, record, true) |
| 2740 | } |
| 2741 | |
| 2742 | fn record_interactive_runtime_usage_inner( |
| 2743 | scope: CostScopeToken, |
| 2744 | record: RuntimeUsageRecord, |
| 2745 | pin: bool, |
| 2746 | ) -> bool { |
| 2747 | with_pending_state_mut(|state| { |
| 2748 | if state.generation != scope.0 { |
| 2749 | return false; |
| 2750 | } |
| 2751 | let key = usage_source_fingerprint(&record.source_id); |
| 2752 | let record_to_store = if let Some(previous) = state.source_records.get(&key) { |
| 2753 | if record.route_conflicts_with(Some(previous)) { |
| 2754 | tracing::warn!( |
| 2755 | source_id = %key, |
| 2756 | "interactive usage source changed route; recording unknown cost" |
| 2757 | ); |
| 2758 | unknown_cost_record( |
| 2759 | &record.source_id, |
| 2760 | &record.usage.route, |
| 2761 | record.usage.usage.clone(), |
| 2762 | ) |
| 2763 | } else if !record.supersedes(Some(previous)) { |
| 2764 | if pin { |
| 2765 | if state.pending.usage_source_fingerprints.contains(&key) { |
| 2766 | state |
| 2767 | .pending |
| 2768 | .pinned_usage_source_fingerprints |
| 2769 | .insert(key.clone()); |
| 2770 | } |
| 2771 | state.pinned_usage_source_fingerprints.insert(key); |
| 2772 | } |
| 2773 | return true; |
| 2774 | } else { |
| 2775 | record |
| 2776 | } |
| 2777 | } else if state.seen_usage_source_fingerprints.contains(&key) { |
| 2778 | if pin { |
| 2779 | if state.pending.usage_source_fingerprints.contains(&key) { |
| 2780 | state |
| 2781 | .pending |
| 2782 | .pinned_usage_source_fingerprints |
| 2783 | .insert(key.clone()); |
| 2784 | } |
| 2785 | state.pinned_usage_source_fingerprints.insert(key); |
| 2786 | } |
| 2787 | return true; |
| 2788 | } else { |
| 2789 | record |
| 2790 | }; |
| 2791 | state.pending.usage_source_fingerprints.insert(key.clone()); |
| 2792 | state.seen_usage_source_fingerprints.insert(key.clone()); |
| 2793 | if pin { |
| 2794 | state |
| 2795 | .pending |
| 2796 | .pinned_usage_source_fingerprints |
| 2797 | .insert(key.clone()); |
| 2798 | state.pinned_usage_source_fingerprints.insert(key.clone()); |
| 2799 | } |
| 2800 | let record_to_store = if record_to_store.settlement.is_none() |
| 2801 | && record_to_store.usage.usage == Usage::default() |
| 2802 | { |
| 2803 | RuntimeUsageDropRecord { |
| 2804 | reason: RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 2805 | source_id: record_to_store.source_id, |
| 2806 | route: record_to_store.usage.route, |
| 2807 | } |
| 2808 | .as_usage_record() |
| 2809 | } else { |
| 2810 | record_to_store |
| 2811 | }; |
| 2812 | if let Some(revision) = record_to_store.settlement.as_ref() { |
| 2813 | state |
| 2814 | .pending |
| 2815 | .source_records |
| 2816 | .retain(|old| usage_source_fingerprint(&old.source_id) != key); |
| 2817 | if matches!( |
| 2818 | revision.coverage, |
| 2819 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2820 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 2821 | ) && record_to_store |
| 2822 | .usage |
| 2823 | .route |
| 2824 | .audit_frozen(&record_to_store.usage.usage) |
| 2825 | .counts_toward_money_coverage() |
| 2826 | { |
| 2827 | let reason_label = revision.reason.unwrap_or_default().label(); |
| 2828 | state.pending.unpriced_reasons.insert(reason_label); |
| 2829 | state.pending.cny_unpriced_reasons.insert(reason_label); |
| 2830 | } |
| 2831 | state |
| 2832 | .source_records |
| 2833 | .insert(key, record_to_store.persisted()); |
| 2834 | state.pending.source_records.push(record_to_store); |
| 2835 | } else { |
| 2836 | state |
| 2837 | .source_records |
| 2838 | .insert(key, record_to_store.persisted()); |
| 2839 | let audit = record_to_store |
| 2840 | .usage |
| 2841 | .route |
| 2842 | .audit_frozen(&record_to_store.usage.usage); |
| 2843 | let receipt = record_to_store.usage.route.receipt(&audit); |
| 2844 | fold_audit_into_pending( |
| 2845 | &mut state.pending, |
| 2846 | receipt, |
| 2847 | &audit, |
| 2848 | &record_to_store.usage.usage, |
| 2849 | ); |
| 2850 | } |
| 2851 | state.compact_fingerprints(); |
| 2852 | true |
| 2853 | }) |
| 2854 | } |
| 2855 | |
| 2856 | pub fn record_interactive_runtime_usage_drop( |
| 2857 | scope: CostScopeToken, |
| 2858 | record: RuntimeUsageDropRecord, |
| 2859 | ) -> bool { |
| 2860 | record_interactive_runtime_usage(scope, record.as_usage_record()) |
| 2861 | } |
| 2862 | |
| 2863 | fn record_interactive_runtime_usage_drop_count( |
| 2864 | scope: CostScopeToken, |
| 2865 | source_id: &str, |
| 2866 | count: u64, |
| 2867 | ) -> bool { |
| 2868 | with_pending_state_mut(|state| { |
| 2869 | if state.generation != scope.0 { |
| 2870 | return false; |
| 2871 | } |
| 2872 | let fingerprint = usage_source_fingerprint(source_id); |
| 2873 | if !state |
| 2874 | .seen_usage_source_fingerprints |
| 2875 | .insert(fingerprint.clone()) |
| 2876 | { |
| 2877 | return true; |
| 2878 | } |
| 2879 | state.pending.usage_source_fingerprints.insert(fingerprint); |
| 2880 | state.compact_fingerprints(); |
| 2881 | let count = u32::try_from(count).unwrap_or(u32::MAX); |
| 2882 | state.pending.unpriced_turns = state.pending.unpriced_turns.saturating_add(count); |
| 2883 | state.pending.cny_unpriced_turns = state.pending.cny_unpriced_turns.saturating_add(count); |
| 2884 | state |
| 2885 | .pending |
| 2886 | .unpriced_reasons |
| 2887 | .insert("routed_usage_receipt_missing"); |
| 2888 | state |
| 2889 | .pending |
| 2890 | .cny_unpriced_reasons |
| 2891 | .insert("routed_usage_receipt_missing"); |
| 2892 | true |
| 2893 | }) |
| 2894 | } |
| 2895 | |
| 2896 | fn fold_audit_into_pending( |
| 2897 | pending: &mut PendingBackgroundCost, |
| 2898 | route_receipt: String, |
| 2899 | audit: &TurnCostAudit, |
| 2900 | usage: &Usage, |
| 2901 | ) { |
| 2902 | if let Some(provenance) = audit.provenance.as_ref() { |
| 2903 | pending.pricing_provenances.insert(provenance.label()); |
| 2904 | } |
| 2905 | if let Some(defect) = audit.live_pricing_defect.as_ref() { |
| 2906 | if audit.estimate.is_some() { |
| 2907 | pending.live_pricing_defects.insert(defect.label()); |
| 2908 | } else { |
| 2909 | pending.live_pricing_unusable_defects.insert(defect.label()); |
| 2910 | } |
| 2911 | } |
| 2912 | if let Some(cost) = audit.estimate { |
| 2913 | pending.estimate = pending.estimate.saturating_add(cost); |
| 2914 | } |
| 2915 | if usage.prompt_cache_hit_tokens.is_some() |
| 2916 | || usage.prompt_cache_miss_tokens.is_some() |
| 2917 | || usage.prompt_cache_write_tokens.is_some() |
| 2918 | { |
| 2919 | let classes = crate::pricing::token_usage_for_pricing(usage); |
| 2920 | let add = |slot: &mut Option<u64>, tokens: u64| { |
| 2921 | *slot = Some(slot.unwrap_or(0).saturating_add(tokens)); |
| 2922 | }; |
| 2923 | add(&mut pending.cache_hit_tokens, classes.cache_read); |
| 2924 | add(&mut pending.cache_miss_tokens, classes.input); |
| 2925 | add(&mut pending.cache_write_tokens, classes.cache_write); |
| 2926 | } |
| 2927 | |
| 2928 | if audit.counts_toward_money_coverage() { |
| 2929 | if audit.usd_priced { |
| 2930 | pending.priced_turns = pending.priced_turns.saturating_add(1); |
| 2931 | } else { |
| 2932 | pending.unpriced_turns = pending.unpriced_turns.saturating_add(1); |
| 2933 | } |
| 2934 | if audit.cny_priced { |
| 2935 | pending.cny_priced_turns = pending.cny_priced_turns.saturating_add(1); |
| 2936 | } else { |
| 2937 | pending.cny_unpriced_turns = pending.cny_unpriced_turns.saturating_add(1); |
| 2938 | } |
| 2939 | for class in &audit.unpriced_classes { |
| 2940 | pending.unpriced_classes.insert(class.label()); |
| 2941 | } |
| 2942 | if !audit.usd_priced |
| 2943 | && let Some(reason) = audit.unpriced_reason |
| 2944 | { |
| 2945 | pending.unpriced_reasons.insert(reason.label()); |
| 2946 | } |
| 2947 | if !audit.cny_priced { |
| 2948 | pending.cny_unpriced_reasons.insert( |
| 2949 | audit |
| 2950 | .unpriced_reason |
| 2951 | .map_or("currency_not_published", |reason| reason.label()), |
| 2952 | ); |
| 2953 | } |
| 2954 | } |
| 2955 | |
| 2956 | pending |
| 2957 | .route_receipts |
| 2958 | .insert(receipt_with_usage_classes(route_receipt, usage)); |
| 2959 | } |
| 2960 | |
| 2961 | #[must_use] |
| 2962 | pub fn drain() -> PendingBackgroundCost { |
| 2963 | with_pending_state_mut(|state| std::mem::take(&mut state.pending)) |
| 2964 | } |
| 2965 | |
| 2966 | #[cfg(any(test, feature = "test-support"))] |
| 2967 | pub fn reset_for_tests() { |
| 2968 | with_pending_state_mut(|state| { |
| 2969 | state.pending = PendingBackgroundCost::default(); |
| 2970 | state.seen_usage_source_fingerprints.clear(); |
| 2971 | state.retired_usage_sources.clear(); |
| 2972 | state.pinned_usage_source_fingerprints.clear(); |
| 2973 | state.source_records.clear(); |
| 2974 | }); |
| 2975 | } |
| 2976 | |
| 2977 | #[cfg(any(test, feature = "test-support"))] |
| 2978 | pub struct TestCostScope; |
| 2979 | |
| 2980 | #[cfg(any(test, feature = "test-support"))] |
| 2981 | impl Drop for TestCostScope { |
| 2982 | fn drop(&mut self) { |
| 2983 | reset_for_tests(); |
| 2984 | } |
| 2985 | } |
| 2986 | |
| 2987 | #[cfg(any(test, feature = "test-support"))] |
| 2988 | pub fn test_scope() -> TestCostScope { |
| 2989 | reset_for_tests(); |
| 2990 | TestCostScope |
| 2991 | } |
| 2992 | |
| 2993 | #[cfg(test)] |
| 2994 | mod tests { |
| 2995 | use super::*; |
| 2996 | use crate::usage_persistence::*; |
| 2997 | |
| 2998 | fn configured_fixture_receipt() -> ( |
| 2999 | codewhale_runtime::config::Config, |
| 3000 | EffectiveRouteEnvelope, |
| 3001 | Usage, |
| 3002 | ) { |
| 3003 | let config = toml::from_str(include_str!( |
| 3004 | "../../config/tests/fixtures/custom_models.toml" |
| 3005 | )) |
| 3006 | .unwrap(); |
| 3007 | let receipt = EffectiveRouteEnvelope::capture( |
| 3008 | Some(&config), |
| 3009 | ProviderKind::Deepseek, |
| 3010 | "deepseek", |
| 3011 | "deepseek-v4.1-flash-expires-on-0910", |
| 3012 | Some("https://models.example.test/v1"), |
| 3013 | Utc::now(), |
| 3014 | ); |
| 3015 | let usage = Usage { |
| 3016 | input_tokens: 1_000_000, |
| 3017 | output_tokens: 1_000_000, |
| 3018 | ..Usage::default() |
| 3019 | }; |
| 3020 | (config, receipt, usage) |
| 3021 | } |
| 3022 | |
| 3023 | #[test] |
| 3024 | fn configured_model_estimate_is_frozen_and_exactly_bound() { |
| 3025 | let (mut config, receipt, usage) = configured_fixture_receipt(); |
| 3026 | let audit = receipt.audit(&usage); |
| 3027 | assert_eq!( |
| 3028 | audit.provenance, |
| 3029 | Some(codewhale_config::pricing::PricingProvenance::UserOverride) |
| 3030 | ); |
| 3031 | assert!((audit.estimate.unwrap().usd - 2.0).abs() < 1e-12); |
| 3032 | let frozen: EffectiveRouteEnvelope = |
| 3033 | serde_json::from_str(&serde_json::to_string(&receipt).unwrap()).unwrap(); |
| 3034 | config.custom_models.as_mut().unwrap()[0] |
| 3035 | .cost |
| 3036 | .as_mut() |
| 3037 | .unwrap() |
| 3038 | .input = Some(9.0); |
| 3039 | assert!((frozen.audit(&usage).estimate.unwrap().usd - 2.0).abs() < 1e-12); |
| 3040 | for (field, value) in [ |
| 3041 | ("model", "deepseek-v4.1-flash"), |
| 3042 | ("identity", "other-provider"), |
| 3043 | ("endpoint", "https://other.example.test/v1"), |
| 3044 | ] { |
| 3045 | let mut wrong = frozen.clone(); |
| 3046 | match field { |
| 3047 | "model" => wrong.model = value.into(), |
| 3048 | "identity" => wrong.provider_identity = value.into(), |
| 3049 | _ => wrong.endpoint_fingerprint = endpoint_fingerprint(value), |
| 3050 | } |
| 3051 | assert!(wrong.audit(&usage).estimate.is_none(), "{field}"); |
| 3052 | } |
| 3053 | for billing in [RouteBillingMode::Local, RouteBillingMode::Subscription] { |
| 3054 | let mut nonmoney = frozen.clone(); |
| 3055 | nonmoney.billing_mode = billing; |
| 3056 | assert_eq!( |
| 3057 | nonmoney.audit(&usage).unpriced_reason, |
| 3058 | Some(crate::pricing::UnpricedReason::NotMoneyMetered) |
| 3059 | ); |
| 3060 | } |
| 3061 | let mut cached = usage.clone(); |
| 3062 | cached.prompt_cache_write_tokens = Some(500); |
| 3063 | assert!(frozen.audit(&cached).estimate.is_none()); |
| 3064 | } |
| 3065 | |
| 3066 | #[test] |
| 3067 | fn configured_model_missing_prices_stay_unknown_and_vendor_pin_still_wins() { |
| 3068 | let (mut config, receipt, usage) = configured_fixture_receipt(); |
| 3069 | config.custom_models.as_mut().unwrap()[0].cost = None; |
| 3070 | let unknown = EffectiveRouteEnvelope::capture( |
| 3071 | Some(&config), |
| 3072 | receipt.provider, |
| 3073 | receipt.provider_identity.clone(), |
| 3074 | receipt.model.clone(), |
| 3075 | Some("https://models.example.test/v1"), |
| 3076 | receipt.dispatched_at, |
| 3077 | ); |
| 3078 | assert!(unknown.provider_live_pricing.is_some()); |
| 3079 | assert!(unknown.audit(&usage).estimate.is_none()); |
| 3080 | let mut pinned = receipt; |
| 3081 | pinned.provider = ProviderKind::Openrouter; |
| 3082 | pinned.openrouter_vendor = Some("exact-upstream".into()); |
| 3083 | pinned.billing_mode = RouteBillingMode::Metered; |
| 3084 | assert_eq!( |
| 3085 | pinned.audit(&usage).unpriced_reason, |
| 3086 | Some(crate::pricing::UnpricedReason::RoutingDependentPrice) |
| 3087 | ); |
| 3088 | } |
| 3089 | |
| 3090 | #[test] |
| 3091 | fn configured_model_client_keeps_its_metadata_snapshot_after_reload() { |
| 3092 | let (mut config, _, usage) = configured_fixture_receipt(); |
| 3093 | config.set_legacy_root(Some("fixture-not-a-provider-credential".into()), None); |
| 3094 | let id = "deepseek-v4.1-flash-expires-on-0910"; |
| 3095 | let route = |
| 3096 | crate::route_runtime::resolve_runtime_route(&config, ProviderKind::Deepseek, Some(id)) |
| 3097 | .unwrap(); |
| 3098 | let client = |
| 3099 | crate::client::CodewhaleClient::from_candidate(&config, &route.candidate).unwrap(); |
| 3100 | config.custom_models.as_mut().unwrap()[0] |
| 3101 | .cost |
| 3102 | .as_mut() |
| 3103 | .unwrap() |
| 3104 | .input = Some(9.0); |
| 3105 | let envelope = client.effective_route_envelope(id, Utc::now()); |
| 3106 | assert!((envelope.audit(&usage).estimate.unwrap().usd - 2.0).abs() < 1e-12); |
| 3107 | assert_eq!( |
| 3108 | client |
| 3109 | .effective_route_envelope("other-model", Utc::now()) |
| 3110 | .provider_live_pricing, |
| 3111 | None |
| 3112 | ); |
| 3113 | } |
| 3114 | |
| 3115 | const DECLARED_OPENROUTER_MODEL: &str = "synthetic/declared-model"; |
| 3116 | |
| 3117 | /// An OpenRouter config on the official endpoint with one |
| 3118 | /// `[[custom_models]]` row; `extra` adds fields such as `cost`. |
| 3119 | fn openrouter_declared_config( |
| 3120 | extra: &str, |
| 3121 | vendor: Option<&str>, |
| 3122 | ) -> codewhale_runtime::config::Config { |
| 3123 | let vendor = vendor.map_or_else(String::new, |vendor| format!("vendor = \"{vendor}\"\n")); |
| 3124 | toml::from_str(&format!( |
| 3125 | "provider = \"openrouter\"\ntelemetry = false\n\n\ |
| 3126 | [[custom_models]]\nprovider = \"openrouter\"\n\ |
| 3127 | base_url = \"{base}\"\nid = \"{DECLARED_OPENROUTER_MODEL}\"\n{extra}\n\n\ |
| 3128 | [providers.openrouter]\nbase_url = \"{base}\"\n\ |
| 3129 | api_key = \"fixture-not-a-provider-credential\"\n{vendor}", |
| 3130 | base = codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3131 | )) |
| 3132 | .expect("declared OpenRouter config") |
| 3133 | } |
| 3134 | |
| 3135 | fn declared_openrouter_client( |
| 3136 | config: &codewhale_runtime::config::Config, |
| 3137 | ) -> crate::client::CodewhaleClient { |
| 3138 | let route = crate::route_runtime::resolve_runtime_route( |
| 3139 | config, |
| 3140 | ProviderKind::Openrouter, |
| 3141 | Some(DECLARED_OPENROUTER_MODEL), |
| 3142 | ) |
| 3143 | .expect("declared OpenRouter route"); |
| 3144 | crate::client::CodewhaleClient::from_candidate(config, &route.candidate) |
| 3145 | .expect("declared OpenRouter client") |
| 3146 | } |
| 3147 | |
| 3148 | /// #6690: a `[[custom_models]]` row declared only to add a model (no |
| 3149 | /// rates) used to freeze a rate-less quote on the main turn and hide the |
| 3150 | /// endpoint's own catalog price. A declared rate still wins, and with no |
| 3151 | /// catalog row the rate-less declaration stays frozen so no same-named |
| 3152 | /// bundled price can fill it. |
| 3153 | #[test] |
| 3154 | fn main_turn_rateless_declaration_yields_to_the_endpoint_catalog_price() { |
| 3155 | let _env = crate::test_support::lock_test_env(); |
| 3156 | let home = tempfile::tempdir().expect("isolated catalog home"); |
| 3157 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3158 | let _reset = ProviderCatalogTestReset; |
| 3159 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3160 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3161 | crate::provider_lake::clear_live_snapshot(); |
| 3162 | |
| 3163 | let fingerprint = endpoint_fingerprint( |
| 3164 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3165 | ) |
| 3166 | .expect("official endpoint"); |
| 3167 | let now = u64::try_from(Utc::now().timestamp()).expect("timestamp"); |
| 3168 | let rateless = declared_openrouter_client(&openrouter_declared_config("", None)); |
| 3169 | let declared = declared_openrouter_client(&openrouter_declared_config( |
| 3170 | "cost = { input = 0.4, output = 1.6 }", |
| 3171 | None, |
| 3172 | )); |
| 3173 | let quote_for = |client: &crate::client::CodewhaleClient| { |
| 3174 | crate::client::main_turn_pricing_quote_at( |
| 3175 | Some(client), |
| 3176 | ProviderKind::Openrouter, |
| 3177 | "openrouter", |
| 3178 | DECLARED_OPENROUTER_MODEL, |
| 3179 | &fingerprint, |
| 3180 | now, |
| 3181 | ) |
| 3182 | .expect("a frozen main-turn quote") |
| 3183 | }; |
| 3184 | |
| 3185 | // No catalog row yet: the rate-less declaration is frozen as-is. |
| 3186 | let frozen = quote_for(&rateless); |
| 3187 | assert_eq!( |
| 3188 | frozen.provenance, |
| 3189 | codewhale_config::pricing::PricingProvenance::UserOverride |
| 3190 | ); |
| 3191 | assert!(!frozen.carries_rates()); |
| 3192 | |
| 3193 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3194 | "openrouter", |
| 3195 | DECLARED_OPENROUTER_MODEL, |
| 3196 | &fingerprint, |
| 3197 | now, |
| 3198 | )); |
| 3199 | let catalog = quote_for(&rateless); |
| 3200 | assert_eq!( |
| 3201 | catalog.provenance, |
| 3202 | codewhale_config::pricing::PricingProvenance::ProviderLive |
| 3203 | ); |
| 3204 | assert_eq!(catalog.input_per_million.as_deref(), Some("1.25")); |
| 3205 | assert_eq!(catalog.output_per_million.as_deref(), Some("5")); |
| 3206 | assert_eq!(catalog.cache_read_per_million.as_deref(), Some("0.25")); |
| 3207 | |
| 3208 | let explicit = quote_for(&declared); |
| 3209 | assert_eq!( |
| 3210 | explicit.provenance, |
| 3211 | codewhale_config::pricing::PricingProvenance::UserOverride |
| 3212 | ); |
| 3213 | assert_eq!(explicit.input_per_million.as_deref(), Some("0.4")); |
| 3214 | assert_eq!(explicit.output_per_million.as_deref(), Some("1.6")); |
| 3215 | } |
| 3216 | |
| 3217 | /// #6690 review: a pinned OpenRouter vendor blocks the aggregate catalog |
| 3218 | /// price, but an operator's own declared rate for the exact route is not |
| 3219 | /// that aggregate and must still price the turn. |
| 3220 | #[test] |
| 3221 | fn openrouter_vendor_pin_is_priced_by_an_explicit_declared_rate() { |
| 3222 | let _env = crate::test_support::lock_test_env(); |
| 3223 | let home = tempfile::tempdir().expect("isolated catalog home"); |
| 3224 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3225 | let _reset = ProviderCatalogTestReset; |
| 3226 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3227 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3228 | crate::provider_lake::clear_live_snapshot(); |
| 3229 | |
| 3230 | let usage = Usage { |
| 3231 | input_tokens: 1_000_000, |
| 3232 | output_tokens: 1_000_000, |
| 3233 | ..Usage::default() |
| 3234 | }; |
| 3235 | let capture = |extra: &str| { |
| 3236 | EffectiveRouteEnvelope::capture( |
| 3237 | Some(&openrouter_declared_config(extra, Some("cerebras"))), |
| 3238 | ProviderKind::Openrouter, |
| 3239 | "openrouter", |
| 3240 | DECLARED_OPENROUTER_MODEL, |
| 3241 | Some(codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL), |
| 3242 | Utc::now(), |
| 3243 | ) |
| 3244 | }; |
| 3245 | |
| 3246 | let declared = capture("cost = { input = 0.4, output = 1.6 }"); |
| 3247 | assert_eq!(declared.openrouter_vendor.as_deref(), Some("cerebras")); |
| 3248 | let audit = declared.audit(&usage); |
| 3249 | assert_eq!(audit.unpriced_reason, None, "{audit:?}"); |
| 3250 | assert_eq!( |
| 3251 | audit.provenance, |
| 3252 | Some(codewhale_config::pricing::PricingProvenance::UserOverride) |
| 3253 | ); |
| 3254 | let usd = audit.estimate.expect("declared estimate").usd; |
| 3255 | assert!((usd - 2.0).abs() < 1e-12, "{usd}"); |
| 3256 | |
| 3257 | // A rate-less declaration is no explicit rate: the pin still wins. |
| 3258 | let rateless = capture(""); |
| 3259 | assert_eq!( |
| 3260 | rateless.audit(&usage).unpriced_reason, |
| 3261 | Some(crate::pricing::UnpricedReason::RoutingDependentPrice) |
| 3262 | ); |
| 3263 | } |
| 3264 | |
| 3265 | struct ProviderCatalogTestReset; |
| 3266 | |
| 3267 | impl Drop for ProviderCatalogTestReset { |
| 3268 | fn drop(&mut self) { |
| 3269 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3270 | crate::provider_lake::clear_live_snapshot(); |
| 3271 | } |
| 3272 | } |
| 3273 | |
| 3274 | fn priced_provider_delta( |
| 3275 | provider: &str, |
| 3276 | model: &str, |
| 3277 | fingerprint: &str, |
| 3278 | fetched_at: u64, |
| 3279 | ) -> codewhale_config::catalog::ProviderCatalogDelta { |
| 3280 | priced_provider_delta_with_rates(provider, model, fingerprint, fetched_at, 1.25, 5.0) |
| 3281 | } |
| 3282 | |
| 3283 | fn priced_provider_delta_with_rates( |
| 3284 | provider: &str, |
| 3285 | model: &str, |
| 3286 | fingerprint: &str, |
| 3287 | fetched_at: u64, |
| 3288 | input: f64, |
| 3289 | output: f64, |
| 3290 | ) -> codewhale_config::catalog::ProviderCatalogDelta { |
| 3291 | codewhale_config::catalog::ProviderCatalogDelta { |
| 3292 | provider: provider.to_string(), |
| 3293 | base_url_fingerprint: fingerprint.to_string(), |
| 3294 | fetched_at, |
| 3295 | offerings: vec![codewhale_config::catalog::CatalogOffering { |
| 3296 | provider: provider.to_string(), |
| 3297 | wire_model_id: model.to_string(), |
| 3298 | endpoint_key: "chat".to_string(), |
| 3299 | cost: Some(codewhale_config::models_dev::ModelsDevCost { |
| 3300 | input: Some(input), |
| 3301 | output: Some(output), |
| 3302 | cache_read: Some(0.25), |
| 3303 | cache_write: None, |
| 3304 | ..Default::default() |
| 3305 | }), |
| 3306 | ..Default::default() |
| 3307 | }], |
| 3308 | } |
| 3309 | } |
| 3310 | |
| 3311 | fn custom_usage_envelope( |
| 3312 | identity: &str, |
| 3313 | model: &str, |
| 3314 | fingerprint: &str, |
| 3315 | billing_mode: RouteBillingMode, |
| 3316 | dispatched_at: DateTime<Utc>, |
| 3317 | ) -> EffectiveRouteEnvelope { |
| 3318 | provider_live_usage_envelope( |
| 3319 | ProviderKind::Custom, |
| 3320 | identity, |
| 3321 | model, |
| 3322 | fingerprint, |
| 3323 | Some(crate::pricing::UNCLASSIFIED_BILLING_SURFACE), |
| 3324 | billing_mode, |
| 3325 | dispatched_at, |
| 3326 | ) |
| 3327 | } |
| 3328 | |
| 3329 | fn provider_live_usage_envelope( |
| 3330 | provider: ProviderKind, |
| 3331 | identity: &str, |
| 3332 | model: &str, |
| 3333 | fingerprint: &str, |
| 3334 | billing_surface: Option<&str>, |
| 3335 | billing_mode: RouteBillingMode, |
| 3336 | dispatched_at: DateTime<Utc>, |
| 3337 | ) -> EffectiveRouteEnvelope { |
| 3338 | let provider_live_pricing = |
| 3339 | u64::try_from(dispatched_at.timestamp()) |
| 3340 | .ok() |
| 3341 | .and_then(|dispatched_at_unix| { |
| 3342 | crate::provider_catalog_live::fresh_provider_live_pricing_quote_at( |
| 3343 | provider, |
| 3344 | identity, |
| 3345 | model, |
| 3346 | fingerprint, |
| 3347 | dispatched_at_unix, |
| 3348 | ) |
| 3349 | }); |
| 3350 | EffectiveRouteEnvelope { |
| 3351 | provider, |
| 3352 | provider_identity: identity.to_string(), |
| 3353 | model: model.to_string(), |
| 3354 | openrouter_vendor: None, |
| 3355 | billing_surface: billing_surface.map(str::to_string), |
| 3356 | endpoint_fingerprint: Some(fingerprint.to_string()), |
| 3357 | provider_live_pricing, |
| 3358 | billing_mode, |
| 3359 | dispatched_at, |
| 3360 | } |
| 3361 | } |
| 3362 | |
| 3363 | fn small_usage() -> Usage { |
| 3364 | Usage { |
| 3365 | input_tokens: 1_000, |
| 3366 | output_tokens: 500, |
| 3367 | ..Default::default() |
| 3368 | } |
| 3369 | } |
| 3370 | |
| 3371 | #[test] |
| 3372 | fn baseten_usage_prices_only_the_reviewed_identity_on_the_official_endpoint() { |
| 3373 | let _env = crate::test_support::lock_test_env(); |
| 3374 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3375 | let home = tempfile::tempdir().expect("test home"); |
| 3376 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3377 | let _reset = ProviderCatalogTestReset; |
| 3378 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3379 | crate::provider_lake::clear_live_snapshot(); |
| 3380 | |
| 3381 | let now = Utc::now(); |
| 3382 | let fetched_at = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 3383 | let model = "synthetic-baseten-priced-model"; |
| 3384 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 3385 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3386 | ); |
| 3387 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3388 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3389 | model, |
| 3390 | &fingerprint, |
| 3391 | fetched_at, |
| 3392 | )); |
| 3393 | let usage = Usage { |
| 3394 | input_tokens: 1_000_000, |
| 3395 | ..Usage::default() |
| 3396 | }; |
| 3397 | |
| 3398 | let exact = custom_usage_envelope( |
| 3399 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3400 | model, |
| 3401 | &fingerprint, |
| 3402 | RouteBillingMode::Unknown, |
| 3403 | now, |
| 3404 | ) |
| 3405 | .audit(&usage); |
| 3406 | assert!(exact.is_priced(), "{exact:?}"); |
| 3407 | assert_eq!( |
| 3408 | exact.provenance, |
| 3409 | Some(codewhale_config::pricing::PricingProvenance::ProviderLive) |
| 3410 | ); |
| 3411 | assert_eq!(exact.estimate.expect("priced").usd, 1.25); |
| 3412 | |
| 3413 | // A reviewed schema alias remains a distinct custom ownership scope. |
| 3414 | // It becomes billable only after that exact identity refreshed its own |
| 3415 | // catalog; it cannot borrow the canonical `baseten` partition above. |
| 3416 | let alias = "base-ten"; |
| 3417 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3418 | alias, |
| 3419 | model, |
| 3420 | &fingerprint, |
| 3421 | fetched_at, |
| 3422 | )); |
| 3423 | let alias_audit = |
| 3424 | custom_usage_envelope(alias, model, &fingerprint, RouteBillingMode::Unknown, now) |
| 3425 | .audit(&usage); |
| 3426 | assert!(alias_audit.is_priced(), "{alias_audit:?}"); |
| 3427 | assert_eq!( |
| 3428 | alias_audit.provenance, |
| 3429 | Some(codewhale_config::pricing::PricingProvenance::ProviderLive) |
| 3430 | ); |
| 3431 | assert_eq!(alias_audit.estimate.expect("priced").usd, 1.25); |
| 3432 | |
| 3433 | let generic = custom_usage_envelope( |
| 3434 | "custom-lab", |
| 3435 | model, |
| 3436 | &fingerprint, |
| 3437 | RouteBillingMode::Metered, |
| 3438 | now, |
| 3439 | ) |
| 3440 | .audit(&usage); |
| 3441 | assert!(!generic.is_priced(), "{generic:?}"); |
| 3442 | // The endpoint fingerprint establishes Baseten's billing contract no |
| 3443 | // matter the table name, so the failure is an unverified price for |
| 3444 | // this identity — not an unknown basis (#6289). |
| 3445 | assert_eq!( |
| 3446 | generic.unpriced_reason, |
| 3447 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3448 | ); |
| 3449 | |
| 3450 | let wrong_fingerprint = |
| 3451 | codewhale_config::catalog::base_url_fingerprint("https://proxy.example/v1"); |
| 3452 | let wrong_endpoint = custom_usage_envelope( |
| 3453 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3454 | model, |
| 3455 | &wrong_fingerprint, |
| 3456 | RouteBillingMode::Metered, |
| 3457 | now, |
| 3458 | ) |
| 3459 | .audit(&usage); |
| 3460 | assert!(!wrong_endpoint.is_priced(), "{wrong_endpoint:?}"); |
| 3461 | assert_eq!( |
| 3462 | wrong_endpoint.unpriced_reason, |
| 3463 | Some(crate::pricing::UnpricedReason::UnknownBillingBasis) |
| 3464 | ); |
| 3465 | } |
| 3466 | |
| 3467 | #[test] |
| 3468 | fn baseten_usage_rejects_unknown_stale_and_failed_live_catalogs() { |
| 3469 | let _env = crate::test_support::lock_test_env(); |
| 3470 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3471 | let home = tempfile::tempdir().expect("test home"); |
| 3472 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3473 | let _reset = ProviderCatalogTestReset; |
| 3474 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3475 | crate::provider_lake::clear_live_snapshot(); |
| 3476 | |
| 3477 | let now = Utc::now(); |
| 3478 | let now_unix = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 3479 | let model = "synthetic-baseten-status-model"; |
| 3480 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 3481 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3482 | ); |
| 3483 | let unknown_route = custom_usage_envelope( |
| 3484 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3485 | model, |
| 3486 | &fingerprint, |
| 3487 | RouteBillingMode::Unknown, |
| 3488 | now, |
| 3489 | ); |
| 3490 | assert!(unknown_route.provider_live_pricing.is_none()); |
| 3491 | let usage = Usage { |
| 3492 | input_tokens: 1_000_000, |
| 3493 | ..Usage::default() |
| 3494 | }; |
| 3495 | |
| 3496 | // A same-model price owned by another custom partition cannot price a |
| 3497 | // Baseten receipt whose exact catalog was never refreshed. |
| 3498 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3499 | "other-custom", |
| 3500 | model, |
| 3501 | &fingerprint, |
| 3502 | now_unix, |
| 3503 | )); |
| 3504 | let unknown = unknown_route.audit(&usage); |
| 3505 | assert!(!unknown.is_priced(), "{unknown:?}"); |
| 3506 | assert_eq!( |
| 3507 | unknown.unpriced_reason, |
| 3508 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3509 | ); |
| 3510 | |
| 3511 | let stale_at = now_unix |
| 3512 | .saturating_sub(crate::provider_catalog_live::DEFAULT_PROVIDER_CATALOG_TTL_SECS) |
| 3513 | .saturating_sub(1); |
| 3514 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3515 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3516 | model, |
| 3517 | &fingerprint, |
| 3518 | stale_at, |
| 3519 | )); |
| 3520 | let stale_route = custom_usage_envelope( |
| 3521 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3522 | model, |
| 3523 | &fingerprint, |
| 3524 | RouteBillingMode::Unknown, |
| 3525 | now, |
| 3526 | ); |
| 3527 | assert!(stale_route.provider_live_pricing.is_none()); |
| 3528 | let stale = stale_route.audit(&usage); |
| 3529 | assert!(!stale.is_priced(), "{stale:?}"); |
| 3530 | assert_eq!( |
| 3531 | stale.unpriced_reason, |
| 3532 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3533 | ); |
| 3534 | |
| 3535 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3536 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3537 | model, |
| 3538 | &fingerprint, |
| 3539 | now_unix, |
| 3540 | )); |
| 3541 | crate::provider_catalog_live::record_failure( |
| 3542 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3543 | &fingerprint, |
| 3544 | codewhale_config::catalog::CatalogRefreshError::Network, |
| 3545 | ); |
| 3546 | let failed_route = custom_usage_envelope( |
| 3547 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3548 | model, |
| 3549 | &fingerprint, |
| 3550 | RouteBillingMode::Unknown, |
| 3551 | now, |
| 3552 | ); |
| 3553 | assert!(failed_route.provider_live_pricing.is_none()); |
| 3554 | let failed = failed_route.audit(&usage); |
| 3555 | assert!(!failed.is_priced(), "{failed:?}"); |
| 3556 | assert_eq!( |
| 3557 | failed.unpriced_reason, |
| 3558 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3559 | ); |
| 3560 | } |
| 3561 | |
| 3562 | #[test] |
| 3563 | fn reviewed_provider_live_quotes_survive_same_second_refresh_and_key_state_changes() { |
| 3564 | let _env = crate::test_support::lock_test_env(); |
| 3565 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3566 | let home = tempfile::tempdir().expect("test home"); |
| 3567 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3568 | let _reset = ProviderCatalogTestReset; |
| 3569 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3570 | crate::provider_lake::clear_live_snapshot(); |
| 3571 | |
| 3572 | let now = Utc::now(); |
| 3573 | let fetched_at = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 3574 | let cases = [ |
| 3575 | ( |
| 3576 | ProviderKind::Openrouter, |
| 3577 | ProviderKind::Openrouter.as_str(), |
| 3578 | "synthetic-openrouter-frozen-price", |
| 3579 | codewhale_config::catalog::base_url_fingerprint( |
| 3580 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3581 | ), |
| 3582 | crate::pricing::AGGREGATOR_BILLING_SURFACE, |
| 3583 | RouteBillingMode::Metered, |
| 3584 | ), |
| 3585 | ( |
| 3586 | ProviderKind::Custom, |
| 3587 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3588 | "synthetic-baseten-frozen-price", |
| 3589 | codewhale_config::catalog::base_url_fingerprint( |
| 3590 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3591 | ), |
| 3592 | crate::pricing::UNCLASSIFIED_BILLING_SURFACE, |
| 3593 | RouteBillingMode::Unknown, |
| 3594 | ), |
| 3595 | ]; |
| 3596 | let usage = Usage { |
| 3597 | input_tokens: 1_000_000, |
| 3598 | ..Usage::default() |
| 3599 | }; |
| 3600 | |
| 3601 | for (provider, identity, model, fingerprint, surface, mode) in cases { |
| 3602 | crate::provider_catalog_live::record_success(priced_provider_delta_with_rates( |
| 3603 | identity, |
| 3604 | model, |
| 3605 | &fingerprint, |
| 3606 | fetched_at, |
| 3607 | 1.25, |
| 3608 | 5.0, |
| 3609 | )); |
| 3610 | let first = provider_live_usage_envelope( |
| 3611 | provider, |
| 3612 | identity, |
| 3613 | model, |
| 3614 | &fingerprint, |
| 3615 | Some(surface), |
| 3616 | mode, |
| 3617 | now, |
| 3618 | ); |
| 3619 | let first_quote = first |
| 3620 | .provider_live_pricing |
| 3621 | .as_ref() |
| 3622 | .expect("fresh exact scope freezes a quote"); |
| 3623 | |
| 3624 | // A second refresh in the same Unix second must still be a distinct |
| 3625 | // catalog revision and must not retroactively change `first`. |
| 3626 | crate::provider_catalog_live::record_success(priced_provider_delta_with_rates( |
| 3627 | identity, |
| 3628 | model, |
| 3629 | &fingerprint, |
| 3630 | fetched_at, |
| 3631 | 9.5, |
| 3632 | 19.0, |
| 3633 | )); |
| 3634 | let second = provider_live_usage_envelope( |
| 3635 | provider, |
| 3636 | identity, |
| 3637 | model, |
| 3638 | &fingerprint, |
| 3639 | Some(surface), |
| 3640 | mode, |
| 3641 | now, |
| 3642 | ); |
| 3643 | let second_quote = second |
| 3644 | .provider_live_pricing |
| 3645 | .as_ref() |
| 3646 | .expect("replacement fresh scope freezes a quote"); |
| 3647 | assert_ne!( |
| 3648 | first_quote.catalog_revision, second_quote.catalog_revision, |
| 3649 | "same-second price changes need distinct revisions" |
| 3650 | ); |
| 3651 | |
| 3652 | crate::provider_catalog_live::record_failure( |
| 3653 | identity, |
| 3654 | &fingerprint, |
| 3655 | codewhale_config::catalog::CatalogRefreshError::Unauthorized, |
| 3656 | ); |
| 3657 | if provider == ProviderKind::Custom { |
| 3658 | // Baseten's same URL can represent another account after a key |
| 3659 | // switch. Starting that refresh clears the mutable old scope. |
| 3660 | let _new_key_refresh = crate::provider_catalog_live::begin_refresh_for_identity( |
| 3661 | provider, |
| 3662 | identity, |
| 3663 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3664 | ); |
| 3665 | } |
| 3666 | |
| 3667 | let first_audit = first.audit(&usage); |
| 3668 | let second_audit = second.audit(&usage); |
| 3669 | assert_eq!(first_audit.estimate.expect("first quote priced").usd, 1.25); |
| 3670 | assert_eq!(second_audit.estimate.expect("second quote priced").usd, 9.5); |
| 3671 | |
| 3672 | let after_mutation = provider_live_usage_envelope( |
| 3673 | provider, |
| 3674 | identity, |
| 3675 | model, |
| 3676 | &fingerprint, |
| 3677 | Some(surface), |
| 3678 | mode, |
| 3679 | now, |
| 3680 | ); |
| 3681 | assert!( |
| 3682 | after_mutation.provider_live_pricing.is_none(), |
| 3683 | "failed or cleared mutable state cannot mint a new quote" |
| 3684 | ); |
| 3685 | } |
| 3686 | } |
| 3687 | |
| 3688 | #[test] |
| 3689 | fn legacy_no_quote_receipts_cannot_be_retro_priced_by_a_later_refresh() { |
| 3690 | let _env = crate::test_support::lock_test_env(); |
| 3691 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3692 | let home = tempfile::tempdir().expect("test home"); |
| 3693 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3694 | let _reset = ProviderCatalogTestReset; |
| 3695 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3696 | crate::provider_lake::clear_live_snapshot(); |
| 3697 | |
| 3698 | let now = Utc::now(); |
| 3699 | let fetched_at = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 3700 | let routes = [ |
| 3701 | provider_live_usage_envelope( |
| 3702 | ProviderKind::Openrouter, |
| 3703 | ProviderKind::Openrouter.as_str(), |
| 3704 | "synthetic-openrouter-legacy", |
| 3705 | &codewhale_config::catalog::base_url_fingerprint( |
| 3706 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3707 | ), |
| 3708 | Some(crate::pricing::AGGREGATOR_BILLING_SURFACE), |
| 3709 | RouteBillingMode::Metered, |
| 3710 | now, |
| 3711 | ), |
| 3712 | custom_usage_envelope( |
| 3713 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3714 | "synthetic-baseten-legacy", |
| 3715 | &codewhale_config::catalog::base_url_fingerprint( |
| 3716 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3717 | ), |
| 3718 | RouteBillingMode::Unknown, |
| 3719 | now, |
| 3720 | ), |
| 3721 | ]; |
| 3722 | assert!( |
| 3723 | routes |
| 3724 | .iter() |
| 3725 | .all(|route| route.provider_live_pricing.is_none()) |
| 3726 | ); |
| 3727 | |
| 3728 | for route in &routes { |
| 3729 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3730 | &route.provider_identity, |
| 3731 | &route.model, |
| 3732 | route.endpoint_fingerprint.as_deref().expect("fingerprint"), |
| 3733 | fetched_at, |
| 3734 | )); |
| 3735 | let audit = route.audit(&Usage { |
| 3736 | input_tokens: 1_000_000, |
| 3737 | ..Usage::default() |
| 3738 | }); |
| 3739 | assert_eq!( |
| 3740 | audit.unpriced_reason, |
| 3741 | Some(if route.provider == ProviderKind::Openrouter { |
| 3742 | crate::pricing::UnpricedReason::NoPricingRow |
| 3743 | } else { |
| 3744 | crate::pricing::UnpricedReason::UnverifiedLivePricing |
| 3745 | }), |
| 3746 | "a completion-time refresh must not price {route:?}" |
| 3747 | ); |
| 3748 | } |
| 3749 | } |
| 3750 | |
| 3751 | #[test] |
| 3752 | fn openrouter_offline_bundled_price_is_immutable_after_dispatch() { |
| 3753 | let _env = crate::test_support::lock_test_env(); |
| 3754 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3755 | let home = tempfile::tempdir().expect("test home"); |
| 3756 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3757 | let _reset = ProviderCatalogTestReset; |
| 3758 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3759 | crate::provider_lake::clear_live_snapshot(); |
| 3760 | |
| 3761 | let dispatched_at = Utc::now(); |
| 3762 | let fetched_at = u64::try_from(dispatched_at.timestamp()).expect("timestamp"); |
| 3763 | let model = "qwen/qwen3.8-flash"; |
| 3764 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 3765 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3766 | ); |
| 3767 | let route = provider_live_usage_envelope( |
| 3768 | ProviderKind::Openrouter, |
| 3769 | ProviderKind::Openrouter.as_str(), |
| 3770 | model, |
| 3771 | &fingerprint, |
| 3772 | Some(crate::pricing::AGGREGATOR_BILLING_SURFACE), |
| 3773 | RouteBillingMode::Metered, |
| 3774 | dispatched_at, |
| 3775 | ); |
| 3776 | assert!(route.provider_live_pricing.is_none()); |
| 3777 | |
| 3778 | let usage = Usage { |
| 3779 | input_tokens: 1_000_000, |
| 3780 | ..Usage::default() |
| 3781 | }; |
| 3782 | let offline = route.audit(&usage); |
| 3783 | assert_eq!( |
| 3784 | offline.estimate.expect("bundled OpenRouter price").usd, |
| 3785 | 0.15 |
| 3786 | ); |
| 3787 | assert_eq!( |
| 3788 | offline.provenance, |
| 3789 | Some(codewhale_config::pricing::PricingProvenance::ModelsDevBundled) |
| 3790 | ); |
| 3791 | |
| 3792 | // A later mutable refresh cannot change a turn that had no quote at |
| 3793 | // the application-dispatch boundary. |
| 3794 | crate::provider_catalog_live::record_success(priced_provider_delta_with_rates( |
| 3795 | ProviderKind::Openrouter.as_str(), |
| 3796 | model, |
| 3797 | &fingerprint, |
| 3798 | fetched_at, |
| 3799 | 19.0, |
| 3800 | 29.0, |
| 3801 | )); |
| 3802 | let after_refresh = route.audit(&usage); |
| 3803 | assert_eq!(after_refresh, offline); |
| 3804 | |
| 3805 | // Admission without provider usage does not create a charge. |
| 3806 | let no_usage = route.audit(&Usage::default()); |
| 3807 | let no_usage_estimate = no_usage.estimate.expect("known zero usage is priced"); |
| 3808 | assert_eq!(no_usage_estimate.usd, 0.0); |
| 3809 | assert_eq!(no_usage_estimate.cny, 0.0); |
| 3810 | } |
| 3811 | |
| 3812 | #[test] |
| 3813 | fn provider_live_quotes_reject_future_prices_and_every_route_binding_mismatch() { |
| 3814 | let _env = crate::test_support::lock_test_env(); |
| 3815 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3816 | let home = tempfile::tempdir().expect("test home"); |
| 3817 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3818 | let _reset = ProviderCatalogTestReset; |
| 3819 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3820 | crate::provider_lake::clear_live_snapshot(); |
| 3821 | |
| 3822 | let dispatched_at = Utc::now(); |
| 3823 | let dispatch_unix = u64::try_from(dispatched_at.timestamp()).expect("timestamp"); |
| 3824 | let future_at = dispatched_at + chrono::Duration::seconds(1); |
| 3825 | let future_unix = dispatch_unix.saturating_add(1); |
| 3826 | let cases = [ |
| 3827 | ( |
| 3828 | ProviderKind::Openrouter, |
| 3829 | ProviderKind::Openrouter.as_str(), |
| 3830 | "synthetic-openrouter-future", |
| 3831 | codewhale_config::catalog::base_url_fingerprint( |
| 3832 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 3833 | ), |
| 3834 | crate::pricing::AGGREGATOR_BILLING_SURFACE, |
| 3835 | RouteBillingMode::Metered, |
| 3836 | ), |
| 3837 | ( |
| 3838 | ProviderKind::Custom, |
| 3839 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3840 | "synthetic-baseten-future", |
| 3841 | codewhale_config::catalog::base_url_fingerprint( |
| 3842 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3843 | ), |
| 3844 | crate::pricing::UNCLASSIFIED_BILLING_SURFACE, |
| 3845 | RouteBillingMode::Unknown, |
| 3846 | ), |
| 3847 | ]; |
| 3848 | let usage = Usage { |
| 3849 | input_tokens: 1_000_000, |
| 3850 | ..Usage::default() |
| 3851 | }; |
| 3852 | |
| 3853 | for (provider, identity, model, fingerprint, surface, mode) in cases { |
| 3854 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3855 | identity, |
| 3856 | model, |
| 3857 | &fingerprint, |
| 3858 | future_unix, |
| 3859 | )); |
| 3860 | let no_future_quote = provider_live_usage_envelope( |
| 3861 | provider, |
| 3862 | identity, |
| 3863 | model, |
| 3864 | &fingerprint, |
| 3865 | Some(surface), |
| 3866 | mode, |
| 3867 | dispatched_at, |
| 3868 | ); |
| 3869 | assert!(no_future_quote.provider_live_pricing.is_none()); |
| 3870 | assert_eq!( |
| 3871 | no_future_quote.audit(&usage).unpriced_reason, |
| 3872 | Some(if provider == ProviderKind::Openrouter { |
| 3873 | crate::pricing::UnpricedReason::NoPricingRow |
| 3874 | } else { |
| 3875 | crate::pricing::UnpricedReason::UnverifiedLivePricing |
| 3876 | }) |
| 3877 | ); |
| 3878 | |
| 3879 | let captured = provider_live_usage_envelope( |
| 3880 | provider, |
| 3881 | identity, |
| 3882 | model, |
| 3883 | &fingerprint, |
| 3884 | Some(surface), |
| 3885 | mode, |
| 3886 | future_at, |
| 3887 | ); |
| 3888 | assert!(captured.provider_live_pricing.is_some()); |
| 3889 | |
| 3890 | let mut future_relative_to_dispatch = captured.clone(); |
| 3891 | future_relative_to_dispatch.dispatched_at = dispatched_at; |
| 3892 | assert_eq!( |
| 3893 | future_relative_to_dispatch.audit(&usage).unpriced_reason, |
| 3894 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3895 | ); |
| 3896 | let persisted = serde_json::to_value(&future_relative_to_dispatch) |
| 3897 | .expect("invalid future quote serializes only as absent"); |
| 3898 | assert!(persisted["provider_live_pricing"].is_null()); |
| 3899 | |
| 3900 | let mut wrong_model = captured.clone(); |
| 3901 | wrong_model.model.push_str("-other"); |
| 3902 | assert_eq!( |
| 3903 | wrong_model.audit(&usage).unpriced_reason, |
| 3904 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3905 | ); |
| 3906 | |
| 3907 | let mut wrong_identity = captured.clone(); |
| 3908 | wrong_identity.provider_identity.push_str("-other"); |
| 3909 | // The endpoint fingerprint still establishes the billing contract, |
| 3910 | // so a renamed identity fails quote verification (#6289). |
| 3911 | assert_eq!( |
| 3912 | wrong_identity.audit(&usage).unpriced_reason, |
| 3913 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 3914 | ); |
| 3915 | |
| 3916 | let mut wrong_endpoint = captured; |
| 3917 | wrong_endpoint.endpoint_fingerprint = Some( |
| 3918 | codewhale_config::catalog::base_url_fingerprint("https://proxy.example/v1"), |
| 3919 | ); |
| 3920 | assert_eq!( |
| 3921 | wrong_endpoint.audit(&usage).unpriced_reason, |
| 3922 | Some(if provider == ProviderKind::Custom { |
| 3923 | crate::pricing::UnpricedReason::UnknownBillingBasis |
| 3924 | } else { |
| 3925 | crate::pricing::UnpricedReason::UnverifiedLivePricing |
| 3926 | }) |
| 3927 | ); |
| 3928 | } |
| 3929 | } |
| 3930 | |
| 3931 | #[test] |
| 3932 | fn provider_live_quote_serialization_is_secret_free_and_legacy_compatible() { |
| 3933 | let _env = crate::test_support::lock_test_env(); |
| 3934 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3935 | let home = tempfile::tempdir().expect("test home"); |
| 3936 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3937 | let _reset = ProviderCatalogTestReset; |
| 3938 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3939 | crate::provider_lake::clear_live_snapshot(); |
| 3940 | |
| 3941 | let now = Utc::now(); |
| 3942 | let fetched_at = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 3943 | let model = "synthetic-baseten-serialized-quote"; |
| 3944 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 3945 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3946 | ); |
| 3947 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 3948 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3949 | model, |
| 3950 | &fingerprint, |
| 3951 | fetched_at, |
| 3952 | )); |
| 3953 | let route = custom_usage_envelope( |
| 3954 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 3955 | model, |
| 3956 | &fingerprint, |
| 3957 | RouteBillingMode::Unknown, |
| 3958 | now, |
| 3959 | ); |
| 3960 | assert!(route.provider_live_pricing.is_some()); |
| 3961 | |
| 3962 | let serialized = serde_json::to_string(&route).expect("serialize frozen route"); |
| 3963 | assert!(serialized.contains("provider_live_pricing")); |
| 3964 | assert!(serialized.contains("catalog_revision")); |
| 3965 | assert!(serialized.contains("input_per_million")); |
| 3966 | for secret in [ |
| 3967 | codewhale_config::catalog::BASETEN_BASE_URL, |
| 3968 | "api_key", |
| 3969 | "Bearer ", |
| 3970 | ] { |
| 3971 | // The assertion message must not itself become a logging sink for |
| 3972 | // the credential fragment it checks for — name the check, not the |
| 3973 | // secret. |
| 3974 | assert!( |
| 3975 | !serialized.contains(secret), |
| 3976 | "frozen route serialization leaked a credential fragment" |
| 3977 | ); |
| 3978 | } |
| 3979 | |
| 3980 | let mut child = serde_json::json!({}); |
| 3981 | attach_child_usage_metadata(&mut child, &route, &Usage::default()); |
| 3982 | let child_route = child_route_envelope_from_metadata(&child).expect("child route"); |
| 3983 | assert_eq!(child_route, route.sanitized_for_persistence()); |
| 3984 | |
| 3985 | let mut legacy: serde_json::Value = |
| 3986 | serde_json::from_str(&serialized).expect("route JSON value"); |
| 3987 | legacy |
| 3988 | .as_object_mut() |
| 3989 | .expect("route object") |
| 3990 | .remove("provider_live_pricing"); |
| 3991 | let legacy: EffectiveRouteEnvelope = |
| 3992 | serde_json::from_value(legacy).expect("legacy route remains readable"); |
| 3993 | assert!(legacy.provider_live_pricing.is_none()); |
| 3994 | let audit = legacy.audit(&Usage { |
| 3995 | input_tokens: 1_000_000, |
| 3996 | ..Usage::default() |
| 3997 | }); |
| 3998 | assert_eq!( |
| 3999 | audit.unpriced_reason, |
| 4000 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 4001 | ); |
| 4002 | |
| 4003 | let mut wrong_model = route.clone(); |
| 4004 | wrong_model.model.push_str("-other"); |
| 4005 | assert_eq!( |
| 4006 | wrong_model.audit(&Usage::default()).unpriced_reason, |
| 4007 | Some(crate::pricing::UnpricedReason::UnverifiedLivePricing) |
| 4008 | ); |
| 4009 | } |
| 4010 | |
| 4011 | #[test] |
| 4012 | fn routed_child_batch_is_preferred_bounded_and_sanitized() { |
| 4013 | let route = deepseek_envelope(); |
| 4014 | let records = vec![ |
| 4015 | RuntimeUsageRecord::legacy( |
| 4016 | "raw-provider-response-id-one".to_string(), |
| 4017 | EffectiveRouteUsage { |
| 4018 | route: route.clone(), |
| 4019 | usage: Usage { |
| 4020 | input_tokens: 11, |
| 4021 | ..Usage::default() |
| 4022 | }, |
| 4023 | }, |
| 4024 | ), |
| 4025 | RuntimeUsageRecord::legacy( |
| 4026 | "raw-provider-response-id-two".to_string(), |
| 4027 | EffectiveRouteUsage { |
| 4028 | route: route.clone(), |
| 4029 | usage: Usage { |
| 4030 | output_tokens: 7, |
| 4031 | ..Usage::default() |
| 4032 | }, |
| 4033 | }, |
| 4034 | ), |
| 4035 | ]; |
| 4036 | let mut metadata = serde_json::json!({}); |
| 4037 | attach_child_usage_metadata(&mut metadata, &route, &Usage::default()); |
| 4038 | attach_child_usage_batch_metadata( |
| 4039 | &mut metadata, |
| 4040 | &RuntimeUsageBatch { |
| 4041 | decisions: Vec::new(), |
| 4042 | records, |
| 4043 | drop_records: Vec::new(), |
| 4044 | dropped_records: 0, |
| 4045 | }, |
| 4046 | ); |
| 4047 | |
| 4048 | let serialized = serde_json::to_string(&metadata).expect("batch metadata"); |
| 4049 | assert!(!serialized.contains("raw-provider-response-id")); |
| 4050 | let batch = child_usage_records_from_metadata(&metadata).expect("preferred batch"); |
| 4051 | assert_eq!(batch.records.len(), 2); |
| 4052 | assert_eq!(batch.records[0].usage.usage.input_tokens, 11); |
| 4053 | assert_eq!(batch.records[1].usage.usage.output_tokens, 7); |
| 4054 | assert_eq!(batch.dropped_records, 0); |
| 4055 | |
| 4056 | metadata[CHILD_USAGE_RECORDS_KEY] = serde_json::json!([{"bad": true}]); |
| 4057 | let malformed = child_usage_records_from_metadata(&metadata).expect("batch key wins"); |
| 4058 | assert!(malformed.records.is_empty()); |
| 4059 | assert_eq!(malformed.dropped_records, 1); |
| 4060 | } |
| 4061 | |
| 4062 | #[test] |
| 4063 | fn decision_receipts_metadata_round_trip_is_bounded_and_legacy_compatible() { |
| 4064 | let receipt = decision_receipt_fixture("raw-child-decision-id"); |
| 4065 | let mut metadata = serde_json::json!({}); |
| 4066 | attach_child_usage_batch_metadata( |
| 4067 | &mut metadata, |
| 4068 | &RuntimeUsageBatch { |
| 4069 | decisions: vec![receipt.clone()], |
| 4070 | ..Default::default() |
| 4071 | }, |
| 4072 | ); |
| 4073 | assert!(!metadata.to_string().contains("raw-child-decision-id")); |
| 4074 | let decoded = child_usage_records_from_metadata(&metadata).expect("batch"); |
| 4075 | assert_eq!(decoded.decisions, vec![receipt.sanitized()]); |
| 4076 | assert_eq!(decoded.dropped_records, 0); |
| 4077 | metadata[CHILD_DECISION_RECEIPTS_KEY][0]["evidence"]["response_model"] = |
| 4078 | serde_json::json!("x".repeat(129)); |
| 4079 | let invalid = child_usage_records_from_metadata(&metadata).expect("batch"); |
| 4080 | assert!(invalid.decisions.is_empty()); |
| 4081 | assert_eq!(invalid.dropped_records, 1); |
| 4082 | metadata |
| 4083 | .as_object_mut() |
| 4084 | .expect("metadata") |
| 4085 | .remove(CHILD_DECISION_RECEIPTS_KEY); |
| 4086 | assert!( |
| 4087 | child_usage_records_from_metadata(&metadata) |
| 4088 | .expect("old batch") |
| 4089 | .decisions |
| 4090 | .is_empty() |
| 4091 | ); |
| 4092 | let mut oversized = receipt; |
| 4093 | oversized.evidence.response_model = Some("x".repeat(129)); |
| 4094 | attach_child_usage_batch_metadata( |
| 4095 | &mut metadata, |
| 4096 | &RuntimeUsageBatch { |
| 4097 | decisions: vec![oversized], |
| 4098 | ..Default::default() |
| 4099 | }, |
| 4100 | ); |
| 4101 | let invalid = child_usage_records_from_metadata(&metadata).expect("bounded batch"); |
| 4102 | assert!(invalid.decisions.is_empty()); |
| 4103 | assert_eq!( |
| 4104 | invalid.dropped_records, 1, |
| 4105 | "discarded evidence must leave an explicit coverage gap" |
| 4106 | ); |
| 4107 | } |
| 4108 | |
| 4109 | fn deepseek() -> BackgroundRoute<'static> { |
| 4110 | BackgroundRoute::new(ProviderKind::Deepseek, "deepseek-v4-flash").with_base_url(Some( |
| 4111 | codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL, |
| 4112 | )) |
| 4113 | } |
| 4114 | |
| 4115 | fn deepseek_envelope() -> EffectiveRouteEnvelope { |
| 4116 | let config = codewhale_runtime::config::Config::default(); |
| 4117 | let identity = config |
| 4118 | .active_provider_identity() |
| 4119 | .expect("captured DeepSeek identity"); |
| 4120 | EffectiveRouteEnvelope::from_admitted( |
| 4121 | Some(&config), |
| 4122 | &identity, |
| 4123 | "deepseek-v4-flash", |
| 4124 | Some(codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL), |
| 4125 | Utc::now(), |
| 4126 | ) |
| 4127 | } |
| 4128 | |
| 4129 | #[test] |
| 4130 | fn child_cache_classes_reach_the_background_pool_only_when_reported() { |
| 4131 | // #6565: sub-agent cache was missing from session totals. |
| 4132 | let reported = background_cost_for_runtime_usage(&RuntimeUsageRecord::legacy( |
| 4133 | "child-cache-reported", |
| 4134 | EffectiveRouteUsage { |
| 4135 | route: deepseek_envelope(), |
| 4136 | usage: Usage { |
| 4137 | input_tokens: 1_000, |
| 4138 | output_tokens: 50, |
| 4139 | prompt_cache_hit_tokens: Some(700), |
| 4140 | prompt_cache_miss_tokens: Some(300), |
| 4141 | ..Usage::default() |
| 4142 | }, |
| 4143 | }, |
| 4144 | )); |
| 4145 | assert_eq!(reported.cache_hit_tokens, Some(700)); |
| 4146 | assert_eq!(reported.cache_miss_tokens, Some(300)); |
| 4147 | assert_eq!(reported.cache_write_tokens, Some(0)); |
| 4148 | |
| 4149 | let silent = background_cost_for_runtime_usage(&RuntimeUsageRecord::legacy( |
| 4150 | "child-cache-silent", |
| 4151 | EffectiveRouteUsage { |
| 4152 | route: deepseek_envelope(), |
| 4153 | usage: Usage { |
| 4154 | input_tokens: 1_000, |
| 4155 | output_tokens: 50, |
| 4156 | ..Usage::default() |
| 4157 | }, |
| 4158 | }, |
| 4159 | )); |
| 4160 | assert_eq!(silent.cache_hit_tokens, None, "no report is not 0%"); |
| 4161 | assert_eq!(silent.cache_miss_tokens, None); |
| 4162 | } |
| 4163 | |
| 4164 | #[test] |
| 4165 | fn background_cache_write_only_telemetry_is_recorded() { |
| 4166 | for written in [0, 400] { |
| 4167 | let pending = background_cost_for_runtime_usage(&RuntimeUsageRecord::legacy( |
| 4168 | "child-cache-write-only", |
| 4169 | EffectiveRouteUsage { |
| 4170 | route: deepseek_envelope(), |
| 4171 | usage: Usage { |
| 4172 | input_tokens: 1_000, |
| 4173 | prompt_cache_write_tokens: Some(written), |
| 4174 | ..Usage::default() |
| 4175 | }, |
| 4176 | }, |
| 4177 | )); |
| 4178 | assert_eq!(pending.cache_hit_tokens, Some(0)); |
| 4179 | assert_eq!(pending.cache_miss_tokens, Some(u64::from(1_000 - written))); |
| 4180 | assert_eq!(pending.cache_write_tokens, Some(u64::from(written))); |
| 4181 | } |
| 4182 | } |
| 4183 | |
| 4184 | #[test] |
| 4185 | fn default_usage_is_one_missing_receipt_across_canonical_replay_and_owners() { |
| 4186 | let _g = test_scope(); |
| 4187 | let route = deepseek_envelope(); |
| 4188 | let raw = "compaction:turn:response"; |
| 4189 | let fingerprint = usage_source_fingerprint(raw); |
| 4190 | let encoded = format!("routed:{fingerprint}"); |
| 4191 | for source in [raw, fingerprint.as_str(), encoded.as_str()] { |
| 4192 | record_runtime_usage( |
| 4193 | scope_token(), |
| 4194 | None, |
| 4195 | &RuntimeUsageRecord::legacy( |
| 4196 | source, |
| 4197 | EffectiveRouteUsage { |
| 4198 | route: route.clone(), |
| 4199 | usage: Usage::default(), |
| 4200 | }, |
| 4201 | ), |
| 4202 | ); |
| 4203 | } |
| 4204 | let missing = drain(); |
| 4205 | assert_eq!(missing.source_records.len(), 1); |
| 4206 | assert_eq!( |
| 4207 | missing.usage_source_fingerprints, |
| 4208 | BTreeSet::from([fingerprint.clone()]) |
| 4209 | ); |
| 4210 | let contrib = UsageSourceContribution::for_record(&missing.source_records[0]); |
| 4211 | assert_eq!(contrib.priced, 0); |
| 4212 | assert_eq!(contrib.unpriced, 1); |
| 4213 | assert_eq!(contrib.cny_unpriced, 1); |
| 4214 | |
| 4215 | record_runtime_usage( |
| 4216 | scope_token(), |
| 4217 | None, |
| 4218 | &RuntimeUsageRecord::legacy( |
| 4219 | &encoded, |
| 4220 | EffectiveRouteUsage { |
| 4221 | route: route.clone(), |
| 4222 | usage: Usage::default(), |
| 4223 | }, |
| 4224 | ), |
| 4225 | ); |
| 4226 | assert!( |
| 4227 | drain().is_empty(), |
| 4228 | "replayed metadata must stay consumed after drain" |
| 4229 | ); |
| 4230 | |
| 4231 | let recorded_owner = Arc::new(Mutex::new(Vec::new())); |
| 4232 | let recorded_sink = Arc::clone(&recorded_owner); |
| 4233 | let origin = NativeUsageOrigin::captured_runtime( |
| 4234 | scope_token(), |
| 4235 | "runtime-default-usage-owner".to_string(), |
| 4236 | Arc::new(move |record| { |
| 4237 | recorded_sink.lock().unwrap().push(record); |
| 4238 | true |
| 4239 | }), |
| 4240 | ); |
| 4241 | for source in [raw, fingerprint.as_str(), encoded.as_str()] { |
| 4242 | record_runtime_usage( |
| 4243 | scope_token(), |
| 4244 | Some(&origin), |
| 4245 | &RuntimeUsageRecord::legacy( |
| 4246 | source, |
| 4247 | EffectiveRouteUsage { |
| 4248 | route: route.clone(), |
| 4249 | usage: Usage::default(), |
| 4250 | }, |
| 4251 | ), |
| 4252 | ); |
| 4253 | } |
| 4254 | assert_eq!(recorded_owner.lock().unwrap().len(), 3); |
| 4255 | assert!(drain().is_empty()); |
| 4256 | |
| 4257 | for billing_mode in [RouteBillingMode::Subscription, RouteBillingMode::Local] { |
| 4258 | let mut nonmetered = route.clone(); |
| 4259 | nonmetered.billing_mode = billing_mode; |
| 4260 | let cost = background_cost_for_runtime_usage(&RuntimeUsageRecord::legacy( |
| 4261 | raw, |
| 4262 | EffectiveRouteUsage { |
| 4263 | route: nonmetered, |
| 4264 | usage: Usage::default(), |
| 4265 | }, |
| 4266 | )); |
| 4267 | let c = UsageSourceContribution::for_record(&cost.source_records[0]); |
| 4268 | assert_eq!(c.unpriced, 0); |
| 4269 | assert_eq!(c.cny_unpriced, 0); |
| 4270 | assert_eq!(cost.usage_source_fingerprints.len(), 1); |
| 4271 | } |
| 4272 | |
| 4273 | let tmp = tempfile::tempdir().unwrap(); |
| 4274 | let manager = |
| 4275 | crate::session_manager::SessionManager::new(tmp.path().join("sessions")).unwrap(); |
| 4276 | let session = crate::session_manager::create_saved_session_with_id_and_mode( |
| 4277 | "missing-origin".into(), |
| 4278 | &[], |
| 4279 | "deepseek-v4-flash", |
| 4280 | tmp.path(), |
| 4281 | 0, |
| 4282 | None, |
| 4283 | Some("agent"), |
| 4284 | ); |
| 4285 | manager.save_session(&session).unwrap(); |
| 4286 | let origin_scope = scope_token(); |
| 4287 | assert!(close_current_scope().is_empty()); |
| 4288 | assert!(report_effective_route_for_interactive_origin_with_manager( |
| 4289 | origin_scope, |
| 4290 | "missing-origin", |
| 4291 | "turn", |
| 4292 | raw, |
| 4293 | &route, |
| 4294 | &Usage::default(), |
| 4295 | &manager, |
| 4296 | )); |
| 4297 | for _ in 0..2 { |
| 4298 | let snapshot = manager.load_session_snapshot("missing-origin").unwrap(); |
| 4299 | assert_eq!(snapshot.metadata.total_tokens, 0); |
| 4300 | assert_eq!(snapshot.metadata.cost.priced_turns, 0); |
| 4301 | assert_eq!(snapshot.metadata.cost.unpriced_turns, 1); |
| 4302 | assert_eq!(snapshot.metadata.cost.cny_unpriced_turns, 1); |
| 4303 | assert_eq!(snapshot.metadata.cost.usage_source_fingerprints.len(), 1); |
| 4304 | manager.save_session(&snapshot).unwrap(); |
| 4305 | } |
| 4306 | assert!(drain().is_empty()); |
| 4307 | } |
| 4308 | |
| 4309 | #[test] |
| 4310 | fn openrouter_vendor_pin_does_not_inherit_aggregate_catalog_price() { |
| 4311 | let _env = crate::test_support::lock_test_env(); |
| 4312 | let home = tempfile::tempdir().expect("isolated catalog home"); |
| 4313 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 4314 | let _reset = ProviderCatalogTestReset; |
| 4315 | crate::provider_catalog_live::reset_cache_for_test(); |
| 4316 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 4317 | crate::provider_lake::clear_live_snapshot(); |
| 4318 | let mut route = EffectiveRouteEnvelope::capture( |
| 4319 | None, |
| 4320 | ProviderKind::Openrouter, |
| 4321 | "openrouter", |
| 4322 | "qwen/qwen3.7-plus", |
| 4323 | Some(ProviderKind::Openrouter.provider().default_base_url()), |
| 4324 | Utc::now(), |
| 4325 | ); |
| 4326 | let usage = small_usage(); |
| 4327 | let aggregate = route.audit(&usage); |
| 4328 | assert!( |
| 4329 | aggregate.is_priced(), |
| 4330 | "aggregate fixture must be priced: {aggregate:?}" |
| 4331 | ); |
| 4332 | |
| 4333 | route.openrouter_vendor = Some("cerebras".to_string()); |
| 4334 | let audit = route.audit(&usage); |
| 4335 | assert_eq!( |
| 4336 | audit.unpriced_reason, |
| 4337 | Some(crate::pricing::UnpricedReason::RoutingDependentPrice) |
| 4338 | ); |
| 4339 | assert!(audit.estimate.is_none()); |
| 4340 | assert!(audit.counts_toward_money_coverage()); |
| 4341 | assert!(route.receipt(&audit).contains("openrouter_vendor=cerebras")); |
| 4342 | |
| 4343 | // Even a valid, frozen aggregate quote has no upstream-vendor dimension. |
| 4344 | let fingerprint = route |
| 4345 | .endpoint_fingerprint |
| 4346 | .clone() |
| 4347 | .expect("official endpoint"); |
| 4348 | let dispatched_at = u64::try_from(route.dispatched_at.timestamp()).expect("timestamp"); |
| 4349 | crate::provider_catalog_live::record_success(priced_provider_delta( |
| 4350 | "openrouter", |
| 4351 | &route.model, |
| 4352 | &fingerprint, |
| 4353 | dispatched_at, |
| 4354 | )); |
| 4355 | route.provider_live_pricing = |
| 4356 | crate::provider_catalog_live::fresh_provider_live_pricing_quote_at( |
| 4357 | route.provider, |
| 4358 | &route.provider_identity, |
| 4359 | &route.model, |
| 4360 | &fingerprint, |
| 4361 | dispatched_at, |
| 4362 | ); |
| 4363 | assert!(route.provider_live_pricing.is_some()); |
| 4364 | let saved: EffectiveRouteEnvelope = |
| 4365 | serde_json::from_value(serde_json::to_value(&route).unwrap()).unwrap(); |
| 4366 | let child = child_route_envelope_from_metadata(&serde_json::Value::Object( |
| 4367 | child_usage_metadata_fields(&saved, &usage), |
| 4368 | )) |
| 4369 | .expect("child envelope"); |
| 4370 | for receipt in [&route, &saved, &child] { |
| 4371 | assert_eq!( |
| 4372 | receipt.audit(&usage).unpriced_reason, |
| 4373 | Some(crate::pricing::UnpricedReason::RoutingDependentPrice) |
| 4374 | ); |
| 4375 | } |
| 4376 | |
| 4377 | for (billing_mode, reason) in [ |
| 4378 | ( |
| 4379 | RouteBillingMode::Subscription, |
| 4380 | crate::pricing::UnpricedReason::NotMoneyMetered, |
| 4381 | ), |
| 4382 | ( |
| 4383 | RouteBillingMode::Local, |
| 4384 | crate::pricing::UnpricedReason::NotMoneyMetered, |
| 4385 | ), |
| 4386 | ( |
| 4387 | RouteBillingMode::Unknown, |
| 4388 | crate::pricing::UnpricedReason::UnknownBillingBasis, |
| 4389 | ), |
| 4390 | ] { |
| 4391 | route.billing_mode = billing_mode; |
| 4392 | assert_eq!(route.audit(&usage).unpriced_reason, Some(reason)); |
| 4393 | } |
| 4394 | } |
| 4395 | |
| 4396 | #[test] |
| 4397 | fn openrouter_vendor_pin_survives_envelope_and_child_metadata_persistence() { |
| 4398 | let mut config = { |
| 4399 | let __cw_config_init_0_0 = Some("openrouter".to_string()); |
| 4400 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 4401 | Default::default(); |
| 4402 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 4403 | __cw_config_init_0_value |
| 4404 | }; |
| 4405 | config |
| 4406 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openrouter)) |
| 4407 | .unwrap() |
| 4408 | .vendor = Some("cerebras".to_string()); |
| 4409 | let route = EffectiveRouteEnvelope::capture( |
| 4410 | Some(&config), |
| 4411 | ProviderKind::Openrouter, |
| 4412 | "openrouter", |
| 4413 | "qwen/qwen3.7-plus", |
| 4414 | Some(ProviderKind::Openrouter.provider().default_base_url()), |
| 4415 | Utc::now(), |
| 4416 | ); |
| 4417 | config |
| 4418 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openrouter)) |
| 4419 | .unwrap() |
| 4420 | .vendor = None; |
| 4421 | assert_eq!(route.openrouter_vendor.as_deref(), Some("cerebras")); |
| 4422 | |
| 4423 | let mut json = serde_json::to_value(&route).expect("serialize route"); |
| 4424 | let restored: EffectiveRouteEnvelope = |
| 4425 | serde_json::from_value(json.clone()).expect("restore route"); |
| 4426 | assert_eq!(restored, route); |
| 4427 | let metadata = |
| 4428 | serde_json::Value::Object(child_usage_metadata_fields(&route, &small_usage())); |
| 4429 | assert_eq!(child_route_envelope_from_metadata(&metadata), Some(route)); |
| 4430 | |
| 4431 | json.as_object_mut() |
| 4432 | .expect("route object") |
| 4433 | .remove("openrouter_vendor"); |
| 4434 | let legacy: EffectiveRouteEnvelope = serde_json::from_value(json).expect("legacy route"); |
| 4435 | assert_eq!(legacy.openrouter_vendor, None); |
| 4436 | } |
| 4437 | |
| 4438 | #[test] |
| 4439 | fn child_metadata_round_trip_preserves_zero_and_reasoning_usage() { |
| 4440 | let route = deepseek_envelope(); |
| 4441 | let mut usage = Usage { |
| 4442 | input_tokens: 0, |
| 4443 | output_tokens: 9, |
| 4444 | reasoning_tokens: Some(7), |
| 4445 | reasoning_replay_tokens: Some(3), |
| 4446 | input_audio_tokens: Some(0), |
| 4447 | output_audio_tokens: Some(1), |
| 4448 | ..Usage::default() |
| 4449 | }; |
| 4450 | usage.request_usages.push(usage.clone()); |
| 4451 | let mut metadata = serde_json::json!({"tool": "rlm_eval"}); |
| 4452 | attach_child_usage_metadata(&mut metadata, &route, &usage); |
| 4453 | |
| 4454 | assert_eq!(child_route_envelope_from_metadata(&metadata), Some(route)); |
| 4455 | assert_eq!(child_usage_from_metadata(&metadata), Some(usage.clone())); |
| 4456 | metadata |
| 4457 | .as_object_mut() |
| 4458 | .unwrap() |
| 4459 | .remove("child_request_usages"); |
| 4460 | let mut legacy = usage.clone(); |
| 4461 | legacy.request_usages.clear(); |
| 4462 | assert_eq!(child_usage_from_metadata(&metadata), Some(legacy)); |
| 4463 | for malformed in [ |
| 4464 | serde_json::json!(null), |
| 4465 | serde_json::json!({}), |
| 4466 | serde_json::json!([{}]), |
| 4467 | serde_json::json!([{ "input_tokens": -1, "output_tokens": 9 }]), |
| 4468 | serde_json::json!([{ "input_tokens": 0, "output_tokens": 9, "request_usages": [{}] }]), |
| 4469 | serde_json::json!(vec![Usage::default(); 1025]), |
| 4470 | ] { |
| 4471 | metadata["child_request_usages"] = malformed; |
| 4472 | let decoded = child_usage_from_metadata(&metadata).unwrap(); |
| 4473 | assert!(matches!( |
| 4474 | codewhale_config::pricing::OfferingPricing::default() |
| 4475 | .quote_cost(&crate::pricing::token_usage_for_pricing(&decoded)), |
| 4476 | Err(codewhale_config::pricing::PricingQuoteError::InvalidUsage) |
| 4477 | )); |
| 4478 | } |
| 4479 | let pricing = codewhale_config::pricing::OfferingPricing { |
| 4480 | input_per_million: Some(1.0), |
| 4481 | output_per_million: Some(0.0), |
| 4482 | context_tiers: vec![ |
| 4483 | serde_json::from_value(serde_json::json!({ |
| 4484 | "tier": { "type": "context", "size": 200_000 }, |
| 4485 | "input": 2.0, |
| 4486 | "output": 0.0, |
| 4487 | })) |
| 4488 | .unwrap(), |
| 4489 | ], |
| 4490 | ..Default::default() |
| 4491 | }; |
| 4492 | let mut aggregate = Usage::default(); |
| 4493 | for _ in 0..3 { |
| 4494 | crate::core::turn::add_usage_to( |
| 4495 | &mut aggregate, |
| 4496 | &Usage { |
| 4497 | input_tokens: 100_000, |
| 4498 | ..Default::default() |
| 4499 | }, |
| 4500 | ); |
| 4501 | } |
| 4502 | let fields = child_usage_metadata_fields(&deepseek_envelope(), &aggregate); |
| 4503 | let mut decoded = child_usage_from_metadata(&serde_json::Value::Object(fields)).unwrap(); |
| 4504 | assert_eq!( |
| 4505 | pricing |
| 4506 | .quote_cost(&crate::pricing::token_usage_for_pricing(&decoded)) |
| 4507 | .unwrap() |
| 4508 | .amount, |
| 4509 | "0.3" |
| 4510 | ); |
| 4511 | decoded.request_usages.clear(); |
| 4512 | assert_eq!( |
| 4513 | pricing |
| 4514 | .quote_cost(&crate::pricing::token_usage_for_pricing(&decoded)) |
| 4515 | .unwrap() |
| 4516 | .amount, |
| 4517 | "0.6" |
| 4518 | ); |
| 4519 | |
| 4520 | let mut zero_metadata = serde_json::json!({}); |
| 4521 | let zero = Usage::default(); |
| 4522 | attach_child_usage_metadata(&mut zero_metadata, &deepseek_envelope(), &zero); |
| 4523 | assert_eq!(child_usage_from_metadata(&zero_metadata), Some(zero)); |
| 4524 | } |
| 4525 | |
| 4526 | #[test] |
| 4527 | fn runtime_owned_usage_is_isolated_from_tui_pool() { |
| 4528 | let _g = test_scope(); |
| 4529 | let route = deepseek_envelope(); |
| 4530 | let usage = small_usage(); |
| 4531 | let records_a = Arc::new(Mutex::new(Vec::new())); |
| 4532 | let records_b = Arc::new(Mutex::new(Vec::new())); |
| 4533 | let sink_a = Arc::clone(&records_a); |
| 4534 | let sink_b = Arc::clone(&records_b); |
| 4535 | let origin_a = NativeUsageOrigin::captured_runtime( |
| 4536 | scope_token(), |
| 4537 | "turn-a".to_string(), |
| 4538 | Arc::new(move |r| { |
| 4539 | sink_a.lock().unwrap().push(r); |
| 4540 | true |
| 4541 | }), |
| 4542 | ); |
| 4543 | let origin_b = NativeUsageOrigin::captured_runtime( |
| 4544 | scope_token(), |
| 4545 | "turn-b".to_string(), |
| 4546 | Arc::new(move |r| { |
| 4547 | sink_b.lock().unwrap().push(r); |
| 4548 | true |
| 4549 | }), |
| 4550 | ); |
| 4551 | let record_a = NativeUsageSource::capture("response-a", UsageSpendOwner::Auxiliary) |
| 4552 | .reported(&route, &usage); |
| 4553 | let record_b = NativeUsageSource::capture("response-b", UsageSpendOwner::Auxiliary) |
| 4554 | .reported(&route, &usage); |
| 4555 | record_runtime_usage(scope_token(), Some(&origin_a), &record_a); |
| 4556 | record_runtime_usage(scope_token(), Some(&origin_b), &record_b); |
| 4557 | |
| 4558 | assert_eq!(records_a.lock().unwrap().len(), 1); |
| 4559 | assert_eq!(records_b.lock().unwrap().len(), 1); |
| 4560 | assert!( |
| 4561 | drain().is_empty(), |
| 4562 | "runtime-owned usage must not enter TUI cost" |
| 4563 | ); |
| 4564 | |
| 4565 | let tui_record = NativeUsageSource::capture("response-tui", UsageSpendOwner::Auxiliary) |
| 4566 | .reported(&route, &usage); |
| 4567 | record_runtime_usage(scope_token(), None, &tui_record); |
| 4568 | assert_eq!( |
| 4569 | drain().source_records.len(), |
| 4570 | 1, |
| 4571 | "ownerless usage belongs to TUI" |
| 4572 | ); |
| 4573 | } |
| 4574 | |
| 4575 | #[test] |
| 4576 | fn route_labels_redact_local_paths_but_preserve_model_namespaces() { |
| 4577 | let route = EffectiveRouteEnvelope { |
| 4578 | openrouter_vendor: None, |
| 4579 | provider: ProviderKind::Openrouter, |
| 4580 | provider_identity: "/Users/alice/.config/provider-secret".to_string(), |
| 4581 | model: "/Volumes/private/checkpoints/model.gguf".to_string(), |
| 4582 | billing_surface: None, |
| 4583 | endpoint_fingerprint: None, |
| 4584 | provider_live_pricing: None, |
| 4585 | billing_mode: RouteBillingMode::Metered, |
| 4586 | dispatched_at: Utc::now(), |
| 4587 | }; |
| 4588 | let sanitized = route.sanitized_for_persistence(); |
| 4589 | assert_eq!(sanitized.provider_identity, "redacted-local-path"); |
| 4590 | assert_eq!(sanitized.model, "redacted-local-path"); |
| 4591 | let receipt = route.receipt(&TurnCostAudit::unpriced( |
| 4592 | crate::pricing::UnpricedReason::NoPricingRow, |
| 4593 | )); |
| 4594 | assert!(!receipt.contains("alice")); |
| 4595 | assert!(!receipt.contains("Volumes")); |
| 4596 | |
| 4597 | assert_eq!( |
| 4598 | sanitize_persisted_route_label("anthropic/claude-sonnet-5"), |
| 4599 | "anthropic/claude-sonnet-5" |
| 4600 | ); |
| 4601 | } |
| 4602 | |
| 4603 | #[test] |
| 4604 | fn route_label_sanitizer_rejects_credentials_urls_and_relative_paths() { |
| 4605 | for credential in [ |
| 4606 | "Bearer secret-token", |
| 4607 | "Authorization: Basic abc123", |
| 4608 | "OPENAI_API_KEY=sk-secret", |
| 4609 | "service_token: ghp_secret", |
| 4610 | "hf_secret-token", |
| 4611 | "glpat-secret-token", |
| 4612 | "db-password=hunter2", |
| 4613 | "sk-live-secret", |
| 4614 | "https://alice:password@example.test/v1?api_key=secret#fragment", |
| 4615 | ] { |
| 4616 | let sanitized = sanitize_persisted_route_label(credential); |
| 4617 | assert!( |
| 4618 | sanitized.starts_with("redacted-"), |
| 4619 | "credential was not redacted: {credential:?} -> {sanitized:?}" |
| 4620 | ); |
| 4621 | } |
| 4622 | for path in [ |
| 4623 | ".ssh/id_ed25519", |
| 4624 | "../secrets/provider.key", |
| 4625 | "workspace/.ssh/config", |
| 4626 | "relative/path/to/credential", |
| 4627 | r"relative\path\credential", |
| 4628 | ] { |
| 4629 | assert_eq!( |
| 4630 | sanitize_persisted_route_label(path), |
| 4631 | "redacted-local-path", |
| 4632 | "path was not redacted: {path:?}" |
| 4633 | ); |
| 4634 | } |
| 4635 | assert_eq!( |
| 4636 | sanitize_persisted_route_label("moonshot/kimi-k3"), |
| 4637 | "moonshot/kimi-k3" |
| 4638 | ); |
| 4639 | } |
| 4640 | |
| 4641 | #[test] |
| 4642 | fn serialized_route_envelopes_records_and_child_receipts_are_secret_free() { |
| 4643 | let route = EffectiveRouteEnvelope { |
| 4644 | openrouter_vendor: Some("Authorization: Bearer vendor-secret".to_string()), |
| 4645 | provider: ProviderKind::Custom, |
| 4646 | provider_identity: "Authorization: Bearer provider-secret".to_string(), |
| 4647 | model: "MODEL_API_KEY=sk-model-secret".to_string(), |
| 4648 | billing_surface: Some( |
| 4649 | "https://alice:password@example.test/v1?token=secret#fragment".to_string(), |
| 4650 | ), |
| 4651 | endpoint_fingerprint: Some("../.ssh/provider_key".to_string()), |
| 4652 | provider_live_pricing: None, |
| 4653 | billing_mode: RouteBillingMode::Metered, |
| 4654 | dispatched_at: Utc::now(), |
| 4655 | }; |
| 4656 | let usage = Usage { |
| 4657 | input_tokens: 7, |
| 4658 | output_tokens: 3, |
| 4659 | ..Usage::default() |
| 4660 | }; |
| 4661 | |
| 4662 | let envelope_json = serde_json::to_string(&route).expect("serialize envelope"); |
| 4663 | let record_json = serde_json::to_string(&EffectiveRouteUsage { |
| 4664 | route: route.clone(), |
| 4665 | usage: usage.clone(), |
| 4666 | }) |
| 4667 | .expect("serialize route usage"); |
| 4668 | let child_json = serde_json::to_string(&child_usage_metadata_fields(&route, &usage)) |
| 4669 | .expect("serialize child receipt"); |
| 4670 | for serialized in [&envelope_json, &record_json, &child_json] { |
| 4671 | for secret in [ |
| 4672 | "vendor-secret", |
| 4673 | "provider-secret", |
| 4674 | "sk-model-secret", |
| 4675 | "alice", |
| 4676 | "password", |
| 4677 | "token=secret", |
| 4678 | ".ssh", |
| 4679 | ] { |
| 4680 | assert!( |
| 4681 | !serialized.contains(secret), |
| 4682 | "serialized route leaked {secret:?}: {serialized}" |
| 4683 | ); |
| 4684 | } |
| 4685 | } |
| 4686 | } |
| 4687 | |
| 4688 | #[test] |
| 4689 | fn report_adds_to_pool_and_drain_returns_then_resets() { |
| 4690 | let _g = test_scope(); |
| 4691 | report(scope_token(), &deepseek(), &small_usage()); |
| 4692 | let first = drain(); |
| 4693 | assert!( |
| 4694 | first.estimate.usd > 0.0, |
| 4695 | "expected positive USD cost, got {first:?}" |
| 4696 | ); |
| 4697 | assert!( |
| 4698 | first.estimate.cny > 0.0, |
| 4699 | "expected positive CNY cost, got {first:?}" |
| 4700 | ); |
| 4701 | assert_eq!(first.priced_turns, 1); |
| 4702 | assert_eq!(first.unpriced_turns, 0); |
| 4703 | assert_eq!(first.cny_priced_turns, 1); |
| 4704 | assert_eq!(first.cny_unpriced_turns, 0); |
| 4705 | // The receipt names the route without leaking the endpoint URL. |
| 4706 | assert_eq!(first.route_receipts.len(), 1); |
| 4707 | let receipt = first.route_receipts.iter().next().expect("receipt"); |
| 4708 | assert!(receipt.contains("provider=deepseek"), "{receipt}"); |
| 4709 | assert!(receipt.contains("model=deepseek-v4-flash"), "{receipt}"); |
| 4710 | assert!(receipt.contains("currency=usd+cny"), "{receipt}"); |
| 4711 | assert!(!receipt.contains("http"), "{receipt}"); |
| 4712 | |
| 4713 | let second = drain(); |
| 4714 | assert!(second.is_empty(), "drain must zero the pool: {second:?}"); |
| 4715 | } |
| 4716 | |
| 4717 | #[test] |
| 4718 | fn reports_from_a_closed_session_scope_are_discarded() { |
| 4719 | let _g = test_scope(); |
| 4720 | let old_scope = scope_token(); |
| 4721 | let settled = close_current_scope(); |
| 4722 | assert!(settled.is_empty()); |
| 4723 | |
| 4724 | report(old_scope, &deepseek(), &small_usage()); |
| 4725 | assert!(drain().is_empty(), "old session usage crossed the boundary"); |
| 4726 | |
| 4727 | report(scope_token(), &deepseek(), &small_usage()); |
| 4728 | assert_eq!(drain().priced_turns, 1); |
| 4729 | } |
| 4730 | |
| 4731 | #[test] |
| 4732 | fn retired_origin_suppresses_replay_without_accrual_or_scope_leak() { |
| 4733 | let _g = test_scope(); |
| 4734 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 4735 | let manager = crate::session_manager::SessionManager::new(tmp.path().join("sessions")) |
| 4736 | .expect("manager"); |
| 4737 | let session = crate::session_manager::create_saved_session_with_id_and_mode( |
| 4738 | "retired-origin".to_string(), |
| 4739 | &[], |
| 4740 | "deepseek-v4-flash", |
| 4741 | tmp.path(), |
| 4742 | 0, |
| 4743 | None, |
| 4744 | Some("agent"), |
| 4745 | ); |
| 4746 | manager.save_session(&session).expect("save origin"); |
| 4747 | let origin_scope = scope_token(); |
| 4748 | manager |
| 4749 | .delete_session("retired-origin") |
| 4750 | .expect("delete origin"); |
| 4751 | let route = deepseek_envelope(); |
| 4752 | for _ in 0..2 { |
| 4753 | assert!(report_effective_route_for_interactive_origin_with_manager( |
| 4754 | origin_scope, |
| 4755 | "retired-origin", |
| 4756 | "origin-turn", |
| 4757 | "retired-usage", |
| 4758 | &route, |
| 4759 | &small_usage(), |
| 4760 | &manager, |
| 4761 | )); |
| 4762 | assert!(report_unreceipted_for_interactive_origin_with_manager( |
| 4763 | origin_scope, |
| 4764 | "retired-origin", |
| 4765 | "origin-turn", |
| 4766 | "retired-drop", |
| 4767 | &route, |
| 4768 | &manager, |
| 4769 | )); |
| 4770 | } |
| 4771 | assert!(usage_source_seen("retired-usage")); |
| 4772 | assert!(usage_source_seen("retired-drop")); |
| 4773 | assert!( |
| 4774 | drain().is_empty(), |
| 4775 | "retirement must not create any pending projection" |
| 4776 | ); |
| 4777 | assert!( |
| 4778 | !manager |
| 4779 | .sessions_dir() |
| 4780 | .join(".late-usage/retired-origin.json") |
| 4781 | .exists() |
| 4782 | ); |
| 4783 | |
| 4784 | assert!(close_current_scope().is_empty()); |
| 4785 | assert!(!usage_source_seen("retired-usage")); |
| 4786 | assert!(report_effective_route_for_interactive_origin_with_manager( |
| 4787 | origin_scope, |
| 4788 | "retired-origin", |
| 4789 | "origin-turn", |
| 4790 | "after-scope-change", |
| 4791 | &route, |
| 4792 | &small_usage(), |
| 4793 | &manager, |
| 4794 | )); |
| 4795 | assert!( |
| 4796 | !usage_source_seen("after-scope-change"), |
| 4797 | "old retirement cannot poison a new scope" |
| 4798 | ); |
| 4799 | assert!(drain().is_empty()); |
| 4800 | record_runtime_usage( |
| 4801 | scope_token(), |
| 4802 | None, |
| 4803 | &RuntimeUsageRecord::legacy( |
| 4804 | "after-scope-change", |
| 4805 | EffectiveRouteUsage { |
| 4806 | route, |
| 4807 | usage: small_usage(), |
| 4808 | }, |
| 4809 | ), |
| 4810 | ); |
| 4811 | assert_eq!( |
| 4812 | drain().priced_turns, |
| 4813 | 1, |
| 4814 | "the replacement scope still admits its own response" |
| 4815 | ); |
| 4816 | } |
| 4817 | |
| 4818 | #[test] |
| 4819 | fn detached_advisor_and_translation_receipts_survive_new_exactly_once() { |
| 4820 | let _g = test_scope(); |
| 4821 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 4822 | let manager = crate::session_manager::SessionManager::new(tmp.path().join("sessions")) |
| 4823 | .expect("session manager"); |
| 4824 | let old_session_id = "origin-session"; |
| 4825 | let new_session_id = "replacement-session"; |
| 4826 | for session_id in [old_session_id, new_session_id] { |
| 4827 | let session = crate::session_manager::create_saved_session_with_id_and_mode( |
| 4828 | session_id.to_string(), |
| 4829 | &[], |
| 4830 | "deepseek-v4-flash", |
| 4831 | tmp.path(), |
| 4832 | 0, |
| 4833 | None, |
| 4834 | Some("agent"), |
| 4835 | ); |
| 4836 | manager.save_session(&session).expect("save session"); |
| 4837 | } |
| 4838 | |
| 4839 | let origin_scope = scope_token(); |
| 4840 | let origin = NativeUsageOrigin::session( |
| 4841 | origin_scope, |
| 4842 | manager.sessions_dir().to_path_buf(), |
| 4843 | old_session_id.to_string(), |
| 4844 | ); |
| 4845 | |
| 4846 | assert!(close_current_scope().is_empty()); |
| 4847 | let route = deepseek_envelope(); |
| 4848 | let usage = Usage { |
| 4849 | input_tokens: 17, |
| 4850 | output_tokens: 5, |
| 4851 | ..Usage::default() |
| 4852 | }; |
| 4853 | let advisor_source = NativeUsageSource::capture_with_origin( |
| 4854 | "advisor:origin-turn:response", |
| 4855 | UsageSpendOwner::Auxiliary, |
| 4856 | Some(origin.clone()), |
| 4857 | ); |
| 4858 | let advisor_record = advisor_source.reported(&route, &usage); |
| 4859 | let advisor_missing_source = NativeUsageSource::capture_with_origin( |
| 4860 | "advisor:origin-turn:missing-usage", |
| 4861 | UsageSpendOwner::Auxiliary, |
| 4862 | Some(origin.clone()), |
| 4863 | ); |
| 4864 | let advisor_missing_record = advisor_missing_source.prepare( |
| 4865 | &route, |
| 4866 | &Usage::default(), |
| 4867 | crate::llm_client::ProviderUsageCoverage::Missing, |
| 4868 | RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 4869 | ); |
| 4870 | for _ in 0..2 { |
| 4871 | record_runtime_usage(origin_scope, Some(&origin), &advisor_record); |
| 4872 | record_runtime_usage(origin_scope, Some(&origin), &advisor_missing_record); |
| 4873 | assert!(report_effective_route_for_interactive_origin_with_manager( |
| 4874 | origin_scope, |
| 4875 | old_session_id, |
| 4876 | "origin-turn", |
| 4877 | "translation:origin-turn:assistant", |
| 4878 | &route, |
| 4879 | &usage, |
| 4880 | &manager, |
| 4881 | )); |
| 4882 | assert!(report_unreceipted_for_interactive_origin_with_manager( |
| 4883 | origin_scope, |
| 4884 | old_session_id, |
| 4885 | "origin-turn", |
| 4886 | "translation:origin-turn:thinking-missing-usage", |
| 4887 | &route, |
| 4888 | &manager, |
| 4889 | )); |
| 4890 | } |
| 4891 | |
| 4892 | assert!(drain().is_empty(), "late receipts polluted the new scope"); |
| 4893 | |
| 4894 | let old = manager |
| 4895 | .load_session_snapshot(old_session_id) |
| 4896 | .expect("load origin session"); |
| 4897 | assert_eq!(old.metadata.total_tokens, 44); |
| 4898 | assert_eq!(old.metadata.cost.priced_turns, 2); |
| 4899 | assert_eq!(old.metadata.cost.unpriced_turns, 2); |
| 4900 | assert_eq!(old.metadata.cost.cny_unpriced_turns, 2); |
| 4901 | assert_eq!(old.metadata.cost.usage_source_fingerprints.len(), 4); |
| 4902 | |
| 4903 | let replay = manager |
| 4904 | .load_session_snapshot(old_session_id) |
| 4905 | .expect("replay origin session"); |
| 4906 | assert_eq!(replay.metadata.total_tokens, 44); |
| 4907 | assert_eq!(replay.metadata.cost.usage_source_fingerprints.len(), 4); |
| 4908 | |
| 4909 | let replacement = manager |
| 4910 | .load_session_snapshot(new_session_id) |
| 4911 | .expect("load replacement session"); |
| 4912 | assert_eq!(replacement.metadata.total_tokens, 0); |
| 4913 | assert_eq!(replacement.metadata.cost.priced_turns, 0); |
| 4914 | assert_eq!(replacement.metadata.cost.unpriced_turns, 0); |
| 4915 | assert!( |
| 4916 | replacement |
| 4917 | .metadata |
| 4918 | .cost |
| 4919 | .usage_source_fingerprints |
| 4920 | .is_empty() |
| 4921 | ); |
| 4922 | } |
| 4923 | |
| 4924 | #[test] |
| 4925 | fn report_counts_unknown_models_as_missing_spend_not_as_free() { |
| 4926 | let _g = test_scope(); |
| 4927 | // NIM-hosted models intentionally have no DeepSeek pricing, but the |
| 4928 | // route *is* money-metered — so the turn is missing spend, not absent. |
| 4929 | report( |
| 4930 | scope_token(), |
| 4931 | &BackgroundRoute::new(ProviderKind::NvidiaNim, "deepseek-ai/deepseek-v4-pro"), |
| 4932 | &small_usage(), |
| 4933 | ); |
| 4934 | let drained = drain(); |
| 4935 | assert_eq!(drained.estimate, CostEstimate::default()); |
| 4936 | assert_eq!(drained.priced_turns, 0); |
| 4937 | assert_eq!(drained.unpriced_turns, 1); |
| 4938 | assert!(!drained.unpriced_reasons.is_empty()); |
| 4939 | } |
| 4940 | |
| 4941 | #[test] |
| 4942 | fn report_skips_codex_oauth_pricing_without_calling_it_incomplete() { |
| 4943 | let _g = test_scope(); |
| 4944 | report( |
| 4945 | scope_token(), |
| 4946 | &BackgroundRoute::new(ProviderKind::OpenaiCodex, "gpt-5.5") |
| 4947 | .with_base_url(Some("https://chatgpt.com/backend-api/codex")), |
| 4948 | &small_usage(), |
| 4949 | ); |
| 4950 | let drained = drain(); |
| 4951 | assert_eq!(drained.estimate, CostEstimate::default()); |
| 4952 | // Exactly non-metered: not counted in either coverage bucket. |
| 4953 | assert_eq!(drained.priced_turns, 0); |
| 4954 | assert_eq!(drained.unpriced_turns, 0); |
| 4955 | assert!(drained.unpriced_reasons.is_empty()); |
| 4956 | assert!(drained.cny_unpriced_reasons.is_empty()); |
| 4957 | } |
| 4958 | |
| 4959 | #[test] |
| 4960 | fn report_skips_stepfun_without_billing_surface() { |
| 4961 | let _g = test_scope(); |
| 4962 | report( |
| 4963 | scope_token(), |
| 4964 | &BackgroundRoute::new(ProviderKind::Stepfun, "step-3.7-flash"), |
| 4965 | &small_usage(), |
| 4966 | ); |
| 4967 | report( |
| 4968 | scope_token(), |
| 4969 | &BackgroundRoute::new(ProviderKind::Openrouter, "step-3.7-flash"), |
| 4970 | &small_usage(), |
| 4971 | ); |
| 4972 | let drained = drain(); |
| 4973 | assert_eq!(drained.estimate, CostEstimate::default()); |
| 4974 | // Both are metered-or-unknown routes that could not be priced, so both |
| 4975 | // are reported as missing rather than dropped. |
| 4976 | assert_eq!(drained.unpriced_turns, 2); |
| 4977 | } |
| 4978 | |
| 4979 | /// A local runtime and a plan endpoint must never be guessed into public |
| 4980 | /// per-token dollars just because the provider also sells a paid API. |
| 4981 | #[test] |
| 4982 | fn local_and_plan_endpoints_are_never_treated_as_public_payg() { |
| 4983 | let _g = test_scope(); |
| 4984 | report( |
| 4985 | scope_token(), |
| 4986 | &BackgroundRoute::new(ProviderKind::Ollama, "llama3.2"), |
| 4987 | &small_usage(), |
| 4988 | ); |
| 4989 | report( |
| 4990 | scope_token(), |
| 4991 | &BackgroundRoute::new(ProviderKind::Zai, "glm-5.2") |
| 4992 | .with_base_url(Some("https://api.z.ai/api/coding/paas/v4")), |
| 4993 | &small_usage(), |
| 4994 | ); |
| 4995 | report( |
| 4996 | scope_token(), |
| 4997 | &BackgroundRoute::new(ProviderKind::Moonshot, "kimi-for-coding").with_base_url(Some( |
| 4998 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 4999 | )), |
| 5000 | &small_usage(), |
| 5001 | ); |
| 5002 | let drained = drain(); |
| 5003 | assert_eq!(drained.estimate, CostEstimate::default()); |
| 5004 | assert_eq!(drained.priced_turns, 0); |
| 5005 | assert_eq!( |
| 5006 | drained.unpriced_turns, 0, |
| 5007 | "exactly non-metered routes are not missing dollars: {drained:?}" |
| 5008 | ); |
| 5009 | assert!(drained.unpriced_reasons.is_empty()); |
| 5010 | assert!(drained.cny_unpriced_reasons.is_empty()); |
| 5011 | assert!( |
| 5012 | drained |
| 5013 | .route_receipts |
| 5014 | .iter() |
| 5015 | .any(|receipt| receipt.contains("surface=zai-coding-plan")), |
| 5016 | "{drained:?}" |
| 5017 | ); |
| 5018 | assert!( |
| 5019 | drained |
| 5020 | .route_receipts |
| 5021 | .iter() |
| 5022 | .any(|receipt| receipt.contains("surface=local-no-bill")), |
| 5023 | "{drained:?}" |
| 5024 | ); |
| 5025 | assert!( |
| 5026 | drained |
| 5027 | .route_receipts |
| 5028 | .iter() |
| 5029 | .any(|receipt| receipt.contains("surface=moonshot-kimi-code")), |
| 5030 | "{drained:?}" |
| 5031 | ); |
| 5032 | } |
| 5033 | |
| 5034 | /// The receipt carries an endpoint *fingerprint*, never the URL. |
| 5035 | #[test] |
| 5036 | fn route_receipts_fingerprint_the_endpoint_and_keep_secrets_out() { |
| 5037 | let _g = test_scope(); |
| 5038 | let base_url = "https://api.deepseek.com/v1"; |
| 5039 | report( |
| 5040 | scope_token(), |
| 5041 | &deepseek().with_base_url(Some(base_url)), |
| 5042 | &small_usage(), |
| 5043 | ); |
| 5044 | let drained = drain(); |
| 5045 | let receipt = drained.route_receipts.iter().next().expect("receipt"); |
| 5046 | let expected_fp = endpoint_fingerprint(base_url).expect("valid endpoint fingerprint"); |
| 5047 | assert!( |
| 5048 | receipt.contains(&format!("endpoint_fp={expected_fp}")), |
| 5049 | "{receipt}" |
| 5050 | ); |
| 5051 | for needle in ["http", "api.deepseek.com", "sk-", "/Users/", "/home/"] { |
| 5052 | assert!(!receipt.contains(needle), "{needle} leaked into {receipt}"); |
| 5053 | } |
| 5054 | } |
| 5055 | |
| 5056 | #[test] |
| 5057 | fn receipt_fields_are_bounded_and_secret_bearing_urls_are_not_hashed() { |
| 5058 | let hostile = format!("model\nAuthorization: bearer {}", "x".repeat(400)); |
| 5059 | let receipt = route_receipt( |
| 5060 | ProviderKind::Deepseek, |
| 5061 | Some("identity\r\nforged=yes"), |
| 5062 | &hostile, |
| 5063 | Some(crate::pricing::FIRST_PARTY_PAYG_BILLING_SURFACE), |
| 5064 | None, |
| 5065 | RouteBillingMode::Metered, |
| 5066 | "usd+cny", |
| 5067 | ); |
| 5068 | assert!(!receipt.contains('\n'), "{receipt}"); |
| 5069 | assert!(!receipt.contains('\r'), "{receipt}"); |
| 5070 | assert!( |
| 5071 | receipt.len() < 420, |
| 5072 | "receipt was not bounded: {}", |
| 5073 | receipt.len() |
| 5074 | ); |
| 5075 | |
| 5076 | for secret_url in [ |
| 5077 | "https://user:secret@api.example.com/v1", |
| 5078 | "https://api.example.com/v1?api_key=secret", |
| 5079 | "https://api.example.com/v1#secret", |
| 5080 | ] { |
| 5081 | assert_eq!(endpoint_fingerprint(secret_url), None, "{secret_url}"); |
| 5082 | } |
| 5083 | assert_eq!( |
| 5084 | endpoint_fingerprint("https://API.Example.com/v1/") |
| 5085 | .expect("valid endpoint") |
| 5086 | .len(), |
| 5087 | 64 |
| 5088 | ); |
| 5089 | } |
| 5090 | |
| 5091 | #[test] |
| 5092 | fn report_accumulates_across_multiple_calls() { |
| 5093 | let _g = test_scope(); |
| 5094 | report(scope_token(), &deepseek(), &small_usage()); |
| 5095 | report(scope_token(), &deepseek(), &small_usage()); |
| 5096 | let total = drain(); |
| 5097 | // Two equal reports — total must be 2× a single report. |
| 5098 | let single = crate::pricing::calculate_turn_cost_estimate_from_usage( |
| 5099 | "deepseek-v4-flash", |
| 5100 | &small_usage(), |
| 5101 | ) |
| 5102 | .unwrap(); |
| 5103 | assert!((total.estimate.usd - 2.0 * single.usd).abs() < 1e-12); |
| 5104 | assert!((total.estimate.cny - 2.0 * single.cny).abs() < 1e-12); |
| 5105 | assert_eq!(total.priced_turns, 2); |
| 5106 | // Identical routes collapse to one receipt rather than growing without |
| 5107 | // bound across a long session. |
| 5108 | assert_eq!(total.route_receipts.len(), 1); |
| 5109 | } |
| 5110 | |
| 5111 | /// A cache-write turn on a route with no published write rate must show up |
| 5112 | /// as missing spend naming the class, not as a discounted total. |
| 5113 | #[test] |
| 5114 | fn unpriced_cache_write_class_is_reported_not_absorbed() { |
| 5115 | let _g = test_scope(); |
| 5116 | let write_heavy = Usage { |
| 5117 | input_tokens: 1_000_000, |
| 5118 | output_tokens: 100_000, |
| 5119 | prompt_cache_hit_tokens: Some(200_000), |
| 5120 | prompt_cache_write_tokens: Some(100_000), |
| 5121 | ..Default::default() |
| 5122 | }; |
| 5123 | report( |
| 5124 | scope_token(), |
| 5125 | &BackgroundRoute::new(ProviderKind::Moonshot, "kimi-k2.7-code") |
| 5126 | .with_base_url(Some("https://api.moonshot.ai/v1")), |
| 5127 | &write_heavy, |
| 5128 | ); |
| 5129 | let drained = drain(); |
| 5130 | assert_eq!(drained.estimate, CostEstimate::default()); |
| 5131 | assert_eq!(drained.unpriced_turns, 1); |
| 5132 | assert!(drained.unpriced_reasons.contains("missing_class_price")); |
| 5133 | assert!(drained.unpriced_classes.contains("cache_write")); |
| 5134 | assert!( |
| 5135 | drained |
| 5136 | .route_receipts |
| 5137 | .iter() |
| 5138 | .any(|receipt| receipt.contains("cache_write=yes")), |
| 5139 | "{drained:?}" |
| 5140 | ); |
| 5141 | } |
| 5142 | |
| 5143 | #[test] |
| 5144 | fn missing_usage_reason_preserves_legacy_bytes_and_metadata_identity() { |
| 5145 | let route = deepseek_envelope(); |
| 5146 | let old = serde_json::json!({"source_id":"opaque-response", "route":route}); |
| 5147 | let legacy: RuntimeUsageDropRecord = serde_json::from_value(old.clone()).unwrap(); |
| 5148 | assert_eq!( |
| 5149 | legacy.reason, |
| 5150 | RuntimeUsageMissingReason::SuccessWithoutUsage |
| 5151 | ); |
| 5152 | assert_eq!(serde_json::to_value(&legacy).unwrap(), old); |
| 5153 | let unknown = RuntimeUsageDropRecord { |
| 5154 | reason: RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 5155 | ..legacy |
| 5156 | }; |
| 5157 | let mut metadata = serde_json::json!({}); |
| 5158 | attach_child_usage_batch_metadata( |
| 5159 | &mut metadata, |
| 5160 | &RuntimeUsageBatch { |
| 5161 | drop_records: vec![unknown], |
| 5162 | dropped_records: 1, |
| 5163 | ..Default::default() |
| 5164 | }, |
| 5165 | ); |
| 5166 | let recovered = child_usage_records_from_metadata(&metadata).unwrap(); |
| 5167 | assert_eq!( |
| 5168 | recovered.drop_records[0].reason, |
| 5169 | RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 5170 | ); |
| 5171 | assert_eq!( |
| 5172 | recovered.drop_records[0].source_id, |
| 5173 | usage_source_fingerprint("opaque-response") |
| 5174 | ); |
| 5175 | assert_eq!(recovered.dropped_records, 1); |
| 5176 | assert!( |
| 5177 | !serde_json::to_string(&metadata) |
| 5178 | .unwrap() |
| 5179 | .contains("opaque-response") |
| 5180 | ); |
| 5181 | } |
| 5182 | |
| 5183 | #[test] |
| 5184 | fn runtime_unknown_batch_promotes_and_prunes_reason_via_supersedes() { |
| 5185 | let _scope = test_scope(); |
| 5186 | let route = deepseek_envelope(); |
| 5187 | let batch = RuntimeUsageBatch { |
| 5188 | drop_records: vec![RuntimeUsageDropRecord { |
| 5189 | reason: RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 5190 | source_id: "batch-attempt".to_string(), |
| 5191 | route: route.clone(), |
| 5192 | }], |
| 5193 | dropped_records: 1, |
| 5194 | ..Default::default() |
| 5195 | }; |
| 5196 | let mut metadata = serde_json::json!({}); |
| 5197 | attach_child_usage_batch_metadata(&mut metadata, &batch); |
| 5198 | let batch = child_usage_records_from_metadata(&metadata).unwrap(); |
| 5199 | record_runtime_usage_batch(scope_token(), None, &batch); |
| 5200 | record_runtime_usage_batch(scope_token(), None, &batch); |
| 5201 | let missing = drain(); |
| 5202 | assert_eq!(missing.source_records.len(), 1); |
| 5203 | let prior = &missing.source_records[0]; |
| 5204 | let mut accounted = BTreeMap::from([( |
| 5205 | usage_source_fingerprint("batch-attempt"), |
| 5206 | UsageSourceContribution::for_record(prior), |
| 5207 | )]); |
| 5208 | let mut reasons = BTreeSet::from(["request_outcome_unknown".to_string()]); |
| 5209 | let mut cny_reasons = BTreeSet::from(["request_outcome_unknown".to_string()]); |
| 5210 | assert_eq!(accounted.values().next().unwrap().unpriced, 1); |
| 5211 | |
| 5212 | let settled = NativeUsageSource::capture("batch-attempt", UsageSpendOwner::Auxiliary) |
| 5213 | .reported(&route, &small_usage()); |
| 5214 | assert!(settled.supersedes(Some(prior))); |
| 5215 | record_runtime_usage(scope_token(), None, &settled); |
| 5216 | let known = drain(); |
| 5217 | assert_eq!(known.source_records.len(), 1); |
| 5218 | let next = UsageSourceContribution::for_record(&known.source_records[0]); |
| 5219 | assert_eq!(next.priced, 1); |
| 5220 | assert_eq!(next.unpriced, 0); |
| 5221 | accounted.insert(usage_source_fingerprint("batch-attempt"), next); |
| 5222 | prune_settled_missing_reasons(&accounted, 0, 0, &mut reasons, &mut cny_reasons); |
| 5223 | assert!(!reasons.contains("request_outcome_unknown")); |
| 5224 | assert!(!cny_reasons.contains("request_outcome_unknown")); |
| 5225 | } |
| 5226 | |
| 5227 | #[test] |
| 5228 | fn late_unknown_receipt_promotes_after_restart_without_charging_replacement_session() { |
| 5229 | let _scope = test_scope(); |
| 5230 | let tmp = tempfile::tempdir().unwrap(); |
| 5231 | let sessions = tmp.path().join("sessions"); |
| 5232 | let manager = crate::session_manager::SessionManager::new(sessions.clone()).unwrap(); |
| 5233 | for id in ["unknown-origin", "replacement"] { |
| 5234 | let session = crate::session_manager::create_saved_session_with_id_and_mode( |
| 5235 | id.into(), |
| 5236 | &[], |
| 5237 | "deepseek-v4-flash", |
| 5238 | tmp.path(), |
| 5239 | 0, |
| 5240 | None, |
| 5241 | Some("agent"), |
| 5242 | ); |
| 5243 | manager.save_session(&session).unwrap(); |
| 5244 | } |
| 5245 | let origin = scope_token(); |
| 5246 | assert!(close_current_scope().is_empty()); |
| 5247 | let route = deepseek_envelope(); |
| 5248 | assert!(report_missing_usage_for_interactive_origin_with_manager( |
| 5249 | origin, |
| 5250 | "unknown-origin", |
| 5251 | "origin-turn", |
| 5252 | "late-attempt", |
| 5253 | &route, |
| 5254 | RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 5255 | &manager |
| 5256 | )); |
| 5257 | let missing = manager.load_session_snapshot("unknown-origin").unwrap(); |
| 5258 | assert_eq!(missing.metadata.cost.unpriced_turns, 1); |
| 5259 | assert!( |
| 5260 | missing |
| 5261 | .metadata |
| 5262 | .cost |
| 5263 | .unpriced_reasons |
| 5264 | .contains("request_outcome_unknown") |
| 5265 | ); |
| 5266 | manager.save_session(&missing).unwrap(); |
| 5267 | drop(manager); |
| 5268 | let manager = crate::session_manager::SessionManager::new(sessions).unwrap(); |
| 5269 | for _ in 0..2 { |
| 5270 | assert!(report_effective_route_for_interactive_origin_with_manager( |
| 5271 | origin, |
| 5272 | "unknown-origin", |
| 5273 | "origin-turn", |
| 5274 | "late-attempt", |
| 5275 | &route, |
| 5276 | &small_usage(), |
| 5277 | &manager |
| 5278 | )); |
| 5279 | let known = manager.load_session_snapshot("unknown-origin").unwrap(); |
| 5280 | assert_eq!(known.metadata.cost.priced_turns, 1); |
| 5281 | assert_eq!(known.metadata.cost.unpriced_turns, 0); |
| 5282 | assert!( |
| 5283 | !known |
| 5284 | .metadata |
| 5285 | .cost |
| 5286 | .unpriced_reasons |
| 5287 | .contains("request_outcome_unknown") |
| 5288 | ); |
| 5289 | assert_eq!( |
| 5290 | known.metadata.total_tokens, |
| 5291 | u64::from(small_usage().input_tokens) + u64::from(small_usage().output_tokens) |
| 5292 | ); |
| 5293 | manager.save_session(&known).unwrap(); |
| 5294 | } |
| 5295 | assert!(!report_effective_route_for_interactive_origin_with_manager( |
| 5296 | origin, |
| 5297 | "unknown-origin", |
| 5298 | "different-turn", |
| 5299 | "late-attempt", |
| 5300 | &route, |
| 5301 | &small_usage(), |
| 5302 | &manager |
| 5303 | )); |
| 5304 | let replacement = manager.load_session_snapshot("replacement").unwrap(); |
| 5305 | assert_eq!(replacement.metadata.total_tokens, 0); |
| 5306 | assert_eq!( |
| 5307 | ( |
| 5308 | replacement.metadata.cost.priced_turns, |
| 5309 | replacement.metadata.cost.unpriced_turns |
| 5310 | ), |
| 5311 | (0, 0) |
| 5312 | ); |
| 5313 | assert!(drain().is_empty()); |
| 5314 | } |
| 5315 | |
| 5316 | #[test] |
| 5317 | fn frozen_dispatch_quotes_price_google_and_major_providers_while_unpriced_models_fail_closed() { |
| 5318 | let _env = crate::test_support::lock_test_env(); |
| 5319 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 5320 | let home = tempfile::tempdir().expect("test home"); |
| 5321 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 5322 | let _reset = ProviderCatalogTestReset; |
| 5323 | crate::provider_catalog_live::reset_cache_for_test(); |
| 5324 | crate::provider_lake::clear_live_snapshot(); |
| 5325 | |
| 5326 | let now = Utc::now(); |
| 5327 | let now_unix = u64::try_from(now.timestamp()).expect("nonnegative timestamp"); |
| 5328 | let google_base = ProviderKind::Google.provider().default_base_url(); |
| 5329 | let google_fp = codewhale_config::catalog::base_url_fingerprint(google_base); |
| 5330 | |
| 5331 | let google_roster = codewhale_config::catalog::ProviderCatalogDelta { |
| 5332 | provider: "google".to_string(), |
| 5333 | base_url_fingerprint: google_fp.clone(), |
| 5334 | fetched_at: now_unix, |
| 5335 | offerings: [ |
| 5336 | "models/gemini-4-carbon", |
| 5337 | "models/gemini-4-hydrogen", |
| 5338 | "models/gemini-4-argon", |
| 5339 | "models/gemini-4-neon", |
| 5340 | ] |
| 5341 | .into_iter() |
| 5342 | .map(|id| codewhale_config::catalog::CatalogOffering { |
| 5343 | provider: "google".to_string(), |
| 5344 | wire_model_id: id.to_string(), |
| 5345 | endpoint_key: "chat".to_string(), |
| 5346 | source: codewhale_config::catalog::CatalogSource::Live { |
| 5347 | base_url_fingerprint: google_fp.clone(), |
| 5348 | fetched_at: now_unix, |
| 5349 | }, |
| 5350 | ..Default::default() |
| 5351 | }) |
| 5352 | .collect(), |
| 5353 | }; |
| 5354 | assert_eq!( |
| 5355 | crate::provider_catalog_live::record_success(google_roster), |
| 5356 | codewhale_config::catalog::CatalogStatus::Fresh |
| 5357 | ); |
| 5358 | |
| 5359 | let google_usage = Usage { |
| 5360 | input_tokens: 136_287, |
| 5361 | output_tokens: 46, |
| 5362 | prompt_cache_hit_tokens: Some(131_324), |
| 5363 | prompt_cache_miss_tokens: Some(4_963), |
| 5364 | ..Usage::default() |
| 5365 | }; |
| 5366 | let roster_probe = Usage { |
| 5367 | input_tokens: 1, |
| 5368 | output_tokens: 1, |
| 5369 | ..Usage::default() |
| 5370 | }; |
| 5371 | |
| 5372 | for (model, expected_usd) in [ |
| 5373 | ( |
| 5374 | "gemini-4-carbon", |
| 5375 | 4_963.0 * 2e-6 + 131_324.0 * 0.1e-6 + 46.0 * 10e-6, |
| 5376 | ), |
| 5377 | ( |
| 5378 | "models/gemini-4-carbon", |
| 5379 | 4_963.0 * 2e-6 + 131_324.0 * 0.1e-6 + 46.0 * 10e-6, |
| 5380 | ), |
| 5381 | ( |
| 5382 | "gemini-4-hydrogen", |
| 5383 | 4_963.0 * 1.5e-6 + 131_324.0 * 0.075e-6 + 46.0 * 7.5e-6, |
| 5384 | ), |
| 5385 | ( |
| 5386 | "models/gemini-4-hydrogen", |
| 5387 | 4_963.0 * 1.5e-6 + 131_324.0 * 0.075e-6 + 46.0 * 7.5e-6, |
| 5388 | ), |
| 5389 | ( |
| 5390 | "gemini-4-neon", |
| 5391 | 4_963.0 * 3e-6 + 131_324.0 * 0.15e-6 + 46.0 * 15e-6, |
| 5392 | ), |
| 5393 | ( |
| 5394 | "models/gemini-4-neon", |
| 5395 | 4_963.0 * 3e-6 + 131_324.0 * 0.15e-6 + 46.0 * 15e-6, |
| 5396 | ), |
| 5397 | ] { |
| 5398 | let route = EffectiveRouteEnvelope::capture_observed( |
| 5399 | ProviderKind::Google, |
| 5400 | "google", |
| 5401 | model, |
| 5402 | Some(google_base), |
| 5403 | now, |
| 5404 | ); |
| 5405 | assert!(route.provider_live_pricing.is_some(), "{model}"); |
| 5406 | let audit = route.audit_frozen(&google_usage); |
| 5407 | assert!(audit.usd_priced, "{model}: {audit:?}"); |
| 5408 | assert_eq!(audit.unpriced_reason, None, "{model}: {audit:?}"); |
| 5409 | assert!( |
| 5410 | (audit.estimate.expect("priced").usd - expected_usd).abs() < 1e-12, |
| 5411 | "{model}: {audit:?}" |
| 5412 | ); |
| 5413 | let probe = route.audit(&roster_probe); |
| 5414 | assert!( |
| 5415 | probe.estimate.is_some_and(CostEstimate::is_positive), |
| 5416 | "{model} roster probe: {probe:?}" |
| 5417 | ); |
| 5418 | assert_eq!(probe.unpriced_reason, None, "{model} roster probe"); |
| 5419 | } |
| 5420 | |
| 5421 | let live_models_dev = codewhale_config::catalog::CatalogSnapshot { |
| 5422 | offerings: vec![ |
| 5423 | codewhale_config::catalog::CatalogOffering { |
| 5424 | provider: "google".to_string(), |
| 5425 | wire_model_id: "gemini-4-neon".to_string(), |
| 5426 | endpoint_key: "chat".to_string(), |
| 5427 | cost: Some(codewhale_config::models_dev::ModelsDevCost { |
| 5428 | input: Some(3.0), |
| 5429 | output: Some(15.0), |
| 5430 | cache_read: Some(0.15), |
| 5431 | input_audio: Some(3.0), |
| 5432 | ..Default::default() |
| 5433 | }), |
| 5434 | source: codewhale_config::catalog::CatalogSource::ModelsDevLive { |
| 5435 | fetched_at: now_unix, |
| 5436 | }, |
| 5437 | ..Default::default() |
| 5438 | }, |
| 5439 | codewhale_config::catalog::CatalogOffering { |
| 5440 | provider: "google".to_string(), |
| 5441 | wire_model_id: "gemini-4-carbon".to_string(), |
| 5442 | endpoint_key: "chat".to_string(), |
| 5443 | cost: Some(codewhale_config::models_dev::ModelsDevCost { |
| 5444 | input: Some(2.0), |
| 5445 | output: Some(10.0), |
| 5446 | cache_read: Some(0.1), |
| 5447 | input_audio: Some(2.0), |
| 5448 | ..Default::default() |
| 5449 | }), |
| 5450 | source: codewhale_config::catalog::CatalogSource::ModelsDevLive { |
| 5451 | fetched_at: now_unix.saturating_sub( |
| 5452 | crate::provider_catalog_live::DEFAULT_PROVIDER_CATALOG_TTL_SECS + 60, |
| 5453 | ), |
| 5454 | }, |
| 5455 | ..Default::default() |
| 5456 | }, |
| 5457 | ], |
| 5458 | }; |
| 5459 | crate::provider_lake::set_live_snapshot( |
| 5460 | live_models_dev, |
| 5461 | crate::provider_lake::LiveSource::ModelsDev, |
| 5462 | ); |
| 5463 | |
| 5464 | let expected_neon = 4_963.0 * 3e-6 + 131_324.0 * 0.15e-6 + 46.0 * 15e-6; |
| 5465 | for model in ["gemini-4-neon", "models/gemini-4-neon"] { |
| 5466 | let route = EffectiveRouteEnvelope::capture_observed( |
| 5467 | ProviderKind::Google, |
| 5468 | "google", |
| 5469 | model, |
| 5470 | Some(google_base), |
| 5471 | now, |
| 5472 | ); |
| 5473 | let audit = route.audit_frozen(&google_usage); |
| 5474 | assert!(audit.usd_priced, "{model}: {audit:?}"); |
| 5475 | assert_eq!( |
| 5476 | audit.provenance, |
| 5477 | Some(codewhale_config::pricing::PricingProvenance::ModelsDevLive) |
| 5478 | ); |
| 5479 | assert!( |
| 5480 | (audit.estimate.expect("priced").usd - expected_neon).abs() < 1e-12, |
| 5481 | "{model}: {audit:?}" |
| 5482 | ); |
| 5483 | } |
| 5484 | |
| 5485 | let stale_degraded = EffectiveRouteEnvelope::capture_observed( |
| 5486 | ProviderKind::Google, |
| 5487 | "google", |
| 5488 | "gemini-4-carbon", |
| 5489 | Some(google_base), |
| 5490 | now, |
| 5491 | ); |
| 5492 | let stale_audit = stale_degraded.audit_frozen(&google_usage); |
| 5493 | assert!(stale_audit.usd_priced, "{stale_audit:?}"); |
| 5494 | assert_eq!( |
| 5495 | stale_audit.provenance, |
| 5496 | Some(codewhale_config::pricing::PricingProvenance::ModelsDevBundled) |
| 5497 | ); |
| 5498 | |
| 5499 | for (provider, identity, model, base_url) in [ |
| 5500 | ( |
| 5501 | ProviderKind::Openai, |
| 5502 | "openai", |
| 5503 | "gpt-5.6", |
| 5504 | "https://api.openai.com/v1", |
| 5505 | ), |
| 5506 | ( |
| 5507 | ProviderKind::Anthropic, |
| 5508 | "anthropic", |
| 5509 | "claude-fable-5-2", |
| 5510 | "https://api.anthropic.com", |
| 5511 | ), |
| 5512 | ( |
| 5513 | ProviderKind::Deepseek, |
| 5514 | "deepseek", |
| 5515 | "deepseek-v4-flash", |
| 5516 | "https://api.deepseek.com/beta", |
| 5517 | ), |
| 5518 | ( |
| 5519 | ProviderKind::Openrouter, |
| 5520 | "openrouter", |
| 5521 | "deepseek/deepseek-v4-pro", |
| 5522 | "https://openrouter.ai/api/v1", |
| 5523 | ), |
| 5524 | ( |
| 5525 | ProviderKind::Zai, |
| 5526 | "zai", |
| 5527 | "glm-5.2", |
| 5528 | "https://api.z.ai/api/paas/v4", |
| 5529 | ), |
| 5530 | ( |
| 5531 | ProviderKind::Stepfun, |
| 5532 | "stepfun", |
| 5533 | "step-3.7-flash", |
| 5534 | "https://api.stepfun.ai/v1", |
| 5535 | ), |
| 5536 | ] { |
| 5537 | let api_key_config = codewhale_runtime::config::Config::default(); |
| 5538 | let route = if provider == ProviderKind::Anthropic { |
| 5539 | let observed = EffectiveRouteEnvelope::capture_observed( |
| 5540 | provider, |
| 5541 | identity, |
| 5542 | model, |
| 5543 | Some(base_url), |
| 5544 | now, |
| 5545 | ); |
| 5546 | assert!( |
| 5547 | !observed.audit_frozen(&small_usage()).is_priced(), |
| 5548 | "{model} {base_url}" |
| 5549 | ); |
| 5550 | EffectiveRouteEnvelope::from_admitted( |
| 5551 | Some(&api_key_config), |
| 5552 | &api_key_config.test_identity_for_kind(provider), |
| 5553 | model, |
| 5554 | Some(base_url), |
| 5555 | now, |
| 5556 | ) |
| 5557 | } else { |
| 5558 | EffectiveRouteEnvelope::capture_observed( |
| 5559 | provider, |
| 5560 | identity, |
| 5561 | model, |
| 5562 | Some(base_url), |
| 5563 | now, |
| 5564 | ) |
| 5565 | }; |
| 5566 | assert!( |
| 5567 | route.provider_live_pricing.is_some(), |
| 5568 | "{provider:?} {model} {base_url}" |
| 5569 | ); |
| 5570 | let audit = route.audit_frozen(&small_usage()); |
| 5571 | assert!( |
| 5572 | audit.usd_priced && audit.estimate.is_some_and(CostEstimate::is_positive), |
| 5573 | "{provider:?} {model} {base_url}: {audit:?}" |
| 5574 | ); |
| 5575 | } |
| 5576 | |
| 5577 | let proxy_route = EffectiveRouteEnvelope::capture_observed( |
| 5578 | ProviderKind::Google, |
| 5579 | "google", |
| 5580 | "gemini-4-carbon", |
| 5581 | Some("https://proxy.example/v1"), |
| 5582 | now, |
| 5583 | ); |
| 5584 | assert!(proxy_route.provider_live_pricing.is_none()); |
| 5585 | assert!(!proxy_route.audit_frozen(&google_usage).is_priced()); |
| 5586 | |
| 5587 | let custom_route = EffectiveRouteEnvelope::capture_observed( |
| 5588 | ProviderKind::Custom, |
| 5589 | "my-local-gateway", |
| 5590 | "totally-unknown-custom-model", |
| 5591 | Some("https://gateway.example/v1"), |
| 5592 | now, |
| 5593 | ); |
| 5594 | assert!(custom_route.provider_live_pricing.is_none()); |
| 5595 | assert!(!custom_route.audit_frozen(&small_usage()).is_priced()); |
| 5596 | } |
| 5597 | |
| 5598 | #[test] |
| 5599 | fn ordered_fingerprint_set_round_trips_legacy_sorted_json_and_evicts_oldest_unpinned() { |
| 5600 | let mut set: OrderedFingerprintSet = |
| 5601 | serde_json::from_str(r#"["fp-a","fp-b","fp-c","fp-b"]"#).expect("legacy json"); |
| 5602 | assert_eq!(set.len(), 3); |
| 5603 | assert_eq!( |
| 5604 | set.iter().map(String::as_str).collect::<Vec<_>>(), |
| 5605 | vec!["fp-a", "fp-b", "fp-c"] |
| 5606 | ); |
| 5607 | |
| 5608 | assert!(!set.insert("fp-b".to_string())); |
| 5609 | assert!(set.insert("fp-d".to_string())); |
| 5610 | assert!(set.insert("fp-e".to_string())); |
| 5611 | let evicted = set.compact_keeping_pinned(3, |fp| fp == "fp-a"); |
| 5612 | assert_eq!(evicted, 2); |
| 5613 | assert_eq!( |
| 5614 | set.iter().map(String::as_str).collect::<Vec<_>>(), |
| 5615 | vec!["fp-a", "fp-d", "fp-e"] |
| 5616 | ); |
| 5617 | |
| 5618 | let all_pinned_evicted = set.compact_keeping_pinned(1, |_| true); |
| 5619 | assert_eq!(all_pinned_evicted, 0); |
| 5620 | assert_eq!(set.len(), 3); |
| 5621 | |
| 5622 | let serialized = serde_json::to_string(&set).expect("serialize"); |
| 5623 | assert_eq!(serialized, r#"["fp-a","fp-d","fp-e"]"#); |
| 5624 | let round_trip: OrderedFingerprintSet = |
| 5625 | serde_json::from_str(&serialized).expect("round trip"); |
| 5626 | assert_eq!(round_trip, set); |
| 5627 | assert_eq!( |
| 5628 | round_trip.iter().map(String::as_str).collect::<Vec<_>>(), |
| 5629 | vec!["fp-a", "fp-d", "fp-e"] |
| 5630 | ); |
| 5631 | } |
| 5632 | |
| 5633 | #[test] |
| 5634 | fn record_interactive_runtime_usage_pinned_atomically_emits_and_preserves_pin() { |
| 5635 | let _g = test_scope(); |
| 5636 | let scope = scope_token(); |
| 5637 | let route = EffectiveRouteEnvelope::capture_observed( |
| 5638 | ProviderKind::Anthropic, |
| 5639 | "anthropic", |
| 5640 | "claude-sonnet-4-5", |
| 5641 | Some("https://api.anthropic.com"), |
| 5642 | Utc::now(), |
| 5643 | ); |
| 5644 | let source_id = "atomic-pinned-late-source"; |
| 5645 | let fp = usage_source_fingerprint(source_id); |
| 5646 | let record = RuntimeUsageRecord::legacy( |
| 5647 | source_id.to_string(), |
| 5648 | EffectiveRouteUsage { |
| 5649 | route, |
| 5650 | usage: small_usage(), |
| 5651 | }, |
| 5652 | ); |
| 5653 | |
| 5654 | assert!(record_interactive_runtime_usage_pinned( |
| 5655 | scope, |
| 5656 | record.clone() |
| 5657 | )); |
| 5658 | let drained = drain(); |
| 5659 | assert!(drained.usage_source_fingerprints.contains(&fp)); |
| 5660 | assert!(drained.pinned_usage_source_fingerprints.contains(&fp)); |
| 5661 | |
| 5662 | assert!(record_interactive_runtime_usage_pinned(scope, record)); |
| 5663 | assert!(drain().is_empty()); |
| 5664 | |
| 5665 | for index in 0..(MAX_USAGE_SOURCE_FINGERPRINTS + 20) { |
| 5666 | mark_retired_usage_source(scope, &format!("unpinned-retired-{index}")); |
| 5667 | } |
| 5668 | assert!(usage_source_seen(source_id)); |
| 5669 | } |
| 5670 | |
| 5671 | #[test] |
| 5672 | fn usage_source_revision_omits_missing_reason_for_reported_and_normalizes_legacy_json() { |
| 5673 | let route = deepseek_envelope(); |
| 5674 | let reported = NativeUsageSource::capture("reported-src", UsageSpendOwner::Primary) |
| 5675 | .reported(&route, &small_usage()); |
| 5676 | let reported_revision = reported.settlement.as_ref().expect("reported settlement"); |
| 5677 | assert_eq!( |
| 5678 | reported_revision.coverage, |
| 5679 | crate::llm_client::ProviderUsageCoverage::Reported |
| 5680 | ); |
| 5681 | assert_eq!(reported_revision.reason, None); |
| 5682 | let reported_json = serde_json::to_value(&reported).expect("serialize reported"); |
| 5683 | assert!( |
| 5684 | reported_json["settlement"].get("reason").is_none(), |
| 5685 | "{reported_json}" |
| 5686 | ); |
| 5687 | |
| 5688 | for coverage in [ |
| 5689 | crate::llm_client::ProviderUsageCoverage::NotDispatched, |
| 5690 | crate::llm_client::ProviderUsageCoverage::Rejected, |
| 5691 | ] { |
| 5692 | let refused = NativeUsageSource::capture("refused-src", UsageSpendOwner::Auxiliary) |
| 5693 | .prepare( |
| 5694 | &route, |
| 5695 | &Usage::default(), |
| 5696 | coverage, |
| 5697 | RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 5698 | ); |
| 5699 | assert_eq!( |
| 5700 | refused.settlement.as_ref().expect("settlement").reason, |
| 5701 | None |
| 5702 | ); |
| 5703 | let refused_json = serde_json::to_value(&refused).expect("serialize refused"); |
| 5704 | assert!( |
| 5705 | refused_json["settlement"].get("reason").is_none(), |
| 5706 | "{refused_json}" |
| 5707 | ); |
| 5708 | } |
| 5709 | |
| 5710 | let missing = NativeUsageSource::capture("missing-src", UsageSpendOwner::Auxiliary) |
| 5711 | .prepare( |
| 5712 | &route, |
| 5713 | &Usage::default(), |
| 5714 | crate::llm_client::ProviderUsageCoverage::Missing, |
| 5715 | RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 5716 | ); |
| 5717 | assert_eq!( |
| 5718 | missing.settlement.as_ref().expect("settlement").reason, |
| 5719 | Some(RuntimeUsageMissingReason::SuccessWithoutUsage) |
| 5720 | ); |
| 5721 | let missing_json = serde_json::to_value(&missing).expect("serialize missing"); |
| 5722 | assert_eq!( |
| 5723 | missing_json["settlement"]["reason"], |
| 5724 | serde_json::json!("success_without_usage") |
| 5725 | ); |
| 5726 | |
| 5727 | let incomplete = NativeUsageSource::capture("incomplete-src", UsageSpendOwner::Auxiliary) |
| 5728 | .prepare( |
| 5729 | &route, |
| 5730 | &small_usage(), |
| 5731 | crate::llm_client::ProviderUsageCoverage::Incomplete, |
| 5732 | RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 5733 | ); |
| 5734 | assert_eq!( |
| 5735 | incomplete.settlement.as_ref().expect("settlement").reason, |
| 5736 | Some(RuntimeUsageMissingReason::RequestOutcomeUnknown) |
| 5737 | ); |
| 5738 | let incomplete_json = serde_json::to_value(&incomplete).expect("serialize incomplete"); |
| 5739 | assert_eq!( |
| 5740 | incomplete_json["settlement"]["reason"], |
| 5741 | serde_json::json!("request_outcome_unknown") |
| 5742 | ); |
| 5743 | |
| 5744 | let contribution = UsageSourceContribution::for_record(&reported); |
| 5745 | let mut legacy_json = serde_json::to_value(&contribution).expect("serialize contribution"); |
| 5746 | legacy_json["record"]["settlement"]["reason"] = serde_json::json!("success_without_usage"); |
| 5747 | let decoded: UsageSourceContribution = |
| 5748 | serde_json::from_value(legacy_json).expect("decode legacy reported contribution"); |
| 5749 | assert_eq!( |
| 5750 | decoded |
| 5751 | .record |
| 5752 | .settlement |
| 5753 | .as_ref() |
| 5754 | .expect("settlement") |
| 5755 | .reason, |
| 5756 | None |
| 5757 | ); |
| 5758 | decoded |
| 5759 | .validate() |
| 5760 | .expect("legacy reported contribution validates cleanly"); |
| 5761 | assert_eq!(decoded, contribution); |
| 5762 | let resaved = serde_json::to_value(&decoded).expect("reserialize normalized contribution"); |
| 5763 | assert!( |
| 5764 | resaved["record"]["settlement"].get("reason").is_none(), |
| 5765 | "{resaved}" |
| 5766 | ); |
| 5767 | } |
| 5768 | } |
| 5769 |