| 1 | //! Durable, secret-free per-provider `/models` catalog cache. |
| 2 | //! |
| 3 | //! This is the persistence owner for [`codewhale_config::catalog::ProviderCatalogCache`]. |
| 4 | //! It replaces the process-only client refresh and provider_lake CLI cache writers: successful |
| 5 | //! refreshes replace one exact `(provider kind, identity, base URL fingerprint)` |
| 6 | //! partition, failures retain that partition's prior rows, and startup loads |
| 7 | //! only the active route's exact partition. Credentials authorize the fetch in |
| 8 | //! `client`; they never enter this module or its disk envelope. Baseten and |
| 9 | //! Codewhale account rosters are memory-only and cleared when their binding changes; |
| 10 | //! a named custom route at either official endpoint follows the same rule. |
| 11 | //! |
| 12 | //! The former unscoped OpenRouter cache reader is retired; installed old files |
| 13 | //! are preserved and never imported as provider authority. |
| 14 | //! `catalog/provider-catalogs.json` is the sole writer-owned live roster store. |
| 15 | //! Older per-endpoint `provider-*.json` files also lack the built-in/custom |
| 16 | //! kind boundary and account-roster exclusion, so they are left untouched and |
| 17 | //! replaced only by a newly authenticated refresh into this store. |
| 18 | |
| 19 | use std::collections::BTreeMap; |
| 20 | use std::fs::{self, OpenOptions}; |
| 21 | use std::io::Read as _; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 24 | use std::sync::{LazyLock, RwLock}; |
| 25 | |
| 26 | use anyhow::{Context, Result}; |
| 27 | use codewhale_config::catalog::now_unix; |
| 28 | use codewhale_config::catalog::{ |
| 29 | CatalogRefreshError, CatalogSnapshot, CatalogStatus, ProviderCatalogCache, |
| 30 | ProviderCatalogDelta, base_url_fingerprint, |
| 31 | }; |
| 32 | use codewhale_config::credentials::CredentialGeneration; |
| 33 | use codewhale_config::persistence::atomic_write_json; |
| 34 | use codewhale_config::pricing::{Currency, OfferingPricing, PricingProvenance}; |
| 35 | use serde::{Deserialize, Serialize}; |
| 36 | |
| 37 | use codewhale_config::ProviderKind; |
| 38 | use codewhale_runtime::config::Config; |
| 39 | |
| 40 | const CACHE_SCHEMA_VERSION: u32 = 3; |
| 41 | const CACHE_FILE: &str = "provider-catalogs.json"; |
| 42 | const MAX_CACHE_BYTES: u64 = 32 * 1024 * 1024; |
| 43 | const MAX_CACHE_SCOPES: usize = 64; |
| 44 | const MAX_CACHE_ROWS: usize = 50_000; |
| 45 | |
| 46 | #[derive(Debug, Clone, Copy)] |
| 47 | struct CachePersistenceLimits { |
| 48 | max_bytes: u64, |
| 49 | max_scopes: usize, |
| 50 | max_rows: usize, |
| 51 | } |
| 52 | |
| 53 | const CACHE_PERSISTENCE_LIMITS: CachePersistenceLimits = CachePersistenceLimits { |
| 54 | max_bytes: MAX_CACHE_BYTES, |
| 55 | max_scopes: MAX_CACHE_SCOPES, |
| 56 | max_rows: MAX_CACHE_ROWS, |
| 57 | }; |
| 58 | |
| 59 | /// Provider-owned catalogs are refreshed daily. Past-TTL rows remain visible |
| 60 | /// with an explicit stale receipt until a successful replacement arrives. |
| 61 | pub const DEFAULT_PROVIDER_CATALOG_TTL_SECS: u64 = 24 * 60 * 60; |
| 62 | |
| 63 | static DISK_LOADED: AtomicBool = AtomicBool::new(false); |
| 64 | |
| 65 | static CACHE: LazyLock<RwLock<ProviderCatalogCache>> = |
| 66 | LazyLock::new(|| RwLock::new(ProviderCatalogCache::new())); |
| 67 | static REFRESH_GENERATIONS: LazyLock<RwLock<BTreeMap<String, InventoryFence>>> = |
| 68 | LazyLock::new(|| RwLock::new(BTreeMap::new())); |
| 69 | |
| 70 | #[derive(Default)] |
| 71 | struct InventoryFence { |
| 72 | generation: u64, |
| 73 | observation: Option<crate::provider_readiness::ProviderRouteIdentity>, |
| 74 | request_scope: Option<CredentialGeneration>, |
| 75 | endpoint_fingerprint: String, |
| 76 | durable_catalog: bool, |
| 77 | binding: String, |
| 78 | account: Option<String>, |
| 79 | refresh: std::sync::Arc<tokio::sync::Mutex<()>>, |
| 80 | error: Option<CatalogRefreshError>, |
| 81 | revision: std::sync::atomic::AtomicU64, |
| 82 | publication: std::sync::Mutex<()>, |
| 83 | } |
| 84 | |
| 85 | pub fn inventory_scope( |
| 86 | config: &Config, |
| 87 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 88 | ) -> Result<(String, u64), String> { |
| 89 | config.verify_provider_identity(identity)?; |
| 90 | ensure_cache_loaded().map_err(|error| error.to_string())?; |
| 91 | let observation = crate::provider_readiness::inventory_observation_for_route(config, identity); |
| 92 | let base_url = config.base_url_for_route(identity); |
| 93 | let endpoint_fingerprint = base_url_fingerprint(&base_url); |
| 94 | let scope = storage_provider(identity.provider, identity.key.as_str()); |
| 95 | let auth_class = crate::provider_readiness::auth_class_for_provider(config, identity); |
| 96 | let global_headers: BTreeMap<_, _> = config.http_headers.iter().flatten().collect(); |
| 97 | let provider_headers: BTreeMap<_, _> = config |
| 98 | .provider_config_for(identity) |
| 99 | .and_then(|provider| provider.http_headers.as_ref()) |
| 100 | .into_iter() |
| 101 | .flatten() |
| 102 | .collect(); |
| 103 | let request_scope = CredentialGeneration::derive( |
| 104 | &base_url, |
| 105 | &serde_json::to_string(&(&global_headers, &provider_headers)) |
| 106 | .map_err(|error| error.to_string())?, |
| 107 | ); |
| 108 | let durable_catalog = !is_account_scoped_scope(&scope, &endpoint_fingerprint) |
| 109 | && (crate::client::CodewhaleClient::public_catalog_for_route(config, identity) |
| 110 | || (matches!( |
| 111 | auth_class, |
| 112 | crate::provider_readiness::ProviderAuthClass::NoAuth |
| 113 | | crate::provider_readiness::ProviderAuthClass::Local |
| 114 | ) && observation.has_keyless_credential(&base_url) |
| 115 | && global_headers.is_empty() |
| 116 | && provider_headers.is_empty() |
| 117 | && reqwest::Url::parse(&base_url).is_ok_and(|url| { |
| 118 | url.username().is_empty() |
| 119 | && url.password().is_none() |
| 120 | && url.query().is_none() |
| 121 | && url.fragment().is_none() |
| 122 | }))); |
| 123 | let account = if identity.provider == ProviderKind::OpenaiCodex { |
| 124 | codewhale_runtime::codex_model_roster::snapshot_path(config) |
| 125 | .map(|path| path.to_string_lossy().into_owned()) |
| 126 | } else if identity.provider == ProviderKind::Codewhale { |
| 127 | config |
| 128 | .account_model_access |
| 129 | .read() |
| 130 | .as_ref() |
| 131 | .filter(|access| access.profile == config.account_profile) |
| 132 | .map(|access| access.session_id.clone()) |
| 133 | } else { |
| 134 | None |
| 135 | }; |
| 136 | let binding = codewhale_runtime::hashing::sha256_hex( |
| 137 | serde_json::to_vec(&( |
| 138 | identity.persisted_kind(), |
| 139 | identity.persisted_id(), |
| 140 | identity.key.as_str(), |
| 141 | &base_url, |
| 142 | format!("{auth_class:?}"), |
| 143 | &account, |
| 144 | )) |
| 145 | .map_err(|error| error.to_string())?, |
| 146 | ); |
| 147 | let mut fences = REFRESH_GENERATIONS |
| 148 | .write() |
| 149 | .map_err(|_| "inventory fence unavailable")?; |
| 150 | let fence = fences.entry(scope).or_default(); |
| 151 | if fence.observation.as_ref() != Some(&observation) |
| 152 | || fence.account != account |
| 153 | || fence.request_scope.as_ref() != Some(&request_scope) |
| 154 | || fence.durable_catalog != durable_catalog |
| 155 | { |
| 156 | let same_account = account.is_some() && fence.account == account; |
| 157 | if !same_account || fence.binding != binding { |
| 158 | fence.binding = binding; |
| 159 | if account.is_none() { |
| 160 | fence.binding = uuid::Uuid::new_v4().to_string(); |
| 161 | } |
| 162 | } |
| 163 | if !durable_catalog || (fence.observation.is_some() && !fence.durable_catalog) { |
| 164 | forget_account_scoped_provider(identity.provider, identity.key.as_str()); |
| 165 | } |
| 166 | fence.refresh = Default::default(); |
| 167 | fence.error = None; |
| 168 | fence.account = account; |
| 169 | fence.observation = Some(observation); |
| 170 | fence.request_scope = Some(request_scope); |
| 171 | fence.endpoint_fingerprint = endpoint_fingerprint; |
| 172 | fence.durable_catalog = durable_catalog; |
| 173 | fence.generation = fence.generation.saturating_add(1); |
| 174 | } |
| 175 | Ok((fence.binding.clone(), fence.generation)) |
| 176 | } |
| 177 | |
| 178 | pub(crate) fn current_catalog_binding( |
| 179 | kind: ProviderKind, |
| 180 | identity: &str, |
| 181 | base: &str, |
| 182 | ) -> Option<String> { |
| 183 | let fences = REFRESH_GENERATIONS.read().ok()?; |
| 184 | let fence = fences.get(&storage_provider(kind, identity))?; |
| 185 | (fence.endpoint_fingerprint == base_url_fingerprint(base) && !fence.binding.is_empty()) |
| 186 | .then(|| fence.binding.clone()) |
| 187 | } |
| 188 | |
| 189 | pub(crate) fn go_has_typed_catalog(identity: &str, base: &str) -> bool { |
| 190 | CACHE.read().map_or(true, |cache| { |
| 191 | cache |
| 192 | .get( |
| 193 | &storage_provider(ProviderKind::OpencodeGo, identity), |
| 194 | &base_url_fingerprint(base), |
| 195 | ) |
| 196 | .is_some_and(|entry| entry.offerings.iter().any(|row| row.model_type.is_some())) |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | pub(crate) fn go_route_is_current( |
| 201 | connection: &codewhale_config::route::CatalogConnection, |
| 202 | model: &str, |
| 203 | endpoint_key: &str, |
| 204 | endpoint_url: &str, |
| 205 | ) -> bool { |
| 206 | let Ok(fences) = REFRESH_GENERATIONS.read() else { |
| 207 | return false; |
| 208 | }; |
| 209 | let owner = storage_provider(ProviderKind::OpencodeGo, &connection.identity); |
| 210 | let fingerprint = base_url_fingerprint(&connection.base_url); |
| 211 | let Some(fence) = fences.get(&owner) else { |
| 212 | return false; |
| 213 | }; |
| 214 | if fence.binding != connection.binding |
| 215 | || fence.endpoint_fingerprint != fingerprint |
| 216 | || fence.error.is_some() |
| 217 | { |
| 218 | return false; |
| 219 | } |
| 220 | CACHE.read().ok().is_some_and(|cache| { |
| 221 | cache.get(&owner, &fingerprint).is_some_and(|entry| { |
| 222 | entry.is_fresh(codewhale_config::catalog::now_unix()) |
| 223 | && entry.offerings.iter().any(|row| { |
| 224 | row.wire_model_id == model |
| 225 | && row.model_type.as_deref() == Some("chat") |
| 226 | && row.endpoint_key == endpoint_key |
| 227 | && row.provider_api.as_deref() == Some(endpoint_url) |
| 228 | }) |
| 229 | }) |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | pub fn record_inventory_error( |
| 234 | ticket: &ProviderCatalogRefreshTicket, |
| 235 | error: Option<CatalogRefreshError>, |
| 236 | ) { |
| 237 | if let Ok(mut fences) = REFRESH_GENERATIONS.write() |
| 238 | && let Some(fence) = |
| 239 | fences.get_mut(&storage_provider(ticket.provider_kind, &ticket.provider)) |
| 240 | && fence.generation == ticket.generation |
| 241 | && fence.error != error |
| 242 | { |
| 243 | fence.error = error; |
| 244 | fence.revision.fetch_add(2, Ordering::SeqCst); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | pub fn inventory_error( |
| 249 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 250 | generation: u64, |
| 251 | ) -> Option<CatalogRefreshError> { |
| 252 | REFRESH_GENERATIONS |
| 253 | .read() |
| 254 | .ok()? |
| 255 | .get(&storage_provider(identity.provider, identity.key.as_str())) |
| 256 | .filter(|fence| fence.generation == generation)? |
| 257 | .error |
| 258 | } |
| 259 | |
| 260 | pub fn begin_scoped_refresh( |
| 261 | config: &Config, |
| 262 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 263 | base_url: &str, |
| 264 | ) -> Result<ProviderCatalogRefreshTicket, String> { |
| 265 | let (_, generation) = inventory_scope(config, identity)?; |
| 266 | begin_inventory_refresh(identity, base_url, generation) |
| 267 | .ok_or_else(|| "refresh_superseded".to_string()) |
| 268 | } |
| 269 | |
| 270 | pub fn inventory_observation_revision( |
| 271 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 272 | generation: u64, |
| 273 | ) -> Option<u64> { |
| 274 | let fences = REFRESH_GENERATIONS.read().ok()?; |
| 275 | let fence = fences.get(&storage_provider(identity.provider, identity.key.as_str()))?; |
| 276 | let revision = fence.revision.load(Ordering::SeqCst); |
| 277 | (fence.generation == generation && revision % 2 == 0).then_some(revision) |
| 278 | } |
| 279 | |
| 280 | pub fn begin_inventory_refresh( |
| 281 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 282 | base_url: &str, |
| 283 | expected_generation: u64, |
| 284 | ) -> Option<ProviderCatalogRefreshTicket> { |
| 285 | let fingerprint = base_url_fingerprint(base_url); |
| 286 | let mut fences = REFRESH_GENERATIONS.write().ok()?; |
| 287 | let fence = fences.get_mut(&storage_provider(identity.provider, identity.key.as_str()))?; |
| 288 | if fence.generation != expected_generation || fence.endpoint_fingerprint != fingerprint { |
| 289 | return None; |
| 290 | } |
| 291 | fence.generation = fence.generation.saturating_add(1); |
| 292 | Some(ProviderCatalogRefreshTicket { |
| 293 | provider: canonical_provider_scope(identity.key.as_str()), |
| 294 | provider_kind: identity.provider, |
| 295 | fingerprint: Some(fingerprint), |
| 296 | generation: fence.generation, |
| 297 | durable_catalog: fence.durable_catalog, |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | pub fn try_inventory_refresh( |
| 302 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 303 | ) -> Option<tokio::sync::OwnedMutexGuard<()>> { |
| 304 | REFRESH_GENERATIONS |
| 305 | .read() |
| 306 | .ok()? |
| 307 | .get(&storage_provider(identity.provider, identity.key.as_str()))? |
| 308 | .refresh |
| 309 | .clone() |
| 310 | .try_lock_owned() |
| 311 | .ok() |
| 312 | } |
| 313 | |
| 314 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 315 | pub struct ProviderCatalogRefreshTicket { |
| 316 | provider: String, |
| 317 | provider_kind: ProviderKind, |
| 318 | fingerprint: Option<String>, |
| 319 | generation: u64, |
| 320 | durable_catalog: bool, |
| 321 | } |
| 322 | |
| 323 | /// Immutable, secret-free catalog rate evidence captured at dispatch. |
| 324 | /// |
| 325 | /// Rates are stored as canonical decimal strings rather than `f64` so route |
| 326 | /// receipts retain exact equality and stable JSON. `catalog_revision` binds |
| 327 | /// every identity, scope, timestamp, currency, provenance, and rate field; it |
| 328 | /// therefore changes even when two refreshes land in the same Unix second. |
| 329 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 330 | pub struct ProviderLivePricingQuote { |
| 331 | pub provider: ProviderKind, |
| 332 | pub provider_identity: String, |
| 333 | pub wire_model: String, |
| 334 | pub endpoint_fingerprint: String, |
| 335 | pub catalog_fetched_at: u64, |
| 336 | pub catalog_revision: String, |
| 337 | pub currency: Currency, |
| 338 | pub provenance: PricingProvenance, |
| 339 | pub cloud_facts: Option<CloudFactsPricingSource>, |
| 340 | pub pricing_schedule: Option<String>, |
| 341 | pub input_per_million: Option<String>, |
| 342 | pub output_per_million: Option<String>, |
| 343 | pub cache_read_per_million: Option<String>, |
| 344 | pub cache_write_per_million: Option<String>, |
| 345 | } |
| 346 | |
| 347 | /// Signed source identity and validity, bound into a frozen rate receipt. |
| 348 | /// The base URL is admitted only through the canonical official-endpoint |
| 349 | /// contract; custom URLs or credential-bearing URLs cannot enter this field. |
| 350 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 351 | pub struct CloudFactsPricingSource { |
| 352 | pub facts_version: u64, |
| 353 | pub key_id: String, |
| 354 | pub valid_until: Option<u64>, |
| 355 | pub base_url: String, |
| 356 | } |
| 357 | |
| 358 | #[derive(Serialize, Deserialize)] |
| 359 | struct ProviderLivePricingQuoteWire { |
| 360 | provider: String, |
| 361 | provider_identity: String, |
| 362 | wire_model: String, |
| 363 | endpoint_fingerprint: String, |
| 364 | catalog_fetched_at: u64, |
| 365 | catalog_revision: String, |
| 366 | currency: Currency, |
| 367 | provenance: PricingProvenance, |
| 368 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 369 | cloud_facts: Option<CloudFactsPricingSource>, |
| 370 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 371 | pricing_schedule: Option<String>, |
| 372 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 373 | input_per_million: Option<String>, |
| 374 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 375 | output_per_million: Option<String>, |
| 376 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 377 | cache_read_per_million: Option<String>, |
| 378 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 379 | cache_write_per_million: Option<String>, |
| 380 | } |
| 381 | |
| 382 | impl TryFrom<&ProviderLivePricingQuote> for ProviderLivePricingQuoteWire { |
| 383 | type Error = &'static str; |
| 384 | fn try_from(quote: &ProviderLivePricingQuote) -> Result<Self, Self::Error> { |
| 385 | let provider = codewhale_config::descriptors::tui_wire_tag_for_route( |
| 386 | quote.provider, |
| 387 | "e.provider_identity, |
| 388 | ) |
| 389 | .ok_or("contradictory pricing provider identity")?; |
| 390 | Ok(Self { |
| 391 | provider: provider.into(), |
| 392 | provider_identity: quote.provider_identity.clone(), |
| 393 | wire_model: quote.wire_model.clone(), |
| 394 | endpoint_fingerprint: quote.endpoint_fingerprint.clone(), |
| 395 | catalog_fetched_at: quote.catalog_fetched_at, |
| 396 | catalog_revision: quote.catalog_revision.clone(), |
| 397 | currency: quote.currency.clone(), |
| 398 | provenance: quote.provenance.clone(), |
| 399 | cloud_facts: quote.cloud_facts.clone(), |
| 400 | pricing_schedule: quote.pricing_schedule.clone(), |
| 401 | input_per_million: quote.input_per_million.clone(), |
| 402 | output_per_million: quote.output_per_million.clone(), |
| 403 | cache_read_per_million: quote.cache_read_per_million.clone(), |
| 404 | cache_write_per_million: quote.cache_write_per_million.clone(), |
| 405 | }) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | impl Serialize for ProviderLivePricingQuote { |
| 410 | fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 411 | where |
| 412 | S: serde::Serializer, |
| 413 | { |
| 414 | if !self.is_structurally_valid() { |
| 415 | return serializer.serialize_none(); |
| 416 | } |
| 417 | ProviderLivePricingQuoteWire::try_from(self) |
| 418 | .map_err(serde::ser::Error::custom)? |
| 419 | .serialize(serializer) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | impl<'de> Deserialize<'de> for ProviderLivePricingQuote { |
| 424 | fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> |
| 425 | where |
| 426 | D: serde::Deserializer<'de>, |
| 427 | { |
| 428 | let wire = ProviderLivePricingQuoteWire::deserialize(deserializer)?; |
| 429 | let provider = codewhale_config::descriptors::kind_from_tui_wire_tag( |
| 430 | &wire.provider, |
| 431 | &wire.provider_identity, |
| 432 | ) |
| 433 | .ok_or_else(|| serde::de::Error::custom("contradictory pricing provider identity"))?; |
| 434 | let quote = Self { |
| 435 | provider, |
| 436 | provider_identity: wire.provider_identity, |
| 437 | wire_model: wire.wire_model, |
| 438 | endpoint_fingerprint: wire.endpoint_fingerprint, |
| 439 | catalog_fetched_at: wire.catalog_fetched_at, |
| 440 | catalog_revision: wire.catalog_revision, |
| 441 | currency: wire.currency, |
| 442 | provenance: wire.provenance, |
| 443 | cloud_facts: wire.cloud_facts, |
| 444 | pricing_schedule: wire.pricing_schedule, |
| 445 | input_per_million: wire.input_per_million, |
| 446 | output_per_million: wire.output_per_million, |
| 447 | cache_read_per_million: wire.cache_read_per_million, |
| 448 | cache_write_per_million: wire.cache_write_per_million, |
| 449 | }; |
| 450 | quote |
| 451 | .is_structurally_valid() |
| 452 | .then_some(quote) |
| 453 | .ok_or_else(|| serde::de::Error::custom("invalid provider-live pricing quote")) |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | pub fn deserialize_optional_provider_live_pricing<'de, D>( |
| 458 | deserializer: D, |
| 459 | ) -> std::result::Result<Option<ProviderLivePricingQuote>, D::Error> |
| 460 | where |
| 461 | D: serde::Deserializer<'de>, |
| 462 | { |
| 463 | let value = Option::<serde_json::Value>::deserialize(deserializer)?; |
| 464 | Ok(value.and_then(|value| serde_json::from_value(value).ok())) |
| 465 | } |
| 466 | |
| 467 | impl ProviderLivePricingQuote { |
| 468 | /// Whether the quote names at least one rate. A `[[custom_models]]` row |
| 469 | /// declared only to add a model to a roster freezes a rate-less quote. |
| 470 | #[must_use] |
| 471 | pub fn carries_rates(&self) -> bool { |
| 472 | [ |
| 473 | &self.input_per_million, |
| 474 | &self.output_per_million, |
| 475 | &self.cache_read_per_million, |
| 476 | &self.cache_write_per_million, |
| 477 | ] |
| 478 | .into_iter() |
| 479 | .any(Option::is_some) |
| 480 | } |
| 481 | |
| 482 | pub fn carries_pricing_decision(&self) -> bool { |
| 483 | self.carries_rates() |
| 484 | || self |
| 485 | .pricing_schedule |
| 486 | .as_deref() |
| 487 | .filter(|schedule| schedule.len() <= 32_768) |
| 488 | .and_then(|schedule| { |
| 489 | serde_json::from_str::<(OfferingPricing, Option<OfferingPricing>)>(schedule) |
| 490 | .ok() |
| 491 | }) |
| 492 | .is_some_and(|(pricing, _)| pricing.has_any_price() || pricing.rate_withheld) |
| 493 | } |
| 494 | |
| 495 | pub fn secondary_pricing_for_route( |
| 496 | &self, |
| 497 | provider: ProviderKind, |
| 498 | identity: &str, |
| 499 | model: &str, |
| 500 | fingerprint: &str, |
| 501 | at: u64, |
| 502 | ) -> Option<OfferingPricing> { |
| 503 | self.pricing_for_route(provider, identity, model, fingerprint, at)?; |
| 504 | serde_json::from_str::<(OfferingPricing, Option<OfferingPricing>)>( |
| 505 | self.pricing_schedule.as_deref()?, |
| 506 | ) |
| 507 | .ok()? |
| 508 | .1 |
| 509 | } |
| 510 | |
| 511 | fn is_structurally_valid(&self) -> bool { |
| 512 | self.pricing_for_route( |
| 513 | self.provider, |
| 514 | &self.provider_identity, |
| 515 | &self.wire_model, |
| 516 | &self.endpoint_fingerprint, |
| 517 | self.catalog_fetched_at, |
| 518 | ) |
| 519 | .is_some() |
| 520 | } |
| 521 | fn canonical_rate(rate: Option<f64>) -> Option<String> { |
| 522 | rate.map(|rate| rate.to_string()) |
| 523 | } |
| 524 | |
| 525 | fn revision_for( |
| 526 | provider: ProviderKind, |
| 527 | provider_identity: &str, |
| 528 | wire_model: &str, |
| 529 | endpoint_fingerprint: &str, |
| 530 | catalog_fetched_at: u64, |
| 531 | currency: &Currency, |
| 532 | provenance: &PricingProvenance, |
| 533 | input_per_million: &Option<String>, |
| 534 | output_per_million: &Option<String>, |
| 535 | cache_read_per_million: &Option<String>, |
| 536 | cache_write_per_million: &Option<String>, |
| 537 | cloud_facts: Option<&CloudFactsPricingSource>, |
| 538 | pricing_schedule: Option<&str>, |
| 539 | ) -> Option<String> { |
| 540 | let payload = serde_json::to_vec(&( |
| 541 | "codewhale-provider-live-pricing-quote-v1", |
| 542 | codewhale_config::descriptors::tui_wire_tag_for_route(provider, provider_identity)?, |
| 543 | provider_identity, |
| 544 | wire_model, |
| 545 | endpoint_fingerprint, |
| 546 | catalog_fetched_at, |
| 547 | currency, |
| 548 | provenance, |
| 549 | input_per_million, |
| 550 | output_per_million, |
| 551 | cache_read_per_million, |
| 552 | cache_write_per_million, |
| 553 | )) |
| 554 | .ok()?; |
| 555 | // Preserve the existing provider-live wire revision. The additional |
| 556 | // cloud source is independently domain-separated and hashes the whole |
| 557 | // original binding as well as the signed version/key/expiry. |
| 558 | let payload = match cloud_facts { |
| 559 | Some(source) => { |
| 560 | serde_json::to_vec(&("codewhale-cloud-facts-pricing-quote-v1", payload, source)) |
| 561 | .ok()? |
| 562 | } |
| 563 | None => payload, |
| 564 | }; |
| 565 | let payload = match pricing_schedule { |
| 566 | Some(schedule) => { |
| 567 | serde_json::to_vec(&("codewhale-pricing-schedule-v2", payload, schedule)).ok()? |
| 568 | } |
| 569 | None => payload, |
| 570 | }; |
| 571 | Some(format!( |
| 572 | "sha256:{}", |
| 573 | codewhale_runtime::hashing::sha256_hex(payload) |
| 574 | )) |
| 575 | } |
| 576 | |
| 577 | fn from_pricing( |
| 578 | provider: ProviderKind, |
| 579 | provider_identity: &str, |
| 580 | wire_model: &str, |
| 581 | endpoint_fingerprint: &str, |
| 582 | catalog_fetched_at: u64, |
| 583 | pricing: &OfferingPricing, |
| 584 | ) -> Option<Self> { |
| 585 | let provider_identity = provider_identity.trim(); |
| 586 | let wire_model = wire_model.trim(); |
| 587 | if codewhale_runtime::safe_label::sanitize_persisted_route_label(provider_identity) |
| 588 | != provider_identity |
| 589 | || codewhale_runtime::safe_label::sanitize_persisted_route_label(wire_model) |
| 590 | != wire_model |
| 591 | { |
| 592 | return None; |
| 593 | } |
| 594 | let input_per_million = Self::canonical_rate(pricing.input_per_million); |
| 595 | let output_per_million = Self::canonical_rate(pricing.output_per_million); |
| 596 | let cache_read_per_million = Self::canonical_rate(pricing.cache_read_per_million); |
| 597 | let cache_write_per_million = Self::canonical_rate(pricing.cache_write_per_million); |
| 598 | let mut owned = pricing.clone(); |
| 599 | owned.provider = provider_identity.into(); |
| 600 | owned.wire_model_id = wire_model.into(); |
| 601 | let pricing_schedule = |
| 602 | Some(serde_json::to_string(&(owned, Option::<OfferingPricing>::None)).ok()?); |
| 603 | let catalog_revision = Self::revision_for( |
| 604 | provider, |
| 605 | provider_identity, |
| 606 | wire_model, |
| 607 | endpoint_fingerprint, |
| 608 | catalog_fetched_at, |
| 609 | &pricing.currency, |
| 610 | &pricing.provenance, |
| 611 | &input_per_million, |
| 612 | &output_per_million, |
| 613 | &cache_read_per_million, |
| 614 | &cache_write_per_million, |
| 615 | None, |
| 616 | pricing_schedule.as_deref(), |
| 617 | )?; |
| 618 | Some(Self { |
| 619 | provider, |
| 620 | provider_identity: provider_identity.to_string(), |
| 621 | wire_model: wire_model.to_string(), |
| 622 | endpoint_fingerprint: endpoint_fingerprint.to_string(), |
| 623 | catalog_fetched_at, |
| 624 | catalog_revision, |
| 625 | currency: pricing.currency.clone(), |
| 626 | provenance: pricing.provenance.clone(), |
| 627 | cloud_facts: None, |
| 628 | pricing_schedule, |
| 629 | input_per_million, |
| 630 | output_per_million, |
| 631 | cache_read_per_million, |
| 632 | cache_write_per_million, |
| 633 | }) |
| 634 | } |
| 635 | |
| 636 | fn parse_rate(rate: &Option<String>) -> Option<Option<f64>> { |
| 637 | let Some(rate) = rate else { |
| 638 | return Some(None); |
| 639 | }; |
| 640 | let parsed = rate.parse::<f64>().ok()?; |
| 641 | (parsed.is_finite() && parsed >= 0.0 && parsed.to_string() == *rate).then_some(Some(parsed)) |
| 642 | } |
| 643 | |
| 644 | /// Rehydrate the frozen row only when every receipt binding is intact. |
| 645 | /// This is deliberately cache-free: a refresh after dispatch cannot alter |
| 646 | /// an earlier turn, while malformed or legacy receipts fail closed. |
| 647 | pub fn pricing_for_route( |
| 648 | &self, |
| 649 | provider: ProviderKind, |
| 650 | provider_identity: &str, |
| 651 | wire_model: &str, |
| 652 | endpoint_fingerprint: &str, |
| 653 | dispatched_at_unix: u64, |
| 654 | ) -> Option<OfferingPricing> { |
| 655 | let provider_identity = provider_identity.trim(); |
| 656 | let wire_model = wire_model.trim(); |
| 657 | if self.provider != provider |
| 658 | || codewhale_runtime::safe_label::sanitize_persisted_route_label( |
| 659 | &self.provider_identity, |
| 660 | ) != self.provider_identity |
| 661 | || codewhale_runtime::safe_label::sanitize_persisted_route_label(&self.wire_model) |
| 662 | != self.wire_model |
| 663 | || self.endpoint_fingerprint.len() != 64 |
| 664 | || !self |
| 665 | .endpoint_fingerprint |
| 666 | .bytes() |
| 667 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 668 | || self.provider_identity != provider_identity |
| 669 | || self.wire_model != wire_model |
| 670 | || self.endpoint_fingerprint != endpoint_fingerprint |
| 671 | || self.catalog_fetched_at > dispatched_at_unix |
| 672 | || !(self.currency == Currency::Usd |
| 673 | || (self.currency == Currency::Cny |
| 674 | && self.provenance == PricingProvenance::UserOverride)) |
| 675 | { |
| 676 | return None; |
| 677 | } |
| 678 | match (&self.provenance, &self.cloud_facts) { |
| 679 | (PricingProvenance::UserOverride, None) => {} |
| 680 | ( |
| 681 | PricingProvenance::ModelsDevBundled |
| 682 | | PricingProvenance::ProviderDocs |
| 683 | | PricingProvenance::CodewhaleCatalog, |
| 684 | None, |
| 685 | ) if published_pricing_scope(provider, provider_identity, endpoint_fingerprint) => {} |
| 686 | (PricingProvenance::ModelsDevLive, None) |
| 687 | if dispatched_at_unix.saturating_sub(self.catalog_fetched_at) |
| 688 | < DEFAULT_PROVIDER_CATALOG_TTL_SECS |
| 689 | && published_pricing_scope( |
| 690 | provider, |
| 691 | provider_identity, |
| 692 | endpoint_fingerprint, |
| 693 | ) => {} |
| 694 | (PricingProvenance::ProviderLive, None) |
| 695 | if dispatched_at_unix.saturating_sub(self.catalog_fetched_at) |
| 696 | < DEFAULT_PROVIDER_CATALOG_TTL_SECS |
| 697 | && (reviewed_provider_live_scope( |
| 698 | provider, |
| 699 | provider_identity, |
| 700 | endpoint_fingerprint, |
| 701 | ) || published_pricing_scope( |
| 702 | provider, |
| 703 | provider_identity, |
| 704 | endpoint_fingerprint, |
| 705 | )) => {} |
| 706 | (PricingProvenance::CloudFacts, Some(source)) |
| 707 | if source.facts_version > 0 |
| 708 | && !source.key_id.is_empty() |
| 709 | && source.key_id.len() <= 128 |
| 710 | && source |
| 711 | .key_id |
| 712 | .bytes() |
| 713 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) |
| 714 | && source |
| 715 | .valid_until |
| 716 | .is_none_or(|expires| dispatched_at_unix <= expires) |
| 717 | && cloud_pricing_scope(provider, provider_identity, &source.base_url) |
| 718 | && base_url_fingerprint(&source.base_url) == endpoint_fingerprint => {} |
| 719 | _ => return None, |
| 720 | } |
| 721 | let input_per_million = Self::parse_rate(&self.input_per_million)?; |
| 722 | let output_per_million = Self::parse_rate(&self.output_per_million)?; |
| 723 | let cache_read_per_million = Self::parse_rate(&self.cache_read_per_million)?; |
| 724 | let cache_write_per_million = Self::parse_rate(&self.cache_write_per_million)?; |
| 725 | let cost = codewhale_config::models_dev::ModelsDevCost { |
| 726 | input: input_per_million, |
| 727 | output: output_per_million, |
| 728 | cache_read: cache_read_per_million, |
| 729 | cache_write: cache_write_per_million, |
| 730 | ..Default::default() |
| 731 | }; |
| 732 | if !codewhale_config::pricing::catalog_cost_is_valid(&cost) { |
| 733 | return None; |
| 734 | } |
| 735 | // A reviewed per-token route needs both ordinary request classes. Cache |
| 736 | // classes remain optional and fail closed later if a turn used them. |
| 737 | if self.provenance == PricingProvenance::ProviderLive |
| 738 | && (cost.input.is_none() || cost.output.is_none()) |
| 739 | { |
| 740 | return None; |
| 741 | } |
| 742 | if cost.input.is_none() |
| 743 | && cost.output.is_none() |
| 744 | && cost.cache_read.is_none() |
| 745 | && cost.cache_write.is_none() |
| 746 | && self.provenance != PricingProvenance::UserOverride |
| 747 | && self.pricing_schedule.is_none() |
| 748 | { |
| 749 | return None; |
| 750 | } |
| 751 | let expected_revision = Self::revision_for( |
| 752 | self.provider, |
| 753 | &self.provider_identity, |
| 754 | &self.wire_model, |
| 755 | &self.endpoint_fingerprint, |
| 756 | self.catalog_fetched_at, |
| 757 | &self.currency, |
| 758 | &self.provenance, |
| 759 | &self.input_per_million, |
| 760 | &self.output_per_million, |
| 761 | &self.cache_read_per_million, |
| 762 | &self.cache_write_per_million, |
| 763 | self.cloud_facts.as_ref(), |
| 764 | self.pricing_schedule.as_deref(), |
| 765 | )?; |
| 766 | if self.catalog_revision != expected_revision { |
| 767 | return None; |
| 768 | } |
| 769 | if let Some(schedule) = self.pricing_schedule.as_deref() { |
| 770 | if schedule.len() > 32_768 { |
| 771 | return None; |
| 772 | } |
| 773 | let (pricing, secondary): (OfferingPricing, Option<OfferingPricing>) = |
| 774 | serde_json::from_str(schedule).ok()?; |
| 775 | if pricing.provider != self.provider_identity |
| 776 | || pricing.wire_model_id != self.wire_model |
| 777 | || pricing.provenance != self.provenance |
| 778 | || pricing.currency != self.currency |
| 779 | || pricing.input_per_million != cost.input |
| 780 | || pricing.output_per_million != cost.output |
| 781 | || pricing.cache_read_per_million != cost.cache_read |
| 782 | || pricing.cache_write_per_million != cost.cache_write |
| 783 | || !codewhale_config::pricing::catalog_cost_is_valid(&pricing.cost_structure()) |
| 784 | || (matches!( |
| 785 | self.provenance, |
| 786 | PricingProvenance::ModelsDevLive | PricingProvenance::ProviderLive |
| 787 | ) && pricing.fetched_at.or(pricing.effective_at) |
| 788 | != Some(self.catalog_fetched_at)) |
| 789 | || (self.provenance == PricingProvenance::ProviderLive |
| 790 | && pricing.endpoint_fingerprint.as_deref() |
| 791 | != Some(self.endpoint_fingerprint.as_str())) |
| 792 | || (self.provenance != PricingProvenance::ModelsDevBundled |
| 793 | && pricing |
| 794 | .expires_at |
| 795 | .is_some_and(|expires| dispatched_at_unix >= expires)) |
| 796 | || secondary.as_ref().is_some_and(|row| { |
| 797 | row.provider != self.provider_identity |
| 798 | || row.wire_model_id != self.wire_model |
| 799 | || row.currency != Currency::Cny |
| 800 | || row.provenance != self.provenance |
| 801 | || self.provenance != PricingProvenance::ProviderDocs |
| 802 | || !codewhale_config::pricing::catalog_cost_is_valid(&row.cost_structure()) |
| 803 | }) |
| 804 | { |
| 805 | return None; |
| 806 | } |
| 807 | return Some(pricing); |
| 808 | } |
| 809 | Some(OfferingPricing { |
| 810 | provider: self.provider_identity.clone(), |
| 811 | wire_model_id: self.wire_model.clone(), |
| 812 | canonical_model: None, |
| 813 | currency: self.currency.clone(), |
| 814 | input_per_million: cost.input, |
| 815 | output_per_million: cost.output, |
| 816 | cache_read_per_million: cost.cache_read, |
| 817 | cache_write_per_million: cost.cache_write, |
| 818 | provenance: self.provenance.clone(), |
| 819 | effective_at: Some(self.catalog_fetched_at), |
| 820 | endpoint_fingerprint: Some(self.endpoint_fingerprint.clone()), |
| 821 | |
| 822 | ..Default::default() |
| 823 | }) |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 828 | struct PersistedProviderCatalogs { |
| 829 | schema_version: u32, |
| 830 | cache: ProviderCatalogCache, |
| 831 | } |
| 832 | |
| 833 | #[derive(Serialize)] |
| 834 | struct PersistedProviderCatalogsRef<'a> { |
| 835 | schema_version: u32, |
| 836 | cache: &'a ProviderCatalogCache, |
| 837 | } |
| 838 | |
| 839 | /// Resolve the cache under Codewhale's catalog state directory. |
| 840 | /// |
| 841 | /// Unguarded tests are confined to the TUI test root, matching the Models.dev |
| 842 | /// cache contract, so they never inspect a developer's real provider catalog. |
| 843 | #[must_use] |
| 844 | pub fn cache_path() -> Option<PathBuf> { |
| 845 | #[cfg(any(test, feature = "test-support"))] |
| 846 | { |
| 847 | if !crate::test_support::guarded_environment_provides_state_paths() { |
| 848 | return Some( |
| 849 | crate::test_support::unsealed_test_state_root() |
| 850 | .join("catalog") |
| 851 | .join(CACHE_FILE), |
| 852 | ); |
| 853 | } |
| 854 | } |
| 855 | codewhale_config::resolve_state_dir("catalog") |
| 856 | .ok() |
| 857 | .map(|dir| dir.join(CACHE_FILE)) |
| 858 | } |
| 859 | |
| 860 | fn canonical_provider_scope(provider: &str) -> String { |
| 861 | // Despite the historical name, this is the exact configured ownership |
| 862 | // scope. Never collapse a custom table that happens to resemble a built-in |
| 863 | // or setup-template alias. |
| 864 | crate::provider_lake::catalog_partition_key(provider) |
| 865 | } |
| 866 | |
| 867 | #[cfg(any(test, feature = "test-support"))] |
| 868 | fn inferred_provider_kind(identity: &str) -> ProviderKind { |
| 869 | // No recognized built-in spelling resolves to a compatible-template id, |
| 870 | // so the parse fallback below already answers Custom for every named |
| 871 | // custom table (#6289). |
| 872 | ProviderKind::parse(identity).unwrap_or(ProviderKind::Custom) |
| 873 | } |
| 874 | |
| 875 | fn storage_provider(kind: ProviderKind, identity: &str) -> String { |
| 876 | format!("{}:{}", kind.as_str(), identity.trim()) |
| 877 | } |
| 878 | |
| 879 | /// Providers whose model list is owned by their own `/v1/models` roster |
| 880 | /// rather than the cross-provider Models.dev snapshot: the named live |
| 881 | /// gateways, custom hosts whose private roster no snapshot can serve, and any |
| 882 | /// builtin name pointed at an endpoint outside its official family (#6289 |
| 883 | /// widened). |
| 884 | /// |
| 885 | /// `base_url` is what separates the last two: `openai` against |
| 886 | /// `api.openai.com` is the reviewed snapshot row, while `openai` against a |
| 887 | /// relay is a private roster only its own listing can describe. A vendor-named |
| 888 | /// table that actually relays a private host is as unserved by the snapshot as |
| 889 | /// a `[providers.<name>]` table is. The active-provider refresh and the |
| 890 | /// picker's freshness receipt both gate on this one predicate, so they cannot |
| 891 | /// drift apart. |
| 892 | #[cfg(any(test, feature = "test-support"))] |
| 893 | #[test] |
| 894 | fn orcarouter_and_existing_custom_routes_own_live_catalogs() { |
| 895 | assert!(provider_owns_live_catalog(ProviderKind::Orcarouter, "")); |
| 896 | assert!(provider_owns_live_catalog(ProviderKind::Custom, "")); |
| 897 | assert!(provider_owns_live_catalog(ProviderKind::Openrouter, "")); |
| 898 | assert!(provider_owns_live_catalog(ProviderKind::Ollama, "")); |
| 899 | assert!(provider_owns_live_catalog(ProviderKind::Vllm, "")); |
| 900 | assert!(provider_owns_live_catalog(ProviderKind::Sglang, "")); |
| 901 | // A builtin name on its own official endpoint keeps the snapshot row. |
| 902 | assert!(!provider_owns_live_catalog( |
| 903 | ProviderKind::Openai, |
| 904 | "https://api.openai.com/v1" |
| 905 | )); |
| 906 | // The same name on a private relay owns its roster. |
| 907 | assert!(provider_owns_live_catalog( |
| 908 | ProviderKind::Openai, |
| 909 | "https://relay.example.test/v1" |
| 910 | )); |
| 911 | } |
| 912 | |
| 913 | pub fn provider_owns_live_catalog(provider: ProviderKind, base_url: &str) -> bool { |
| 914 | if crate::client::model_listing_unavailable(provider, base_url) { |
| 915 | return false; |
| 916 | } |
| 917 | matches!( |
| 918 | provider, |
| 919 | ProviderKind::Openrouter |
| 920 | | ProviderKind::OpencodeGo |
| 921 | | ProviderKind::Orcarouter |
| 922 | | ProviderKind::Telecomjs |
| 923 | | ProviderKind::Edenai |
| 924 | | ProviderKind::Zenmux |
| 925 | | ProviderKind::Concentrate |
| 926 | | ProviderKind::Codewhale |
| 927 | | ProviderKind::Ollama |
| 928 | | ProviderKind::Vllm |
| 929 | | ProviderKind::Sglang |
| 930 | ) || provider == ProviderKind::Custom |
| 931 | || codewhale_config::provider_preserves_custom_base_url_model(provider, base_url) |
| 932 | } |
| 933 | |
| 934 | /// Whether a persisted `/models` partition is current evidence for its route. |
| 935 | /// |
| 936 | /// A route that owns its own roster (a relay, a private endpoint) is |
| 937 | /// authoritative even when the fetch is old: nothing else describes it. For an |
| 938 | /// official endpoint the partition competes with the catalog snapshot, and an |
| 939 | /// old or failed fetch is not evidence about what is served today, so it must |
| 940 | /// not shadow a fresher roster. |
| 941 | pub fn cached_roster_is_authoritative( |
| 942 | kind: ProviderKind, |
| 943 | base_url: &str, |
| 944 | entry: &codewhale_config::catalog::CachedProviderCatalog, |
| 945 | ) -> bool { |
| 946 | (kind != ProviderKind::OpencodeGo && provider_owns_live_catalog(kind, base_url)) |
| 947 | || entry.is_fresh(codewhale_config::catalog::now_unix()) |
| 948 | } |
| 949 | |
| 950 | /// Whether a catalog scope holds an account-scoped roster that must never be |
| 951 | /// shared across credentials (#6289). |
| 952 | /// |
| 953 | /// Baseten's `/models` answers per workspace, so its rows are fenced by |
| 954 | /// endpoint fingerprint — never by table name. The Codewhale API's own rows |
| 955 | /// are fenced the same way. |
| 956 | fn is_account_scoped_scope(provider: &str, fingerprint: &str) -> bool { |
| 957 | codewhale_plugins::providers::is_account_catalog_scope(provider, fingerprint) |
| 958 | || provider.starts_with("codewhale:") |
| 959 | || provider.starts_with("opencode-go:") |
| 960 | || fingerprint == base_url_fingerprint(codewhale_config::catalog::BASETEN_BASE_URL) |
| 961 | || fingerprint |
| 962 | == base_url_fingerprint(ProviderKind::Codewhale.provider().default_base_url()) |
| 963 | } |
| 964 | |
| 965 | pub fn route_is_account_scoped( |
| 966 | config: &Config, |
| 967 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 968 | ) -> bool { |
| 969 | is_account_scoped_scope( |
| 970 | &storage_provider( |
| 971 | identity.provider, |
| 972 | &canonical_provider_scope(identity.key.as_str()), |
| 973 | ), |
| 974 | &base_url_fingerprint(&config.base_url_for_route(identity)), |
| 975 | ) |
| 976 | } |
| 977 | |
| 978 | fn cache_lock_path(path: &Path) -> PathBuf { |
| 979 | let mut name = path |
| 980 | .file_name() |
| 981 | .map(|name| name.to_os_string()) |
| 982 | .unwrap_or_else(|| CACHE_FILE.into()); |
| 983 | name.push(".lock"); |
| 984 | path.with_file_name(name) |
| 985 | } |
| 986 | |
| 987 | fn open_cache_lock(path: &Path) -> Result<fs::File> { |
| 988 | let parent = path |
| 989 | .parent() |
| 990 | .context("provider catalog lock path has no parent")?; |
| 991 | fs::create_dir_all(parent) |
| 992 | .with_context(|| format!("create provider catalog directory {}", parent.display()))?; |
| 993 | let mut options = OpenOptions::new(); |
| 994 | options.read(true).write(true).create(true).truncate(false); |
| 995 | #[cfg(unix)] |
| 996 | { |
| 997 | use std::os::unix::fs::OpenOptionsExt as _; |
| 998 | options |
| 999 | .mode(0o600) |
| 1000 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK); |
| 1001 | } |
| 1002 | #[cfg(windows)] |
| 1003 | { |
| 1004 | use std::os::windows::fs::OpenOptionsExt as _; |
| 1005 | options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT |
| 1006 | } |
| 1007 | let file = options |
| 1008 | .open(path) |
| 1009 | .with_context(|| format!("open provider catalog lock {}", path.display()))?; |
| 1010 | let metadata = file |
| 1011 | .metadata() |
| 1012 | .with_context(|| format!("inspect provider catalog lock {}", path.display()))?; |
| 1013 | anyhow::ensure!( |
| 1014 | metadata.is_file(), |
| 1015 | "provider catalog lock {} must be a regular file", |
| 1016 | path.display() |
| 1017 | ); |
| 1018 | #[cfg(unix)] |
| 1019 | { |
| 1020 | use std::os::unix::fs::MetadataExt as _; |
| 1021 | anyhow::ensure!( |
| 1022 | metadata.nlink() == 1, |
| 1023 | "provider catalog lock {} must not be hard linked", |
| 1024 | path.display() |
| 1025 | ); |
| 1026 | } |
| 1027 | #[cfg(windows)] |
| 1028 | { |
| 1029 | use std::os::windows::fs::MetadataExt as _; |
| 1030 | const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; |
| 1031 | anyhow::ensure!( |
| 1032 | metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0, |
| 1033 | "provider catalog lock {} must not be a reparse point", |
| 1034 | path.display() |
| 1035 | ); |
| 1036 | } |
| 1037 | Ok(file) |
| 1038 | } |
| 1039 | |
| 1040 | fn load_from_disk_unlocked_with_limit(path: &Path, max_bytes: u64) -> Option<ProviderCatalogCache> { |
| 1041 | let mut options = OpenOptions::new(); |
| 1042 | options.read(true); |
| 1043 | #[cfg(unix)] |
| 1044 | { |
| 1045 | use std::os::unix::fs::OpenOptionsExt as _; |
| 1046 | options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK); |
| 1047 | } |
| 1048 | #[cfg(windows)] |
| 1049 | { |
| 1050 | use std::os::windows::fs::OpenOptionsExt as _; |
| 1051 | options.custom_flags(0x0020_0000); |
| 1052 | } |
| 1053 | let file = options.open(path).ok()?; |
| 1054 | let metadata = file.metadata().ok()?; |
| 1055 | if !metadata.is_file() { |
| 1056 | return None; |
| 1057 | } |
| 1058 | #[cfg(unix)] |
| 1059 | { |
| 1060 | use std::os::unix::fs::MetadataExt as _; |
| 1061 | if metadata.nlink() != 1 { |
| 1062 | return None; |
| 1063 | } |
| 1064 | } |
| 1065 | #[cfg(windows)] |
| 1066 | { |
| 1067 | use std::os::windows::fs::MetadataExt as _; |
| 1068 | if metadata.file_attributes() & 0x0000_0400 != 0 { |
| 1069 | return None; |
| 1070 | } |
| 1071 | } |
| 1072 | if metadata.len() > max_bytes { |
| 1073 | tracing::debug!( |
| 1074 | target: "provider_catalog", |
| 1075 | path = %path.display(), |
| 1076 | max_bytes, |
| 1077 | "provider catalog cache exceeds read limit" |
| 1078 | ); |
| 1079 | return None; |
| 1080 | } |
| 1081 | // Re-check through `take`: the file can grow after metadata is sampled. |
| 1082 | let mut body = Vec::new(); |
| 1083 | file.take(max_bytes.saturating_add(1)) |
| 1084 | .read_to_end(&mut body) |
| 1085 | .ok()?; |
| 1086 | if body.len() as u64 > max_bytes { |
| 1087 | return None; |
| 1088 | } |
| 1089 | let persisted: PersistedProviderCatalogs = serde_json::from_slice(&body).ok()?; |
| 1090 | if persisted.schema_version == 2 { |
| 1091 | return Some(ProviderCatalogCache::new()); |
| 1092 | } |
| 1093 | if persisted.schema_version != CACHE_SCHEMA_VERSION { |
| 1094 | return None; |
| 1095 | } |
| 1096 | let mut cache = persisted.cache; |
| 1097 | if cache.entries.len() > MAX_CACHE_SCOPES || cached_row_count(&cache) > MAX_CACHE_ROWS { |
| 1098 | return None; |
| 1099 | } |
| 1100 | let scopes_before = cache.entries.len(); |
| 1101 | cache.entries.retain(|key, entry| { |
| 1102 | let Some((kind, identity)) = entry.provider.split_once(':') else { |
| 1103 | return false; |
| 1104 | }; |
| 1105 | let parsed_kind = |
| 1106 | ProviderKind::parse_config_identity(kind).filter(|parsed| parsed.as_str() == kind); |
| 1107 | let scope_valid = parsed_kind.is_some() |
| 1108 | && !identity.is_empty() |
| 1109 | && key |
| 1110 | == &ProviderCatalogCache::cache_key(&entry.provider, &entry.base_url_fingerprint); |
| 1111 | if !scope_valid { |
| 1112 | tracing::debug!( |
| 1113 | target: "provider_catalog", |
| 1114 | scope = %entry.provider, |
| 1115 | "dropping invalid provider catalog scope" |
| 1116 | ); |
| 1117 | return false; |
| 1118 | } |
| 1119 | let parsed_kind = parsed_kind.expect("validated kind"); |
| 1120 | let entry_fingerprint = entry.base_url_fingerprint.clone(); |
| 1121 | let entry_fetched_at = entry.fetched_at; |
| 1122 | let rows_before = entry.offerings.len(); |
| 1123 | entry.offerings.retain(|row| { |
| 1124 | row.provider == identity |
| 1125 | && codewhale_runtime::catalog_cache::valid_catalog_model_id(&row.wire_model_id) |
| 1126 | && provider_cost_source_allowed(row) |
| 1127 | && matches!(&row.source, codewhale_config::catalog::CatalogSource::Live { |
| 1128 | base_url_fingerprint, fetched_at |
| 1129 | } if base_url_fingerprint == &entry_fingerprint && *fetched_at == entry_fetched_at) |
| 1130 | }); |
| 1131 | normalize_provider_catalog_offerings(parsed_kind, &entry_fingerprint, &mut entry.offerings); |
| 1132 | if entry.offerings.len() != rows_before { |
| 1133 | tracing::warn!( |
| 1134 | target: "provider_catalog", |
| 1135 | scope = %entry.provider, |
| 1136 | rejected = rows_before - entry.offerings.len(), |
| 1137 | kept = entry.offerings.len(), |
| 1138 | "dropped unusable rows from a cached provider catalog" |
| 1139 | ); |
| 1140 | } |
| 1141 | if rows_before > 0 && entry.offerings.is_empty() { |
| 1142 | tracing::debug!( |
| 1143 | target: "provider_catalog", |
| 1144 | scope = %entry.provider, |
| 1145 | "dropping provider catalog scope whose every row was unusable" |
| 1146 | ); |
| 1147 | return false; |
| 1148 | } |
| 1149 | true |
| 1150 | }); |
| 1151 | if cache.entries.len() != scopes_before { |
| 1152 | tracing::debug!( |
| 1153 | target: "provider_catalog", |
| 1154 | dropped = scopes_before - cache.entries.len(), |
| 1155 | "provider catalog cache loaded with invalid scopes dropped" |
| 1156 | ); |
| 1157 | } |
| 1158 | // Older builds could durably cache account-scoped rosters. Scrub |
| 1159 | // those entries on every load so upgrading cannot attach one workspace's |
| 1160 | // catalog to a different credential. |
| 1161 | cache |
| 1162 | .entries |
| 1163 | .retain(|_, entry| !is_account_scoped_scope(&entry.provider, &entry.base_url_fingerprint)); |
| 1164 | Some(cache) |
| 1165 | } |
| 1166 | |
| 1167 | fn normalize_google_wire_model_id(wire_model_id: &str) -> Option<&str> { |
| 1168 | let trimmed = wire_model_id.trim(); |
| 1169 | const PREFIX: &str = "models/"; |
| 1170 | if trimmed.len() > PREFIX.len() |
| 1171 | && trimmed.as_bytes()[..PREFIX.len()].eq_ignore_ascii_case(PREFIX.as_bytes()) |
| 1172 | { |
| 1173 | let bare = trimmed[PREFIX.len()..].trim(); |
| 1174 | if codewhale_runtime::catalog_cache::valid_catalog_model_id(bare) { |
| 1175 | return Some(bare); |
| 1176 | } |
| 1177 | } |
| 1178 | None |
| 1179 | } |
| 1180 | |
| 1181 | fn normalize_provider_catalog_offerings( |
| 1182 | kind: ProviderKind, |
| 1183 | fingerprint: &str, |
| 1184 | offerings: &mut Vec<codewhale_config::catalog::CatalogOffering>, |
| 1185 | ) { |
| 1186 | if kind != ProviderKind::Google |
| 1187 | || !codewhale_config::provider_published_pricing_base_urls(kind) |
| 1188 | .iter() |
| 1189 | .any(|url| base_url_fingerprint(url) == fingerprint) |
| 1190 | { |
| 1191 | return; |
| 1192 | } |
| 1193 | let mut seen = std::collections::HashSet::with_capacity(offerings.len()); |
| 1194 | offerings.retain_mut(|row| { |
| 1195 | if let Some(bare) = normalize_google_wire_model_id(&row.wire_model_id) { |
| 1196 | row.wire_model_id = bare.to_string(); |
| 1197 | } |
| 1198 | seen.insert(row.wire_model_id.clone()) |
| 1199 | }); |
| 1200 | } |
| 1201 | |
| 1202 | fn provider_cost_source_allowed(row: &codewhale_config::catalog::CatalogOffering) -> bool { |
| 1203 | use codewhale_config::catalog::CatalogSource; |
| 1204 | matches!( |
| 1205 | row.cost_source, |
| 1206 | None | Some( |
| 1207 | CatalogSource::Bundled |
| 1208 | | CatalogSource::CodewhaleBundled { .. } |
| 1209 | | CatalogSource::ModelsDevLive { .. } |
| 1210 | ) |
| 1211 | ) |
| 1212 | } |
| 1213 | |
| 1214 | fn load_from_disk_unlocked(path: &Path) -> Option<ProviderCatalogCache> { |
| 1215 | load_from_disk_unlocked_with_limit(path, MAX_CACHE_BYTES) |
| 1216 | } |
| 1217 | |
| 1218 | fn load_from_disk() -> Option<ProviderCatalogCache> { |
| 1219 | let path = cache_path()?; |
| 1220 | if !path.is_file() { |
| 1221 | return None; |
| 1222 | } |
| 1223 | let lock_file = open_cache_lock(&cache_lock_path(&path)).ok()?; |
| 1224 | let lock = fd_lock::RwLock::new(lock_file); |
| 1225 | let _guard = lock.read().ok()?; |
| 1226 | load_from_disk_unlocked(&path) |
| 1227 | } |
| 1228 | |
| 1229 | fn ensure_cache_loaded() -> Result<()> { |
| 1230 | if DISK_LOADED.load(Ordering::Acquire) { |
| 1231 | return Ok(()); |
| 1232 | } |
| 1233 | let mut cache = CACHE |
| 1234 | .write() |
| 1235 | .map_err(|_| anyhow::anyhow!("catalog cache unavailable"))?; |
| 1236 | if DISK_LOADED.load(Ordering::Acquire) { |
| 1237 | return Ok(()); |
| 1238 | } |
| 1239 | if let Some(path) = cache_path() { |
| 1240 | match fs::symlink_metadata(&path) { |
| 1241 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} |
| 1242 | Err(err) => return Err(err.into()), |
| 1243 | Ok(_) => { |
| 1244 | let loaded = load_from_disk().context("invalid provider catalog cache")?; |
| 1245 | for (key, entry) in loaded.entries { |
| 1246 | if cache |
| 1247 | .entries |
| 1248 | .get(&key) |
| 1249 | .is_none_or(|local| entry.fetched_at >= local.fetched_at) |
| 1250 | { |
| 1251 | cache.entries.insert(key, entry); |
| 1252 | } |
| 1253 | } |
| 1254 | } |
| 1255 | } |
| 1256 | } |
| 1257 | DISK_LOADED.store(true, Ordering::Release); |
| 1258 | Ok(()) |
| 1259 | } |
| 1260 | |
| 1261 | /// Read one exact cached route without creating a client or fetching credentials. |
| 1262 | pub fn cached_entry_for_route( |
| 1263 | kind: ProviderKind, |
| 1264 | identity: &str, |
| 1265 | base_url: &str, |
| 1266 | ) -> Result<Option<codewhale_config::catalog::CachedProviderCatalog>> { |
| 1267 | ensure_cache_loaded()?; |
| 1268 | let cache = CACHE |
| 1269 | .read() |
| 1270 | .map_err(|_| anyhow::anyhow!("catalog cache unavailable"))?; |
| 1271 | Ok(cache |
| 1272 | .get( |
| 1273 | &storage_provider(kind, identity), |
| 1274 | &base_url_fingerprint(base_url), |
| 1275 | ) |
| 1276 | .cloned()) |
| 1277 | } |
| 1278 | |
| 1279 | /// Borrow one exact cached route for the duration of `read`. |
| 1280 | /// |
| 1281 | /// The picker asks about one route once per model row, and on a relay |
| 1282 | /// publishing a few hundred models that turned into one full deep clone of the |
| 1283 | /// whole catalog entry per row. Callers that only need to look something up |
| 1284 | /// (rather than keep the entry) use this instead. |
| 1285 | pub fn with_cached_entry_for_route<R>( |
| 1286 | kind: ProviderKind, |
| 1287 | identity: &str, |
| 1288 | base_url: &str, |
| 1289 | read: impl FnOnce(&codewhale_config::catalog::CachedProviderCatalog) -> R, |
| 1290 | ) -> Result<Option<R>> { |
| 1291 | ensure_cache_loaded()?; |
| 1292 | let cache = CACHE |
| 1293 | .read() |
| 1294 | .map_err(|_| anyhow::anyhow!("catalog cache unavailable"))?; |
| 1295 | Ok(cache |
| 1296 | .get( |
| 1297 | &storage_provider(kind, identity), |
| 1298 | &base_url_fingerprint(base_url), |
| 1299 | ) |
| 1300 | .map(read)) |
| 1301 | } |
| 1302 | |
| 1303 | /// Whether a saved `(provider, model)` pin is absent from that exact route's |
| 1304 | /// FRESH live roster (#6035). `None` when no fresh roster exists: a stale, |
| 1305 | /// failed, or absent roster cannot prove drift, and bundled catalog rows say |
| 1306 | /// nothing about what the account serves today. Absence is a warning, never a |
| 1307 | /// reason to rewrite the pin: the id may still answer (soft deprecation) and |
| 1308 | /// other hosts may serve it on their own routes. |
| 1309 | pub fn pin_missing_from_fresh_roster(config: &Config, provider: &str, model: &str) -> Option<bool> { |
| 1310 | let captured = config.resolve_provider_pin_identity(provider).ok()?; |
| 1311 | let kind = captured.provider; |
| 1312 | let identity = captured.key.as_str(); |
| 1313 | let base_url = config.base_url_for_route(&captured); |
| 1314 | // `status_for_route` reads memory only. A fresh process (doctor, a |
| 1315 | // just-started TUI) must see the roster an earlier process persisted. |
| 1316 | ensure_cache_loaded().ok()?; |
| 1317 | if status_for_route(kind, identity, &base_url) != CatalogStatus::Fresh { |
| 1318 | return None; |
| 1319 | } |
| 1320 | let normalized_pin = if kind == ProviderKind::Google { |
| 1321 | normalize_google_wire_model_id(model).unwrap_or(model) |
| 1322 | } else { |
| 1323 | model |
| 1324 | }; |
| 1325 | let listed = cached_entry_for_route(kind, identity, &base_url) |
| 1326 | .ok() |
| 1327 | .flatten() |
| 1328 | .is_some_and(|entry| { |
| 1329 | entry.offerings.iter().any(|offering| { |
| 1330 | offering.wire_model_id == model |
| 1331 | || offering.wire_model_id == normalized_pin |
| 1332 | || offering.canonical_model.as_deref() == Some(model) |
| 1333 | || offering.canonical_model.as_deref() == Some(normalized_pin) |
| 1334 | }) |
| 1335 | }); |
| 1336 | Some(!listed) |
| 1337 | } |
| 1338 | |
| 1339 | fn merge_durable_scope( |
| 1340 | mut durable_cache: ProviderCatalogCache, |
| 1341 | process_cache: &ProviderCatalogCache, |
| 1342 | provider: &str, |
| 1343 | fingerprint: &str, |
| 1344 | durable_catalog: bool, |
| 1345 | ) -> ProviderCatalogCache { |
| 1346 | durable_cache |
| 1347 | .entries |
| 1348 | .retain(|_, entry| !is_account_scoped_scope(&entry.provider, &entry.base_url_fingerprint)); |
| 1349 | if durable_catalog |
| 1350 | && !is_account_scoped_scope(provider, fingerprint) |
| 1351 | && let Some(entry) = process_cache.get(provider, fingerprint).cloned() |
| 1352 | { |
| 1353 | durable_cache.entries.insert( |
| 1354 | ProviderCatalogCache::cache_key(provider, fingerprint), |
| 1355 | entry, |
| 1356 | ); |
| 1357 | } |
| 1358 | durable_cache |
| 1359 | } |
| 1360 | |
| 1361 | fn persisted_envelope_len(cache: &ProviderCatalogCache) -> Result<u64> { |
| 1362 | struct Counter(u64); |
| 1363 | impl std::io::Write for Counter { |
| 1364 | fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 1365 | self.0 = self.0.saturating_add(bytes.len() as u64); |
| 1366 | Ok(bytes.len()) |
| 1367 | } |
| 1368 | fn flush(&mut self) -> std::io::Result<()> { |
| 1369 | Ok(()) |
| 1370 | } |
| 1371 | } |
| 1372 | let envelope = PersistedProviderCatalogsRef { |
| 1373 | schema_version: CACHE_SCHEMA_VERSION, |
| 1374 | cache, |
| 1375 | }; |
| 1376 | let mut counter = Counter(0); |
| 1377 | serde_json::to_writer_pretty(&mut counter, &envelope) |
| 1378 | .context("measure provider catalog cache for bounded persistence")?; |
| 1379 | Ok(counter.0.saturating_add(1)) |
| 1380 | } |
| 1381 | |
| 1382 | fn cached_row_count(cache: &ProviderCatalogCache) -> usize { |
| 1383 | cache.entries.values().fold(0usize, |total, entry| { |
| 1384 | total.saturating_add(entry.offerings.len()) |
| 1385 | }) |
| 1386 | } |
| 1387 | |
| 1388 | /// Compact a durable cache without ever truncating one provider roster. |
| 1389 | /// |
| 1390 | /// The exact scope being written is protected: if that scope alone fits, older |
| 1391 | /// failed/stale scopes are evicted whole until the envelope is bounded. If the |
| 1392 | /// protected scope alone does not fit, persistence is refused and the prior |
| 1393 | /// atomic file remains intact. This avoids both self-bricking the 32 MiB read |
| 1394 | /// limit and turning a partial provider roster into false authoritative truth. |
| 1395 | fn bounded_cache_for_persistence( |
| 1396 | mut cache: ProviderCatalogCache, |
| 1397 | protected_scope: Option<(&str, &str)>, |
| 1398 | now: u64, |
| 1399 | limits: CachePersistenceLimits, |
| 1400 | ) -> Result<ProviderCatalogCache> { |
| 1401 | cache |
| 1402 | .entries |
| 1403 | .retain(|_, entry| !is_account_scoped_scope(&entry.provider, &entry.base_url_fingerprint)); |
| 1404 | |
| 1405 | let protected_key = protected_scope |
| 1406 | .filter(|(provider, fingerprint)| !is_account_scoped_scope(provider, fingerprint)) |
| 1407 | .map(|(provider, fingerprint)| ProviderCatalogCache::cache_key(provider, fingerprint)); |
| 1408 | |
| 1409 | if let Some(key) = protected_key.as_deref() |
| 1410 | && let Some(entry) = cache.entries.get(key).cloned() |
| 1411 | { |
| 1412 | let mut protected_only = ProviderCatalogCache::new(); |
| 1413 | protected_only.entries.insert(key.to_string(), entry); |
| 1414 | anyhow::ensure!( |
| 1415 | protected_only.entries.len() <= limits.max_scopes.min(MAX_CACHE_SCOPES) |
| 1416 | && cached_row_count(&protected_only) <= limits.max_rows |
| 1417 | && persisted_envelope_len(&protected_only)? <= limits.max_bytes, |
| 1418 | "provider catalog scope {key:?} exceeds bounded persistence limits" |
| 1419 | ); |
| 1420 | } |
| 1421 | |
| 1422 | // Rank once while the cache/file locks are held. An older implementation |
| 1423 | // reserialized and rescanned the entire envelope for every eviction, which |
| 1424 | // made a valid sub-32-MiB file with many tiny scopes quadratic to compact. |
| 1425 | let mut eviction_keys = cache |
| 1426 | .entries |
| 1427 | .iter() |
| 1428 | .filter(|(key, _)| protected_key.as_deref() != Some(key.as_str())) |
| 1429 | .map(|(key, entry)| { |
| 1430 | let health_rank = if matches!(entry.status, CatalogStatus::Failed { .. }) { |
| 1431 | 0u8 |
| 1432 | } else if entry.is_stale(now) || matches!(entry.status, CatalogStatus::Stale { .. }) { |
| 1433 | 1u8 |
| 1434 | } else { |
| 1435 | 2u8 |
| 1436 | }; |
| 1437 | (health_rank, entry.fetched_at, key.clone()) |
| 1438 | }) |
| 1439 | .collect::<Vec<_>>(); |
| 1440 | eviction_keys.sort(); |
| 1441 | let eviction_keys = eviction_keys |
| 1442 | .into_iter() |
| 1443 | .map(|(_, _, key)| key) |
| 1444 | .collect::<Vec<_>>(); |
| 1445 | let mut eviction_index = 0usize; |
| 1446 | let mut rows = cached_row_count(&cache); |
| 1447 | let max_scopes = limits.max_scopes.min(MAX_CACHE_SCOPES); |
| 1448 | |
| 1449 | let mut evict_next = |cache: &mut ProviderCatalogCache| -> Result<usize> { |
| 1450 | let key = eviction_keys |
| 1451 | .get(eviction_index) |
| 1452 | .context("provider catalog envelope cannot fit even after whole-scope compaction")?; |
| 1453 | eviction_index = eviction_index.saturating_add(1); |
| 1454 | let entry = cache |
| 1455 | .entries |
| 1456 | .remove(key) |
| 1457 | .context("provider catalog eviction candidate disappeared")?; |
| 1458 | Ok(entry.offerings.len()) |
| 1459 | }; |
| 1460 | |
| 1461 | // First enforce the cheap cardinality limits in bulk. Only after at most 64 |
| 1462 | // scopes remain do we serialize to enforce the exact on-disk byte limit. |
| 1463 | while cache.entries.len() > max_scopes || rows > limits.max_rows { |
| 1464 | rows = rows.saturating_sub(evict_next(&mut cache)?); |
| 1465 | } |
| 1466 | while persisted_envelope_len(&cache)? > limits.max_bytes { |
| 1467 | let _removed_rows = evict_next(&mut cache)?; |
| 1468 | } |
| 1469 | |
| 1470 | Ok(cache) |
| 1471 | } |
| 1472 | |
| 1473 | fn write_bounded_cache( |
| 1474 | path: &Path, |
| 1475 | cache: ProviderCatalogCache, |
| 1476 | protected_scope: Option<(&str, &str)>, |
| 1477 | limits: CachePersistenceLimits, |
| 1478 | ) -> Result<()> { |
| 1479 | let cache = bounded_cache_for_persistence(cache, protected_scope, now_unix(), limits)?; |
| 1480 | let envelope = PersistedProviderCatalogs { |
| 1481 | schema_version: CACHE_SCHEMA_VERSION, |
| 1482 | cache, |
| 1483 | }; |
| 1484 | anyhow::ensure!( |
| 1485 | persisted_envelope_len(&envelope.cache)? <= limits.max_bytes, |
| 1486 | "bounded provider catalog cache exceeds its write limit" |
| 1487 | ); |
| 1488 | atomic_write_json(path, &envelope) |
| 1489 | } |
| 1490 | |
| 1491 | fn persist_scope( |
| 1492 | cache: &ProviderCatalogCache, |
| 1493 | provider: &str, |
| 1494 | fingerprint: &str, |
| 1495 | durable_catalog: bool, |
| 1496 | ) -> bool { |
| 1497 | let Some(path) = cache_path() else { |
| 1498 | return false; |
| 1499 | }; |
| 1500 | let provider = canonical_provider_scope(provider); |
| 1501 | let result = (|| -> Result<()> { |
| 1502 | let lock_file = open_cache_lock(&cache_lock_path(&path))?; |
| 1503 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 1504 | let _guard = lock |
| 1505 | .write() |
| 1506 | .with_context(|| format!("write-lock provider catalog cache {}", path.display()))?; |
| 1507 | // Merge only the exact scope this process just changed into the latest |
| 1508 | // disk snapshot. A stale long-running TUI therefore cannot erase a |
| 1509 | // different scope written by the Runtime API (or vice versa). |
| 1510 | let prior_cache = if path.exists() { |
| 1511 | load_from_disk_unlocked(&path).context("invalid prior catalog cache")? |
| 1512 | } else { |
| 1513 | ProviderCatalogCache::new() |
| 1514 | }; |
| 1515 | let prior_was_empty = prior_cache.entries.is_empty(); |
| 1516 | let durable_cache = |
| 1517 | merge_durable_scope(prior_cache, cache, &provider, fingerprint, durable_catalog); |
| 1518 | if !durable_catalog && prior_was_empty && durable_cache.entries.is_empty() { |
| 1519 | return Ok(()); |
| 1520 | } |
| 1521 | write_bounded_cache( |
| 1522 | &path, |
| 1523 | durable_cache, |
| 1524 | Some((&provider, fingerprint)), |
| 1525 | CACHE_PERSISTENCE_LIMITS, |
| 1526 | ) |
| 1527 | .with_context(|| format!("atomically write provider catalog {}", path.display())) |
| 1528 | })(); |
| 1529 | if let Err(error) = result { |
| 1530 | tracing::debug!( |
| 1531 | target: "provider_catalog", |
| 1532 | error = %error, |
| 1533 | "provider catalog cache write failed" |
| 1534 | ); |
| 1535 | return false; |
| 1536 | } |
| 1537 | true |
| 1538 | } |
| 1539 | |
| 1540 | /// Persist a failure without letting a stale process replace newer rows from |
| 1541 | /// another Codewhale process for the same exact scope. |
| 1542 | /// |
| 1543 | /// The ordinary scoped merge is sufficient for successes because the response |
| 1544 | /// being committed is the new roster. A failure is different: its process may |
| 1545 | /// have started with an older last-known-good entry. Re-read the durable exact |
| 1546 | /// scope while holding the cross-process write lock, prefer it when it is at |
| 1547 | /// least as recent, then change only the status before writing. Thus a failed |
| 1548 | /// refresh can preserve the newest roster without resurrecting its own stale |
| 1549 | /// snapshot over another process's success. |
| 1550 | fn persist_failure_scope( |
| 1551 | cache: &mut ProviderCatalogCache, |
| 1552 | provider: &str, |
| 1553 | fingerprint: &str, |
| 1554 | reason: CatalogRefreshError, |
| 1555 | ) { |
| 1556 | let Some(path) = cache_path() else { |
| 1557 | return; |
| 1558 | }; |
| 1559 | let provider = canonical_provider_scope(provider); |
| 1560 | let result = (|| -> Result<()> { |
| 1561 | let lock_file = open_cache_lock(&cache_lock_path(&path))?; |
| 1562 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 1563 | let _guard = lock |
| 1564 | .write() |
| 1565 | .with_context(|| format!("write-lock provider catalog cache {}", path.display()))?; |
| 1566 | let durable_cache = if path.exists() { |
| 1567 | load_from_disk_unlocked(&path).context("invalid prior catalog cache")? |
| 1568 | } else { |
| 1569 | ProviderCatalogCache::new() |
| 1570 | }; |
| 1571 | |
| 1572 | if !is_account_scoped_scope(&provider, fingerprint) |
| 1573 | && let Some(durable_entry) = durable_cache.get(&provider, fingerprint).cloned() |
| 1574 | { |
| 1575 | let durable_is_newer = cache |
| 1576 | .get(&provider, fingerprint) |
| 1577 | .is_none_or(|local| durable_entry.fetched_at >= local.fetched_at); |
| 1578 | if durable_is_newer { |
| 1579 | cache.entries.insert( |
| 1580 | ProviderCatalogCache::cache_key(&provider, fingerprint), |
| 1581 | durable_entry, |
| 1582 | ); |
| 1583 | cache.record_failure(&provider, fingerprint, reason); |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | let durable_cache = merge_durable_scope(durable_cache, cache, &provider, fingerprint, true); |
| 1588 | write_bounded_cache( |
| 1589 | &path, |
| 1590 | durable_cache, |
| 1591 | Some((&provider, fingerprint)), |
| 1592 | CACHE_PERSISTENCE_LIMITS, |
| 1593 | ) |
| 1594 | .with_context(|| format!("atomically write provider catalog {}", path.display())) |
| 1595 | })(); |
| 1596 | if let Err(error) = result { |
| 1597 | tracing::debug!( |
| 1598 | target: "provider_catalog", |
| 1599 | error = %error, |
| 1600 | "provider catalog failure receipt write failed" |
| 1601 | ); |
| 1602 | } |
| 1603 | } |
| 1604 | |
| 1605 | fn publish_exact_scope_for_identity( |
| 1606 | cache: &ProviderCatalogCache, |
| 1607 | provider_kind: ProviderKind, |
| 1608 | provider_identity: &str, |
| 1609 | fingerprint: &str, |
| 1610 | ) -> usize { |
| 1611 | let provider = canonical_provider_scope(provider_identity); |
| 1612 | let offerings = cache |
| 1613 | .get(&storage_provider(provider_kind, &provider), fingerprint) |
| 1614 | .map(|entry| entry.offerings.clone()) |
| 1615 | .unwrap_or_default(); |
| 1616 | let count = offerings.len(); |
| 1617 | crate::provider_lake::replace_provider_live_snapshot_for_identity( |
| 1618 | provider_kind, |
| 1619 | &provider, |
| 1620 | CatalogSnapshot { offerings }, |
| 1621 | ); |
| 1622 | count |
| 1623 | } |
| 1624 | |
| 1625 | /// Load and publish only the active route's exact provider/base-URL scope. |
| 1626 | /// |
| 1627 | /// A cache created for another custom endpoint or for an old endpoint override |
| 1628 | /// is retained on disk but cannot leak into the active picker. |
| 1629 | pub fn maybe_load_persisted_cache_for_config(config: &Config) -> usize { |
| 1630 | let Ok(identity) = config.active_provider_identity() else { |
| 1631 | return 0; |
| 1632 | }; |
| 1633 | let provider = identity.provider; |
| 1634 | let provider_identity = canonical_provider_scope(identity.key.as_str()); |
| 1635 | let base_url = config.base_url_for_route(&identity); |
| 1636 | let fingerprint = base_url_fingerprint(&base_url); |
| 1637 | let Ok((_, generation)) = inventory_scope(config, &identity) else { |
| 1638 | return 0; |
| 1639 | }; |
| 1640 | let durable_catalog = REFRESH_GENERATIONS.read().is_ok_and(|fences| { |
| 1641 | fences |
| 1642 | .get(&storage_provider(provider, &provider_identity)) |
| 1643 | .is_some_and(|fence| fence.generation == generation && fence.durable_catalog) |
| 1644 | }); |
| 1645 | if !durable_catalog { |
| 1646 | return cached_entry_for_route(provider, &provider_identity, &base_url) |
| 1647 | .ok() |
| 1648 | .flatten() |
| 1649 | .map_or(0, |entry| entry.offerings.len()); |
| 1650 | } |
| 1651 | let ticket = ProviderCatalogRefreshTicket { |
| 1652 | provider: provider_identity.clone(), |
| 1653 | provider_kind: provider, |
| 1654 | fingerprint: Some(fingerprint.clone()), |
| 1655 | generation, |
| 1656 | durable_catalog, |
| 1657 | }; |
| 1658 | with_current_route_ticket(&ticket, provider, &provider_identity, &base_url, || { |
| 1659 | if let Some(loaded) = load_from_disk() |
| 1660 | && let Some(entry) = loaded.get( |
| 1661 | &storage_provider(provider, &provider_identity), |
| 1662 | &fingerprint, |
| 1663 | ) |
| 1664 | && let Ok(mut guard) = CACHE.write() |
| 1665 | { |
| 1666 | let key = ProviderCatalogCache::cache_key( |
| 1667 | &storage_provider(provider, &provider_identity), |
| 1668 | &fingerprint, |
| 1669 | ); |
| 1670 | if guard |
| 1671 | .entries |
| 1672 | .get(&key) |
| 1673 | .is_none_or(|current| entry.fetched_at >= current.fetched_at) |
| 1674 | { |
| 1675 | guard.entries.insert(key, entry.clone()); |
| 1676 | } |
| 1677 | } |
| 1678 | CACHE |
| 1679 | .read() |
| 1680 | .map(|guard| { |
| 1681 | if provider_owns_live_catalog(provider, &base_url) { |
| 1682 | publish_exact_scope_for_identity( |
| 1683 | &guard, |
| 1684 | provider, |
| 1685 | &provider_identity, |
| 1686 | &fingerprint, |
| 1687 | ) |
| 1688 | } else { |
| 1689 | crate::provider_lake::replace_provider_live_snapshot_for_identity( |
| 1690 | provider, |
| 1691 | &provider_identity, |
| 1692 | CatalogSnapshot::default(), |
| 1693 | ); |
| 1694 | 0 |
| 1695 | } |
| 1696 | }) |
| 1697 | .unwrap_or(0) |
| 1698 | }) |
| 1699 | .unwrap_or(0) |
| 1700 | } |
| 1701 | |
| 1702 | fn forget_account_scoped_provider(provider_kind: ProviderKind, provider: &str) { |
| 1703 | let provider = canonical_provider_scope(provider); |
| 1704 | if let Ok(mut cache) = CACHE.write() { |
| 1705 | cache |
| 1706 | .entries |
| 1707 | .retain(|_, entry| entry.provider != storage_provider(provider_kind, &provider)); |
| 1708 | } |
| 1709 | crate::provider_lake::replace_provider_live_snapshot_for_identity( |
| 1710 | provider_kind, |
| 1711 | &provider, |
| 1712 | CatalogSnapshot::default(), |
| 1713 | ); |
| 1714 | } |
| 1715 | |
| 1716 | /// Begin a provider refresh and invalidate older in-flight results. |
| 1717 | /// |
| 1718 | /// Account-scoped routes without an established observation drop their prior |
| 1719 | /// in-memory rosters. Scoped callers invalidate binding changes before refresh. |
| 1720 | #[cfg(any(test, feature = "test-support"))] |
| 1721 | pub fn begin_refresh(provider: &str) -> ProviderCatalogRefreshTicket { |
| 1722 | begin_refresh_inner(inferred_provider_kind(provider), provider, None) |
| 1723 | } |
| 1724 | |
| 1725 | pub fn begin_refresh_for_identity( |
| 1726 | provider_kind: ProviderKind, |
| 1727 | provider: &str, |
| 1728 | base_url: &str, |
| 1729 | ) -> ProviderCatalogRefreshTicket { |
| 1730 | begin_refresh_inner( |
| 1731 | provider_kind, |
| 1732 | provider, |
| 1733 | Some(base_url_fingerprint(base_url)), |
| 1734 | ) |
| 1735 | } |
| 1736 | |
| 1737 | fn begin_refresh_inner( |
| 1738 | provider_kind: ProviderKind, |
| 1739 | provider: &str, |
| 1740 | fingerprint: Option<String>, |
| 1741 | ) -> ProviderCatalogRefreshTicket { |
| 1742 | let provider = canonical_provider_scope(provider); |
| 1743 | let scope = storage_provider(provider_kind, &provider); |
| 1744 | // Hold the generation gate through account-roster invalidation, so an older |
| 1745 | // refresh can never publish between the new ticket and the clear. |
| 1746 | let generation = if let Ok(mut generations) = REFRESH_GENERATIONS.write() { |
| 1747 | let generation = generations.entry(scope.clone()).or_default(); |
| 1748 | generation.generation = generation.generation.saturating_add(1); |
| 1749 | if fingerprint |
| 1750 | .as_deref() |
| 1751 | .is_some_and(|fp| is_account_scoped_scope(&scope, fp)) |
| 1752 | { |
| 1753 | forget_account_scoped_provider(provider_kind, &provider); |
| 1754 | } |
| 1755 | generation.generation |
| 1756 | } else { |
| 1757 | 0 |
| 1758 | }; |
| 1759 | ProviderCatalogRefreshTicket { |
| 1760 | provider, |
| 1761 | provider_kind, |
| 1762 | fingerprint, |
| 1763 | generation, |
| 1764 | durable_catalog: cfg!(any(test, feature = "test-support")), |
| 1765 | } |
| 1766 | } |
| 1767 | |
| 1768 | fn with_current_ticket<T>( |
| 1769 | ticket: &ProviderCatalogRefreshTicket, |
| 1770 | provider: &str, |
| 1771 | operation: impl FnOnce() -> T, |
| 1772 | ) -> Option<T> { |
| 1773 | let provider = canonical_provider_scope(provider); |
| 1774 | if ticket.provider != provider { |
| 1775 | return None; |
| 1776 | } |
| 1777 | let generations = REFRESH_GENERATIONS.read().ok()?; |
| 1778 | if generations |
| 1779 | .get(&storage_provider(ticket.provider_kind, &ticket.provider)) |
| 1780 | .map(|fence| fence.generation) |
| 1781 | != Some(ticket.generation) |
| 1782 | { |
| 1783 | return None; |
| 1784 | } |
| 1785 | // Keep the generation read guard alive through publication. A newer |
| 1786 | // `begin_refresh` needs the write lock, so it cannot slip between the |
| 1787 | // current-ticket check and this operation's cache/lake update. |
| 1788 | let fence = generations.get(&storage_provider(ticket.provider_kind, &ticket.provider))?; |
| 1789 | let publication = fence.publication.lock().ok()?; |
| 1790 | fence.revision.fetch_add(1, Ordering::SeqCst); |
| 1791 | let result = operation(); |
| 1792 | fence.revision.fetch_add(1, Ordering::SeqCst); |
| 1793 | drop(publication); |
| 1794 | drop(generations); |
| 1795 | Some(result) |
| 1796 | } |
| 1797 | |
| 1798 | pub fn with_current_route_ticket<T>( |
| 1799 | ticket: &ProviderCatalogRefreshTicket, |
| 1800 | provider_kind: ProviderKind, |
| 1801 | provider: &str, |
| 1802 | base_url: &str, |
| 1803 | operation: impl FnOnce() -> T, |
| 1804 | ) -> Option<T> { |
| 1805 | if ticket.provider_kind != provider_kind |
| 1806 | || ticket.fingerprint.as_deref() != Some(base_url_fingerprint(base_url).as_str()) |
| 1807 | { |
| 1808 | return None; |
| 1809 | } |
| 1810 | with_current_ticket(ticket, provider, operation) |
| 1811 | } |
| 1812 | |
| 1813 | /// Record a successful refresh only if no newer refresh superseded it. |
| 1814 | pub fn record_success_if_current( |
| 1815 | ticket: &ProviderCatalogRefreshTicket, |
| 1816 | delta: ProviderCatalogDelta, |
| 1817 | ) -> Option<CatalogStatus> { |
| 1818 | let provider = canonical_provider_scope(&delta.provider); |
| 1819 | if ticket |
| 1820 | .fingerprint |
| 1821 | .as_ref() |
| 1822 | .is_some_and(|fp| fp != &delta.base_url_fingerprint) |
| 1823 | { |
| 1824 | return None; |
| 1825 | } |
| 1826 | with_current_ticket(ticket, &provider, || { |
| 1827 | record_success_for_identity(ticket.provider_kind, delta, ticket.durable_catalog) |
| 1828 | }) |
| 1829 | } |
| 1830 | |
| 1831 | /// Record a failed refresh only if no newer refresh superseded it. |
| 1832 | pub fn record_failure_if_current( |
| 1833 | ticket: &ProviderCatalogRefreshTicket, |
| 1834 | provider: &str, |
| 1835 | fingerprint: &str, |
| 1836 | reason: CatalogRefreshError, |
| 1837 | ) -> Option<CatalogStatus> { |
| 1838 | let provider = canonical_provider_scope(provider); |
| 1839 | if ticket |
| 1840 | .fingerprint |
| 1841 | .as_deref() |
| 1842 | .is_some_and(|fp| fp != fingerprint) |
| 1843 | { |
| 1844 | return None; |
| 1845 | } |
| 1846 | with_current_ticket(ticket, &provider, || { |
| 1847 | record_failure_for_identity( |
| 1848 | ticket.provider_kind, |
| 1849 | &provider, |
| 1850 | fingerprint, |
| 1851 | reason, |
| 1852 | ticket.durable_catalog, |
| 1853 | ) |
| 1854 | }) |
| 1855 | } |
| 1856 | |
| 1857 | /// Current freshness receipt for one exact provider/base-URL scope. |
| 1858 | /// |
| 1859 | /// Runtime route resolution uses this independently from picker visibility: |
| 1860 | /// stale or failed rows may remain selectable as an explicit fallback, but |
| 1861 | /// their limits, capabilities, and prices are not treated as current endpoint |
| 1862 | /// facts during execution. |
| 1863 | #[cfg(any(test, feature = "test-support"))] |
| 1864 | pub fn status_for_scope(provider: &str, base_url: &str) -> CatalogStatus { |
| 1865 | let fingerprint = base_url_fingerprint(base_url); |
| 1866 | status_for_fingerprint(provider, &fingerprint) |
| 1867 | } |
| 1868 | |
| 1869 | /// Current freshness receipt when the caller already owns the endpoint |
| 1870 | /// fingerprint (for example, an immutable usage-pricing receipt). |
| 1871 | #[cfg(any(test, feature = "test-support"))] |
| 1872 | pub fn status_for_fingerprint(provider: &str, fingerprint: &str) -> CatalogStatus { |
| 1873 | status_for_route_fingerprint(inferred_provider_kind(provider), provider, fingerprint) |
| 1874 | } |
| 1875 | |
| 1876 | pub fn status_for_route(provider: ProviderKind, identity: &str, base_url: &str) -> CatalogStatus { |
| 1877 | status_for_route_fingerprint(provider, identity, &base_url_fingerprint(base_url)) |
| 1878 | } |
| 1879 | |
| 1880 | fn status_for_route_fingerprint( |
| 1881 | kind: ProviderKind, |
| 1882 | provider: &str, |
| 1883 | fingerprint: &str, |
| 1884 | ) -> CatalogStatus { |
| 1885 | let provider = storage_provider(kind, provider); |
| 1886 | CACHE |
| 1887 | .read() |
| 1888 | .map(|cache| cache.status(&provider, fingerprint, now_unix())) |
| 1889 | .unwrap_or(CatalogStatus::Unknown) |
| 1890 | } |
| 1891 | |
| 1892 | /// Freeze the exact reviewed provider-live rate row fresh at CodeWhale's |
| 1893 | /// pre-permit application-dispatch boundary. |
| 1894 | /// |
| 1895 | /// Status, scope, model, source, and rates are all read beneath one `CACHE` |
| 1896 | /// read guard. The returned value owns every fact needed by later auditing, so |
| 1897 | /// completion-time code never re-opens mutable catalog or provider-lake state. |
| 1898 | fn reviewed_provider_live_scope( |
| 1899 | provider: ProviderKind, |
| 1900 | provider_identity: &str, |
| 1901 | endpoint_fingerprint: &str, |
| 1902 | ) -> bool { |
| 1903 | match provider { |
| 1904 | ProviderKind::Openrouter => { |
| 1905 | provider_identity == ProviderKind::Openrouter.as_str() |
| 1906 | && endpoint_fingerprint |
| 1907 | == base_url_fingerprint( |
| 1908 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 1909 | ) |
| 1910 | } |
| 1911 | ProviderKind::Custom => { |
| 1912 | endpoint_fingerprint |
| 1913 | == base_url_fingerprint(codewhale_config::catalog::BASETEN_BASE_URL) |
| 1914 | } |
| 1915 | _ => false, |
| 1916 | } |
| 1917 | } |
| 1918 | |
| 1919 | fn published_pricing_scope(provider: ProviderKind, identity: &str, fingerprint: &str) -> bool { |
| 1920 | !matches!( |
| 1921 | provider, |
| 1922 | ProviderKind::Custom | ProviderKind::OpenaiCodex | ProviderKind::OpencodeGo |
| 1923 | ) && identity == provider.as_str() |
| 1924 | && codewhale_config::provider_published_pricing_base_urls(provider) |
| 1925 | .iter() |
| 1926 | .any(|base_url| fingerprint == base_url_fingerprint(base_url)) |
| 1927 | } |
| 1928 | |
| 1929 | #[must_use] |
| 1930 | pub fn fresh_provider_live_pricing_quote_at( |
| 1931 | provider: ProviderKind, |
| 1932 | provider_identity: &str, |
| 1933 | wire_model: &str, |
| 1934 | endpoint_fingerprint: &str, |
| 1935 | dispatched_at_unix: u64, |
| 1936 | ) -> Option<ProviderLivePricingQuote> { |
| 1937 | let provider_identity = canonical_provider_scope(provider_identity); |
| 1938 | let wire_model = wire_model.trim(); |
| 1939 | let endpoint_fingerprint = endpoint_fingerprint.trim(); |
| 1940 | if provider_identity.is_empty() |
| 1941 | || wire_model.is_empty() |
| 1942 | || !reviewed_provider_live_scope(provider, &provider_identity, endpoint_fingerprint) |
| 1943 | { |
| 1944 | return None; |
| 1945 | } |
| 1946 | |
| 1947 | let cache = CACHE.read().ok()?; |
| 1948 | let storage_scope = storage_provider(provider, &provider_identity); |
| 1949 | if cache.status(&storage_scope, endpoint_fingerprint, dispatched_at_unix) |
| 1950 | != CatalogStatus::Fresh |
| 1951 | { |
| 1952 | return None; |
| 1953 | } |
| 1954 | let entry = cache.get(&storage_scope, endpoint_fingerprint)?; |
| 1955 | if entry.provider != storage_scope |
| 1956 | || entry.base_url_fingerprint.trim() != endpoint_fingerprint |
| 1957 | || entry.fetched_at > dispatched_at_unix |
| 1958 | { |
| 1959 | return None; |
| 1960 | } |
| 1961 | let offering = entry.offerings.iter().find(|offering| { |
| 1962 | offering.provider.trim() == provider_identity && offering.wire_model_id.trim() == wire_model |
| 1963 | })?; |
| 1964 | let pricing = OfferingPricing::from_catalog_offering(offering)?; |
| 1965 | if pricing.provider.trim() != provider_identity |
| 1966 | || pricing.wire_model_id.trim() != wire_model |
| 1967 | || pricing.currency != Currency::Usd |
| 1968 | || pricing.provenance != PricingProvenance::ProviderLive |
| 1969 | || pricing.fetched_at.or(pricing.effective_at) != Some(entry.fetched_at) |
| 1970 | || pricing.endpoint_fingerprint.as_deref() != Some(endpoint_fingerprint) |
| 1971 | || pricing.input_per_million.is_none() |
| 1972 | || pricing.output_per_million.is_none() |
| 1973 | { |
| 1974 | return None; |
| 1975 | } |
| 1976 | ProviderLivePricingQuote::from_pricing( |
| 1977 | provider, |
| 1978 | &provider_identity, |
| 1979 | wire_model, |
| 1980 | endpoint_fingerprint, |
| 1981 | entry.fetched_at, |
| 1982 | &pricing, |
| 1983 | ) |
| 1984 | } |
| 1985 | |
| 1986 | /// A price is a fact, so it is in scope exactly where a fact is. |
| 1987 | /// |
| 1988 | /// This defers to [`crate::provider_lake::cloud_facts_apply_to_route`] rather |
| 1989 | /// than repeating the scope table. The copy it replaces admitted the dual-wire |
| 1990 | /// and regional routes (`deepseek-anthropic`, `siliconflow-CN`) that the |
| 1991 | /// catalog gate refuses; no price actually escaped through it, because the |
| 1992 | /// offering lookup below independently returns a non-`CloudFacts` row on those |
| 1993 | /// routes and the quote then fails — but that is one authority masking another, |
| 1994 | /// not agreement, and it would become a real leak the moment either moved. The |
| 1995 | /// copy also carried its own `!= OpenaiCodex` test, which `cloud_facts::scope` |
| 1996 | /// has always enforced for every consumer. |
| 1997 | /// |
| 1998 | /// The one condition that is this file's own: the *configured* identity must be |
| 1999 | /// the canonical provider. A differently-named provider table pointing at the |
| 2000 | /// official host is a separate credential and billing relationship. |
| 2001 | fn cloud_pricing_scope(provider: ProviderKind, identity: &str, base_url: &str) -> bool { |
| 2002 | crate::provider_lake::cloud_facts_apply_to_route(provider, identity, base_url) |
| 2003 | } |
| 2004 | |
| 2005 | /// Capture the effective mutable price authority once. Provider-owned live |
| 2006 | /// prices retain priority; signed cloud prices are admitted only on the exact |
| 2007 | /// canonical official route. The historical wire field name remains stable. |
| 2008 | pub fn configured_dispatch_pricing_quote_at( |
| 2009 | models: &[codewhale_config::catalog::configured::ConfiguredModel], |
| 2010 | provider: ProviderKind, |
| 2011 | identity: &str, |
| 2012 | model: &str, |
| 2013 | base_url: &str, |
| 2014 | dispatched_at: u64, |
| 2015 | ) -> Option<ProviderLivePricingQuote> { |
| 2016 | if provider == ProviderKind::OpenaiCodex { |
| 2017 | return None; |
| 2018 | } |
| 2019 | codewhale_config::catalog::configured::validate_configured_models(models).ok()?; |
| 2020 | let declared = models |
| 2021 | .iter() |
| 2022 | .find(|row| row.id == model && row.matches_route(identity, base_url))?; |
| 2023 | let cost = declared.cost.clone().unwrap_or_default(); |
| 2024 | let currency = declared.resolved_cost_currency()?; |
| 2025 | let pricing = OfferingPricing { |
| 2026 | provider: identity.to_string(), |
| 2027 | wire_model_id: model.to_string(), |
| 2028 | canonical_model: None, |
| 2029 | currency, |
| 2030 | input_per_million: cost.input, |
| 2031 | output_per_million: cost.output, |
| 2032 | cache_read_per_million: cost.cache_read, |
| 2033 | cache_write_per_million: cost.cache_write, |
| 2034 | reasoning_per_million: cost.reasoning, |
| 2035 | input_audio_per_million: cost.input_audio, |
| 2036 | output_audio_per_million: cost.output_audio, |
| 2037 | context_tiers: cost.context_tiers(), |
| 2038 | rate_withheld: declared.cost.is_some() |
| 2039 | && !OfferingPricing { |
| 2040 | input_per_million: cost.input, |
| 2041 | output_per_million: cost.output, |
| 2042 | cache_read_per_million: cost.cache_read, |
| 2043 | cache_write_per_million: cost.cache_write, |
| 2044 | reasoning_per_million: cost.reasoning, |
| 2045 | input_audio_per_million: cost.input_audio, |
| 2046 | output_audio_per_million: cost.output_audio, |
| 2047 | context_tiers: cost.context_tiers(), |
| 2048 | ..Default::default() |
| 2049 | } |
| 2050 | .has_any_price(), |
| 2051 | provenance: PricingProvenance::UserOverride, |
| 2052 | effective_at: None, |
| 2053 | endpoint_fingerprint: Some(base_url_fingerprint(base_url)), |
| 2054 | |
| 2055 | ..Default::default() |
| 2056 | }; |
| 2057 | // Freeze even an unpriced declaration: missing rates must not fall through |
| 2058 | // to a same-named bundled or subsequently refreshed price. |
| 2059 | ProviderLivePricingQuote::from_pricing( |
| 2060 | provider, |
| 2061 | identity, |
| 2062 | model, |
| 2063 | &base_url_fingerprint(base_url), |
| 2064 | dispatched_at, |
| 2065 | &pricing, |
| 2066 | ) |
| 2067 | } |
| 2068 | |
| 2069 | /// Pick the dispatch quote from an operator declaration and the endpoint's |
| 2070 | /// catalog. A declared rate wins. A declaration with no rates yields to the |
| 2071 | /// catalog's price for the same exact endpoint (#6690), and is kept (frozen, |
| 2072 | /// rate-less) only when the catalog has none, so a same-named bundled price |
| 2073 | /// still cannot fill the gap. |
| 2074 | pub fn declared_or_catalog_quote( |
| 2075 | declared: Option<ProviderLivePricingQuote>, |
| 2076 | catalog: impl FnOnce() -> Option<ProviderLivePricingQuote>, |
| 2077 | ) -> Option<ProviderLivePricingQuote> { |
| 2078 | match declared { |
| 2079 | Some(quote) if quote.carries_pricing_decision() => Some(quote), |
| 2080 | Some(declared) => catalog() |
| 2081 | .filter(|quote| { |
| 2082 | matches!( |
| 2083 | quote.provenance, |
| 2084 | PricingProvenance::ProviderLive |
| 2085 | | PricingProvenance::ModelsDevLive |
| 2086 | | PricingProvenance::CloudFacts |
| 2087 | ) |
| 2088 | }) |
| 2089 | .or(Some(declared)), |
| 2090 | None => catalog(), |
| 2091 | } |
| 2092 | } |
| 2093 | |
| 2094 | fn resolve_catalog_pricing_for_dispatch( |
| 2095 | provider: ProviderKind, |
| 2096 | provider_identity: &str, |
| 2097 | wire_model: &str, |
| 2098 | lookup_model: &str, |
| 2099 | base_url: &str, |
| 2100 | endpoint_fingerprint: &str, |
| 2101 | dispatched_at_unix: u64, |
| 2102 | ) -> Option<OfferingPricing> { |
| 2103 | let offering_pricing = |mut offering: codewhale_config::catalog::CatalogOffering| { |
| 2104 | if crate::provider_lake::live_catalog_origin(provider, &offering.wire_model_id) |
| 2105 | == Some(crate::provider_lake::LiveSource::ModelsDev) |
| 2106 | && let codewhale_config::catalog::CatalogSource::Live { fetched_at, .. } = |
| 2107 | offering.pricing_source() |
| 2108 | { |
| 2109 | offering.cost_source = Some(codewhale_config::catalog::CatalogSource::ModelsDevLive { |
| 2110 | fetched_at: *fetched_at, |
| 2111 | }); |
| 2112 | } |
| 2113 | let pricing = OfferingPricing::from_catalog_offering_at(&offering, dispatched_at_unix)?; |
| 2114 | if matches!( |
| 2115 | pricing.provenance, |
| 2116 | PricingProvenance::ProviderLive | PricingProvenance::ModelsDevLive |
| 2117 | ) && pricing |
| 2118 | .fetched_at |
| 2119 | .or(pricing.effective_at) |
| 2120 | .is_some_and(|effective_at| effective_at > dispatched_at_unix) |
| 2121 | { |
| 2122 | return Some(Err(())); |
| 2123 | } |
| 2124 | if pricing |
| 2125 | .live_pricing_defect( |
| 2126 | Some(endpoint_fingerprint), |
| 2127 | Some(dispatched_at_unix), |
| 2128 | DEFAULT_PROVIDER_CATALOG_TTL_SECS, |
| 2129 | ) |
| 2130 | .is_some() |
| 2131 | { |
| 2132 | return None; |
| 2133 | } |
| 2134 | Some(Ok(pricing)) |
| 2135 | }; |
| 2136 | |
| 2137 | let route_offering = crate::provider_lake::catalog_offering_for_route( |
| 2138 | provider, |
| 2139 | provider_identity, |
| 2140 | base_url, |
| 2141 | wire_model, |
| 2142 | ) |
| 2143 | .filter(|offering| offering.wire_model_id == wire_model) |
| 2144 | .or_else(|| { |
| 2145 | (lookup_model != wire_model) |
| 2146 | .then(|| { |
| 2147 | crate::provider_lake::catalog_offering_for_route( |
| 2148 | provider, |
| 2149 | provider_identity, |
| 2150 | base_url, |
| 2151 | lookup_model, |
| 2152 | ) |
| 2153 | .filter(|offering| offering.wire_model_id == lookup_model) |
| 2154 | }) |
| 2155 | .flatten() |
| 2156 | }); |
| 2157 | |
| 2158 | if let Some(offering) = route_offering { |
| 2159 | if matches!( |
| 2160 | offering.pricing_source(), |
| 2161 | codewhale_config::catalog::CatalogSource::CloudFacts { .. } |
| 2162 | ) { |
| 2163 | return None; |
| 2164 | } |
| 2165 | match offering_pricing(offering) { |
| 2166 | Some(Ok(pricing)) => return Some(pricing), |
| 2167 | Some(Err(())) => return None, |
| 2168 | None => {} |
| 2169 | } |
| 2170 | } |
| 2171 | |
| 2172 | if provider_owns_live_catalog(provider, base_url) { |
| 2173 | if provider == ProviderKind::Openrouter { |
| 2174 | return crate::provider_lake::bundled_catalog_offering_for_model( |
| 2175 | provider, |
| 2176 | lookup_model, |
| 2177 | ) |
| 2178 | .and_then(|offering| { |
| 2179 | OfferingPricing::from_catalog_offering_at(&offering, dispatched_at_unix) |
| 2180 | }); |
| 2181 | } |
| 2182 | return None; |
| 2183 | } |
| 2184 | |
| 2185 | if let Some(offering) = crate::provider_lake::catalog_offering_for_model_identity( |
| 2186 | provider, |
| 2187 | Some(provider_identity), |
| 2188 | lookup_model, |
| 2189 | ) { |
| 2190 | if matches!( |
| 2191 | offering.pricing_source(), |
| 2192 | codewhale_config::catalog::CatalogSource::CloudFacts { .. } |
| 2193 | ) { |
| 2194 | return None; |
| 2195 | } |
| 2196 | match offering_pricing(offering) { |
| 2197 | Some(Ok(pricing)) => return Some(pricing), |
| 2198 | Some(Err(())) => return None, |
| 2199 | None => {} |
| 2200 | } |
| 2201 | } |
| 2202 | |
| 2203 | crate::provider_lake::bundled_catalog_offering_for_model(provider, lookup_model).and_then( |
| 2204 | |offering| OfferingPricing::from_catalog_offering_at(&offering, dispatched_at_unix), |
| 2205 | ) |
| 2206 | } |
| 2207 | |
| 2208 | pub fn fresh_dispatch_pricing_quote_at( |
| 2209 | provider: ProviderKind, |
| 2210 | provider_identity: &str, |
| 2211 | wire_model: &str, |
| 2212 | base_url: &str, |
| 2213 | dispatched_at_unix: u64, |
| 2214 | ) -> Option<ProviderLivePricingQuote> { |
| 2215 | let endpoint_fingerprint = base_url_fingerprint(base_url); |
| 2216 | if let Some(quote) = fresh_provider_live_pricing_quote_at( |
| 2217 | provider, |
| 2218 | provider_identity, |
| 2219 | wire_model, |
| 2220 | &endpoint_fingerprint, |
| 2221 | dispatched_at_unix, |
| 2222 | ) { |
| 2223 | return Some(quote); |
| 2224 | } |
| 2225 | if !published_pricing_scope(provider, provider_identity, &endpoint_fingerprint) { |
| 2226 | if let Some(quote) = fresh_cloud_dispatch_pricing_quote_at( |
| 2227 | provider, |
| 2228 | provider_identity, |
| 2229 | wire_model, |
| 2230 | base_url, |
| 2231 | dispatched_at_unix, |
| 2232 | ) { |
| 2233 | return Some(quote); |
| 2234 | } |
| 2235 | return None; |
| 2236 | } |
| 2237 | let trimmed_model = wire_model.trim(); |
| 2238 | if trimmed_model.is_empty() |
| 2239 | || trimmed_model.chars().any(char::is_control) |
| 2240 | || trimmed_model.eq_ignore_ascii_case("auto") |
| 2241 | { |
| 2242 | return None; |
| 2243 | } |
| 2244 | let at = chrono::DateTime::from_timestamp(i64::try_from(dispatched_at_unix).ok()?, 0)?; |
| 2245 | let resolved_model = codewhale_config::route::resolve_model(provider, trimmed_model, None) |
| 2246 | .ok() |
| 2247 | .filter(|resolved| !resolved.is_auto) |
| 2248 | .map(|resolved| resolved.logical); |
| 2249 | let lookup_model = resolved_model.as_deref().unwrap_or(trimmed_model); |
| 2250 | let hand = crate::pricing::dispatch_hand_quote_rows(provider, lookup_model, base_url, at); |
| 2251 | let needs_schedule = crate::pricing::hand_pricing_overrides_catalog(provider, lookup_model); |
| 2252 | let catalog = resolve_catalog_pricing_for_dispatch( |
| 2253 | provider, |
| 2254 | provider_identity, |
| 2255 | trimmed_model, |
| 2256 | lookup_model, |
| 2257 | base_url, |
| 2258 | &endpoint_fingerprint, |
| 2259 | dispatched_at_unix, |
| 2260 | ); |
| 2261 | let catalog_is_live = catalog.as_ref().is_some_and(|pricing| { |
| 2262 | matches!( |
| 2263 | pricing.provenance, |
| 2264 | PricingProvenance::ModelsDevLive | PricingProvenance::ProviderLive |
| 2265 | ) |
| 2266 | }); |
| 2267 | let (pricing, mut secondary) = if needs_schedule && hand.is_some() { |
| 2268 | hand? |
| 2269 | } else if catalog_is_live { |
| 2270 | catalog.map(|pricing| (pricing, None)).or(hand)? |
| 2271 | } else if hand.is_some() { |
| 2272 | hand? |
| 2273 | } else if let Some(quote) = fresh_cloud_dispatch_pricing_quote_at( |
| 2274 | provider, |
| 2275 | provider_identity, |
| 2276 | wire_model, |
| 2277 | base_url, |
| 2278 | dispatched_at_unix, |
| 2279 | ) { |
| 2280 | return Some(quote); |
| 2281 | } else { |
| 2282 | catalog.map(|pricing| (pricing, None))? |
| 2283 | }; |
| 2284 | let mut quote = ProviderLivePricingQuote::from_pricing( |
| 2285 | provider, |
| 2286 | provider_identity, |
| 2287 | wire_model, |
| 2288 | &endpoint_fingerprint, |
| 2289 | pricing.fetched_at.unwrap_or(dispatched_at_unix), |
| 2290 | &pricing, |
| 2291 | )?; |
| 2292 | if let Some(row) = secondary.as_mut() { |
| 2293 | row.provider = provider_identity.into(); |
| 2294 | row.wire_model_id = wire_model.into(); |
| 2295 | let (primary, _): (OfferingPricing, Option<OfferingPricing>) = |
| 2296 | serde_json::from_str(quote.pricing_schedule.as_deref()?).ok()?; |
| 2297 | quote.pricing_schedule = Some(serde_json::to_string(&(primary, secondary)).ok()?); |
| 2298 | quote.catalog_revision = ProviderLivePricingQuote::revision_for( |
| 2299 | quote.provider, |
| 2300 | "e.provider_identity, |
| 2301 | "e.wire_model, |
| 2302 | "e.endpoint_fingerprint, |
| 2303 | quote.catalog_fetched_at, |
| 2304 | "e.currency, |
| 2305 | "e.provenance, |
| 2306 | "e.input_per_million, |
| 2307 | "e.output_per_million, |
| 2308 | "e.cache_read_per_million, |
| 2309 | "e.cache_write_per_million, |
| 2310 | None, |
| 2311 | quote.pricing_schedule.as_deref(), |
| 2312 | )?; |
| 2313 | } |
| 2314 | quote.pricing_for_route( |
| 2315 | provider, |
| 2316 | provider_identity, |
| 2317 | wire_model, |
| 2318 | &endpoint_fingerprint, |
| 2319 | dispatched_at_unix, |
| 2320 | )?; |
| 2321 | Some(quote) |
| 2322 | } |
| 2323 | |
| 2324 | fn fresh_cloud_dispatch_pricing_quote_at( |
| 2325 | provider: ProviderKind, |
| 2326 | provider_identity: &str, |
| 2327 | wire_model: &str, |
| 2328 | base_url: &str, |
| 2329 | dispatched_at_unix: u64, |
| 2330 | ) -> Option<ProviderLivePricingQuote> { |
| 2331 | let endpoint_fingerprint = base_url_fingerprint(base_url); |
| 2332 | if !cloud_pricing_scope(provider, provider_identity, base_url) { |
| 2333 | return None; |
| 2334 | } |
| 2335 | let snapshot = codewhale_config::cloud_facts::overlay::snapshot(); |
| 2336 | let facts = snapshot.facts.as_ref()?; |
| 2337 | let trimmed_model = wire_model.trim(); |
| 2338 | let lookup_model = codewhale_config::route::resolve_model(provider, trimmed_model, None) |
| 2339 | .ok() |
| 2340 | .filter(|resolved| !resolved.is_auto) |
| 2341 | .map(|resolved| resolved.logical); |
| 2342 | let lookup = lookup_model.as_deref().unwrap_or(trimmed_model); |
| 2343 | let offering = crate::provider_lake::catalog_offering_for_route( |
| 2344 | provider, |
| 2345 | provider_identity, |
| 2346 | base_url, |
| 2347 | trimmed_model, |
| 2348 | ) |
| 2349 | .or_else(|| { |
| 2350 | (lookup != trimmed_model).then(|| { |
| 2351 | crate::provider_lake::catalog_offering_for_route( |
| 2352 | provider, |
| 2353 | provider_identity, |
| 2354 | base_url, |
| 2355 | lookup, |
| 2356 | ) |
| 2357 | })? |
| 2358 | })?; |
| 2359 | let codewhale_config::catalog::CatalogSource::CloudFacts { |
| 2360 | facts_version, |
| 2361 | key_id, |
| 2362 | fetched_at, |
| 2363 | valid_until, |
| 2364 | } = offering.pricing_source() |
| 2365 | else { |
| 2366 | return None; |
| 2367 | }; |
| 2368 | // Provider cache files cannot authenticate a cloud price by copying a |
| 2369 | // source stamp. This row must be a projection of the current verified |
| 2370 | // overlay, with matching independent price authority and exact wire ID. |
| 2371 | if (offering.wire_model_id != trimmed_model && offering.wire_model_id != lookup) |
| 2372 | || !matches!( |
| 2373 | offering.source, |
| 2374 | codewhale_config::catalog::CatalogSource::CloudFacts { .. } |
| 2375 | ) |
| 2376 | || *facts_version != facts.facts_version |
| 2377 | || key_id != &facts.key_id |
| 2378 | || *valid_until != facts.valid_until |
| 2379 | { |
| 2380 | return None; |
| 2381 | } |
| 2382 | let pricing = OfferingPricing::from_catalog_offering_at(&offering, dispatched_at_unix)?; |
| 2383 | let mut quote = ProviderLivePricingQuote::from_pricing( |
| 2384 | provider, |
| 2385 | provider_identity, |
| 2386 | wire_model, |
| 2387 | &endpoint_fingerprint, |
| 2388 | *fetched_at, |
| 2389 | &pricing, |
| 2390 | )?; |
| 2391 | quote.cloud_facts = Some(CloudFactsPricingSource { |
| 2392 | facts_version: *facts_version, |
| 2393 | key_id: key_id.clone(), |
| 2394 | valid_until: *valid_until, |
| 2395 | base_url: base_url.to_string(), |
| 2396 | }); |
| 2397 | quote.catalog_revision = ProviderLivePricingQuote::revision_for( |
| 2398 | quote.provider, |
| 2399 | "e.provider_identity, |
| 2400 | "e.wire_model, |
| 2401 | "e.endpoint_fingerprint, |
| 2402 | quote.catalog_fetched_at, |
| 2403 | "e.currency, |
| 2404 | "e.provenance, |
| 2405 | "e.input_per_million, |
| 2406 | "e.output_per_million, |
| 2407 | "e.cache_read_per_million, |
| 2408 | "e.cache_write_per_million, |
| 2409 | quote.cloud_facts.as_ref(), |
| 2410 | quote.pricing_schedule.as_deref(), |
| 2411 | )?; |
| 2412 | quote.pricing_for_route( |
| 2413 | provider, |
| 2414 | provider_identity, |
| 2415 | wire_model, |
| 2416 | &endpoint_fingerprint, |
| 2417 | dispatched_at_unix, |
| 2418 | )?; |
| 2419 | (snapshot.generation == codewhale_config::cloud_facts::overlay::snapshot().generation) |
| 2420 | .then_some(quote) |
| 2421 | } |
| 2422 | |
| 2423 | /// Record and atomically persist a successful provider refresh. |
| 2424 | /// |
| 2425 | /// `ProviderCatalogCache::record_success` replaces the exact scope, so models |
| 2426 | /// removed upstream disappear instead of accumulating forever. |
| 2427 | #[cfg(any(test, feature = "test-support"))] |
| 2428 | pub fn record_success(delta: ProviderCatalogDelta) -> CatalogStatus { |
| 2429 | record_success_for_identity(inferred_provider_kind(&delta.provider), delta, true) |
| 2430 | } |
| 2431 | |
| 2432 | fn record_success_for_identity( |
| 2433 | kind: ProviderKind, |
| 2434 | mut delta: ProviderCatalogDelta, |
| 2435 | durable_catalog: bool, |
| 2436 | ) -> CatalogStatus { |
| 2437 | let provider = canonical_provider_scope(&delta.provider); |
| 2438 | delta.provider = storage_provider(kind, &provider); |
| 2439 | let submitted = delta.offerings.len(); |
| 2440 | delta.offerings.retain(|row| { |
| 2441 | row.provider == provider |
| 2442 | && codewhale_runtime::catalog_cache::valid_catalog_model_id(&row.wire_model_id) |
| 2443 | && provider_cost_source_allowed(row) |
| 2444 | }); |
| 2445 | normalize_provider_catalog_offerings(kind, &delta.base_url_fingerprint, &mut delta.offerings); |
| 2446 | if delta.offerings.len() < submitted { |
| 2447 | tracing::warn!( |
| 2448 | target: "provider_catalog", |
| 2449 | scope = %provider, |
| 2450 | rejected = submitted - delta.offerings.len(), |
| 2451 | kept = delta.offerings.len(), |
| 2452 | "dropping unusable rows from a provider catalog refresh" |
| 2453 | ); |
| 2454 | } |
| 2455 | if submitted > 0 && delta.offerings.is_empty() { |
| 2456 | return record_failure_for_identity( |
| 2457 | kind, |
| 2458 | &provider, |
| 2459 | &delta.base_url_fingerprint, |
| 2460 | CatalogRefreshError::InvalidResponse, |
| 2461 | durable_catalog, |
| 2462 | ); |
| 2463 | } |
| 2464 | let fingerprint = delta.base_url_fingerprint.clone(); |
| 2465 | let Ok(mut guard) = CACHE.write() else { |
| 2466 | return CatalogStatus::Unknown; |
| 2467 | }; |
| 2468 | guard.record_success(delta, DEFAULT_PROVIDER_CATALOG_TTL_SECS); |
| 2469 | let persisted = persist_scope( |
| 2470 | &guard, |
| 2471 | &storage_provider(kind, &provider), |
| 2472 | &fingerprint, |
| 2473 | durable_catalog, |
| 2474 | ); |
| 2475 | publish_exact_scope_for_identity(&guard, kind, &provider, &fingerprint); |
| 2476 | if persisted { |
| 2477 | CatalogStatus::Fresh |
| 2478 | } else { |
| 2479 | CatalogStatus::Unknown |
| 2480 | } |
| 2481 | } |
| 2482 | |
| 2483 | /// Record a typed failure while preserving and republishing prior rows for the |
| 2484 | /// exact route scope. |
| 2485 | #[cfg(any(test, feature = "test-support"))] |
| 2486 | pub fn record_failure( |
| 2487 | provider: &str, |
| 2488 | fingerprint: &str, |
| 2489 | reason: CatalogRefreshError, |
| 2490 | ) -> CatalogStatus { |
| 2491 | record_failure_for_identity( |
| 2492 | inferred_provider_kind(provider), |
| 2493 | provider, |
| 2494 | fingerprint, |
| 2495 | reason, |
| 2496 | true, |
| 2497 | ) |
| 2498 | } |
| 2499 | |
| 2500 | fn record_failure_for_identity( |
| 2501 | kind: ProviderKind, |
| 2502 | provider: &str, |
| 2503 | fingerprint: &str, |
| 2504 | reason: CatalogRefreshError, |
| 2505 | durable_catalog: bool, |
| 2506 | ) -> CatalogStatus { |
| 2507 | let provider = canonical_provider_scope(provider); |
| 2508 | let scope = storage_provider(kind, &provider); |
| 2509 | let Ok(mut guard) = CACHE.write() else { |
| 2510 | return CatalogStatus::Failed { reason }; |
| 2511 | }; |
| 2512 | guard.record_failure(&scope, fingerprint, reason); |
| 2513 | if durable_catalog { |
| 2514 | persist_failure_scope(&mut guard, &scope, fingerprint, reason); |
| 2515 | } else { |
| 2516 | persist_scope(&guard, &scope, fingerprint, false); |
| 2517 | } |
| 2518 | publish_exact_scope_for_identity(&guard, kind, &provider, fingerprint); |
| 2519 | CatalogStatus::Failed { reason } |
| 2520 | } |
| 2521 | |
| 2522 | #[cfg(any(test, feature = "test-support"))] |
| 2523 | pub fn reset_cache_for_test() { |
| 2524 | DISK_LOADED.store(false, Ordering::Release); |
| 2525 | if let Ok(mut cache) = CACHE.write() { |
| 2526 | *cache = ProviderCatalogCache::new(); |
| 2527 | } |
| 2528 | } |
| 2529 | |
| 2530 | #[cfg(test)] |
| 2531 | mod tests { |
| 2532 | use super::*; |
| 2533 | |
| 2534 | #[test] |
| 2535 | fn google_models_prefix_is_stripped_only_on_the_official_endpoint() { |
| 2536 | let rows = || { |
| 2537 | vec![codewhale_config::catalog::CatalogOffering { |
| 2538 | provider: "google".into(), |
| 2539 | wire_model_id: "models/acme-chat".into(), |
| 2540 | ..Default::default() |
| 2541 | }] |
| 2542 | }; |
| 2543 | let mut proxy = rows(); |
| 2544 | normalize_provider_catalog_offerings( |
| 2545 | ProviderKind::Google, |
| 2546 | &base_url_fingerprint("https://proxy.example/v1"), |
| 2547 | &mut proxy, |
| 2548 | ); |
| 2549 | assert_eq!(proxy[0].wire_model_id, "models/acme-chat"); |
| 2550 | let mut official = rows(); |
| 2551 | normalize_provider_catalog_offerings( |
| 2552 | ProviderKind::Google, |
| 2553 | &base_url_fingerprint(ProviderKind::Google.provider().default_base_url()), |
| 2554 | &mut official, |
| 2555 | ); |
| 2556 | assert_eq!(official[0].wire_model_id, "acme-chat"); |
| 2557 | } |
| 2558 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 2559 | use codewhale_config::ProviderKind; |
| 2560 | use codewhale_config::catalog::{CatalogOffering, CatalogSource}; |
| 2561 | use codewhale_runtime::config::{ProviderConfig, ProvidersConfig}; |
| 2562 | |
| 2563 | fn delta(provider: &str, fingerprint: &str, ids: &[&str]) -> ProviderCatalogDelta { |
| 2564 | delta_at(provider, fingerprint, ids, now_unix()) |
| 2565 | } |
| 2566 | |
| 2567 | fn delta_at( |
| 2568 | provider: &str, |
| 2569 | fingerprint: &str, |
| 2570 | ids: &[&str], |
| 2571 | fetched_at: u64, |
| 2572 | ) -> ProviderCatalogDelta { |
| 2573 | ProviderCatalogDelta { |
| 2574 | provider: provider.to_string(), |
| 2575 | base_url_fingerprint: fingerprint.to_string(), |
| 2576 | fetched_at, |
| 2577 | offerings: ids |
| 2578 | .iter() |
| 2579 | .map(|id| CatalogOffering { |
| 2580 | provider: provider.to_string(), |
| 2581 | wire_model_id: (*id).to_string(), |
| 2582 | endpoint_key: "chat".to_string(), |
| 2583 | source: CatalogSource::Live { |
| 2584 | base_url_fingerprint: fingerprint.to_string(), |
| 2585 | fetched_at, |
| 2586 | }, |
| 2587 | ..CatalogOffering::default() |
| 2588 | }) |
| 2589 | .collect(), |
| 2590 | } |
| 2591 | } |
| 2592 | |
| 2593 | fn scope(identity: &str) -> String { |
| 2594 | storage_provider(inferred_provider_kind(identity), identity) |
| 2595 | } |
| 2596 | |
| 2597 | fn stored_delta(provider: &str, fingerprint: &str, ids: &[&str]) -> ProviderCatalogDelta { |
| 2598 | stored_delta_at(provider, fingerprint, ids, now_unix()) |
| 2599 | } |
| 2600 | |
| 2601 | fn stored_delta_at( |
| 2602 | provider: &str, |
| 2603 | fingerprint: &str, |
| 2604 | ids: &[&str], |
| 2605 | fetched_at: u64, |
| 2606 | ) -> ProviderCatalogDelta { |
| 2607 | let mut delta = delta_at(provider, fingerprint, ids, fetched_at); |
| 2608 | delta.provider = scope(provider); |
| 2609 | delta |
| 2610 | } |
| 2611 | |
| 2612 | #[test] |
| 2613 | fn authenticated_catalogs_are_fenced_in_memory_and_keyless_catalogs_survive_restart() { |
| 2614 | let _env = lock_test_env(); |
| 2615 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2616 | let home = tempfile::tempdir().unwrap(); |
| 2617 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2618 | let _cli = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2619 | reset_cache_for_test(); |
| 2620 | let mut config: Config = toml::from_str( |
| 2621 | r#" |
| 2622 | provider = "account-fence" |
| 2623 | [providers.account-fence] |
| 2624 | kind = "openai-compatible" |
| 2625 | base_url = "https://account-catalog.example/v1" |
| 2626 | api_key = "fixture-first-account" |
| 2627 | [providers.vllm] |
| 2628 | base_url = "http://127.0.0.1:18576/v1" |
| 2629 | auth_mode = "none" |
| 2630 | [providers.public-fence] |
| 2631 | kind = "openai-compatible" |
| 2632 | base_url = "https://pass.wafer.ai/v1" |
| 2633 | api_key = "fixture-public-listing-key" |
| 2634 | "#, |
| 2635 | ) |
| 2636 | .unwrap(); |
| 2637 | let private = config.active_provider_identity().unwrap(); |
| 2638 | let keyless = config |
| 2639 | .builtin_provider_identity(ProviderKind::Vllm) |
| 2640 | .unwrap(); |
| 2641 | let public = config |
| 2642 | .resolve_provider_pin_identity("public-fence") |
| 2643 | .unwrap(); |
| 2644 | let publish = |config: &Config, identity: &codewhale_runtime::config::ProviderIdentity| { |
| 2645 | let base = config.base_url_for_route(identity); |
| 2646 | let ticket = begin_scoped_refresh(config, identity, &base).unwrap(); |
| 2647 | assert_eq!( |
| 2648 | record_success_if_current( |
| 2649 | &ticket, |
| 2650 | delta( |
| 2651 | identity.key.as_str(), |
| 2652 | &base_url_fingerprint(&base), |
| 2653 | &["model-a"] |
| 2654 | ), |
| 2655 | ), |
| 2656 | Some(CatalogStatus::Fresh) |
| 2657 | ); |
| 2658 | ticket |
| 2659 | }; |
| 2660 | let private_url = config.base_url_for_route(&private); |
| 2661 | let keyless_url = config.base_url_for_route(&keyless); |
| 2662 | let public_url = config.base_url_for_route(&public); |
| 2663 | publish(&config, &keyless); |
| 2664 | publish(&config, &public); |
| 2665 | let first_ticket = publish(&config, &private); |
| 2666 | let read = |identity: &codewhale_runtime::config::ProviderIdentity, base: &str| { |
| 2667 | cached_entry_for_route(identity.provider, identity.key.as_str(), base).unwrap() |
| 2668 | }; |
| 2669 | assert!(read(&private, &private_url).is_some()); |
| 2670 | let (first_binding, _) = inventory_scope(&config, &private).unwrap(); |
| 2671 | config |
| 2672 | .set_provider_api_key_override(&private, Some("fixture-second-account".into())) |
| 2673 | .unwrap(); |
| 2674 | let (second_binding, _) = inventory_scope(&config, &private).unwrap(); |
| 2675 | assert_ne!(first_binding, second_binding); |
| 2676 | assert!(read(&private, &private_url).is_none()); |
| 2677 | let fingerprint = base_url_fingerprint(&private_url); |
| 2678 | assert!( |
| 2679 | record_success_if_current( |
| 2680 | &first_ticket, |
| 2681 | delta(private.key.as_str(), &fingerprint, &["model-a"]), |
| 2682 | ) |
| 2683 | .is_none() |
| 2684 | ); |
| 2685 | let second_ticket = begin_scoped_refresh(&config, &private, &private_url).unwrap(); |
| 2686 | record_failure_if_current( |
| 2687 | &second_ticket, |
| 2688 | private.key.as_str(), |
| 2689 | &fingerprint, |
| 2690 | CatalogRefreshError::Network, |
| 2691 | ) |
| 2692 | .unwrap(); |
| 2693 | assert!(read(&private, &private_url).unwrap().offerings.is_empty()); |
| 2694 | reset_cache_for_test(); |
| 2695 | assert!(read(&private, &private_url).is_none()); |
| 2696 | assert_eq!(read(&keyless, &keyless_url).unwrap().offerings.len(), 1); |
| 2697 | assert_eq!(read(&public, &public_url).unwrap().offerings.len(), 1); |
| 2698 | |
| 2699 | let mut legacy = ProviderCatalogCache::new(); |
| 2700 | let mut legacy_delta = delta(private.key.as_str(), &fingerprint, &["legacy-model"]); |
| 2701 | legacy_delta.provider = storage_provider(private.provider, private.key.as_str()); |
| 2702 | legacy.record_success(legacy_delta, DEFAULT_PROVIDER_CATALOG_TTL_SECS); |
| 2703 | let path = home.path().join("legacy-cache.json"); |
| 2704 | atomic_write_json( |
| 2705 | &path, |
| 2706 | &PersistedProviderCatalogs { |
| 2707 | schema_version: 2, |
| 2708 | cache: legacy, |
| 2709 | }, |
| 2710 | ) |
| 2711 | .unwrap(); |
| 2712 | assert!(load_from_disk_unlocked(&path).unwrap().entries.is_empty()); |
| 2713 | reset_cache_for_test(); |
| 2714 | crate::provider_lake::clear_live_snapshot(); |
| 2715 | } |
| 2716 | |
| 2717 | #[test] |
| 2718 | fn success_replaces_scope_and_failure_preserves_last_rows_on_disk() { |
| 2719 | let _env = lock_test_env(); |
| 2720 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2721 | let home = tempfile::tempdir().expect("home"); |
| 2722 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2723 | if let Ok(mut cache) = CACHE.write() { |
| 2724 | *cache = ProviderCatalogCache::new(); |
| 2725 | } |
| 2726 | |
| 2727 | assert_eq!( |
| 2728 | record_success(delta("openrouter", "fp", &["old"])), |
| 2729 | CatalogStatus::Fresh |
| 2730 | ); |
| 2731 | assert_eq!( |
| 2732 | record_success(delta("openrouter", "fp", &["new"])), |
| 2733 | CatalogStatus::Fresh |
| 2734 | ); |
| 2735 | assert!(matches!( |
| 2736 | record_failure("openrouter", "fp", CatalogRefreshError::RateLimited), |
| 2737 | CatalogStatus::Failed { |
| 2738 | reason: CatalogRefreshError::RateLimited |
| 2739 | } |
| 2740 | )); |
| 2741 | |
| 2742 | let loaded = load_from_disk().expect("persisted cache"); |
| 2743 | let entry = loaded |
| 2744 | .get(&scope("openrouter"), "fp") |
| 2745 | .expect("OpenRouter scope"); |
| 2746 | assert_eq!(entry.offerings.len(), 1); |
| 2747 | assert_eq!(entry.offerings[0].wire_model_id, "new"); |
| 2748 | assert!(matches!(entry.status, CatalogStatus::Failed { .. })); |
| 2749 | } |
| 2750 | |
| 2751 | #[test] |
| 2752 | fn authenticated_refresh_leaves_a_legacy_cache_file_intact() { |
| 2753 | // Authenticated refreshes are kept out of the durable merge, and a |
| 2754 | // legacy v2 file loads as an empty cache ("unproven v2 observations"). |
| 2755 | // Writing that empty merge back would erase every scope in the file, |
| 2756 | // which is how `codewhale models --update` used to wipe a user's |
| 2757 | // cached rosters. |
| 2758 | let _env = lock_test_env(); |
| 2759 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2760 | let home = tempfile::tempdir().expect("home"); |
| 2761 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2762 | reset_cache_for_test(); |
| 2763 | |
| 2764 | let base_url = "https://open.bigmodel.cn/api/coding/paas/v4"; |
| 2765 | let fingerprint = base_url_fingerprint(base_url); |
| 2766 | let mut legacy = ProviderCatalogCache::new(); |
| 2767 | let mut legacy_delta = delta("zai", &fingerprint, &["glm-5.3", "glm-5.3-flash"]); |
| 2768 | legacy_delta.provider = storage_provider(ProviderKind::Zai, "zai"); |
| 2769 | legacy.record_success(legacy_delta, DEFAULT_PROVIDER_CATALOG_TTL_SECS); |
| 2770 | let path = cache_path().expect("test cache path"); |
| 2771 | if let Some(parent) = path.parent() { |
| 2772 | std::fs::create_dir_all(parent).expect("cache dir"); |
| 2773 | } |
| 2774 | atomic_write_json( |
| 2775 | &path, |
| 2776 | &PersistedProviderCatalogs { |
| 2777 | schema_version: 2, |
| 2778 | cache: legacy, |
| 2779 | }, |
| 2780 | ) |
| 2781 | .expect("write legacy cache"); |
| 2782 | let before = std::fs::read(&path).expect("legacy bytes"); |
| 2783 | |
| 2784 | assert_eq!( |
| 2785 | record_success_for_identity( |
| 2786 | ProviderKind::Zai, |
| 2787 | delta("zai", &fingerprint, &["glm-5.3", "glm-5.4"]), |
| 2788 | false, |
| 2789 | ), |
| 2790 | CatalogStatus::Fresh |
| 2791 | ); |
| 2792 | assert_eq!( |
| 2793 | std::fs::read(&path).expect("cache bytes"), |
| 2794 | before, |
| 2795 | "an authenticated refresh must leave a legacy cache file intact" |
| 2796 | ); |
| 2797 | reset_cache_for_test(); |
| 2798 | } |
| 2799 | |
| 2800 | #[test] |
| 2801 | fn authenticated_refresh_still_scrubs_account_scoped_entries_from_current_cache() { |
| 2802 | let _env = lock_test_env(); |
| 2803 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2804 | let home = tempfile::tempdir().expect("home"); |
| 2805 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2806 | reset_cache_for_test(); |
| 2807 | |
| 2808 | let baseten_fp = base_url_fingerprint(codewhale_config::catalog::BASETEN_BASE_URL); |
| 2809 | let mut current = ProviderCatalogCache::new(); |
| 2810 | let mut baseten_delta = delta("baseten", &baseten_fp, &["private-workspace-model"]); |
| 2811 | baseten_delta.provider = storage_provider(ProviderKind::Custom, "baseten"); |
| 2812 | current.record_success(baseten_delta, DEFAULT_PROVIDER_CATALOG_TTL_SECS); |
| 2813 | let path = cache_path().expect("test cache path"); |
| 2814 | if let Some(parent) = path.parent() { |
| 2815 | std::fs::create_dir_all(parent).expect("cache dir"); |
| 2816 | } |
| 2817 | atomic_write_json( |
| 2818 | &path, |
| 2819 | &PersistedProviderCatalogs { |
| 2820 | schema_version: CACHE_SCHEMA_VERSION, |
| 2821 | cache: current, |
| 2822 | }, |
| 2823 | ) |
| 2824 | .expect("write current cache with account-scoped entry"); |
| 2825 | |
| 2826 | let zai_fp = base_url_fingerprint("https://open.bigmodel.cn/api/coding/paas/v4"); |
| 2827 | assert_eq!( |
| 2828 | record_success_for_identity( |
| 2829 | ProviderKind::Zai, |
| 2830 | delta("zai", &zai_fp, &["glm-5.3", "glm-5.4"]), |
| 2831 | false, |
| 2832 | ), |
| 2833 | CatalogStatus::Fresh |
| 2834 | ); |
| 2835 | let after = load_from_disk_unlocked(&path).expect("reload scrubbed cache"); |
| 2836 | assert!( |
| 2837 | after.entries.is_empty(), |
| 2838 | "account-scoped entries must still be scrubbed on authenticated refresh" |
| 2839 | ); |
| 2840 | reset_cache_for_test(); |
| 2841 | } |
| 2842 | |
| 2843 | #[test] |
| 2844 | fn baseten_workspace_roster_is_session_only_and_clears_before_reauthentication() { |
| 2845 | let _env = lock_test_env(); |
| 2846 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2847 | let home = tempfile::tempdir().expect("home"); |
| 2848 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2849 | reset_cache_for_test(); |
| 2850 | crate::provider_lake::clear_live_snapshot(); |
| 2851 | |
| 2852 | let base_url = codewhale_config::catalog::BASETEN_BASE_URL; |
| 2853 | let fingerprint = base_url_fingerprint(base_url); |
| 2854 | record_success(delta( |
| 2855 | codewhale_config::catalog::BASETEN_PROVIDER_ID, |
| 2856 | &fingerprint, |
| 2857 | &["workspace-a-only-model"], |
| 2858 | )); |
| 2859 | assert!( |
| 2860 | crate::provider_lake::all_catalog_models_for_provider_identity( |
| 2861 | ProviderKind::Custom, |
| 2862 | Some(codewhale_config::catalog::BASETEN_PROVIDER_ID), |
| 2863 | ) |
| 2864 | .contains(&"workspace-a-only-model".to_string()) |
| 2865 | ); |
| 2866 | assert!( |
| 2867 | load_from_disk().is_none_or(|cache| cache |
| 2868 | .get( |
| 2869 | &scope(codewhale_config::catalog::BASETEN_PROVIDER_ID), |
| 2870 | &fingerprint |
| 2871 | ) |
| 2872 | .is_none()), |
| 2873 | "an account-scoped Baseten roster must never be durable without a safe account id" |
| 2874 | ); |
| 2875 | |
| 2876 | let mut custom = std::collections::HashMap::new(); |
| 2877 | custom.insert( |
| 2878 | codewhale_config::catalog::BASETEN_PROVIDER_ID.to_string(), |
| 2879 | ProviderConfig { |
| 2880 | kind: Some("openai-compatible".to_string()), |
| 2881 | base_url: Some(base_url.to_string()), |
| 2882 | model: Some(codewhale_config::catalog::BASETEN_DEFAULT_MODEL.to_string()), |
| 2883 | ..ProviderConfig::default() |
| 2884 | }, |
| 2885 | ); |
| 2886 | let config = { |
| 2887 | let __cw_config_init_0_0 = |
| 2888 | Some(codewhale_config::catalog::BASETEN_PROVIDER_ID.to_string()); |
| 2889 | let __cw_config_init_0_1 = Some(ProvidersConfig { |
| 2890 | custom, |
| 2891 | ..ProvidersConfig::default() |
| 2892 | }); |
| 2893 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 2894 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 2895 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 2896 | __cw_config_init_0_value |
| 2897 | }; |
| 2898 | assert_eq!(maybe_load_persisted_cache_for_config(&config), 0); |
| 2899 | assert!(matches!( |
| 2900 | status_for_scope(codewhale_config::catalog::BASETEN_PROVIDER_ID, base_url), |
| 2901 | CatalogStatus::Unknown |
| 2902 | )); |
| 2903 | assert!( |
| 2904 | !crate::provider_lake::all_catalog_models_for_provider_identity( |
| 2905 | ProviderKind::Custom, |
| 2906 | Some(codewhale_config::catalog::BASETEN_PROVIDER_ID), |
| 2907 | ) |
| 2908 | .contains(&"workspace-a-only-model".to_string()), |
| 2909 | "a new credential attempt must not see the previous workspace roster" |
| 2910 | ); |
| 2911 | |
| 2912 | reset_cache_for_test(); |
| 2913 | crate::provider_lake::clear_live_snapshot(); |
| 2914 | } |
| 2915 | |
| 2916 | #[test] |
| 2917 | fn superseded_refresh_ticket_cannot_publish_a_late_response() { |
| 2918 | let _env = lock_test_env(); |
| 2919 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2920 | let home = tempfile::tempdir().expect("home"); |
| 2921 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2922 | reset_cache_for_test(); |
| 2923 | crate::provider_lake::clear_live_snapshot(); |
| 2924 | |
| 2925 | let old = begin_refresh("openrouter"); |
| 2926 | let current = begin_refresh("openrouter"); |
| 2927 | assert!( |
| 2928 | record_success_if_current(&old, delta("openrouter", "fp", &["late-old-model"])) |
| 2929 | .is_none() |
| 2930 | ); |
| 2931 | assert!( |
| 2932 | record_success_if_current(¤t, delta("openrouter", "fp", &["current-model"]),) |
| 2933 | .is_some() |
| 2934 | ); |
| 2935 | assert_eq!( |
| 2936 | CACHE |
| 2937 | .read() |
| 2938 | .expect("cache") |
| 2939 | .get(&scope("openrouter"), "fp") |
| 2940 | .expect("current scope") |
| 2941 | .offerings[0] |
| 2942 | .wire_model_id, |
| 2943 | "current-model" |
| 2944 | ); |
| 2945 | |
| 2946 | reset_cache_for_test(); |
| 2947 | crate::provider_lake::clear_live_snapshot(); |
| 2948 | } |
| 2949 | |
| 2950 | #[test] |
| 2951 | fn current_ticket_holds_generation_gate_through_publication() { |
| 2952 | let ticket = begin_refresh("generation-barrier-provider"); |
| 2953 | let entered = std::sync::Arc::new(std::sync::Barrier::new(2)); |
| 2954 | let release = std::sync::Arc::new(std::sync::Barrier::new(2)); |
| 2955 | let publish_entered = std::sync::Arc::clone(&entered); |
| 2956 | let publish_release = std::sync::Arc::clone(&release); |
| 2957 | let publisher = std::thread::spawn(move || { |
| 2958 | with_current_ticket(&ticket, "generation-barrier-provider", || { |
| 2959 | publish_entered.wait(); |
| 2960 | publish_release.wait(); |
| 2961 | }) |
| 2962 | }); |
| 2963 | entered.wait(); |
| 2964 | |
| 2965 | let (started_tx, started_rx) = std::sync::mpsc::channel(); |
| 2966 | let (finished_tx, finished_rx) = std::sync::mpsc::channel(); |
| 2967 | let newer = std::thread::spawn(move || { |
| 2968 | started_tx.send(()).expect("signal refresh start"); |
| 2969 | let next = begin_refresh("generation-barrier-provider"); |
| 2970 | finished_tx.send(next).expect("signal refresh finish"); |
| 2971 | }); |
| 2972 | started_rx.recv().expect("new refresh thread started"); |
| 2973 | assert!( |
| 2974 | finished_rx |
| 2975 | .recv_timeout(std::time::Duration::from_millis(50)) |
| 2976 | .is_err(), |
| 2977 | "a newer generation must wait until the accepted result finishes publication" |
| 2978 | ); |
| 2979 | |
| 2980 | release.wait(); |
| 2981 | assert!(publisher.join().expect("publisher thread").is_some()); |
| 2982 | assert!( |
| 2983 | finished_rx |
| 2984 | .recv_timeout(std::time::Duration::from_secs(1)) |
| 2985 | .is_ok() |
| 2986 | ); |
| 2987 | newer.join().expect("newer refresh thread"); |
| 2988 | } |
| 2989 | |
| 2990 | #[test] |
| 2991 | fn stale_process_snapshots_merge_exact_scopes_under_file_lock() { |
| 2992 | let _env = lock_test_env(); |
| 2993 | let home = tempfile::tempdir().expect("home"); |
| 2994 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2995 | |
| 2996 | let mut process_a = ProviderCatalogCache::new(); |
| 2997 | process_a.record_success(stored_delta("CustomA", "fp-a", &["upper-model"]), 60); |
| 2998 | persist_scope(&process_a, &scope("CustomA"), "fp-a", true); |
| 2999 | |
| 3000 | // Simulate another process that started before A wrote and therefore |
| 3001 | // has an empty/stale in-memory snapshot. Its scoped write must merge A |
| 3002 | // from disk rather than replacing the whole envelope. |
| 3003 | let mut process_b = ProviderCatalogCache::new(); |
| 3004 | process_b.record_success(stored_delta("customa", "fp-b", &["lower-model"]), 60); |
| 3005 | persist_scope(&process_b, &scope("customa"), "fp-b", true); |
| 3006 | |
| 3007 | let loaded = load_from_disk().expect("merged durable cache"); |
| 3008 | assert_eq!( |
| 3009 | loaded |
| 3010 | .get(&scope("CustomA"), "fp-a") |
| 3011 | .expect("case-sensitive upper scope") |
| 3012 | .offerings[0] |
| 3013 | .wire_model_id, |
| 3014 | "upper-model" |
| 3015 | ); |
| 3016 | assert_eq!( |
| 3017 | loaded |
| 3018 | .get(&scope("customa"), "fp-b") |
| 3019 | .expect("case-sensitive lower scope") |
| 3020 | .offerings[0] |
| 3021 | .wire_model_id, |
| 3022 | "lower-model" |
| 3023 | ); |
| 3024 | } |
| 3025 | |
| 3026 | #[test] |
| 3027 | fn stale_process_failure_preserves_newer_durable_rows_for_the_same_scope() { |
| 3028 | let _env = lock_test_env(); |
| 3029 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3030 | let home = tempfile::tempdir().expect("home"); |
| 3031 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3032 | reset_cache_for_test(); |
| 3033 | crate::provider_lake::clear_live_snapshot(); |
| 3034 | |
| 3035 | // Process B began with this old roster and still holds it in memory. |
| 3036 | let mut stale_process = ProviderCatalogCache::new(); |
| 3037 | stale_process.record_success(stored_delta_at("openrouter", "fp", &["old-model"], 1), 60); |
| 3038 | persist_scope(&stale_process, &scope("openrouter"), "fp", true); |
| 3039 | *CACHE.write().expect("cache") = stale_process; |
| 3040 | |
| 3041 | // Process A completes a newer successful refresh for the same scope. |
| 3042 | let mut newer_process = ProviderCatalogCache::new(); |
| 3043 | newer_process.record_success(stored_delta_at("openrouter", "fp", &["new-model"], 2), 60); |
| 3044 | persist_scope(&newer_process, &scope("openrouter"), "fp", true); |
| 3045 | |
| 3046 | // B then fails. Its failure status is current, but its old rows are |
| 3047 | // not: the transaction must retain A's newer durable roster. |
| 3048 | assert!(matches!( |
| 3049 | record_failure("openrouter", "fp", CatalogRefreshError::Network), |
| 3050 | CatalogStatus::Failed { |
| 3051 | reason: CatalogRefreshError::Network |
| 3052 | } |
| 3053 | )); |
| 3054 | let in_memory = CACHE.read().expect("cache"); |
| 3055 | let entry = in_memory |
| 3056 | .get(&scope("openrouter"), "fp") |
| 3057 | .expect("failed scope"); |
| 3058 | assert_eq!(entry.offerings[0].wire_model_id, "new-model"); |
| 3059 | assert!(matches!(entry.status, CatalogStatus::Failed { .. })); |
| 3060 | drop(in_memory); |
| 3061 | |
| 3062 | let durable = load_from_disk().expect("durable cache"); |
| 3063 | let entry = durable |
| 3064 | .get(&scope("openrouter"), "fp") |
| 3065 | .expect("durable failed scope"); |
| 3066 | assert_eq!(entry.offerings[0].wire_model_id, "new-model"); |
| 3067 | assert!(matches!(entry.status, CatalogStatus::Failed { .. })); |
| 3068 | |
| 3069 | reset_cache_for_test(); |
| 3070 | crate::provider_lake::clear_live_snapshot(); |
| 3071 | } |
| 3072 | |
| 3073 | #[test] |
| 3074 | fn oversized_cache_file_is_rejected_before_allocation() { |
| 3075 | let _env = lock_test_env(); |
| 3076 | let home = tempfile::tempdir().expect("home"); |
| 3077 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3078 | let path = cache_path().expect("cache path"); |
| 3079 | fs::create_dir_all(path.parent().expect("catalog directory")).expect("catalog directory"); |
| 3080 | fs::File::create(&path) |
| 3081 | .and_then(|file| file.set_len(MAX_CACHE_BYTES + 1)) |
| 3082 | .expect("sparse oversized cache"); |
| 3083 | assert!(load_from_disk().is_none()); |
| 3084 | } |
| 3085 | |
| 3086 | #[test] |
| 3087 | fn bounded_persistence_evicts_failed_then_stale_scopes_and_keeps_exact_owner() { |
| 3088 | let mut cache = ProviderCatalogCache::new(); |
| 3089 | cache.record_success( |
| 3090 | stored_delta_at("failed", "fp", &["failed-model"], 10), |
| 3091 | 1_000, |
| 3092 | ); |
| 3093 | cache.record_failure(&scope("failed"), "fp", CatalogRefreshError::Network); |
| 3094 | cache.record_success(stored_delta_at("stale", "fp", &["stale-model"], 20), 1); |
| 3095 | cache.record_success(stored_delta_at("fresh", "fp", &["fresh-model"], 30), 1_000); |
| 3096 | cache.record_success( |
| 3097 | stored_delta_at("protected", "fp", &["protected-model"], 40), |
| 3098 | 1_000, |
| 3099 | ); |
| 3100 | |
| 3101 | let compacted = bounded_cache_for_persistence( |
| 3102 | cache, |
| 3103 | Some((&scope("protected"), "fp")), |
| 3104 | 100, |
| 3105 | CachePersistenceLimits { |
| 3106 | max_bytes: u64::MAX, |
| 3107 | max_scopes: 2, |
| 3108 | max_rows: 100, |
| 3109 | }, |
| 3110 | ) |
| 3111 | .expect("bounded cache"); |
| 3112 | |
| 3113 | assert!(compacted.get(&scope("protected"), "fp").is_some()); |
| 3114 | assert!(compacted.get(&scope("fresh"), "fp").is_some()); |
| 3115 | assert!(compacted.get(&scope("failed"), "fp").is_none()); |
| 3116 | assert!(compacted.get(&scope("stale"), "fp").is_none()); |
| 3117 | } |
| 3118 | |
| 3119 | #[test] |
| 3120 | fn bounded_persistence_evicts_whole_scopes_and_refuses_an_oversized_owner() { |
| 3121 | let mut cache = ProviderCatalogCache::new(); |
| 3122 | cache.record_success( |
| 3123 | stored_delta_at("protected", "fp", &["one", "two"], 40), |
| 3124 | 1_000, |
| 3125 | ); |
| 3126 | cache.record_success(stored_delta_at("other", "fp", &["other"], 30), 1_000); |
| 3127 | let limits = CachePersistenceLimits { |
| 3128 | max_bytes: u64::MAX, |
| 3129 | max_scopes: 10, |
| 3130 | max_rows: 2, |
| 3131 | }; |
| 3132 | |
| 3133 | let compacted = bounded_cache_for_persistence( |
| 3134 | cache.clone(), |
| 3135 | Some((&scope("protected"), "fp")), |
| 3136 | 50, |
| 3137 | limits, |
| 3138 | ) |
| 3139 | .expect("other scope can be evicted whole"); |
| 3140 | assert_eq!( |
| 3141 | compacted |
| 3142 | .get(&scope("protected"), "fp") |
| 3143 | .expect("protected roster") |
| 3144 | .offerings |
| 3145 | .len(), |
| 3146 | 2 |
| 3147 | ); |
| 3148 | assert!(compacted.get(&scope("other"), "fp").is_none()); |
| 3149 | |
| 3150 | let mut oversized = cache; |
| 3151 | oversized.record_success( |
| 3152 | stored_delta_at("protected", "fp", &["one", "two", "three"], 50), |
| 3153 | 1_000, |
| 3154 | ); |
| 3155 | assert!( |
| 3156 | bounded_cache_for_persistence(oversized, Some((&scope("protected"), "fp")), 50, limits,) |
| 3157 | .is_err(), |
| 3158 | "a provider roster must be refused, never partially persisted" |
| 3159 | ); |
| 3160 | } |
| 3161 | |
| 3162 | #[test] |
| 3163 | fn bounded_cache_write_matches_read_limit_and_round_trips_after_compaction() { |
| 3164 | let directory = tempfile::tempdir().expect("cache directory"); |
| 3165 | let path = directory.path().join(CACHE_FILE); |
| 3166 | let mut protected_only = ProviderCatalogCache::new(); |
| 3167 | protected_only.record_success( |
| 3168 | stored_delta_at("protected", "fp", &["protected-model"], 40), |
| 3169 | 1_000, |
| 3170 | ); |
| 3171 | let exact_bytes = persisted_envelope_len(&protected_only).expect("encoded length"); |
| 3172 | let limits = CachePersistenceLimits { |
| 3173 | max_bytes: exact_bytes, |
| 3174 | max_scopes: 10, |
| 3175 | max_rows: 10, |
| 3176 | }; |
| 3177 | |
| 3178 | let mut combined = protected_only; |
| 3179 | combined.record_success( |
| 3180 | stored_delta_at( |
| 3181 | "evicted", |
| 3182 | "fp", |
| 3183 | &["this-entire-scope-does-not-fit-the-byte-bound"], |
| 3184 | 30, |
| 3185 | ), |
| 3186 | 1_000, |
| 3187 | ); |
| 3188 | write_bounded_cache(&path, combined, Some((&scope("protected"), "fp")), limits) |
| 3189 | .expect("bounded disk write"); |
| 3190 | |
| 3191 | assert!(fs::metadata(&path).expect("cache metadata").len() <= exact_bytes); |
| 3192 | let loaded = load_from_disk_unlocked_with_limit(&path, exact_bytes) |
| 3193 | .expect("bounded cache must remain readable under the same cap"); |
| 3194 | assert!(loaded.get(&scope("protected"), "fp").is_some()); |
| 3195 | assert!(loaded.get(&scope("evicted"), "fp").is_none()); |
| 3196 | } |
| 3197 | |
| 3198 | #[test] |
| 3199 | fn baseten_alias_roster_is_session_only_and_keeps_exact_ownership() { |
| 3200 | let _env = lock_test_env(); |
| 3201 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3202 | let home = tempfile::tempdir().expect("home"); |
| 3203 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3204 | reset_cache_for_test(); |
| 3205 | crate::provider_lake::clear_live_snapshot(); |
| 3206 | |
| 3207 | let alias = "base-ten"; |
| 3208 | let fingerprint = base_url_fingerprint(codewhale_config::catalog::BASETEN_BASE_URL); |
| 3209 | record_success(delta(alias, &fingerprint, &["alias-workspace-model"])); |
| 3210 | |
| 3211 | assert!( |
| 3212 | crate::provider_lake::all_catalog_models_for_provider_identity( |
| 3213 | ProviderKind::Custom, |
| 3214 | Some(alias), |
| 3215 | ) |
| 3216 | .contains(&"alias-workspace-model".to_string()) |
| 3217 | ); |
| 3218 | assert!( |
| 3219 | !crate::provider_lake::all_catalog_models_for_provider_identity( |
| 3220 | ProviderKind::Custom, |
| 3221 | Some(codewhale_config::catalog::BASETEN_PROVIDER_ID), |
| 3222 | ) |
| 3223 | .contains(&"alias-workspace-model".to_string()), |
| 3224 | "a reviewed schema alias must not collapse distinct exact table ownership" |
| 3225 | ); |
| 3226 | assert!( |
| 3227 | load_from_disk().is_none_or(|cache| cache.get(&scope(alias), &fingerprint).is_none()), |
| 3228 | "every Baseten schema alias must remain session-only" |
| 3229 | ); |
| 3230 | |
| 3231 | reset_cache_for_test(); |
| 3232 | crate::provider_lake::clear_live_snapshot(); |
| 3233 | } |
| 3234 | |
| 3235 | #[test] |
| 3236 | fn different_base_url_fingerprints_do_not_share_rows() { |
| 3237 | let mut cache = ProviderCatalogCache::new(); |
| 3238 | cache.record_success(stored_delta("baseten", "one", &["model-one"]), 60); |
| 3239 | cache.record_success(stored_delta("baseten", "two", &["model-two"]), 60); |
| 3240 | assert_eq!( |
| 3241 | cache.get(&scope("baseten"), "one").unwrap().offerings[0].wire_model_id, |
| 3242 | "model-one" |
| 3243 | ); |
| 3244 | assert_eq!( |
| 3245 | cache.get(&scope("baseten"), "two").unwrap().offerings[0].wire_model_id, |
| 3246 | "model-two" |
| 3247 | ); |
| 3248 | } |
| 3249 | |
| 3250 | #[test] |
| 3251 | fn missing_cache_for_changed_base_url_clears_the_previous_provider_partition() { |
| 3252 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3253 | crate::provider_lake::clear_live_snapshot(); |
| 3254 | let mut cache = ProviderCatalogCache::new(); |
| 3255 | cache.record_success( |
| 3256 | stored_delta("baseten", "old-fp", &["old-endpoint-model"]), |
| 3257 | 60, |
| 3258 | ); |
| 3259 | |
| 3260 | assert_eq!( |
| 3261 | publish_exact_scope_for_identity(&cache, ProviderKind::Custom, "baseten", "old-fp"), |
| 3262 | 1 |
| 3263 | ); |
| 3264 | assert_eq!( |
| 3265 | crate::provider_lake::all_catalog_models_for_provider_identity( |
| 3266 | codewhale_config::ProviderKind::Custom, |
| 3267 | Some("baseten"), |
| 3268 | ), |
| 3269 | vec!["old-endpoint-model".to_string()] |
| 3270 | ); |
| 3271 | |
| 3272 | assert_eq!( |
| 3273 | publish_exact_scope_for_identity(&cache, ProviderKind::Custom, "baseten", "new-fp"), |
| 3274 | 0 |
| 3275 | ); |
| 3276 | let after_switch = crate::provider_lake::all_catalog_models_for_provider_identity( |
| 3277 | codewhale_config::ProviderKind::Custom, |
| 3278 | Some("baseten"), |
| 3279 | ); |
| 3280 | assert!( |
| 3281 | after_switch.is_empty(), |
| 3282 | "rows from the old Baseten endpoint must not survive a fingerprint change, and no compiled seed replaces them (#6289)" |
| 3283 | ); |
| 3284 | crate::provider_lake::clear_live_snapshot(); |
| 3285 | } |
| 3286 | |
| 3287 | #[test] |
| 3288 | fn disk_reload_rehydrates_and_exposes_six_hundred_keyless_openrouter_models() { |
| 3289 | let _env = lock_test_env(); |
| 3290 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3291 | let home = tempfile::tempdir().expect("home"); |
| 3292 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3293 | crate::provider_lake::clear_live_snapshot(); |
| 3294 | if let Ok(mut cache) = CACHE.write() { |
| 3295 | *cache = ProviderCatalogCache::new(); |
| 3296 | } |
| 3297 | |
| 3298 | let config = { |
| 3299 | let __cw_config_init_1_0 = Some("openrouter".to_string()); |
| 3300 | let __cw_config_init_1_1 = Some(ProvidersConfig { |
| 3301 | openrouter: ProviderConfig { |
| 3302 | base_url: Some("https://synthetic.openrouter.invalid/api/v1".to_string()), |
| 3303 | auth_mode: Some("none".to_string()), |
| 3304 | ..ProviderConfig::default() |
| 3305 | }, |
| 3306 | ..ProvidersConfig::default() |
| 3307 | }); |
| 3308 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 3309 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 3310 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 3311 | __cw_config_init_1_value |
| 3312 | }; |
| 3313 | let identity = config.active_provider_identity().unwrap(); |
| 3314 | let provider = identity.key.as_str(); |
| 3315 | let fingerprint = base_url_fingerprint(&config.active_route_base_url()); |
| 3316 | let fetched_at = now_unix(); |
| 3317 | let ids: Vec<String> = (0..600) |
| 3318 | .map(|index| format!("synthetic/openrouter-model-{index:03}")) |
| 3319 | .collect(); |
| 3320 | let status = record_success(ProviderCatalogDelta { |
| 3321 | provider: provider.to_string(), |
| 3322 | base_url_fingerprint: fingerprint, |
| 3323 | fetched_at, |
| 3324 | offerings: ids |
| 3325 | .iter() |
| 3326 | .map(|id| CatalogOffering { |
| 3327 | provider: provider.to_string(), |
| 3328 | wire_model_id: id.clone(), |
| 3329 | endpoint_key: "chat".to_string(), |
| 3330 | source: CatalogSource::Live { |
| 3331 | base_url_fingerprint: base_url_fingerprint(&config.active_route_base_url()), |
| 3332 | fetched_at, |
| 3333 | }, |
| 3334 | ..CatalogOffering::default() |
| 3335 | }) |
| 3336 | .collect(), |
| 3337 | }); |
| 3338 | assert_eq!(status, CatalogStatus::Fresh); |
| 3339 | assert!(cache_path().is_some_and(|path| path.is_file())); |
| 3340 | assert_eq!( |
| 3341 | crate::provider_lake::all_catalog_models_for_provider(ProviderKind::Openrouter), |
| 3342 | ids, |
| 3343 | "the string compatibility publisher must retain built-in OpenRouter ownership" |
| 3344 | ); |
| 3345 | assert!( |
| 3346 | crate::provider_lake::all_catalog_models_for_provider_identity( |
| 3347 | ProviderKind::Custom, |
| 3348 | Some("openrouter"), |
| 3349 | ) |
| 3350 | .is_empty(), |
| 3351 | "built-in OpenRouter rows must not enter the custom namespace" |
| 3352 | ); |
| 3353 | |
| 3354 | // Simulate a new process: remove both in-memory owners, then republish |
| 3355 | // only through the durable startup load path. |
| 3356 | if let Ok(mut cache) = CACHE.write() { |
| 3357 | *cache = ProviderCatalogCache::new(); |
| 3358 | } |
| 3359 | crate::provider_lake::clear_live_snapshot(); |
| 3360 | |
| 3361 | assert_eq!(maybe_load_persisted_cache_for_config(&config), 600); |
| 3362 | let visible = |
| 3363 | crate::provider_lake::all_catalog_models_for_provider(ProviderKind::Openrouter); |
| 3364 | assert_eq!(visible.len(), 600); |
| 3365 | assert_eq!(visible.first(), ids.first()); |
| 3366 | assert_eq!(visible.last(), ids.last()); |
| 3367 | |
| 3368 | if let Ok(mut cache) = CACHE.write() { |
| 3369 | *cache = ProviderCatalogCache::new(); |
| 3370 | } |
| 3371 | crate::provider_lake::clear_live_snapshot(); |
| 3372 | } |
| 3373 | #[test] |
| 3374 | fn typed_refresh_keeps_builtin_and_same_named_custom_scopes_separate_on_disk() { |
| 3375 | let _env = lock_test_env(); |
| 3376 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3377 | let home = tempfile::tempdir().unwrap(); |
| 3378 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3379 | reset_cache_for_test(); |
| 3380 | crate::provider_lake::clear_live_snapshot(); |
| 3381 | let endpoint = "https://api.openai.com/v1"; |
| 3382 | let fingerprint = base_url_fingerprint(endpoint); |
| 3383 | let built_in = begin_refresh_for_identity(ProviderKind::Openai, "openai", endpoint); |
| 3384 | let custom = begin_refresh_for_identity(ProviderKind::Custom, "openai", endpoint); |
| 3385 | assert_eq!( |
| 3386 | record_success_if_current( |
| 3387 | &built_in, |
| 3388 | delta("openai", &fingerprint, &["built-in-model"]) |
| 3389 | ), |
| 3390 | Some(CatalogStatus::Fresh) |
| 3391 | ); |
| 3392 | assert_eq!( |
| 3393 | record_success_if_current(&custom, delta("openai", &fingerprint, &["custom-model"])), |
| 3394 | Some(CatalogStatus::Fresh) |
| 3395 | ); |
| 3396 | reset_cache_for_test(); |
| 3397 | crate::provider_lake::clear_live_snapshot(); |
| 3398 | for (kind, expected) in [ |
| 3399 | (ProviderKind::Openai, "built-in-model"), |
| 3400 | (ProviderKind::Custom, "custom-model"), |
| 3401 | ] { |
| 3402 | let entry = cached_entry_for_route(kind, "openai", endpoint) |
| 3403 | .unwrap() |
| 3404 | .unwrap(); |
| 3405 | assert_eq!(entry.offerings[0].wire_model_id, expected); |
| 3406 | assert_eq!(entry.offerings[0].provider, "openai"); |
| 3407 | } |
| 3408 | assert!( |
| 3409 | cached_entry_for_route(ProviderKind::Custom, "OpenAI", endpoint) |
| 3410 | .unwrap() |
| 3411 | .is_none() |
| 3412 | ); |
| 3413 | reset_cache_for_test(); |
| 3414 | } |
| 3415 | |
| 3416 | #[test] |
| 3417 | fn typed_refresh_rejects_wrong_endpoint_and_superseded_endpoint_response() { |
| 3418 | let _env = lock_test_env(); |
| 3419 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3420 | let home = tempfile::tempdir().unwrap(); |
| 3421 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3422 | reset_cache_for_test(); |
| 3423 | crate::provider_lake::clear_live_snapshot(); |
| 3424 | let first_url = "https://first.invalid/v1"; |
| 3425 | let second_url = "https://second.invalid/v1"; |
| 3426 | let first = begin_refresh_for_identity(ProviderKind::Custom, "ExactRoute", first_url); |
| 3427 | assert!( |
| 3428 | record_success_if_current( |
| 3429 | &first, |
| 3430 | delta( |
| 3431 | "ExactRoute", |
| 3432 | &base_url_fingerprint(second_url), |
| 3433 | &["wrong-endpoint"] |
| 3434 | ) |
| 3435 | ) |
| 3436 | .is_none() |
| 3437 | ); |
| 3438 | let second = begin_refresh_for_identity(ProviderKind::Custom, "ExactRoute", second_url); |
| 3439 | assert!( |
| 3440 | record_failure_if_current( |
| 3441 | &second, |
| 3442 | "ExactRoute", |
| 3443 | &base_url_fingerprint(first_url), |
| 3444 | CatalogRefreshError::Network |
| 3445 | ) |
| 3446 | .is_none() |
| 3447 | ); |
| 3448 | assert_eq!( |
| 3449 | record_success_if_current( |
| 3450 | &second, |
| 3451 | delta( |
| 3452 | "ExactRoute", |
| 3453 | &base_url_fingerprint(second_url), |
| 3454 | &["current-model"] |
| 3455 | ) |
| 3456 | ), |
| 3457 | Some(CatalogStatus::Fresh) |
| 3458 | ); |
| 3459 | assert!( |
| 3460 | record_success_if_current( |
| 3461 | &first, |
| 3462 | delta( |
| 3463 | "ExactRoute", |
| 3464 | &base_url_fingerprint(first_url), |
| 3465 | &["late-model"] |
| 3466 | ) |
| 3467 | ) |
| 3468 | .is_none() |
| 3469 | ); |
| 3470 | assert!( |
| 3471 | cached_entry_for_route(ProviderKind::Custom, "ExactRoute", first_url) |
| 3472 | .unwrap() |
| 3473 | .is_none() |
| 3474 | ); |
| 3475 | assert_eq!( |
| 3476 | crate::provider_lake::catalog_models_for_route( |
| 3477 | ProviderKind::Custom, |
| 3478 | "ExactRoute", |
| 3479 | second_url |
| 3480 | ), |
| 3481 | vec!["current-model"] |
| 3482 | ); |
| 3483 | reset_cache_for_test(); |
| 3484 | crate::provider_lake::clear_live_snapshot(); |
| 3485 | } |
| 3486 | |
| 3487 | #[test] |
| 3488 | fn differently_named_baseten_endpoint_never_persists_account_roster() { |
| 3489 | let _env = lock_test_env(); |
| 3490 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3491 | let home = tempfile::tempdir().unwrap(); |
| 3492 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3493 | reset_cache_for_test(); |
| 3494 | crate::provider_lake::clear_live_snapshot(); |
| 3495 | let endpoint = codewhale_config::catalog::BASETEN_BASE_URL; |
| 3496 | let ticket = begin_refresh_for_identity(ProviderKind::Custom, "TeamServing", endpoint); |
| 3497 | assert_eq!( |
| 3498 | record_success_if_current( |
| 3499 | &ticket, |
| 3500 | delta( |
| 3501 | "TeamServing", |
| 3502 | &base_url_fingerprint(endpoint), |
| 3503 | &["private-workspace-model"] |
| 3504 | ) |
| 3505 | ), |
| 3506 | Some(CatalogStatus::Fresh) |
| 3507 | ); |
| 3508 | assert_eq!( |
| 3509 | crate::provider_lake::catalog_models_for_route( |
| 3510 | ProviderKind::Custom, |
| 3511 | "TeamServing", |
| 3512 | endpoint |
| 3513 | ), |
| 3514 | vec!["private-workspace-model"] |
| 3515 | ); |
| 3516 | assert!( |
| 3517 | !fs::read_to_string(cache_path().unwrap()) |
| 3518 | .unwrap() |
| 3519 | .contains("private-workspace-model") |
| 3520 | ); |
| 3521 | let _new_credentials = |
| 3522 | begin_refresh_for_identity(ProviderKind::Custom, "TeamServing", endpoint); |
| 3523 | assert!( |
| 3524 | crate::provider_lake::catalog_models_for_route( |
| 3525 | ProviderKind::Custom, |
| 3526 | "TeamServing", |
| 3527 | endpoint |
| 3528 | ) |
| 3529 | .is_empty() |
| 3530 | ); |
| 3531 | reset_cache_for_test(); |
| 3532 | assert!( |
| 3533 | cached_entry_for_route(ProviderKind::Custom, "TeamServing", endpoint) |
| 3534 | .unwrap() |
| 3535 | .is_none() |
| 3536 | ); |
| 3537 | crate::provider_lake::clear_live_snapshot(); |
| 3538 | } |
| 3539 | |
| 3540 | #[test] |
| 3541 | fn codewhale_account_rosters_are_memory_only_and_replaced_after_credential_refresh() { |
| 3542 | let _env = lock_test_env(); |
| 3543 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3544 | let home = tempfile::tempdir().unwrap(); |
| 3545 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3546 | reset_cache_for_test(); |
| 3547 | crate::provider_lake::clear_live_snapshot(); |
| 3548 | for (kind, identity, endpoint) in [ |
| 3549 | ( |
| 3550 | ProviderKind::Codewhale, |
| 3551 | "codewhale", |
| 3552 | ProviderKind::Codewhale.provider().default_base_url(), |
| 3553 | ), |
| 3554 | ( |
| 3555 | ProviderKind::Codewhale, |
| 3556 | "codewhale", |
| 3557 | "https://codewhale.account.invalid/v1", |
| 3558 | ), |
| 3559 | ( |
| 3560 | ProviderKind::Custom, |
| 3561 | "PrivateAccount", |
| 3562 | ProviderKind::Codewhale.provider().default_base_url(), |
| 3563 | ), |
| 3564 | ] { |
| 3565 | let fingerprint = base_url_fingerprint(endpoint); |
| 3566 | let old = begin_refresh_for_identity(kind, identity, endpoint); |
| 3567 | assert_eq!( |
| 3568 | record_success_if_current( |
| 3569 | &old, |
| 3570 | delta(identity, &fingerprint, &["private-old-account-model"]) |
| 3571 | ), |
| 3572 | Some(CatalogStatus::Fresh) |
| 3573 | ); |
| 3574 | assert!( |
| 3575 | cached_entry_for_route(kind, identity, endpoint) |
| 3576 | .unwrap() |
| 3577 | .is_some() |
| 3578 | ); |
| 3579 | assert!( |
| 3580 | !fs::read_to_string(cache_path().unwrap()) |
| 3581 | .unwrap() |
| 3582 | .contains("private-old-account-model") |
| 3583 | ); |
| 3584 | let current = begin_refresh_for_identity(kind, identity, endpoint); |
| 3585 | assert!( |
| 3586 | cached_entry_for_route(kind, identity, endpoint) |
| 3587 | .unwrap() |
| 3588 | .is_none() |
| 3589 | ); |
| 3590 | assert!( |
| 3591 | !crate::provider_lake::catalog_models_for_route(kind, identity, endpoint) |
| 3592 | .contains(&"private-old-account-model".to_string()) |
| 3593 | ); |
| 3594 | assert!( |
| 3595 | record_success_if_current( |
| 3596 | &old, |
| 3597 | delta(identity, &fingerprint, &["private-old-account-model"]) |
| 3598 | ) |
| 3599 | .is_none() |
| 3600 | ); |
| 3601 | assert_eq!( |
| 3602 | record_success_if_current( |
| 3603 | ¤t, |
| 3604 | delta(identity, &fingerprint, &["private-new-account-model"]) |
| 3605 | ), |
| 3606 | Some(CatalogStatus::Fresh) |
| 3607 | ); |
| 3608 | assert_eq!( |
| 3609 | crate::provider_lake::catalog_models_for_route(kind, identity, endpoint), |
| 3610 | vec!["private-new-account-model"] |
| 3611 | ); |
| 3612 | assert!( |
| 3613 | !fs::read_to_string(cache_path().unwrap()) |
| 3614 | .unwrap() |
| 3615 | .contains("private-new-account-model") |
| 3616 | ); |
| 3617 | reset_cache_for_test(); |
| 3618 | crate::provider_lake::clear_live_snapshot(); |
| 3619 | assert!( |
| 3620 | cached_entry_for_route(kind, identity, endpoint) |
| 3621 | .unwrap() |
| 3622 | .is_none() |
| 3623 | ); |
| 3624 | } |
| 3625 | reset_cache_for_test(); |
| 3626 | crate::provider_lake::clear_live_snapshot(); |
| 3627 | } |
| 3628 | |
| 3629 | #[cfg(unix)] |
| 3630 | #[test] |
| 3631 | fn cache_reader_rejects_links_and_special_files_without_blocking() { |
| 3632 | use std::os::unix::ffi::OsStrExt as _; |
| 3633 | let dir = tempfile::tempdir().unwrap(); |
| 3634 | let target = dir.path().join("target.json"); |
| 3635 | let envelope = PersistedProviderCatalogs { |
| 3636 | schema_version: CACHE_SCHEMA_VERSION, |
| 3637 | cache: ProviderCatalogCache::new(), |
| 3638 | }; |
| 3639 | fs::write(&target, serde_json::to_vec(&envelope).unwrap()).unwrap(); |
| 3640 | let symlink = dir.path().join("symlink.json"); |
| 3641 | std::os::unix::fs::symlink(&target, &symlink).unwrap(); |
| 3642 | assert!(load_from_disk_unlocked_with_limit(&symlink, MAX_CACHE_BYTES).is_none()); |
| 3643 | let hardlink = dir.path().join("hardlink.json"); |
| 3644 | fs::hard_link(&target, &hardlink).unwrap(); |
| 3645 | assert!(load_from_disk_unlocked_with_limit(&hardlink, MAX_CACHE_BYTES).is_none()); |
| 3646 | let fifo = dir.path().join("fifo.json"); |
| 3647 | let fifo_c = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap(); |
| 3648 | // SAFETY: fifo_c owns a NUL-terminated pathname for the call. |
| 3649 | assert_eq!(unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o600) }, 0); |
| 3650 | assert!(load_from_disk_unlocked_with_limit(&fifo, MAX_CACHE_BYTES).is_none()); |
| 3651 | assert!(open_cache_lock(&fifo).is_err()); |
| 3652 | assert!(load_from_disk_unlocked_with_limit(dir.path(), MAX_CACHE_BYTES).is_none()); |
| 3653 | } |
| 3654 | |
| 3655 | struct CloudQuoteReset; |
| 3656 | impl Drop for CloudQuoteReset { |
| 3657 | fn drop(&mut self) { |
| 3658 | codewhale_config::cloud_facts::overlay::clear(); |
| 3659 | crate::provider_lake::clear_live_snapshot(); |
| 3660 | reset_cache_for_test(); |
| 3661 | } |
| 3662 | } |
| 3663 | |
| 3664 | fn install_cloud_quote_fixture( |
| 3665 | channel: &str, |
| 3666 | provider: ProviderKind, |
| 3667 | version: u64, |
| 3668 | input: f64, |
| 3669 | now: u64, |
| 3670 | ) { |
| 3671 | use codewhale_config::cloud_facts::{ |
| 3672 | CloudFactsState, CloudFactsStatus, FactsOrigin, ModelFact, PricingFact, ScopedFacts, |
| 3673 | overlay, |
| 3674 | }; |
| 3675 | let ticket = overlay::configure(true, "cloud-quote-fixture").unwrap(); |
| 3676 | assert!(overlay::publish( |
| 3677 | &ticket, |
| 3678 | Some(ScopedFacts { |
| 3679 | channel: channel.into(), |
| 3680 | facts_version: version, |
| 3681 | key_id: "cwf-test-only".into(), |
| 3682 | valid_until: Some(now + 60), |
| 3683 | models: vec![ModelFact { |
| 3684 | provider: provider.as_str().into(), |
| 3685 | id: "cloud-quote-fixture".into(), |
| 3686 | context_window: Some(16_384), |
| 3687 | pricing: Some(PricingFact { |
| 3688 | input_per_m: Some(input), |
| 3689 | output_per_m: Some(2.0), |
| 3690 | cache_read_per_m: None, |
| 3691 | }), |
| 3692 | ..Default::default() |
| 3693 | }], |
| 3694 | ..Default::default() |
| 3695 | }), |
| 3696 | CloudFactsStatus { |
| 3697 | state: CloudFactsState::Verified { |
| 3698 | channel: channel.into(), |
| 3699 | facts_version: version, |
| 3700 | key_id: "cwf-test-only".into(), |
| 3701 | fetched_at: now, |
| 3702 | origin: FactsOrigin::LocalFile, |
| 3703 | stale: false, |
| 3704 | patches: 1, |
| 3705 | defaults: 0, |
| 3706 | announcements: 0, |
| 3707 | }, |
| 3708 | ..Default::default() |
| 3709 | }, |
| 3710 | )); |
| 3711 | } |
| 3712 | |
| 3713 | #[test] |
| 3714 | fn cloud_quote_freezes_actual_dispatch_and_survives_refresh_disable_and_reload() { |
| 3715 | let _env = lock_test_env(); |
| 3716 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3717 | let home = tempfile::tempdir().unwrap(); |
| 3718 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3719 | let _enabled = EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS"); |
| 3720 | let _reset = CloudQuoteReset; |
| 3721 | reset_cache_for_test(); |
| 3722 | crate::provider_lake::clear_live_snapshot(); |
| 3723 | let now = chrono::Utc::now(); |
| 3724 | let at = now.timestamp() as u64; |
| 3725 | let base = codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL; |
| 3726 | install_cloud_quote_fixture("quote-frozen", ProviderKind::Openai, 91, 1.0, at); |
| 3727 | let route = crate::cost_status::EffectiveRouteEnvelope::capture( |
| 3728 | None, |
| 3729 | ProviderKind::Openai, |
| 3730 | "openai", |
| 3731 | "cloud-quote-fixture", |
| 3732 | Some(base), |
| 3733 | now, |
| 3734 | ); |
| 3735 | let quote = route |
| 3736 | .provider_live_pricing |
| 3737 | .as_ref() |
| 3738 | .expect("frozen cloud price"); |
| 3739 | assert_eq!(quote.provenance, PricingProvenance::CloudFacts); |
| 3740 | assert_eq!(quote.cloud_facts.as_ref().unwrap().facts_version, 91); |
| 3741 | assert_eq!(quote.input_per_million.as_deref(), Some("1")); |
| 3742 | assert!(quote.cache_read_per_million.is_none()); |
| 3743 | let encoded = serde_json::to_string(&route).unwrap(); |
| 3744 | install_cloud_quote_fixture("quote-frozen", ProviderKind::Openai, 92, 9.0, at); |
| 3745 | let newer = fresh_dispatch_pricing_quote_at( |
| 3746 | ProviderKind::Openai, |
| 3747 | "openai", |
| 3748 | "cloud-quote-fixture", |
| 3749 | base, |
| 3750 | at, |
| 3751 | ) |
| 3752 | .unwrap(); |
| 3753 | assert_eq!(newer.input_per_million.as_deref(), Some("9")); |
| 3754 | assert_ne!(newer.catalog_revision, quote.catalog_revision); |
| 3755 | codewhale_config::cloud_facts::overlay::clear(); |
| 3756 | assert!( |
| 3757 | fresh_dispatch_pricing_quote_at( |
| 3758 | ProviderKind::Openai, |
| 3759 | "openai", |
| 3760 | "cloud-quote-fixture", |
| 3761 | base, |
| 3762 | at, |
| 3763 | ) |
| 3764 | .is_none() |
| 3765 | ); |
| 3766 | let restored: crate::cost_status::EffectiveRouteEnvelope = |
| 3767 | serde_json::from_str(&encoded).unwrap(); |
| 3768 | assert_eq!(restored, route); |
| 3769 | let pricing = restored |
| 3770 | .provider_live_pricing |
| 3771 | .as_ref() |
| 3772 | .unwrap() |
| 3773 | .pricing_for_route( |
| 3774 | ProviderKind::Openai, |
| 3775 | "openai", |
| 3776 | "cloud-quote-fixture", |
| 3777 | &base_url_fingerprint(base), |
| 3778 | at, |
| 3779 | ) |
| 3780 | .unwrap(); |
| 3781 | assert_eq!(pricing.input_per_million, Some(1.0)); |
| 3782 | // Expiry is checked at dispatch; loading later does not reprice history. |
| 3783 | assert!( |
| 3784 | quote |
| 3785 | .pricing_for_route( |
| 3786 | ProviderKind::Openai, |
| 3787 | "openai", |
| 3788 | "cloud-quote-fixture", |
| 3789 | &base_url_fingerprint(base), |
| 3790 | at + 61, |
| 3791 | ) |
| 3792 | .is_none() |
| 3793 | ); |
| 3794 | } |
| 3795 | |
| 3796 | #[test] |
| 3797 | fn cloud_quote_rejects_cross_route_and_modified_source_receipts() { |
| 3798 | let _env = lock_test_env(); |
| 3799 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3800 | let home = tempfile::tempdir().unwrap(); |
| 3801 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3802 | let _enabled = EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS"); |
| 3803 | let _reset = CloudQuoteReset; |
| 3804 | reset_cache_for_test(); |
| 3805 | crate::provider_lake::clear_live_snapshot(); |
| 3806 | let at = now_unix(); |
| 3807 | let base = codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL; |
| 3808 | install_cloud_quote_fixture("quote-binding", ProviderKind::Openai, 93, 1.0, at); |
| 3809 | let quote = fresh_dispatch_pricing_quote_at( |
| 3810 | ProviderKind::Openai, |
| 3811 | "openai", |
| 3812 | "cloud-quote-fixture", |
| 3813 | base, |
| 3814 | at, |
| 3815 | ) |
| 3816 | .unwrap(); |
| 3817 | for (provider, identity, endpoint) in [ |
| 3818 | (ProviderKind::Openai, "openai", "https://proxy.example/v1"), |
| 3819 | (ProviderKind::Custom, "openai", base), |
| 3820 | (ProviderKind::Openai, "named-openai", base), |
| 3821 | ( |
| 3822 | ProviderKind::Openai, |
| 3823 | "openai", |
| 3824 | "https://secret@api.openai.com/v1", |
| 3825 | ), |
| 3826 | ] { |
| 3827 | assert!( |
| 3828 | fresh_dispatch_pricing_quote_at( |
| 3829 | provider, |
| 3830 | identity, |
| 3831 | "cloud-quote-fixture", |
| 3832 | endpoint, |
| 3833 | at |
| 3834 | ) |
| 3835 | .is_none() |
| 3836 | ); |
| 3837 | } |
| 3838 | let value = serde_json::to_value("e).unwrap(); |
| 3839 | for (field, replacement) in [ |
| 3840 | ("facts_version", serde_json::json!(94)), |
| 3841 | ("key_id", serde_json::json!("cwf-relabelled")), |
| 3842 | ("valid_until", serde_json::json!(at + 600)), |
| 3843 | ("base_url", serde_json::json!("https://proxy.example/v1")), |
| 3844 | ] { |
| 3845 | let mut modified = value.clone(); |
| 3846 | modified["cloud_facts"][field] = replacement; |
| 3847 | assert!( |
| 3848 | serde_json::from_value::<ProviderLivePricingQuote>(modified).is_err(), |
| 3849 | "changed {field} accepted" |
| 3850 | ); |
| 3851 | } |
| 3852 | let mut invalid = quote.clone(); |
| 3853 | invalid.cloud_facts.as_mut().unwrap().base_url = "https://secret@api.openai.com/v1".into(); |
| 3854 | assert!(serde_json::to_value(invalid).unwrap().is_null()); |
| 3855 | assert!( |
| 3856 | quote |
| 3857 | .pricing_for_route( |
| 3858 | ProviderKind::Openai, |
| 3859 | "openai", |
| 3860 | "different-model", |
| 3861 | &base_url_fingerprint(base), |
| 3862 | at, |
| 3863 | ) |
| 3864 | .is_none() |
| 3865 | ); |
| 3866 | } |
| 3867 | |
| 3868 | #[test] |
| 3869 | fn cloud_quote_static_endpoint_survives_operator_endpoint_changes() { |
| 3870 | let _env = lock_test_env(); |
| 3871 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3872 | let home = tempfile::tempdir().unwrap(); |
| 3873 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3874 | let _enabled = EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS"); |
| 3875 | let _reset = CloudQuoteReset; |
| 3876 | reset_cache_for_test(); |
| 3877 | crate::provider_lake::clear_live_snapshot(); |
| 3878 | let at = now_unix(); |
| 3879 | let base = ProviderKind::Codewhale.provider().default_base_url(); |
| 3880 | let private = "https://private.example/v1?api_key=public-test-marker"; |
| 3881 | let declared = EnvVarGuard::set("CODEWHALE_API_BASE", private); |
| 3882 | // The ordinary runtime credential contract intentionally accepts this |
| 3883 | // explicit operator route. It is not a public signed-facts authority. |
| 3884 | assert!(codewhale_config::provider_base_url_is_official( |
| 3885 | codewhale_config::ProviderKind::Codewhale, |
| 3886 | private, |
| 3887 | )); |
| 3888 | install_cloud_quote_fixture("quote-static", ProviderKind::Codewhale, 94, 1.0, at); |
| 3889 | assert!( |
| 3890 | fresh_dispatch_pricing_quote_at( |
| 3891 | ProviderKind::Codewhale, |
| 3892 | "codewhale", |
| 3893 | "cloud-quote-fixture", |
| 3894 | private, |
| 3895 | at, |
| 3896 | ) |
| 3897 | .is_none() |
| 3898 | ); |
| 3899 | let quote = fresh_dispatch_pricing_quote_at( |
| 3900 | ProviderKind::Codewhale, |
| 3901 | "codewhale", |
| 3902 | "cloud-quote-fixture", |
| 3903 | base, |
| 3904 | at, |
| 3905 | ) |
| 3906 | .unwrap(); |
| 3907 | let encoded = serde_json::to_string("e).unwrap(); |
| 3908 | assert!(!encoded.contains("private.example")); |
| 3909 | assert!(!encoded.contains("public-test-marker")); |
| 3910 | drop(declared); |
| 3911 | let removed = EnvVarGuard::remove("CODEWHALE_API_BASE"); |
| 3912 | let reloaded: ProviderLivePricingQuote = serde_json::from_str(&encoded).unwrap(); |
| 3913 | assert_eq!(reloaded, quote); |
| 3914 | drop(removed); |
| 3915 | let _changed = EnvVarGuard::set("CODEWHALE_API_BASE", "https://another-private.example/v1"); |
| 3916 | assert_eq!( |
| 3917 | serde_json::from_str::<ProviderLivePricingQuote>(&encoded).unwrap(), |
| 3918 | quote |
| 3919 | ); |
| 3920 | assert!( |
| 3921 | quote |
| 3922 | .pricing_for_route( |
| 3923 | ProviderKind::Codewhale, |
| 3924 | "codewhale", |
| 3925 | "cloud-quote-fixture", |
| 3926 | &base_url_fingerprint(base), |
| 3927 | at, |
| 3928 | ) |
| 3929 | .is_some() |
| 3930 | ); |
| 3931 | } |
| 3932 | |
| 3933 | #[test] |
| 3934 | fn durable_provider_catalog_cannot_claim_cloud_or_override_price_authority() { |
| 3935 | let dir = tempfile::tempdir().unwrap(); |
| 3936 | let path = dir.path().join("catalog.json"); |
| 3937 | let mut cache = ProviderCatalogCache::new(); |
| 3938 | cache.record_success( |
| 3939 | stored_delta("openai", "fp", &["fixture"]), |
| 3940 | DEFAULT_PROVIDER_CATALOG_TTL_SECS, |
| 3941 | ); |
| 3942 | let baseline = PersistedProviderCatalogs { |
| 3943 | schema_version: CACHE_SCHEMA_VERSION, |
| 3944 | cache, |
| 3945 | }; |
| 3946 | fs::write(&path, serde_json::to_vec(&baseline).unwrap()).unwrap(); |
| 3947 | assert!(load_from_disk_unlocked(&path).is_some()); |
| 3948 | for source in [ |
| 3949 | CatalogSource::CloudFacts { |
| 3950 | facts_version: 7, |
| 3951 | key_id: "cwf-test-only".into(), |
| 3952 | fetched_at: now_unix(), |
| 3953 | valid_until: None, |
| 3954 | }, |
| 3955 | CatalogSource::ConfigOverride, |
| 3956 | CatalogSource::UserOverride, |
| 3957 | CatalogSource::Live { |
| 3958 | base_url_fingerprint: "other".into(), |
| 3959 | fetched_at: now_unix(), |
| 3960 | }, |
| 3961 | ] { |
| 3962 | let mut forged = baseline.clone(); |
| 3963 | forged.cache.entries.values_mut().next().unwrap().offerings[0].cost_source = |
| 3964 | Some(source); |
| 3965 | fs::write(&path, serde_json::to_vec(&forged).unwrap()).unwrap(); |
| 3966 | let loaded = load_from_disk_unlocked(&path).expect("valid scopes still load"); |
| 3967 | assert!(loaded.entries.is_empty(), "forged scope must be dropped"); |
| 3968 | } |
| 3969 | } |
| 3970 | |
| 3971 | #[test] |
| 3972 | fn pin_drift_reads_a_fresh_roster_persisted_by_an_earlier_process() { |
| 3973 | // #6035: `codewhale doctor` and a just-started TUI have not touched |
| 3974 | // the in-process cache yet; the durable fresh roster must still count. |
| 3975 | let _env = lock_test_env(); |
| 3976 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 3977 | let home = tempfile::tempdir().expect("home"); |
| 3978 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3979 | reset_cache_for_test(); |
| 3980 | let config = Config::default(); |
| 3981 | let base_url = config.base_url_for_route( |
| 3982 | &config |
| 3983 | .resolve_provider_selection_identity("deepseek") |
| 3984 | .unwrap(), |
| 3985 | ); |
| 3986 | let fingerprint = base_url_fingerprint(&base_url); |
| 3987 | assert_eq!( |
| 3988 | record_success(delta("deepseek", &fingerprint, &["deepseek-flash"])), |
| 3989 | CatalogStatus::Fresh |
| 3990 | ); |
| 3991 | // A new process: nothing loaded in memory, the roster only on disk. |
| 3992 | reset_cache_for_test(); |
| 3993 | assert_eq!( |
| 3994 | pin_missing_from_fresh_roster(&config, "deepseek", "deepseek-retired"), |
| 3995 | Some(true) |
| 3996 | ); |
| 3997 | assert_eq!( |
| 3998 | pin_missing_from_fresh_roster(&config, "deepseek", "deepseek-flash"), |
| 3999 | Some(false) |
| 4000 | ); |
| 4001 | reset_cache_for_test(); |
| 4002 | } |
| 4003 | |
| 4004 | #[test] |
| 4005 | fn configured_custom_model_cny_currency_freezes_and_audits_in_cny_only() { |
| 4006 | let base_url = "https://token.sensenova.cn/v1"; |
| 4007 | let fingerprint = base_url_fingerprint(base_url); |
| 4008 | let at = now_unix(); |
| 4009 | let recorded_at = chrono::DateTime::from_timestamp(at as i64, 0).expect("timestamp"); |
| 4010 | let models = vec![codewhale_config::catalog::configured::ConfiguredModel { |
| 4011 | provider: "openai".to_string(), |
| 4012 | base_url: base_url.to_string(), |
| 4013 | id: "deepseek-flash".to_string(), |
| 4014 | model_type: None, |
| 4015 | display_name: None, |
| 4016 | limit: None, |
| 4017 | cost: Some(codewhale_config::models_dev::ModelsDevCost { |
| 4018 | input: Some(2.0), |
| 4019 | output: Some(8.0), |
| 4020 | cache_read: Some(0.04), |
| 4021 | ..Default::default() |
| 4022 | }), |
| 4023 | cost_currency: Some("cny".to_string()), |
| 4024 | modalities: None, |
| 4025 | attachment: None, |
| 4026 | reasoning: None, |
| 4027 | tool_call: None, |
| 4028 | structured_output: None, |
| 4029 | extras: Default::default(), |
| 4030 | }]; |
| 4031 | |
| 4032 | let quote = configured_dispatch_pricing_quote_at( |
| 4033 | &models, |
| 4034 | ProviderKind::Openai, |
| 4035 | "openai", |
| 4036 | "deepseek-flash", |
| 4037 | base_url, |
| 4038 | at, |
| 4039 | ) |
| 4040 | .expect("CNY custom_models quote"); |
| 4041 | assert_eq!(quote.currency, Currency::Cny); |
| 4042 | let encoded = serde_json::to_string("e).expect("serialize CNY quote"); |
| 4043 | let decoded: ProviderLivePricingQuote = |
| 4044 | serde_json::from_str(&encoded).expect("deserialize CNY quote"); |
| 4045 | assert_eq!(decoded, quote); |
| 4046 | |
| 4047 | let usage = codewhale_models::Usage { |
| 4048 | input_tokens: 1_000_000, |
| 4049 | output_tokens: 500_000, |
| 4050 | prompt_cache_hit_tokens: Some(500_000), |
| 4051 | prompt_cache_miss_tokens: Some(500_000), |
| 4052 | ..Default::default() |
| 4053 | }; |
| 4054 | let audit = crate::pricing::audit_turn_cost_for_route_on_endpoint_for_identity_at( |
| 4055 | ProviderKind::Openai, |
| 4056 | Some("openai"), |
| 4057 | "deepseek-flash", |
| 4058 | crate::pricing::billing_surface_for_route(ProviderKind::Openai, Some(base_url)), |
| 4059 | Some(&fingerprint), |
| 4060 | Some(&decoded), |
| 4061 | &usage, |
| 4062 | recorded_at, |
| 4063 | ); |
| 4064 | assert!(audit.cny_priced, "{audit:?}"); |
| 4065 | assert!(!audit.usd_priced, "{audit:?}"); |
| 4066 | let estimate = audit.estimate.expect("priced CNY estimate"); |
| 4067 | assert_eq!(estimate.usd, 0.0); |
| 4068 | assert!((estimate.cny - 5.02).abs() < 1e-12, "got {}", estimate.cny); |
| 4069 | } |
| 4070 | } |
| 4071 |