| 1 | //! Configured provider/model lake facade (#3830, Wave 5b / #4188). |
| 2 | //! |
| 3 | //! Single seam over the Models.dev catalog layers and the configured-provider |
| 4 | //! predicate shared with `/provider`. Precedence is **provider-scoped live > |
| 5 | //! live Models.dev > bundled offline snapshot > legacy hardcoded fallback**. |
| 6 | //! Pickers, hotbar route slots, [`crate::model_inventory::ModelInventory`], |
| 7 | //! slash completions, and subagent validation should read model lists from here. |
| 8 | //! |
| 9 | //! [`codewhale_runtime::config::model_completion_names_for_provider`] is retained only as a |
| 10 | //! compatibility fallback for CodeWhale-only / local providers that Models.dev |
| 11 | //! does not represent (and for unbundled gateways until the live catalog covers |
| 12 | //! them). |
| 13 | |
| 14 | use std::borrow::Cow; |
| 15 | use std::collections::BTreeMap; |
| 16 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 17 | use std::sync::{Arc, RwLock}; |
| 18 | |
| 19 | use codewhale_config::catalog::{ |
| 20 | CatalogOffering, CatalogSnapshot, CatalogSource, CatalogStatus, base_url_fingerprint, |
| 21 | bundled_catalog_offerings, |
| 22 | }; |
| 23 | use codewhale_config::route::{ProviderModelOffering, RouteResolver, bundled_offerings}; |
| 24 | |
| 25 | use crate::codex_model_cache; |
| 26 | use crate::provider_readiness::provider_is_configured_for_active; |
| 27 | use codewhale_config::ProviderKind; |
| 28 | use codewhale_runtime::config::{ |
| 29 | Config, ProviderIdentity, model_completion_names_for_provider, opencode_go_model_id, |
| 30 | }; |
| 31 | |
| 32 | static BUNDLED_SNAPSHOT: std::sync::OnceLock<SharedSnapshot> = std::sync::OnceLock::new(); |
| 33 | |
| 34 | /// A catalog layer whose rows are reference-counted so the merged view can |
| 35 | /// share them instead of deep-cloning every offering. |
| 36 | /// |
| 37 | /// The Models.dev layer is several thousand rows. Holding the merge as owned |
| 38 | /// `CatalogOffering`s kept a second full copy of that layer (and of the |
| 39 | /// bundled layer) resident for the life of the process; sharing rows means |
| 40 | /// only the rows a merge actually changes (cutlines, signed-facts patches, |
| 41 | /// provider-roster completion) are materialized again. |
| 42 | #[derive(Debug, Default)] |
| 43 | struct SharedSnapshot { |
| 44 | offerings: Vec<Arc<CatalogOffering>>, |
| 45 | /// `catalog_partition_key(provider) -> rows`, built once with the |
| 46 | /// snapshot. |
| 47 | /// |
| 48 | /// Callers ask for one provider's rows per model row; scanning every |
| 49 | /// offering in the process for each ask computed a `trim().to_string()` |
| 50 | /// partition key per offering. |
| 51 | by_provider: BTreeMap<String, Vec<Arc<CatalogOffering>>>, |
| 52 | } |
| 53 | |
| 54 | impl SharedSnapshot { |
| 55 | fn from_owned(snapshot: CatalogSnapshot) -> Self { |
| 56 | Self::new(snapshot.offerings.into_iter().map(Arc::new).collect()) |
| 57 | } |
| 58 | |
| 59 | fn new(offerings: Vec<Arc<CatalogOffering>>) -> Self { |
| 60 | let mut by_provider: BTreeMap<String, Vec<Arc<CatalogOffering>>> = BTreeMap::new(); |
| 61 | for row in &offerings { |
| 62 | by_provider |
| 63 | .entry(catalog_partition_key(&row.provider)) |
| 64 | .or_default() |
| 65 | .push(Arc::clone(row)); |
| 66 | } |
| 67 | Self { |
| 68 | offerings, |
| 69 | by_provider, |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn offerings_for_provider(&self, provider: &str) -> Vec<&CatalogOffering> { |
| 74 | self.by_provider |
| 75 | .get(provider) |
| 76 | .map(|rows| rows.iter().map(Arc::as_ref).collect()) |
| 77 | .unwrap_or_default() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Source tag for live-catalog rows. Models.dev is a cross-provider catalog |
| 82 | /// that serves as the primary live layer; per-provider refreshes (e.g. |
| 83 | /// TelecomJS `/v1/models`) are a secondary layer that must coexist alongside |
| 84 | /// Models.dev rows without being wiped by a Models.dev refresh. |
| 85 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 86 | pub enum LiveSource { |
| 87 | /// The cross-provider Models.dev catalog refresh. |
| 88 | ModelsDev, |
| 89 | /// A per-provider `/v1/models` catalog refresh (e.g. TelecomJS TokenHub). |
| 90 | PerProvider, |
| 91 | } |
| 92 | |
| 93 | /// Optional live catalog snapshot(s), source-scoped (#4188 race fix). |
| 94 | /// |
| 95 | /// Models.dev and every provider fetch maintain distinct partitions of live |
| 96 | /// rows. A Models.dev refresh replaces only Models.dev-sourced rows; a |
| 97 | /// per-provider merge adds/replaces only that provider's rows. This prevents a |
| 98 | /// later Models.dev `set_live_snapshot` from erasing TelecomJS rows and keeps |
| 99 | /// independent provider refreshes from erasing each other. |
| 100 | static LIVE_SNAPSHOT: RwLock<LiveSnapshotPartitions> = RwLock::new(LiveSnapshotPartitions { |
| 101 | models_dev: None, |
| 102 | per_provider: BTreeMap::new(), |
| 103 | }); |
| 104 | |
| 105 | /// Internal partition map: one Models.dev snapshot plus one snapshot per |
| 106 | /// provider-specific live fetch. |
| 107 | #[derive(Default)] |
| 108 | struct LiveSnapshotPartitions { |
| 109 | models_dev: Option<SharedSnapshot>, |
| 110 | per_provider: BTreeMap<LivePartitionOwner, CatalogSnapshot>, |
| 111 | } |
| 112 | |
| 113 | /// Internal ownership key for one provider-owned live roster. |
| 114 | /// |
| 115 | /// Catalog rows intentionally keep their public provider string for receipts and |
| 116 | /// cache compatibility. The storage key carries the route kind separately so an |
| 117 | /// exact custom table named `openai` cannot overwrite, suppress, or borrow the |
| 118 | /// built-in OpenAI partition. |
| 119 | #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] |
| 120 | enum LivePartitionOwner { |
| 121 | BuiltIn(String), |
| 122 | Custom(String), |
| 123 | } |
| 124 | |
| 125 | impl LivePartitionOwner { |
| 126 | fn identity(&self) -> &str { |
| 127 | match self { |
| 128 | Self::BuiltIn(identity) | Self::Custom(identity) => identity, |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | fn live_partition_owner_for_route( |
| 134 | provider: ProviderKind, |
| 135 | provider_identity: Option<&str>, |
| 136 | ) -> LivePartitionOwner { |
| 137 | let identity = catalog_provider_id_for_identity(provider, provider_identity); |
| 138 | if provider == ProviderKind::Custom { |
| 139 | LivePartitionOwner::Custom(catalog_partition_key(identity.as_ref())) |
| 140 | } else { |
| 141 | LivePartitionOwner::BuiltIn(catalog_partition_key(identity.as_ref())) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn inferred_live_partition_owner(provider: &str) -> LivePartitionOwner { |
| 146 | let identity = catalog_partition_key(provider); |
| 147 | ProviderKind::parse(&identity).map_or_else( |
| 148 | || LivePartitionOwner::Custom(identity), |
| 149 | |provider| { |
| 150 | LivePartitionOwner::BuiltIn(catalog_partition_key(catalog_provider_id(provider))) |
| 151 | }, |
| 152 | ) |
| 153 | } |
| 154 | |
| 155 | fn offerings_by_provider( |
| 156 | offerings: Vec<CatalogOffering>, |
| 157 | ) -> BTreeMap<LivePartitionOwner, Vec<CatalogOffering>> { |
| 158 | let mut grouped = BTreeMap::new(); |
| 159 | for mut offering in offerings { |
| 160 | let owner = inferred_live_partition_owner(&offering.provider); |
| 161 | offering.provider = owner.identity().to_string(); |
| 162 | grouped.entry(owner).or_insert_with(Vec::new).push(offering); |
| 163 | } |
| 164 | grouped |
| 165 | } |
| 166 | |
| 167 | /// Generation stamp for the live snapshot. Bumped (under the `LIVE_SNAPSHOT` |
| 168 | /// write lock) by [`set_live_snapshot`], [`merge_live_offerings`], and |
| 169 | /// [`clear_live_snapshot`] so the memoized merged snapshot below can detect |
| 170 | /// staleness without re-merging. |
| 171 | static LIVE_GENERATION: AtomicU64 = AtomicU64::new(0); |
| 172 | |
| 173 | pub fn catalog_revision() -> (u64, u64) { |
| 174 | ( |
| 175 | LIVE_GENERATION.load(Ordering::SeqCst), |
| 176 | codewhale_config::cloud_facts::overlay::snapshot().generation, |
| 177 | ) |
| 178 | } |
| 179 | |
| 180 | type MergedCacheEntry = ((u64, u64), Arc<SharedSnapshot>); |
| 181 | |
| 182 | /// Memoized result of [`merged_snapshot`], tagged with the `LIVE_GENERATION` |
| 183 | /// it was computed from. Re-merging ~5,700 offerings per call made every |
| 184 | /// `/model` open pay a multi-second, UI-thread-blocking cost; the merge result |
| 185 | /// only changes when the live snapshot changes, so cache it. |
| 186 | static MERGED_CACHE: RwLock<Option<MergedCacheEntry>> = RwLock::new(None); |
| 187 | |
| 188 | /// Generation/freshness-scoped route resolvers for provider-owned catalogs. |
| 189 | /// Picker calls read the merged snapshot directly; execution projects that |
| 190 | /// snapshot into the immutable `RouteResolver` seam and must not rebuild a |
| 191 | /// 600+ row OpenRouter catalog for every route candidate. |
| 192 | static RUNTIME_RESOLVER_CACHE: RwLock<BTreeMap<String, RuntimeResolverCacheEntry>> = |
| 193 | RwLock::new(BTreeMap::new()); |
| 194 | /// Most distinct endpoints the resolver cache holds at once. Entries from an |
| 195 | /// older catalog generation can never hit again and are dropped on insert; |
| 196 | /// this caps the endpoints of the current generation. |
| 197 | const MAX_RUNTIME_RESOLVER_CACHE_ENTRIES: usize = 64; |
| 198 | |
| 199 | #[derive(Clone)] |
| 200 | struct RuntimeResolverCacheEntry { |
| 201 | generation: u64, |
| 202 | cloud_generation: u64, |
| 203 | status_is_fresh: bool, |
| 204 | go_requires_live_proof: bool, |
| 205 | go_binding: Option<String>, |
| 206 | endpoint_catalog_authoritative: bool, |
| 207 | resolver: RouteResolver, |
| 208 | } |
| 209 | |
| 210 | #[derive(Clone)] |
| 211 | pub struct RuntimeCatalogResolver { |
| 212 | pub resolver: RouteResolver, |
| 213 | pub endpoint_catalog_authoritative: bool, |
| 214 | } |
| 215 | |
| 216 | fn bundled_snapshot() -> &'static SharedSnapshot { |
| 217 | BUNDLED_SNAPSHOT.get_or_init(|| { |
| 218 | SharedSnapshot::from_owned(CatalogSnapshot { |
| 219 | offerings: bundled_catalog_offerings(), |
| 220 | }) |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | /// Remove catalog rows that cannot use the selected provider's wire protocol. |
| 225 | /// |
| 226 | /// OpenCode Go publishes one `/models` roster for both Chat Completions and |
| 227 | /// Anthropic Messages and Responses. Keep saved and live Go rows on the same |
| 228 | /// documented protocol roster, correcting stale endpoint metadata. |
| 229 | fn apply_provider_model_cutlines(mut snapshot: CatalogSnapshot) -> CatalogSnapshot { |
| 230 | let mut is_opencode_go = provider_parse_memo(); |
| 231 | snapshot.offerings = snapshot |
| 232 | .offerings |
| 233 | .into_iter() |
| 234 | .filter_map(|mut offering| { |
| 235 | if is_opencode_go(&offering.provider) { |
| 236 | canonicalize_opencode_go_row(&mut offering)?; |
| 237 | } |
| 238 | Some(offering) |
| 239 | }) |
| 240 | .collect(); |
| 241 | snapshot |
| 242 | } |
| 243 | |
| 244 | /// [`apply_provider_model_cutlines`] over shared rows: only the rows the |
| 245 | /// cutline rewrites are copied; every other row stays shared with its layer. |
| 246 | fn apply_provider_model_cutlines_shared(rows: Vec<Arc<CatalogOffering>>) -> SharedSnapshot { |
| 247 | let mut is_opencode_go = provider_parse_memo(); |
| 248 | let offerings = rows |
| 249 | .into_iter() |
| 250 | .filter_map(|mut offering| { |
| 251 | if is_opencode_go(&offering.provider) { |
| 252 | canonicalize_opencode_go_row(Arc::make_mut(&mut offering))?; |
| 253 | } |
| 254 | Some(offering) |
| 255 | }) |
| 256 | .collect(); |
| 257 | SharedSnapshot::new(offerings) |
| 258 | } |
| 259 | |
| 260 | /// `ProviderKind::parse` scans every provider and alias list per call; the |
| 261 | /// distinct provider strings in a catalog are few, so resolve each distinct |
| 262 | /// string once instead of once per offering (boot-path profiles showed this |
| 263 | /// loop as the largest post-parse compute block). |
| 264 | fn provider_parse_memo() -> impl FnMut(&str) -> bool { |
| 265 | let mut resolved: std::collections::HashMap<String, bool> = std::collections::HashMap::new(); |
| 266 | move |provider: &str| { |
| 267 | if let Some(hit) = resolved.get(provider) { |
| 268 | return *hit; |
| 269 | } |
| 270 | let hit = ProviderKind::parse(provider) == Some(ProviderKind::OpencodeGo); |
| 271 | resolved.insert(provider.to_string(), hit); |
| 272 | hit |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Canonicalize one OpenCode Go row onto its documented protocol roster. |
| 277 | /// `None` means the row is not on that roster and must be dropped. |
| 278 | fn canonicalize_opencode_go_row(offering: &mut CatalogOffering) -> Option<()> { |
| 279 | if matches!( |
| 280 | offering.source, |
| 281 | codewhale_config::catalog::CatalogSource::Live { .. } |
| 282 | ) && offering.model_type.is_some() |
| 283 | { |
| 284 | return Some(()); |
| 285 | } |
| 286 | let canonical = opencode_go_model_id(&offering.wire_model_id)?; |
| 287 | let endpoint_key = codewhale_config::opencode_go_endpoint_key(canonical)?; |
| 288 | offering.provider = ProviderKind::OpencodeGo.as_str().to_string(); |
| 289 | offering.wire_model_id = canonical.to_string(); |
| 290 | offering.endpoint_key = endpoint_key.to_string(); |
| 291 | Some(()) |
| 292 | } |
| 293 | |
| 294 | /// Set the live-catalog snapshot for a given source (#4188 race fix). |
| 295 | /// |
| 296 | /// Source-scoped: a Models.dev refresh replaces only Models.dev-sourced rows; |
| 297 | /// a per-provider refresh replaces only the layers for providers represented |
| 298 | /// in that snapshot. Other providers and sources are preserved. This |
| 299 | /// eliminates the race where a Models.dev `set_live_snapshot` would erase |
| 300 | /// TelecomJS rows merged earlier. |
| 301 | pub fn set_live_snapshot(snapshot: CatalogSnapshot, source: LiveSource) { |
| 302 | if let Ok(mut guard) = LIVE_SNAPSHOT.write() { |
| 303 | let snapshot = apply_provider_model_cutlines(snapshot); |
| 304 | let changed = match source { |
| 305 | LiveSource::ModelsDev => { |
| 306 | guard.models_dev = Some(SharedSnapshot::from_owned(snapshot)); |
| 307 | true |
| 308 | } |
| 309 | LiveSource::PerProvider => { |
| 310 | let grouped = offerings_by_provider(snapshot.offerings); |
| 311 | let changed = !grouped.is_empty(); |
| 312 | for (provider, offerings) in grouped { |
| 313 | guard |
| 314 | .per_provider |
| 315 | .insert(provider, CatalogSnapshot { offerings }); |
| 316 | } |
| 317 | changed |
| 318 | } |
| 319 | }; |
| 320 | // Invalidate the memoized merged snapshot while still holding the |
| 321 | // write lock so no reader can cache the old merge against the new |
| 322 | // generation. |
| 323 | if changed { |
| 324 | LIVE_GENERATION.fetch_add(1, Ordering::SeqCst); |
| 325 | } |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /// Replace one exact provider-owned live partition, including with no rows. |
| 330 | /// |
| 331 | /// The generic [`set_live_snapshot`] derives partitions from rows, so an empty |
| 332 | /// snapshot cannot say which previous partition should disappear. Endpoint- |
| 333 | /// scoped persistent caches need that distinction: switching Baseten to a new |
| 334 | /// base URL with no matching cache must remove the old URL's Baseten rows |
| 335 | /// immediately instead of presenting them as if they belonged to the new host. |
| 336 | #[cfg(any(test, feature = "test-support"))] |
| 337 | pub fn replace_provider_live_snapshot(provider: &str, snapshot: CatalogSnapshot) { |
| 338 | let provider = provider.trim(); |
| 339 | if provider.is_empty() { |
| 340 | return; |
| 341 | } |
| 342 | let owner = inferred_live_partition_owner(provider); |
| 343 | replace_provider_live_snapshot_for_owner(owner, snapshot); |
| 344 | } |
| 345 | |
| 346 | /// Replace one provider-owned partition with an explicit route-kind boundary. |
| 347 | /// |
| 348 | /// Callers that know the concrete route must use this form. The legacy |
| 349 | /// string-only wrapper above remains for built-in publishers and older generic |
| 350 | /// tests, where a built-in-looking string necessarily denotes the built-in. |
| 351 | pub fn replace_provider_live_snapshot_for_identity( |
| 352 | provider: ProviderKind, |
| 353 | provider_identity: &str, |
| 354 | snapshot: CatalogSnapshot, |
| 355 | ) { |
| 356 | let owner = live_partition_owner_for_route(provider, Some(provider_identity)); |
| 357 | if owner.identity().is_empty() { |
| 358 | return; |
| 359 | } |
| 360 | replace_provider_live_snapshot_for_owner(owner, snapshot); |
| 361 | } |
| 362 | |
| 363 | fn replace_provider_live_snapshot_for_owner(owner: LivePartitionOwner, snapshot: CatalogSnapshot) { |
| 364 | let provider_key = owner.identity().to_string(); |
| 365 | let mut snapshot = if matches!(&owner, LivePartitionOwner::Custom(_)) { |
| 366 | snapshot |
| 367 | } else { |
| 368 | apply_provider_model_cutlines(snapshot) |
| 369 | }; |
| 370 | snapshot.offerings.retain_mut(|row| { |
| 371 | if catalog_partition_key(&row.provider) != provider_key { |
| 372 | return false; |
| 373 | } |
| 374 | row.provider.clone_from(&provider_key); |
| 375 | true |
| 376 | }); |
| 377 | |
| 378 | if let Ok(mut guard) = LIVE_SNAPSHOT.write() { |
| 379 | let previous = guard.per_provider.remove(&owner); |
| 380 | let next = (!snapshot.offerings.is_empty()).then_some(snapshot); |
| 381 | if let Some(next) = next.clone() { |
| 382 | guard.per_provider.insert(owner, next); |
| 383 | } |
| 384 | if previous != next { |
| 385 | LIVE_GENERATION.fetch_add(1, Ordering::SeqCst); |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | /// Clear all live snapshots (both Models.dev and per-provider partitions). |
| 391 | /// Used by tests and shutdown paths that need a full reset. |
| 392 | pub fn clear_live_snapshot() { |
| 393 | if let Ok(mut guard) = LIVE_SNAPSHOT.write() { |
| 394 | guard.models_dev = None; |
| 395 | guard.per_provider.clear(); |
| 396 | LIVE_GENERATION.fetch_add(1, Ordering::SeqCst); |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /// Merge additional live offerings into provider-scoped live partitions (#4188). |
| 401 | /// |
| 402 | /// Unlike [`set_live_snapshot`] for `LiveSource::PerProvider` (which replaces |
| 403 | /// each represented provider's partition), this merges new rows by |
| 404 | /// `(provider, wire_model_id)` identity within that provider's partition, |
| 405 | /// preserving every other provider and the Models.dev partition. Production |
| 406 | /// rosters publish through `provider_catalog_live` (the guided-setup key probe |
| 407 | /// included), so this remains a fixture seam for lake tests. |
| 408 | #[cfg(any(test, feature = "test-support"))] |
| 409 | pub fn merge_live_offerings(new_offerings: Vec<CatalogOffering>) { |
| 410 | if new_offerings.is_empty() { |
| 411 | return; |
| 412 | } |
| 413 | if let Ok(mut guard) = LIVE_SNAPSHOT.write() { |
| 414 | for (provider, new_rows) in offerings_by_provider(new_offerings) { |
| 415 | let existing = guard.per_provider.remove(&provider).unwrap_or_default(); |
| 416 | let mut merged: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new(); |
| 417 | for row in existing.offerings { |
| 418 | merged.insert((row.provider.clone(), row.wire_model_id.clone()), row); |
| 419 | } |
| 420 | for row in new_rows { |
| 421 | merged.insert((row.provider.clone(), row.wire_model_id.clone()), row); |
| 422 | } |
| 423 | guard.per_provider.insert( |
| 424 | provider, |
| 425 | CatalogSnapshot { |
| 426 | offerings: merged.into_values().collect(), |
| 427 | }, |
| 428 | ); |
| 429 | } |
| 430 | LIVE_GENERATION.fetch_add(1, Ordering::SeqCst); |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | /// Which live partition currently holds `(provider, wire_model_id)`, if any. |
| 435 | /// |
| 436 | /// Per-provider `/models` rows win on collision, matching merge precedence. |
| 437 | /// Pricing uses this so a Models.dev capabilities overlay is never treated as |
| 438 | /// a rate source (#5241). |
| 439 | #[must_use] |
| 440 | pub fn live_catalog_origin(provider: ProviderKind, wire_model_id: &str) -> Option<LiveSource> { |
| 441 | let catalog_id = catalog_provider_id(provider); |
| 442 | let owner = LivePartitionOwner::BuiltIn(catalog_partition_key(catalog_id)); |
| 443 | let needle = wire_model_id.trim(); |
| 444 | if needle.is_empty() { |
| 445 | return None; |
| 446 | } |
| 447 | let Ok(guard) = LIVE_SNAPSHOT.read() else { |
| 448 | return None; |
| 449 | }; |
| 450 | // Wire ids are opaque and case-sensitive: an exact row in either |
| 451 | // partition decides before a case-folded one does. |
| 452 | for exact in [true, false] { |
| 453 | let matches = |row: &CatalogOffering| { |
| 454 | row.provider.eq_ignore_ascii_case(catalog_id) |
| 455 | && if exact { |
| 456 | row.wire_model_id == needle |
| 457 | } else { |
| 458 | row.wire_model_id.eq_ignore_ascii_case(needle) |
| 459 | } |
| 460 | }; |
| 461 | if guard |
| 462 | .per_provider |
| 463 | .get(&owner) |
| 464 | .is_some_and(|snap| snap.offerings.iter().any(matches)) |
| 465 | { |
| 466 | return Some(LiveSource::PerProvider); |
| 467 | } |
| 468 | if guard |
| 469 | .models_dev |
| 470 | .as_ref() |
| 471 | .is_some_and(|snap| snap.offerings.iter().any(|row| matches(row))) |
| 472 | { |
| 473 | return Some(LiveSource::ModelsDev); |
| 474 | } |
| 475 | } |
| 476 | None |
| 477 | } |
| 478 | |
| 479 | /// The row whose wire id is exactly `needle`, else the one wire id equal to |
| 480 | /// it ignoring ASCII case. Wire ids are opaque and case-sensitive, so the |
| 481 | /// fallback only forgives a case slip when it cannot choose between two |
| 482 | /// distinct ids; otherwise it answers nothing rather than another model's |
| 483 | /// metadata. |
| 484 | fn find_wire_model<'a>( |
| 485 | rows: impl IntoIterator<Item = &'a CatalogOffering>, |
| 486 | needle: &str, |
| 487 | ) -> Option<&'a CatalogOffering> { |
| 488 | let mut folded: Option<&'a CatalogOffering> = None; |
| 489 | let mut ambiguous = false; |
| 490 | for row in rows { |
| 491 | if row.wire_model_id == needle { |
| 492 | return Some(row); |
| 493 | } |
| 494 | if row.wire_model_id.eq_ignore_ascii_case(needle) { |
| 495 | match folded { |
| 496 | None => folded = Some(row), |
| 497 | Some(first) if first.wire_model_id != row.wire_model_id => ambiguous = true, |
| 498 | Some(_) => {} |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | folded.filter(|_| !ambiguous) |
| 503 | } |
| 504 | |
| 505 | /// Serialize tests that mutate the process-wide live snapshot. |
| 506 | /// |
| 507 | /// Lock ordering: this takes the test env barrier FIRST (skipped when the |
| 508 | /// calling thread already sealed the environment). Under `#[cfg(any(test, feature = "test-support"))]` every |
| 509 | /// `codewhale_env_var` read blocks on that barrier, so a thread holding the |
| 510 | /// live-snapshot mutex while it waits for the barrier deadlocks against a |
| 511 | /// thread holding the barrier while it waits for this mutex — and libtest has |
| 512 | /// no per-test timeout, so one inverted pair hangs the whole test binary. |
| 513 | /// Acquiring the barrier here, before the mutex, makes that inversion |
| 514 | /// impossible for every caller at once. |
| 515 | #[cfg(any(test, feature = "test-support"))] |
| 516 | pub struct LiveSnapshotLock { |
| 517 | _live: std::sync::MutexGuard<'static, ()>, |
| 518 | _env: Option<crate::test_support::TestEnvLock>, |
| 519 | } |
| 520 | |
| 521 | #[cfg(any(test, feature = "test-support"))] |
| 522 | pub fn lock_live_snapshot() -> LiveSnapshotLock { |
| 523 | let env = if crate::test_support::current_thread_holds_test_env_lock() { |
| 524 | None |
| 525 | } else { |
| 526 | Some(crate::test_support::lock_test_env()) |
| 527 | }; |
| 528 | static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new(); |
| 529 | let live = LOCK |
| 530 | .get_or_init(|| std::sync::Mutex::new(())) |
| 531 | .lock() |
| 532 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 533 | LiveSnapshotLock { |
| 534 | _live: live, |
| 535 | _env: env, |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | /// The merged catalog snapshot: Models.dev rows override bundled rows on |
| 540 | /// `(provider, wire_model_id)` identity (#4188). A provider-owned live |
| 541 | /// partition is authoritative for that provider's complete roster, so it |
| 542 | /// suppresses both bundled and Models.dev rows for the provider rather than |
| 543 | /// merely overlaying matching ids. This is what lets a successful |
| 544 | /// `/v1/models` refresh remove models retired upstream. Failed refreshes retain |
| 545 | /// the last successful provider partition; clearing a partition restores the |
| 546 | /// offline/cross-provider fallbacks. The one row a provider partition does not |
| 547 | /// suppress is a signed row the payload explicitly attests is unlisted — see |
| 548 | /// the `retain` in [`compute_merged_snapshot`]. Roster rows are completed, not |
| 549 | /// replaced, where the roster itself stated nothing. |
| 550 | /// |
| 551 | /// Memoized: the merge is recomputed only after a live-layer mutation bumps |
| 552 | /// `LIVE_GENERATION`; every other call returns the cached `Arc` (the picker |
| 553 | /// calls this per row, so it must be cheap). |
| 554 | fn merged_snapshot() -> Arc<SharedSnapshot> { |
| 555 | let generation = catalog_revision(); |
| 556 | if let Ok(guard) = MERGED_CACHE.read() |
| 557 | && let Some((cached_generation, cached)) = guard.as_ref() |
| 558 | && *cached_generation == generation |
| 559 | { |
| 560 | return Arc::clone(cached); |
| 561 | } |
| 562 | let merged = Arc::new(compute_merged_snapshot()); |
| 563 | if let Ok(mut guard) = MERGED_CACHE.write() { |
| 564 | // `generation` was sampled before the live snapshot was read, so a |
| 565 | // concurrent set/clear leaves this entry stale-tagged and the next |
| 566 | // reader recomputes; the merge itself is always internally consistent. |
| 567 | *guard = Some((generation, Arc::clone(&merged))); |
| 568 | } |
| 569 | merged |
| 570 | } |
| 571 | |
| 572 | /// Uncached merge (see [`merged_snapshot`] for the caching seam). |
| 573 | fn compute_merged_snapshot() -> SharedSnapshot { |
| 574 | let cloud = codewhale_config::cloud_facts::overlay::snapshot(); |
| 575 | let Ok(live) = LIVE_SNAPSHOT.read() else { |
| 576 | return apply_provider_model_cutlines_shared(bundled_snapshot().offerings.clone()); |
| 577 | }; |
| 578 | if live.models_dev.is_none() && live.per_provider.is_empty() && cloud.facts.is_none() { |
| 579 | return apply_provider_model_cutlines_shared(bundled_snapshot().offerings.clone()); |
| 580 | } |
| 581 | |
| 582 | let authoritative_providers: std::collections::BTreeSet<&str> = live |
| 583 | .per_provider |
| 584 | .keys() |
| 585 | .filter_map(|owner| match owner { |
| 586 | LivePartitionOwner::BuiltIn(identity) => Some(identity.as_str()), |
| 587 | LivePartitionOwner::Custom(_) => None, |
| 588 | }) |
| 589 | .collect(); |
| 590 | let is_authoritative = |provider: &str| { |
| 591 | let key = catalog_partition_key(provider); |
| 592 | authoritative_providers.contains(key.as_str()) |
| 593 | }; |
| 594 | let mut merged: BTreeMap<(String, String), Arc<CatalogOffering>> = BTreeMap::new(); |
| 595 | for row in &bundled_snapshot().offerings { |
| 596 | merged.insert( |
| 597 | (row.provider.clone(), row.wire_model_id.clone()), |
| 598 | Arc::clone(row), |
| 599 | ); |
| 600 | } |
| 601 | if let Some(models_dev) = &live.models_dev { |
| 602 | for row in &models_dev.offerings { |
| 603 | merged.insert( |
| 604 | (row.provider.clone(), row.wire_model_id.clone()), |
| 605 | Arc::clone(row), |
| 606 | ); |
| 607 | } |
| 608 | } |
| 609 | if let Some(facts) = &cloud.facts { |
| 610 | // The patcher only reads, writes, or removes the keys a signed fact |
| 611 | // names, so materialize just those rows as owned values and share the |
| 612 | // rest untouched. |
| 613 | let mut patched: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new(); |
| 614 | for fact in &facts.models { |
| 615 | let key = (fact.provider.clone(), fact.id.clone()); |
| 616 | if let Some(row) = merged.remove(&key) { |
| 617 | patched.insert(key, Arc::unwrap_or_clone(row)); |
| 618 | } |
| 619 | } |
| 620 | codewhale_config::cloud_facts::catalog_patch::apply_model_patches( |
| 621 | &mut patched, |
| 622 | facts, |
| 623 | cloud.fetched_at.unwrap_or(0), |
| 624 | ); |
| 625 | merged.extend(patched.into_iter().map(|(key, row)| (key, Arc::new(row)))); |
| 626 | } |
| 627 | let lower_rows = merged.clone(); |
| 628 | merged.retain(|(provider, model), row| { |
| 629 | !is_authoritative(provider) |
| 630 | || (matches!(row.source, CatalogSource::CloudFacts { .. }) |
| 631 | && cloud.facts.as_ref().is_some_and(|facts| { |
| 632 | codewhale_config::cloud_facts::catalog_patch::is_unlisted_attested( |
| 633 | facts, provider, model, |
| 634 | ) |
| 635 | })) |
| 636 | }); |
| 637 | for (owner, provider_snapshot) in |
| 638 | live.per_provider |
| 639 | .iter() |
| 640 | .filter_map(|(owner, snapshot)| match owner { |
| 641 | LivePartitionOwner::BuiltIn(_) => Some((owner, snapshot)), |
| 642 | LivePartitionOwner::Custom(identity) if ProviderKind::parse(identity).is_none() => { |
| 643 | Some((owner, snapshot)) |
| 644 | } |
| 645 | LivePartitionOwner::Custom(_) => None, |
| 646 | }) |
| 647 | { |
| 648 | for row in &provider_snapshot.offerings { |
| 649 | let mut row = row.clone(); |
| 650 | if matches!(owner, LivePartitionOwner::BuiltIn(_)) |
| 651 | && let Some(lower) = |
| 652 | lower_rows.get(&(row.provider.clone(), row.wire_model_id.clone())) |
| 653 | { |
| 654 | row.complete_from(lower, None); |
| 655 | } |
| 656 | merged.insert( |
| 657 | (row.provider.clone(), row.wire_model_id.clone()), |
| 658 | Arc::new(row), |
| 659 | ); |
| 660 | } |
| 661 | } |
| 662 | apply_provider_model_cutlines_shared(merged.into_values().collect()) |
| 663 | } |
| 664 | |
| 665 | fn apply_cloud_facts_for_provider( |
| 666 | rows: &mut BTreeMap<(String, String), CatalogOffering>, |
| 667 | provider: &str, |
| 668 | cloud: &codewhale_config::cloud_facts::overlay::OverlaySnapshot, |
| 669 | ) { |
| 670 | if let Some(facts) = &cloud.facts { |
| 671 | let mut scoped = (**facts).clone(); |
| 672 | scoped.models.retain(|model| model.provider == provider); |
| 673 | codewhale_config::cloud_facts::catalog_patch::apply_model_patches( |
| 674 | rows, |
| 675 | &scoped, |
| 676 | cloud.fetched_at.unwrap_or(0), |
| 677 | ); |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | static SOURCE_ROWS_CACHE: RwLock<BTreeMap<String, SourceRowsCacheEntry>> = |
| 682 | RwLock::new(BTreeMap::new()); |
| 683 | |
| 684 | /// Most provider partitions [`SOURCE_ROWS_CACHE`] holds. A partition is one |
| 685 | /// provider's bundled + Models.dev rows, so this bounds resident memory to a |
| 686 | /// few providers at a time without tracking recency. |
| 687 | const MAX_SOURCE_ROWS_CACHE_ENTRIES: usize = 32; |
| 688 | |
| 689 | type SourceRowsCacheEntry = ( |
| 690 | (u64, u64, bool), |
| 691 | Arc<BTreeMap<(String, String), CatalogOffering>>, |
| 692 | ); |
| 693 | |
| 694 | /// One provider's bundled + Models.dev rows, memoized per live generation. |
| 695 | /// |
| 696 | /// `live_generation` must be sampled **before** the caller reads |
| 697 | /// `LIVE_SNAPSHOT`: tagging a snapshot read with a newer generation would let a |
| 698 | /// concurrent refresh leave stale rows cached under the current generation. |
| 699 | fn source_rows_for_provider( |
| 700 | provider: &str, |
| 701 | live_generation: u64, |
| 702 | models_dev: Option<&SharedSnapshot>, |
| 703 | cloud: Option<&codewhale_config::cloud_facts::overlay::OverlaySnapshot>, |
| 704 | ) -> Arc<BTreeMap<(String, String), CatalogOffering>> { |
| 705 | let generation = ( |
| 706 | live_generation, |
| 707 | cloud.map_or(u64::MAX, |cloud| cloud.generation), |
| 708 | models_dev.is_some(), |
| 709 | ); |
| 710 | if let Ok(cache) = SOURCE_ROWS_CACHE.read() |
| 711 | && let Some((cached_generation, cached)) = cache.get(provider) |
| 712 | && *cached_generation == generation |
| 713 | { |
| 714 | return Arc::clone(cached); |
| 715 | } |
| 716 | let rows = Arc::new(build_source_rows_for_provider(provider, models_dev, cloud)); |
| 717 | if let Ok(mut cache) = SOURCE_ROWS_CACHE.write() { |
| 718 | cache.retain(|_, (cached_generation, _)| *cached_generation == generation); |
| 719 | if cache.len() >= MAX_SOURCE_ROWS_CACHE_ENTRIES && !cache.contains_key(provider) { |
| 720 | cache.pop_first(); |
| 721 | } |
| 722 | cache.insert(provider.to_string(), (generation, Arc::clone(&rows))); |
| 723 | } |
| 724 | rows |
| 725 | } |
| 726 | |
| 727 | fn build_source_rows_for_provider( |
| 728 | provider: &str, |
| 729 | models_dev: Option<&SharedSnapshot>, |
| 730 | cloud: Option<&codewhale_config::cloud_facts::overlay::OverlaySnapshot>, |
| 731 | ) -> BTreeMap<(String, String), CatalogOffering> { |
| 732 | let mut rows: BTreeMap<_, _> = bundled_snapshot() |
| 733 | .offerings_for_provider(provider) |
| 734 | .into_iter() |
| 735 | .cloned() |
| 736 | .map(|row| ((row.provider.clone(), row.wire_model_id.clone()), row)) |
| 737 | .collect(); |
| 738 | if let Some(models_dev) = models_dev { |
| 739 | for row in models_dev.offerings_for_provider(provider) { |
| 740 | rows.insert( |
| 741 | (row.provider.clone(), row.wire_model_id.clone()), |
| 742 | row.clone(), |
| 743 | ); |
| 744 | } |
| 745 | } |
| 746 | if let Some(cloud) = cloud { |
| 747 | apply_cloud_facts_for_provider(&mut rows, provider, cloud); |
| 748 | } |
| 749 | rows |
| 750 | } |
| 751 | |
| 752 | /// Does the signed cloud layer describe this exact route? |
| 753 | /// |
| 754 | /// Every condition is load-bearing: |
| 755 | /// - the captured route identity is canonical; `deepseek-cn` remains a |
| 756 | /// separate identity even though its transport shares the DeepSeek kind; |
| 757 | /// - the identity the signer names is this route's own. Catalog rows collapse |
| 758 | /// regional and dual-wire aliases onto a vendor primary |
| 759 | /// ([`catalog_provider_id`]), so SiliconFlow China and DeepSeek's |
| 760 | /// Anthropic-wire route read the `siliconflow` / `deepseek` partitions — a |
| 761 | /// fact signed for the primary is not a fact about those other endpoints and |
| 762 | /// only an exact identity match may consume it. This is the same exact- |
| 763 | /// identity keying `cloud_default_model_for_route` already uses for defaults; |
| 764 | /// - the base URL is on that provider's official HTTPS contract, so a custom, |
| 765 | /// proxied or redirected endpoint never inherits signed facts. |
| 766 | /// |
| 767 | /// `cloud_facts::scope` stays the single authority for which providers and |
| 768 | /// hosts are in scope at all (it is what excludes custom/local routes and the |
| 769 | /// Codex account roster); this must not grow a second copy of that table. |
| 770 | pub fn cloud_facts_apply_to_route(provider: ProviderKind, identity: &str, base_url: &str) -> bool { |
| 771 | identity == provider.as_str() |
| 772 | && provider.as_str() == catalog_provider_id(provider) |
| 773 | && codewhale_config::cloud_facts::scope::base_url_allowed(provider.as_str(), base_url) |
| 774 | } |
| 775 | |
| 776 | /// Signed rows for `provider` on this endpoint that the payload explicitly |
| 777 | /// attests exist despite the provider roster omitting them. |
| 778 | /// |
| 779 | /// A provider `/v1/models` roster is authoritative for every id it lists **and |
| 780 | /// for its own omissions**: this client keeps no history of past rosters, so it |
| 781 | /// cannot tell a never-listed preview from a model the provider retired, and it |
| 782 | /// does not guess. The single exception is an explicit signed `allow_unlisted` |
| 783 | /// assertion, which the signer must renew as it expires (`not_after` is |
| 784 | /// mandatory for one). Everything else the payload says about this provider is |
| 785 | /// still a patch on rows that exist — never a reason to add one back. |
| 786 | /// |
| 787 | /// The assertion carries exactly that: existence of that exact id. It is |
| 788 | /// filtered here by the same route gate as every other signed fact, so it |
| 789 | /// cannot reach a custom, proxied, regional or dual-wire endpoint, and it does |
| 790 | /// not touch account entitlement (an OAuth/account roster provider is outside |
| 791 | /// the signed scope entirely). |
| 792 | fn cloud_unlisted_offerings_for_route( |
| 793 | provider: ProviderKind, |
| 794 | identity: &str, |
| 795 | base_url: &str, |
| 796 | ) -> BTreeMap<(String, String), CatalogOffering> { |
| 797 | let mut rows = BTreeMap::new(); |
| 798 | if !cloud_facts_apply_to_route(provider, identity, base_url) { |
| 799 | return rows; |
| 800 | } |
| 801 | let cloud = codewhale_config::cloud_facts::overlay::snapshot(); |
| 802 | let Some(facts) = cloud.facts.as_ref() else { |
| 803 | return rows; |
| 804 | }; |
| 805 | let catalog_id = catalog_provider_id(provider); |
| 806 | apply_cloud_facts_for_provider(&mut rows, catalog_id, &cloud); |
| 807 | rows.retain(|(row_provider, row_id), _| { |
| 808 | codewhale_config::cloud_facts::catalog_patch::is_unlisted_attested( |
| 809 | facts, |
| 810 | row_provider, |
| 811 | row_id, |
| 812 | ) |
| 813 | }); |
| 814 | rows |
| 815 | } |
| 816 | |
| 817 | /// Maps an [`ProviderKind`] to its bundled-catalog provider id. |
| 818 | fn catalog_provider_id(provider: ProviderKind) -> &'static str { |
| 819 | match provider { |
| 820 | ProviderKind::DeepseekAnthropic => "deepseek", |
| 821 | ProviderKind::SiliconflowCN => "siliconflow", |
| 822 | _ => provider.as_str(), |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | /// Exact partition key for one provider-owned catalog. |
| 827 | /// |
| 828 | /// Publishers of built-in catalogs already emit their canonical provider id. |
| 829 | /// Custom table identities are ownership boundaries and therefore remain |
| 830 | /// case-sensitive even when their spelling resembles a built-in provider or a |
| 831 | /// reviewed setup-template alias: `[providers.openai]` may intentionally shadow |
| 832 | /// the built-in, and `CustomA` / `customa` may be different hosts. |
| 833 | pub fn catalog_partition_key(provider: &str) -> String { |
| 834 | provider.trim().to_string() |
| 835 | } |
| 836 | |
| 837 | /// Resolve the catalog partition for a concrete route. |
| 838 | /// |
| 839 | /// `ProviderKind::Custom` is only the wire family. Named compatible providers |
| 840 | /// such as Baseten own independent catalogs and must keep their exact config |
| 841 | /// identity instead of collapsing into a shared `custom` bucket. |
| 842 | fn catalog_provider_id_for_identity<'a>( |
| 843 | provider: ProviderKind, |
| 844 | provider_identity: Option<&'a str>, |
| 845 | ) -> Cow<'a, str> { |
| 846 | if provider == ProviderKind::Custom |
| 847 | && let Some(identity) = provider_identity.map(str::trim).filter(|id| !id.is_empty()) |
| 848 | { |
| 849 | return Cow::Owned(catalog_partition_key(identity)); |
| 850 | } |
| 851 | Cow::Borrowed(catalog_provider_id(provider)) |
| 852 | } |
| 853 | |
| 854 | fn offering_key(offering: &ProviderModelOffering) -> (String, String) { |
| 855 | ( |
| 856 | offering.provider.as_str().trim().to_ascii_lowercase(), |
| 857 | offering.wire_model_id.as_str().to_string(), |
| 858 | ) |
| 859 | } |
| 860 | |
| 861 | fn offering_with_absent_facts_filled( |
| 862 | mut offering: ProviderModelOffering, |
| 863 | lower: &ProviderModelOffering, |
| 864 | ) -> ProviderModelOffering { |
| 865 | if offering.canonical_model.is_none() { |
| 866 | offering.canonical_model.clone_from(&lower.canonical_model); |
| 867 | } |
| 868 | if offering.limits.context_tokens.is_none() { |
| 869 | offering.limits.context_tokens = lower.limits.context_tokens; |
| 870 | } |
| 871 | if offering.limits.input_tokens.is_none() { |
| 872 | offering.limits.input_tokens = lower.limits.input_tokens; |
| 873 | } |
| 874 | if offering.limits.output_tokens.is_none() { |
| 875 | offering.limits.output_tokens = lower.limits.output_tokens; |
| 876 | } |
| 877 | for (target, source) in [ |
| 878 | ( |
| 879 | &mut offering.capabilities.attachments, |
| 880 | lower.capabilities.attachments, |
| 881 | ), |
| 882 | ( |
| 883 | &mut offering.capabilities.image_input, |
| 884 | lower.capabilities.image_input, |
| 885 | ), |
| 886 | ( |
| 887 | &mut offering.capabilities.reasoning, |
| 888 | lower.capabilities.reasoning, |
| 889 | ), |
| 890 | ( |
| 891 | &mut offering.capabilities.native_tool_calls, |
| 892 | lower.capabilities.native_tool_calls, |
| 893 | ), |
| 894 | ( |
| 895 | &mut offering.capabilities.structured_output, |
| 896 | lower.capabilities.structured_output, |
| 897 | ), |
| 898 | ] { |
| 899 | if *target == codewhale_config::route::CapabilityState::Unknown { |
| 900 | *target = source; |
| 901 | } |
| 902 | } |
| 903 | offering |
| 904 | } |
| 905 | |
| 906 | fn row_matches_endpoint_fingerprint(row: &CatalogOffering, fingerprint: &str) -> bool { |
| 907 | matches!( |
| 908 | &row.source, |
| 909 | CatalogSource::Live { |
| 910 | base_url_fingerprint, |
| 911 | .. |
| 912 | } if base_url_fingerprint == fingerprint |
| 913 | ) |
| 914 | } |
| 915 | |
| 916 | fn current_local_context(provider: ProviderKind, mut row: CatalogOffering) -> CatalogOffering { |
| 917 | if provider != ProviderKind::Ollama { |
| 918 | return row; |
| 919 | } |
| 920 | let Some(ps_source) = row.fact_sources.get("limit.context.ps") else { |
| 921 | return row; |
| 922 | }; |
| 923 | let now = codewhale_config::catalog::now_unix(); |
| 924 | let current = matches!( |
| 925 | ps_source, |
| 926 | CatalogSource::Live { base_url_fingerprint, fetched_at } |
| 927 | if row_matches_endpoint_fingerprint(&row, base_url_fingerprint) |
| 928 | && *fetched_at <= now |
| 929 | && now - *fetched_at < 60 |
| 930 | ); |
| 931 | if !current && let Some(limit) = row.limit.as_mut() { |
| 932 | limit.context = limit.input; |
| 933 | } |
| 934 | row |
| 935 | } |
| 936 | |
| 937 | /// Build or reuse the runtime resolver for an exact provider identity. |
| 938 | /// |
| 939 | /// Only a fresh provider-owned partition whose source fingerprint matches the |
| 940 | /// selected endpoint can carry live limits, capabilities, and pricing into an |
| 941 | /// executable route. Stale, failed, unknown, or wrong-endpoint partitions stay |
| 942 | /// visible to the picker but are removed from this resolver and replaced by the |
| 943 | /// ordinary Models.dev/bundled fallback. Named compatible providers such as |
| 944 | /// Baseten are remapped from their exact catalog identity to the resolver's |
| 945 | /// `custom` transport scope only after this check. |
| 946 | pub fn runtime_catalog_resolver_for_identity( |
| 947 | provider: ProviderKind, |
| 948 | provider_identity: Option<&str>, |
| 949 | base_url: &str, |
| 950 | status: CatalogStatus, |
| 951 | ) -> RuntimeCatalogResolver { |
| 952 | let catalog_id = catalog_provider_id_for_identity(provider, provider_identity); |
| 953 | let catalog_key = catalog_partition_key(catalog_id.as_ref()); |
| 954 | let fingerprint = base_url_fingerprint(base_url); |
| 955 | let status_is_fresh = matches!(status, CatalogStatus::Fresh); |
| 956 | let generation = LIVE_GENERATION.load(Ordering::SeqCst); |
| 957 | let cloud = codewhale_config::cloud_facts::overlay::snapshot(); |
| 958 | let cloud_generation = cloud.generation; |
| 959 | let cache_key = format!( |
| 960 | "{}\u{1f}{}\u{1f}{}", |
| 961 | provider.as_str(), |
| 962 | catalog_key, |
| 963 | fingerprint |
| 964 | ); |
| 965 | |
| 966 | let go_binding = (provider == ProviderKind::OpencodeGo) |
| 967 | .then(|| { |
| 968 | crate::provider_catalog_live::current_catalog_binding( |
| 969 | provider, |
| 970 | provider_identity.unwrap_or(provider.as_str()), |
| 971 | base_url, |
| 972 | ) |
| 973 | }) |
| 974 | .flatten(); |
| 975 | let go_requires_live_proof = provider == ProviderKind::OpencodeGo |
| 976 | && crate::client::opencode_catalog::official_listing(base_url) |
| 977 | && (go_binding.is_some() || !matches!(status, CatalogStatus::Unknown)); |
| 978 | if provider != ProviderKind::Ollama |
| 979 | && let Ok(cache) = RUNTIME_RESOLVER_CACHE.read() |
| 980 | && let Some(cached) = cache.get(&cache_key) |
| 981 | && cached.generation == generation |
| 982 | && cached.cloud_generation == cloud_generation |
| 983 | && cached.status_is_fresh == status_is_fresh |
| 984 | && cached.go_requires_live_proof == go_requires_live_proof |
| 985 | && cached.go_binding == go_binding |
| 986 | { |
| 987 | return RuntimeCatalogResolver { |
| 988 | resolver: cached.resolver.clone(), |
| 989 | endpoint_catalog_authoritative: cached.endpoint_catalog_authoritative, |
| 990 | }; |
| 991 | } |
| 992 | |
| 993 | let partition_owner = live_partition_owner_for_route(provider, provider_identity); |
| 994 | let route_cloud = cloud_facts_apply_to_route( |
| 995 | provider, |
| 996 | provider_identity.unwrap_or(provider.as_str()), |
| 997 | base_url, |
| 998 | ) |
| 999 | .then_some(&cloud); |
| 1000 | let (endpoint_catalog_authoritative, selected_rows, lower_rows) = |
| 1001 | if let Ok(live) = LIVE_SNAPSHOT.read() { |
| 1002 | let exact_partition = live.per_provider.get(&partition_owner); |
| 1003 | let exact_matches = status_is_fresh |
| 1004 | && exact_partition.is_some_and(|partition| { |
| 1005 | !partition.offerings.is_empty() |
| 1006 | && partition.offerings.iter().all(|row| { |
| 1007 | catalog_partition_key(&row.provider) == catalog_key |
| 1008 | && row_matches_endpoint_fingerprint(row, &fingerprint) |
| 1009 | }) |
| 1010 | }); |
| 1011 | let rows = if exact_matches { |
| 1012 | exact_partition |
| 1013 | .map(|partition| partition.offerings.clone()) |
| 1014 | .unwrap_or_default() |
| 1015 | } else { |
| 1016 | Vec::new() |
| 1017 | }; |
| 1018 | let lower = if !matches!(provider, ProviderKind::Custom | ProviderKind::OpenaiCodex) { |
| 1019 | source_rows_for_provider( |
| 1020 | catalog_id.as_ref(), |
| 1021 | generation, |
| 1022 | live.models_dev.as_ref(), |
| 1023 | route_cloud, |
| 1024 | ) |
| 1025 | } else { |
| 1026 | Arc::new(BTreeMap::new()) |
| 1027 | }; |
| 1028 | (exact_matches, rows, lower) |
| 1029 | } else { |
| 1030 | let lower = if !matches!(provider, ProviderKind::Custom | ProviderKind::OpenaiCodex) { |
| 1031 | source_rows_for_provider(catalog_id.as_ref(), generation, None, route_cloud) |
| 1032 | } else { |
| 1033 | Arc::new(BTreeMap::new()) |
| 1034 | }; |
| 1035 | (false, Vec::new(), lower) |
| 1036 | }; |
| 1037 | |
| 1038 | // Nonselected providers retain the bundled/curated resolver baseline. |
| 1039 | // Another endpoint's live roster must not alter this route's ownership |
| 1040 | // checks (including strict-direct rejection of known foreign model ids). |
| 1041 | let go_routes = (go_requires_live_proof |
| 1042 | || (provider == ProviderKind::OpencodeGo |
| 1043 | && endpoint_catalog_authoritative |
| 1044 | && selected_rows.iter().any(|row| row.model_type.is_some()))) |
| 1045 | .then(|| { |
| 1046 | selected_rows |
| 1047 | .iter() |
| 1048 | .filter(|row| row.model_type.as_deref() == Some("chat")) |
| 1049 | .filter_map(|row| { |
| 1050 | Some(( |
| 1051 | row.wire_model_id.clone(), |
| 1052 | (row.endpoint_key.clone(), row.provider_api.clone()?), |
| 1053 | )) |
| 1054 | }) |
| 1055 | .collect() |
| 1056 | }); |
| 1057 | |
| 1058 | let mut source_rows: BTreeMap<(String, String), CatalogOffering> = bundled_snapshot() |
| 1059 | .offerings |
| 1060 | .iter() |
| 1061 | .map(|row| CatalogOffering::clone(row)) |
| 1062 | .map(|row| ((row.provider.clone(), row.wire_model_id.clone()), row)) |
| 1063 | .collect(); |
| 1064 | let cloud_applies = !endpoint_catalog_authoritative |
| 1065 | && cloud_facts_apply_to_route( |
| 1066 | provider, |
| 1067 | provider_identity.unwrap_or(provider.as_str()), |
| 1068 | base_url, |
| 1069 | ); |
| 1070 | if !endpoint_catalog_authoritative { |
| 1071 | source_rows.retain(|(row_provider, _), _| row_provider != catalog_id.as_ref()); |
| 1072 | source_rows.extend( |
| 1073 | lower_rows |
| 1074 | .iter() |
| 1075 | .map(|(key, row)| (key.clone(), row.clone())), |
| 1076 | ); |
| 1077 | } |
| 1078 | let mut route_offerings: BTreeMap<(String, String), ProviderModelOffering> = source_rows |
| 1079 | .values() |
| 1080 | .map(CatalogOffering::to_offering) |
| 1081 | .map(|offering| (offering_key(&offering), offering)) |
| 1082 | .collect(); |
| 1083 | // Curated transport facts win ordinary Models.dev collisions, exactly as |
| 1084 | // in RouteResolver::new(). A fresh exact roster replaces its whole scope. |
| 1085 | for offering in bundled_offerings() { |
| 1086 | let key = offering_key(&offering); |
| 1087 | let enriched = match route_offerings.get(&key) { |
| 1088 | Some(lower) => offering_with_absent_facts_filled(offering, lower), |
| 1089 | None => offering, |
| 1090 | }; |
| 1091 | route_offerings.insert(key, enriched); |
| 1092 | } |
| 1093 | // Keep curated transport identity, applying only fields explicitly signed |
| 1094 | // at the lower cloud layer. Hidden rows must not be resurrected here. |
| 1095 | if cloud_applies && let Some(facts) = &cloud.facts { |
| 1096 | for patch in facts |
| 1097 | .models |
| 1098 | .iter() |
| 1099 | .filter(|patch| patch.provider == catalog_id.as_ref()) |
| 1100 | { |
| 1101 | let key = (patch.provider.clone(), patch.id.clone()); |
| 1102 | match patch.op { |
| 1103 | codewhale_config::cloud_facts::types::ModelOp::Hide => { |
| 1104 | route_offerings.remove(&key); |
| 1105 | } |
| 1106 | codewhale_config::cloud_facts::types::ModelOp::Upsert => { |
| 1107 | if let Some(offering) = route_offerings.get_mut(&key) { |
| 1108 | if let Some(context) = patch.context_window { |
| 1109 | offering.limits.context_tokens = Some(context); |
| 1110 | } |
| 1111 | if let Some(output) = patch.max_output { |
| 1112 | offering.limits.output_tokens = Some(output); |
| 1113 | } |
| 1114 | if let Some(reasoning) = patch.reasoning { |
| 1115 | offering.capabilities.reasoning = |
| 1116 | codewhale_config::route::CapabilityState::from_optional_bool(Some( |
| 1117 | reasoning, |
| 1118 | )); |
| 1119 | } |
| 1120 | if patch.pricing.is_some() |
| 1121 | && let Some(row) = source_rows.get(&key) |
| 1122 | { |
| 1123 | offering.pricing = codewhale_config::pricing::route_pricing_sku(row); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | codewhale_config::cloud_facts::types::ModelOp::Deprecate => {} |
| 1128 | } |
| 1129 | } |
| 1130 | } |
| 1131 | if provider == ProviderKind::Ollama { |
| 1132 | route_offerings.retain(|_, offering| offering.provider.as_str() != catalog_id.as_ref()); |
| 1133 | } |
| 1134 | if endpoint_catalog_authoritative { |
| 1135 | let transport_provider = if provider == ProviderKind::Custom { |
| 1136 | ProviderKind::Custom.as_str() |
| 1137 | } else { |
| 1138 | catalog_id.as_ref() |
| 1139 | }; |
| 1140 | route_offerings.retain(|_, offering| offering.provider.as_str() != transport_provider); |
| 1141 | for mut row in selected_rows { |
| 1142 | let typed_go = provider == ProviderKind::OpencodeGo && row.model_type.is_some(); |
| 1143 | if !typed_go |
| 1144 | && let Some(lower) = |
| 1145 | lower_rows.get(&(row.provider.clone(), row.wire_model_id.clone())) |
| 1146 | { |
| 1147 | row.complete_from(lower, Some(base_url)); |
| 1148 | } |
| 1149 | row.provider = transport_provider.to_string(); |
| 1150 | let offering = current_local_context(provider, row).to_offering(); |
| 1151 | route_offerings.insert(offering_key(&offering), offering); |
| 1152 | } |
| 1153 | // The roster replaced its whole scope, but an id it explicitly attests |
| 1154 | // is unlisted is not an id it denied. That signed row is executable |
| 1155 | // beside the roster, carrying only the facts the payload stated — |
| 1156 | // otherwise the picker would offer a model the executor cannot resolve |
| 1157 | // with the same metadata. |
| 1158 | for row in cloud_unlisted_offerings_for_route( |
| 1159 | provider, |
| 1160 | provider_identity.unwrap_or(provider.as_str()), |
| 1161 | base_url, |
| 1162 | ) |
| 1163 | .into_values() |
| 1164 | { |
| 1165 | let offering = current_local_context(provider, row).to_offering(); |
| 1166 | route_offerings |
| 1167 | .entry(offering_key(&offering)) |
| 1168 | .or_insert(offering); |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | let mut resolver = RouteResolver::from_offerings(route_offerings.into_values().collect()); |
| 1173 | if let Some(routes) = go_routes { |
| 1174 | resolver = resolver.with_go_catalog_routes( |
| 1175 | provider_identity.unwrap_or(provider.as_str()), |
| 1176 | go_binding.clone().unwrap_or_default(), |
| 1177 | base_url, |
| 1178 | routes, |
| 1179 | ); |
| 1180 | } |
| 1181 | if provider != ProviderKind::Ollama |
| 1182 | && let Ok(mut cache) = RUNTIME_RESOLVER_CACHE.write() |
| 1183 | { |
| 1184 | cache.retain(|_, entry| { |
| 1185 | entry.generation == generation && entry.cloud_generation == cloud_generation |
| 1186 | }); |
| 1187 | if cache.len() >= MAX_RUNTIME_RESOLVER_CACHE_ENTRIES && !cache.contains_key(&cache_key) { |
| 1188 | cache.pop_first(); |
| 1189 | } |
| 1190 | cache.insert( |
| 1191 | cache_key, |
| 1192 | RuntimeResolverCacheEntry { |
| 1193 | generation, |
| 1194 | cloud_generation, |
| 1195 | status_is_fresh, |
| 1196 | go_requires_live_proof, |
| 1197 | go_binding, |
| 1198 | endpoint_catalog_authoritative, |
| 1199 | resolver: resolver.clone(), |
| 1200 | }, |
| 1201 | ); |
| 1202 | } |
| 1203 | RuntimeCatalogResolver { |
| 1204 | resolver, |
| 1205 | endpoint_catalog_authoritative, |
| 1206 | } |
| 1207 | } |
| 1208 | |
| 1209 | fn offerings_for_provider_identity<'a>( |
| 1210 | snapshot: &'a SharedSnapshot, |
| 1211 | provider_id: &str, |
| 1212 | ) -> Vec<&'a CatalogOffering> { |
| 1213 | snapshot.offerings_for_provider(&catalog_partition_key(provider_id)) |
| 1214 | } |
| 1215 | |
| 1216 | fn exact_custom_offerings(provider_identity: &str) -> Vec<CatalogOffering> { |
| 1217 | let provider_identity = provider_identity.trim(); |
| 1218 | if provider_identity.is_empty() { |
| 1219 | return Vec::new(); |
| 1220 | } |
| 1221 | let owner = LivePartitionOwner::Custom(catalog_partition_key(provider_identity)); |
| 1222 | LIVE_SNAPSHOT |
| 1223 | .read() |
| 1224 | .ok() |
| 1225 | .and_then(|live| live.per_provider.get(&owner).cloned()) |
| 1226 | .map(|snapshot| snapshot.offerings) |
| 1227 | .unwrap_or_default() |
| 1228 | } |
| 1229 | |
| 1230 | /// Wire model ids are opaque and case-sensitive (`org/Model-A` and |
| 1231 | /// `org/model-a` may be two models), so dedup compares them exactly; folding |
| 1232 | /// case here would hide a real row. Only lookup forgives a case slip, and only |
| 1233 | /// when it is unambiguous (see `find_wire_model`). |
| 1234 | fn push_unique_model(models: &mut Vec<String>, model: &str) { |
| 1235 | let model = model.trim(); |
| 1236 | if model.is_empty() { |
| 1237 | return; |
| 1238 | } |
| 1239 | if !models.iter().any(|existing| existing == model) { |
| 1240 | models.push(model.to_string()); |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | fn catalog_models_from_offerings<'a>( |
| 1245 | offerings: impl IntoIterator<Item = &'a CatalogOffering>, |
| 1246 | ) -> Vec<String> { |
| 1247 | let mut rows: Vec<_> = offerings.into_iter().collect(); |
| 1248 | rows.sort_by(|left, right| { |
| 1249 | right |
| 1250 | .default_for_provider |
| 1251 | .cmp(&left.default_for_provider) |
| 1252 | .then_with(|| left.wire_model_id.cmp(&right.wire_model_id)) |
| 1253 | }); |
| 1254 | let mut models = Vec::new(); |
| 1255 | for row in rows { |
| 1256 | push_unique_model(&mut models, &row.wire_model_id); |
| 1257 | } |
| 1258 | models |
| 1259 | } |
| 1260 | |
| 1261 | /// Tags from the provider's own live `/v1/models` partition. |
| 1262 | /// |
| 1263 | /// Models.dev rows must not satisfy a LOCAL default (Ollama). This reads only |
| 1264 | /// the PerProvider snapshot so a cross-provider catalog cannot costume a |
| 1265 | /// machine that has not answered with its own tags. |
| 1266 | #[cfg(any(test, feature = "test-support"))] |
| 1267 | #[must_use] |
| 1268 | pub fn live_per_provider_models(provider: ProviderKind) -> Vec<String> { |
| 1269 | let catalog_id = catalog_provider_id(provider).to_ascii_lowercase(); |
| 1270 | let Ok(guard) = LIVE_SNAPSHOT.read() else { |
| 1271 | return Vec::new(); |
| 1272 | }; |
| 1273 | let owner = LivePartitionOwner::BuiltIn(catalog_id); |
| 1274 | let Some(snapshot) = guard.per_provider.get(&owner) else { |
| 1275 | return Vec::new(); |
| 1276 | }; |
| 1277 | catalog_models_from_offerings(&snapshot.offerings) |
| 1278 | } |
| 1279 | |
| 1280 | /// Catalog-backed model ids for one provider (#4188). |
| 1281 | /// |
| 1282 | /// Precedence: live Models.dev rows (when published) override bundled offline |
| 1283 | /// rows on `(provider, wire_model_id)`; if the merged catalog still has no rows |
| 1284 | /// for the provider, fall back to |
| 1285 | /// `codewhale_runtime::config::model_completion_names_for_provider` so CodeWhale-only / |
| 1286 | /// local providers (and gateways not yet in the offline seed) keep defaults. |
| 1287 | #[must_use] |
| 1288 | pub fn all_catalog_models_for_provider(provider: ProviderKind) -> Vec<String> { |
| 1289 | all_catalog_models_for_provider_identity(provider, None) |
| 1290 | } |
| 1291 | |
| 1292 | /// Catalog-backed model ids for one exact provider route. |
| 1293 | /// |
| 1294 | /// Built-in providers retain their canonical ids. Named custom routes use |
| 1295 | /// `provider_identity`, so one host's live `/v1/models` rows remain isolated |
| 1296 | /// from every other custom host. There are no compiled seed models: a custom |
| 1297 | /// route with no live, bundled, or configured rows offers nothing (#6289). |
| 1298 | #[must_use] |
| 1299 | pub fn all_catalog_models_for_provider_identity( |
| 1300 | provider: ProviderKind, |
| 1301 | provider_identity: Option<&str>, |
| 1302 | ) -> Vec<String> { |
| 1303 | // ChatGPT OAuth availability is account-scoped. A generic OpenAI or |
| 1304 | // Models.dev catalog is not evidence that a model can be routed through |
| 1305 | // a ChatGPT plan, so this provider owns a registration-scoped source. |
| 1306 | if provider == ProviderKind::OpenaiCodex { |
| 1307 | return codewhale_runtime::codex_model_roster::model_roster().model_ids(); |
| 1308 | } |
| 1309 | |
| 1310 | let catalog_id = catalog_provider_id_for_identity(provider, provider_identity); |
| 1311 | let custom_offerings = |
| 1312 | (provider == ProviderKind::Custom).then(|| exact_custom_offerings(catalog_id.as_ref())); |
| 1313 | let merged = merged_snapshot(); |
| 1314 | let mut models = match custom_offerings.as_ref() { |
| 1315 | Some(rows) => catalog_models_from_offerings(rows.iter()), |
| 1316 | None => catalog_models_from_offerings(offerings_for_provider_identity( |
| 1317 | &merged, |
| 1318 | catalog_id.as_ref(), |
| 1319 | )), |
| 1320 | }; |
| 1321 | if models.is_empty() { |
| 1322 | for model in model_completion_names_for_provider(provider) { |
| 1323 | push_unique_model(&mut models, model); |
| 1324 | } |
| 1325 | } |
| 1326 | models |
| 1327 | } |
| 1328 | |
| 1329 | /// Look up a merged-catalog offering for `(provider, wire_model_id)` (#4115). |
| 1330 | /// |
| 1331 | /// Returns the live-over-bundled row when present so picker metadata (context, |
| 1332 | /// pricing, tools, reasoning, freshness) can be projected without a second |
| 1333 | /// catalog walk. `None` for CodeWhale-only / legacy-fallback ids that have no |
| 1334 | /// Models.dev row. |
| 1335 | #[must_use] |
| 1336 | pub fn catalog_offering_for_model( |
| 1337 | provider: ProviderKind, |
| 1338 | wire_model_id: &str, |
| 1339 | ) -> Option<CatalogOffering> { |
| 1340 | catalog_offering_for_model_identity(provider, None, wire_model_id) |
| 1341 | } |
| 1342 | |
| 1343 | /// Look up a merged-catalog offering for one exact provider route. |
| 1344 | #[must_use] |
| 1345 | pub fn catalog_offering_for_model_identity( |
| 1346 | provider: ProviderKind, |
| 1347 | provider_identity: Option<&str>, |
| 1348 | wire_model_id: &str, |
| 1349 | ) -> Option<CatalogOffering> { |
| 1350 | if provider == ProviderKind::OpenaiCodex { |
| 1351 | return None; |
| 1352 | } |
| 1353 | let catalog_id = catalog_provider_id_for_identity(provider, provider_identity); |
| 1354 | let needle = wire_model_id.trim(); |
| 1355 | if needle.is_empty() { |
| 1356 | return None; |
| 1357 | } |
| 1358 | if provider == ProviderKind::Custom { |
| 1359 | let rows = exact_custom_offerings(catalog_id.as_ref()); |
| 1360 | return find_wire_model(&rows, needle).cloned(); |
| 1361 | } |
| 1362 | find_wire_model( |
| 1363 | offerings_for_provider_identity(&merged_snapshot(), catalog_id.as_ref()), |
| 1364 | needle, |
| 1365 | ) |
| 1366 | .cloned() |
| 1367 | .map(|row| current_local_context(provider, row)) |
| 1368 | } |
| 1369 | |
| 1370 | /// What one exact-route lookup found in the provider's own catalog entry. |
| 1371 | enum RouteCatalogLookup { |
| 1372 | /// The roster lists this id; the row is the route's own metadata. |
| 1373 | Listed(Box<CatalogOffering>), |
| 1374 | /// A successful fetch answered and does not list this id, so nothing else |
| 1375 | /// may supply facts for it. |
| 1376 | NotListed, |
| 1377 | /// No usable roster for this route (absent, or never fetched). |
| 1378 | NoRoster, |
| 1379 | } |
| 1380 | |
| 1381 | /// Metadata from the exact route, without borrowing another endpoint's live facts. |
| 1382 | pub fn catalog_offering_for_route( |
| 1383 | provider: ProviderKind, |
| 1384 | identity: &str, |
| 1385 | base_url: &str, |
| 1386 | model: &str, |
| 1387 | ) -> Option<CatalogOffering> { |
| 1388 | // Only the matched row is cloned, and the cache lock is released here |
| 1389 | // instead of spanning the lower-layer completion below. |
| 1390 | let lookup = crate::provider_catalog_live::with_cached_entry_for_route( |
| 1391 | provider, |
| 1392 | identity, |
| 1393 | base_url, |
| 1394 | |entry| { |
| 1395 | if entry.fetched_at == 0 { |
| 1396 | return RouteCatalogLookup::NoRoster; |
| 1397 | } |
| 1398 | match entry |
| 1399 | .offerings |
| 1400 | .iter() |
| 1401 | .find(|row| row.wire_model_id == model) |
| 1402 | { |
| 1403 | Some(row) => RouteCatalogLookup::Listed(Box::new(row.clone())), |
| 1404 | None => RouteCatalogLookup::NotListed, |
| 1405 | } |
| 1406 | }, |
| 1407 | ); |
| 1408 | match lookup { |
| 1409 | Ok(Some(RouteCatalogLookup::Listed(mut row))) => { |
| 1410 | if !matches!(provider, ProviderKind::Custom | ProviderKind::OpenaiCodex) { |
| 1411 | let cloud = codewhale_config::cloud_facts::overlay::snapshot(); |
| 1412 | let route_cloud = |
| 1413 | cloud_facts_apply_to_route(provider, identity, base_url).then_some(&cloud); |
| 1414 | let catalog_id = catalog_provider_id_for_identity(provider, Some(identity)); |
| 1415 | let live_generation = LIVE_GENERATION.load(Ordering::SeqCst); |
| 1416 | let lower_rows = if let Ok(live) = LIVE_SNAPSHOT.read() { |
| 1417 | source_rows_for_provider( |
| 1418 | catalog_id.as_ref(), |
| 1419 | live_generation, |
| 1420 | live.models_dev.as_ref(), |
| 1421 | route_cloud, |
| 1422 | ) |
| 1423 | } else { |
| 1424 | source_rows_for_provider( |
| 1425 | catalog_id.as_ref(), |
| 1426 | live_generation, |
| 1427 | None, |
| 1428 | route_cloud, |
| 1429 | ) |
| 1430 | }; |
| 1431 | if let Some(lower) = lower_rows.get(&(row.provider.clone(), model.to_string())) { |
| 1432 | row.complete_from(lower, Some(base_url)); |
| 1433 | } |
| 1434 | } |
| 1435 | return Some(current_local_context(provider, *row)); |
| 1436 | } |
| 1437 | // A successful fetch that does not list this id is authoritative about |
| 1438 | // its absence. Only an explicitly attested unlisted row may still name |
| 1439 | // it here: falling through to the bundled/Models.dev merge would hand |
| 1440 | // back facts for a model the roster has retired. |
| 1441 | Ok(Some(RouteCatalogLookup::NotListed)) => { |
| 1442 | return cloud_unlisted_offerings_for_route(provider, identity, base_url) |
| 1443 | .into_values() |
| 1444 | .find(|row| row.wire_model_id == model) |
| 1445 | .map(|row| current_local_context(provider, row)); |
| 1446 | } |
| 1447 | Ok(Some(RouteCatalogLookup::NoRoster)) | Ok(None) | Err(_) => {} |
| 1448 | } |
| 1449 | if codewhale_config::provider_preserves_custom_base_url_model(provider, base_url) { |
| 1450 | return None; |
| 1451 | } |
| 1452 | let offering = catalog_offering_for_model_identity(provider, Some(identity), model)?; |
| 1453 | if matches!(offering.source, CatalogSource::CloudFacts { .. }) |
| 1454 | && !cloud_facts_apply_to_route(provider, identity, base_url) |
| 1455 | { |
| 1456 | return bundled_catalog_offering_for_model(provider, model); |
| 1457 | } |
| 1458 | if matches!(offering.source, CatalogSource::Live { .. }) |
| 1459 | && !row_matches_endpoint_fingerprint(&offering, &base_url_fingerprint(base_url)) |
| 1460 | { |
| 1461 | return None; |
| 1462 | } |
| 1463 | Some(current_local_context(provider, offering)) |
| 1464 | } |
| 1465 | |
| 1466 | /// Config declarations take precedence only for the exact selected route. |
| 1467 | pub fn configured_catalog_offering_for_route( |
| 1468 | config: &Config, |
| 1469 | provider: ProviderKind, |
| 1470 | identity: &str, |
| 1471 | base_url: &str, |
| 1472 | model: &str, |
| 1473 | ) -> Option<CatalogOffering> { |
| 1474 | let lower = catalog_offering_for_route(provider, identity, base_url, model); |
| 1475 | codewhale_runtime::config::configured_model_for_route( |
| 1476 | config, provider, identity, base_url, model, |
| 1477 | ) |
| 1478 | .map(|row| { |
| 1479 | let mut offering = row.to_catalog_offering(); |
| 1480 | if let Some(lower) = lower.as_ref() { |
| 1481 | offering.complete_from(lower, Some(base_url)); |
| 1482 | } |
| 1483 | offering |
| 1484 | }) |
| 1485 | .or(lower) |
| 1486 | } |
| 1487 | |
| 1488 | pub fn configured_catalog_models_for_route( |
| 1489 | config: &Config, |
| 1490 | provider: ProviderKind, |
| 1491 | identity: &str, |
| 1492 | base_url: &str, |
| 1493 | ) -> Vec<String> { |
| 1494 | if provider == ProviderKind::OpenaiCodex { |
| 1495 | return codex_model_cache::model_roster_for(config).model_ids(); |
| 1496 | } |
| 1497 | let mut ids = catalog_models_for_route(provider, identity, base_url); |
| 1498 | if provider != ProviderKind::OpenaiCodex { |
| 1499 | let models = config.custom_models.as_deref().unwrap_or_default(); |
| 1500 | if codewhale_config::catalog::configured::validate_configured_models(models).is_ok() { |
| 1501 | for model in models |
| 1502 | .iter() |
| 1503 | .filter(|row| row.matches_route(identity, base_url)) |
| 1504 | { |
| 1505 | if !ids.contains(&model.id) { |
| 1506 | ids.push(model.id.clone()); |
| 1507 | } |
| 1508 | } |
| 1509 | } |
| 1510 | } |
| 1511 | ids |
| 1512 | } |
| 1513 | |
| 1514 | pub fn listed_models_for_route(route_config: &Config, identity: &ProviderIdentity) -> Vec<String> { |
| 1515 | let mut models = configured_catalog_models_for_route( |
| 1516 | route_config, |
| 1517 | identity.provider, |
| 1518 | identity.key.as_str(), |
| 1519 | &route_config.active_route_base_url(), |
| 1520 | ); |
| 1521 | if identity.provider != ProviderKind::OpenaiCodex { |
| 1522 | let default_model = route_config.default_model(); |
| 1523 | if !default_model.is_empty() && !default_model.eq_ignore_ascii_case("auto") { |
| 1524 | push_unique_model(&mut models, &default_model); |
| 1525 | } |
| 1526 | models.sort(); |
| 1527 | models.dedup(); |
| 1528 | } |
| 1529 | models |
| 1530 | } |
| 1531 | |
| 1532 | /// Look up the **bundled-snapshot** offering for `(provider, wire_model_id)`, |
| 1533 | /// ignoring any live rows merged over it. |
| 1534 | /// |
| 1535 | /// Pricing uses this as an honest fallback when a live row cannot be verified as |
| 1536 | /// authoritative for the endpoint being priced (stale fetch, or a fetch from a |
| 1537 | /// different base URL). The bundled snapshot is a published Models.dev seed with |
| 1538 | /// no endpoint scoping, so it is authoritative for the model without needing a |
| 1539 | /// freshness proof — degrading to it is strictly more truthful than billing |
| 1540 | /// against an unverified live rate (#4318). |
| 1541 | #[must_use] |
| 1542 | pub fn bundled_catalog_offering_for_model( |
| 1543 | provider: ProviderKind, |
| 1544 | wire_model_id: &str, |
| 1545 | ) -> Option<CatalogOffering> { |
| 1546 | if provider == ProviderKind::OpenaiCodex { |
| 1547 | return None; |
| 1548 | } |
| 1549 | let catalog_id = catalog_provider_id(provider); |
| 1550 | let needle = wire_model_id.trim(); |
| 1551 | if needle.is_empty() { |
| 1552 | return None; |
| 1553 | } |
| 1554 | find_wire_model( |
| 1555 | bundled_snapshot().offerings_for_provider(catalog_id), |
| 1556 | needle, |
| 1557 | ) |
| 1558 | .cloned() |
| 1559 | } |
| 1560 | |
| 1561 | /// Count of merged-catalog models for one provider (catalog view / dashboard). |
| 1562 | #[must_use] |
| 1563 | pub fn catalog_model_count_for_provider(provider: ProviderKind) -> usize { |
| 1564 | all_catalog_models_for_provider(provider).len() |
| 1565 | } |
| 1566 | |
| 1567 | /// Providers the user has set up — active provider, working credentials/OAuth, |
| 1568 | /// or an explicit `[providers.<name>]` entry (#3830). |
| 1569 | #[must_use] |
| 1570 | pub fn configured_providers(config: &Config) -> Vec<ProviderIdentity> { |
| 1571 | let Ok(active) = config.active_provider_identity() else { |
| 1572 | return Vec::new(); |
| 1573 | }; |
| 1574 | config |
| 1575 | .provider_identities() |
| 1576 | .into_iter() |
| 1577 | .filter(|identity| provider_is_configured_for_active(config, identity, &active)) |
| 1578 | .collect() |
| 1579 | } |
| 1580 | |
| 1581 | /// Catalog models for providers that qualify as configured for `active`, or |
| 1582 | /// whose own endpoint has answered a live listing (a keyless local runtime |
| 1583 | /// that is not the active route). |
| 1584 | #[must_use] |
| 1585 | pub fn models_for_provider(config: &Config, identity: &ProviderIdentity) -> Vec<String> { |
| 1586 | let Ok(active) = config.active_provider_identity() else { |
| 1587 | return Vec::new(); |
| 1588 | }; |
| 1589 | let base_url = config.base_url_for_route(identity); |
| 1590 | let endpoint_listed = crate::provider_catalog_live::cached_entry_for_route( |
| 1591 | identity.provider, |
| 1592 | identity.key.as_str(), |
| 1593 | &base_url, |
| 1594 | ) |
| 1595 | .ok() |
| 1596 | .flatten() |
| 1597 | .is_some_and(|entry| entry.fetched_at > 0 && !entry.offerings.is_empty()); |
| 1598 | if endpoint_listed || provider_is_configured_for_active(config, identity, &active) { |
| 1599 | configured_catalog_models_for_route( |
| 1600 | config, |
| 1601 | identity.provider, |
| 1602 | identity.key.as_str(), |
| 1603 | &base_url, |
| 1604 | ) |
| 1605 | } else { |
| 1606 | Vec::new() |
| 1607 | } |
| 1608 | } |
| 1609 | |
| 1610 | /// Endpoint-scoped roster for CLI, pickers and inventory. A cached provider |
| 1611 | /// listing is authoritative for the IDs it lists **and for its own omissions**; |
| 1612 | /// the only ID appended after it is one the signed payload explicitly attests |
| 1613 | /// as unlisted. A stale listing for an official endpoint is not current |
| 1614 | /// evidence, so it cannot shadow the snapshot roster; its own IDs survive only |
| 1615 | /// as an offline tail. Configured models are retained by the caller. |
| 1616 | #[must_use] |
| 1617 | pub fn catalog_models_for_route( |
| 1618 | provider: ProviderKind, |
| 1619 | identity: &str, |
| 1620 | base_url: &str, |
| 1621 | ) -> Vec<String> { |
| 1622 | if provider == ProviderKind::OpenaiCodex { |
| 1623 | return codewhale_runtime::codex_model_roster::model_roster().model_ids(); |
| 1624 | } |
| 1625 | let cached = crate::provider_catalog_live::cached_entry_for_route(provider, identity, base_url) |
| 1626 | .ok() |
| 1627 | .flatten() |
| 1628 | .filter(|entry| entry.fetched_at > 0); |
| 1629 | let cached_is_authoritative = cached.as_ref().is_some_and(|entry| { |
| 1630 | crate::provider_catalog_live::cached_roster_is_authoritative(provider, base_url, entry) |
| 1631 | }); |
| 1632 | if let Some(entry) = cached.as_ref().filter(|_| cached_is_authoritative) { |
| 1633 | let mut models = Vec::with_capacity(entry.offerings.len()); |
| 1634 | for row in &entry.offerings { |
| 1635 | if provider == ProviderKind::OpencodeGo |
| 1636 | && row.model_type.is_some() |
| 1637 | && (row.model_type.as_deref() != Some("chat") || row.endpoint_key == "unproven") |
| 1638 | { |
| 1639 | continue; |
| 1640 | } |
| 1641 | push_unique_model(&mut models, &row.wire_model_id); |
| 1642 | } |
| 1643 | // Appended, never interleaved: the roster keeps its own order and its |
| 1644 | // own authority, and an explicitly attested unlisted id is offered |
| 1645 | // after it. This is the same list the picker, metadata lookups and the |
| 1646 | // route resolver read, so a user pin stays exactly what it was. |
| 1647 | for row in cloud_unlisted_offerings_for_route(provider, identity, base_url).values() { |
| 1648 | push_unique_model(&mut models, &row.wire_model_id); |
| 1649 | } |
| 1650 | return models; |
| 1651 | } |
| 1652 | if provider == ProviderKind::Custom { |
| 1653 | // No compiled seeds: without a cached listing the caller retains the |
| 1654 | // configured model and the live refresh fills the roster (#6289). |
| 1655 | return Vec::new(); |
| 1656 | } |
| 1657 | if codewhale_config::provider_preserves_custom_base_url_model(provider, base_url) { |
| 1658 | return Vec::new(); |
| 1659 | } |
| 1660 | // Do not borrow a live partition published for another endpoint. |
| 1661 | let catalog_id = catalog_provider_id(provider); |
| 1662 | let live_generation = LIVE_GENERATION.load(Ordering::SeqCst); |
| 1663 | let live = LIVE_SNAPSHOT.read().ok(); |
| 1664 | let cloud = codewhale_config::cloud_facts::overlay::snapshot(); |
| 1665 | let rows = source_rows_for_provider( |
| 1666 | catalog_id, |
| 1667 | live_generation, |
| 1668 | live.as_ref().and_then(|live| live.models_dev.as_ref()), |
| 1669 | cloud_facts_apply_to_route(provider, identity, base_url).then_some(&cloud), |
| 1670 | ); |
| 1671 | let mut models = catalog_models_from_offerings(rows.values()); |
| 1672 | if models.is_empty() && cloud.facts.is_none() { |
| 1673 | models.extend( |
| 1674 | model_completion_names_for_provider(provider) |
| 1675 | .into_iter() |
| 1676 | .map(str::to_string), |
| 1677 | ); |
| 1678 | } |
| 1679 | for row in cached.iter().flat_map(|entry| entry.offerings.iter()) { |
| 1680 | push_unique_model(&mut models, &row.wire_model_id); |
| 1681 | } |
| 1682 | models |
| 1683 | } |
| 1684 | |
| 1685 | #[derive(serde::Serialize)] |
| 1686 | pub struct CatalogUpdateReceipt { |
| 1687 | provider: String, |
| 1688 | source: &'static str, |
| 1689 | outcome: &'static str, |
| 1690 | status: CatalogStatus, |
| 1691 | fetched_at: Option<u64>, |
| 1692 | observed_at: Option<u64>, |
| 1693 | base_url_fingerprint: Option<String>, |
| 1694 | model_count: usize, |
| 1695 | error: Option<&'static str>, |
| 1696 | } |
| 1697 | |
| 1698 | fn cached_receipt(config: &Config, identity: &ProviderIdentity) -> CatalogUpdateReceipt { |
| 1699 | let base_url = config.base_url_for_route(identity); |
| 1700 | let fingerprint = base_url_fingerprint(&base_url); |
| 1701 | let entry = crate::provider_catalog_live::cached_entry_for_route( |
| 1702 | identity.provider, |
| 1703 | identity.key.as_str(), |
| 1704 | &base_url, |
| 1705 | ); |
| 1706 | let cached = entry.as_ref().ok().and_then(Option::as_ref); |
| 1707 | CatalogUpdateReceipt { |
| 1708 | provider: identity.key.to_string(), |
| 1709 | source: "provider_models", |
| 1710 | outcome: "cached", |
| 1711 | status: crate::provider_catalog_live::status_for_route( |
| 1712 | identity.provider, |
| 1713 | identity.key.as_str(), |
| 1714 | &base_url, |
| 1715 | ), |
| 1716 | fetched_at: cached |
| 1717 | .map(|entry| entry.fetched_at) |
| 1718 | .filter(|timestamp| *timestamp > 0), |
| 1719 | observed_at: None, |
| 1720 | base_url_fingerprint: Some(fingerprint), |
| 1721 | model_count: cached.map_or(0, |entry| entry.offerings.len()), |
| 1722 | error: entry.is_err().then_some("cache_read_failed"), |
| 1723 | } |
| 1724 | } |
| 1725 | |
| 1726 | fn roster_receipt( |
| 1727 | config: &Config, |
| 1728 | identity: &ProviderIdentity, |
| 1729 | model_count: usize, |
| 1730 | ) -> CatalogUpdateReceipt { |
| 1731 | let base_url = config.base_url_for_route(identity); |
| 1732 | let live = crate::provider_catalog_live::cached_entry_for_route( |
| 1733 | identity.provider, |
| 1734 | identity.key.as_str(), |
| 1735 | &base_url, |
| 1736 | ) |
| 1737 | .ok() |
| 1738 | .flatten() |
| 1739 | .is_some_and(|entry| { |
| 1740 | entry.fetched_at > 0 |
| 1741 | && crate::provider_catalog_live::cached_roster_is_authoritative( |
| 1742 | identity.provider, |
| 1743 | &base_url, |
| 1744 | &entry, |
| 1745 | ) |
| 1746 | }); |
| 1747 | if live { |
| 1748 | return cached_receipt(config, identity); |
| 1749 | } |
| 1750 | let snapshot = crate::models_dev_live::status(); |
| 1751 | let bundled_fetched_at = codewhale_config::catalog::reviewed::bundled_source_fetched_at(); |
| 1752 | let (status, fetched_at) = match snapshot.freshness { |
| 1753 | crate::models_dev_live::ModelsDevFreshness::Live => ( |
| 1754 | CatalogStatus::Fresh, |
| 1755 | snapshot.fetched_at.or(bundled_fetched_at), |
| 1756 | ), |
| 1757 | crate::models_dev_live::ModelsDevFreshness::Bundled => { |
| 1758 | (CatalogStatus::Fresh, bundled_fetched_at) |
| 1759 | } |
| 1760 | crate::models_dev_live::ModelsDevFreshness::Stale |
| 1761 | | crate::models_dev_live::ModelsDevFreshness::Failed => { |
| 1762 | let fetched_at = snapshot.fetched_at.or(bundled_fetched_at); |
| 1763 | let now = codewhale_config::catalog::now_unix(); |
| 1764 | let status = |
| 1765 | fetched_at.map_or(CatalogStatus::Unknown, |fetched_at| CatalogStatus::Stale { |
| 1766 | age_secs: now.saturating_sub(fetched_at), |
| 1767 | }); |
| 1768 | (status, fetched_at) |
| 1769 | } |
| 1770 | }; |
| 1771 | CatalogUpdateReceipt { |
| 1772 | provider: identity.key.to_string(), |
| 1773 | source: snapshot.provenance.label(), |
| 1774 | outcome: "cached", |
| 1775 | status, |
| 1776 | fetched_at, |
| 1777 | observed_at: None, |
| 1778 | base_url_fingerprint: Some(base_url_fingerprint(&base_url)), |
| 1779 | model_count, |
| 1780 | error: None, |
| 1781 | } |
| 1782 | } |
| 1783 | |
| 1784 | fn catalog_identities( |
| 1785 | config: &Config, |
| 1786 | selected: Option<&str>, |
| 1787 | update: bool, |
| 1788 | ) -> anyhow::Result<Vec<ProviderIdentity>> { |
| 1789 | if let Some(selected) = selected { |
| 1790 | return Ok(vec![ |
| 1791 | config |
| 1792 | .resolve_provider_pin_identity(selected) |
| 1793 | .map_err(anyhow::Error::msg)?, |
| 1794 | ]); |
| 1795 | } |
| 1796 | let active = config |
| 1797 | .active_provider_identity() |
| 1798 | .map_err(anyhow::Error::msg)?; |
| 1799 | if !update { |
| 1800 | return Ok(vec![active]); |
| 1801 | } |
| 1802 | let mut identities = configured_providers(config); |
| 1803 | if !identities.contains(&active) { |
| 1804 | identities.push(active); |
| 1805 | } |
| 1806 | identities.sort_by(|a, b| a.key.as_str().cmp(b.key.as_str())); |
| 1807 | identities.dedup_by(|a, b| a == b); |
| 1808 | Ok(identities) |
| 1809 | } |
| 1810 | |
| 1811 | fn codex_receipt(config: &Config, identity: &ProviderIdentity) -> CatalogUpdateReceipt { |
| 1812 | let roster = codex_model_cache::model_roster_for(config); |
| 1813 | codex_roster_receipt(identity, &roster) |
| 1814 | } |
| 1815 | |
| 1816 | fn codex_roster_receipt( |
| 1817 | identity: &ProviderIdentity, |
| 1818 | roster: &codewhale_runtime::codex_model_roster::CodexModelRoster, |
| 1819 | ) -> CatalogUpdateReceipt { |
| 1820 | let fresh = |
| 1821 | roster.freshness == codewhale_runtime::codex_model_roster::CodexModelCacheFreshness::Fresh; |
| 1822 | CatalogUpdateReceipt { |
| 1823 | provider: identity.key.to_string(), |
| 1824 | source: roster.source, |
| 1825 | outcome: "cached", |
| 1826 | status: if fresh { |
| 1827 | CatalogStatus::Fresh |
| 1828 | } else { |
| 1829 | CatalogStatus::Unknown |
| 1830 | }, |
| 1831 | fetched_at: roster |
| 1832 | .fetched_at |
| 1833 | .and_then(|timestamp| u64::try_from(timestamp.timestamp()).ok()), |
| 1834 | observed_at: roster |
| 1835 | .observed_at |
| 1836 | .and_then(|timestamp| u64::try_from(timestamp.timestamp()).ok()), |
| 1837 | base_url_fingerprint: None, |
| 1838 | model_count: roster.models.len(), |
| 1839 | error: if !fresh { |
| 1840 | Some("chatgpt_catalog_unavailable") |
| 1841 | } else if !roster.observation_persisted { |
| 1842 | Some("chatgpt_catalog_not_persisted") |
| 1843 | } else { |
| 1844 | None |
| 1845 | }, |
| 1846 | } |
| 1847 | } |
| 1848 | |
| 1849 | /// Whether a provider-scoped live listing can never exist for this route. |
| 1850 | /// OAuth-authenticated routes (other than Codex, which owns its own roster) |
| 1851 | /// have no catalog endpoint Codewhale may call, so listings fall back to the |
| 1852 | /// next catalog layer — live Models.dev, then the bundled snapshot — instead |
| 1853 | /// of treating the missing live listing as "no models". |
| 1854 | pub fn live_catalog_unavailable(config: &Config, identity: &ProviderIdentity) -> bool { |
| 1855 | config.verify_provider_identity(identity).is_ok() |
| 1856 | && identity.provider != ProviderKind::OpenaiCodex |
| 1857 | && config |
| 1858 | .auth_mode_for_provider(identity) |
| 1859 | .is_some_and(|mode| mode.eq_ignore_ascii_case("oauth")) |
| 1860 | } |
| 1861 | |
| 1862 | pub async fn update_provider_catalog( |
| 1863 | config: &Config, |
| 1864 | identity: &ProviderIdentity, |
| 1865 | ) -> CatalogUpdateReceipt { |
| 1866 | if config.verify_provider_identity(identity).is_err() { |
| 1867 | let mut receipt = cached_receipt(config, identity); |
| 1868 | receipt.outcome = "skipped"; |
| 1869 | receipt.error = Some("provider_identity_changed"); |
| 1870 | return receipt; |
| 1871 | } |
| 1872 | let Ok((_, observation_generation)) = |
| 1873 | crate::provider_catalog_live::inventory_scope(config, identity) |
| 1874 | else { |
| 1875 | let mut receipt = cached_receipt(config, identity); |
| 1876 | receipt.outcome = "failed"; |
| 1877 | receipt.error = receipt.error.or(Some("inventory_scope_unavailable")); |
| 1878 | return receipt; |
| 1879 | }; |
| 1880 | if identity.provider == ProviderKind::OpenaiCodex { |
| 1881 | let mut route_config = config.clone(); |
| 1882 | if route_config.scope_to_provider_identity(identity).is_err() { |
| 1883 | let mut receipt = cached_receipt(config, identity); |
| 1884 | receipt.outcome = "skipped"; |
| 1885 | receipt.error = Some("provider_identity_changed"); |
| 1886 | return receipt; |
| 1887 | } |
| 1888 | return match codex_model_cache::update_from_chatgpt(&route_config).await { |
| 1889 | Ok(roster) => { |
| 1890 | let mut receipt = codex_roster_receipt(identity, &roster); |
| 1891 | receipt.outcome = "updated"; |
| 1892 | receipt |
| 1893 | } |
| 1894 | Err(error) => { |
| 1895 | let mut receipt = codex_receipt(&route_config, identity); |
| 1896 | receipt.outcome = "failed"; |
| 1897 | receipt.error = Some(error); |
| 1898 | receipt |
| 1899 | } |
| 1900 | }; |
| 1901 | } |
| 1902 | let Some(_refresh) = crate::provider_catalog_live::try_inventory_refresh(identity) else { |
| 1903 | let mut receipt = cached_receipt(config, identity); |
| 1904 | receipt.outcome = "skipped"; |
| 1905 | receipt.error = Some("refresh_pending"); |
| 1906 | return receipt; |
| 1907 | }; |
| 1908 | let mut route_config = config.clone(); |
| 1909 | if route_config.scope_to_provider_identity(identity).is_err() { |
| 1910 | let mut receipt = cached_receipt(config, identity); |
| 1911 | receipt.outcome = "skipped"; |
| 1912 | receipt.error = Some("provider_identity_changed"); |
| 1913 | return receipt; |
| 1914 | } |
| 1915 | let base_url = route_config.active_route_base_url(); |
| 1916 | let fingerprint = base_url_fingerprint(&base_url); |
| 1917 | let mut receipt = cached_receipt(&route_config, identity); |
| 1918 | if crate::client::model_listing_unavailable(identity.provider, &base_url) { |
| 1919 | receipt.outcome = "skipped"; |
| 1920 | receipt.error = Some("provider_model_listing_unavailable"); |
| 1921 | return receipt; |
| 1922 | } |
| 1923 | if identity.provider == ProviderKind::Antigravity { |
| 1924 | receipt.outcome = "skipped"; |
| 1925 | receipt.error = Some("provider_retired"); |
| 1926 | return receipt; |
| 1927 | } |
| 1928 | if codewhale_runtime::config::explicit_cli_api_key_override().is_some() |
| 1929 | && config.active_provider_identity().ok().as_ref() != Some(identity) |
| 1930 | { |
| 1931 | receipt.outcome = "skipped"; |
| 1932 | receipt.error = Some("cli_key_is_scoped_to_active_provider"); |
| 1933 | return receipt; |
| 1934 | } |
| 1935 | if live_catalog_unavailable(&route_config, identity) { |
| 1936 | receipt.outcome = "skipped"; |
| 1937 | receipt.error = Some("oauth_catalog_unavailable"); |
| 1938 | return receipt; |
| 1939 | } |
| 1940 | // Ordinary model listing never constructs a client. Explicit refresh uses |
| 1941 | // the existing read-only resolver: no secret migration or OAuth refresh. |
| 1942 | let account_owner = route_config.account_model_access.read().clone(); |
| 1943 | let prepared = |
| 1944 | if crate::client::CodewhaleClient::public_catalog_for_route(&route_config, identity) { |
| 1945 | Ok(route_config.clone()) |
| 1946 | } else { |
| 1947 | route_config.with_read_only_api_key_for_diagnostic() |
| 1948 | }; |
| 1949 | let credential = prepared |
| 1950 | .as_ref() |
| 1951 | .ok() |
| 1952 | .and_then(|config| config.active_route_api_key_read_only().ok()); |
| 1953 | let client = |
| 1954 | prepared.and_then(|config| crate::client::CodewhaleClient::for_catalog_refresh(&config)); |
| 1955 | let client = match client { |
| 1956 | Ok(client) => client, |
| 1957 | Err(_) => { |
| 1958 | receipt.outcome = "skipped"; |
| 1959 | receipt.error = Some("credentials_or_route_unavailable"); |
| 1960 | return receipt; |
| 1961 | } |
| 1962 | }; |
| 1963 | if receipt.error.is_some() { |
| 1964 | receipt.outcome = "failed"; |
| 1965 | return receipt; |
| 1966 | } |
| 1967 | let Some(ticket) = crate::provider_catalog_live::begin_inventory_refresh( |
| 1968 | identity, |
| 1969 | &base_url, |
| 1970 | observation_generation, |
| 1971 | ) else { |
| 1972 | receipt.outcome = "skipped"; |
| 1973 | receipt.error = Some("refresh_superseded"); |
| 1974 | return receipt; |
| 1975 | }; |
| 1976 | let result = tokio::time::timeout( |
| 1977 | std::time::Duration::from_secs(20), |
| 1978 | client.fetch_catalog_delta(), |
| 1979 | ) |
| 1980 | .await |
| 1981 | .unwrap_or(Err(codewhale_config::catalog::CatalogRefreshError::Network)); |
| 1982 | // Resolve from the original route, not the materialized client clone: the |
| 1983 | // shared session or secure credential may have changed during the request. |
| 1984 | if route_config.active_route_api_key_read_only().ok() != credential { |
| 1985 | receipt.outcome = "skipped"; |
| 1986 | receipt.error = Some("refresh_credentials_changed"); |
| 1987 | return receipt; |
| 1988 | } |
| 1989 | let owner = |access: &codewhale_runtime::config::AccountModelAccess| { |
| 1990 | ( |
| 1991 | access.session_id.clone(), |
| 1992 | access.profile.clone(), |
| 1993 | access.credential.expose_secret().to_string(), |
| 1994 | ) |
| 1995 | }; |
| 1996 | let account_unchanged = { |
| 1997 | let access = route_config.account_model_access.read(); |
| 1998 | access.as_ref().map(owner) == account_owner.as_ref().map(owner) |
| 1999 | }; |
| 2000 | if !account_unchanged { |
| 2001 | receipt.outcome = "skipped"; |
| 2002 | receipt.error = Some("refresh_credentials_changed"); |
| 2003 | return receipt; |
| 2004 | } |
| 2005 | match result { |
| 2006 | Ok(mut delta) => { |
| 2007 | if delta.base_url_fingerprint != fingerprint { |
| 2008 | receipt.outcome = "failed"; |
| 2009 | receipt.error = Some("catalog_endpoint_mismatch"); |
| 2010 | return receipt; |
| 2011 | } |
| 2012 | delta.provider = identity.key.to_string(); |
| 2013 | match crate::provider_catalog_live::record_success_if_current(&ticket, delta) { |
| 2014 | None => { |
| 2015 | receipt.outcome = "skipped"; |
| 2016 | receipt.error = Some("refresh_superseded"); |
| 2017 | return receipt; |
| 2018 | } |
| 2019 | Some(CatalogStatus::Fresh) => receipt.outcome = "updated", |
| 2020 | Some(CatalogStatus::Failed { reason }) => { |
| 2021 | receipt.outcome = "failed"; |
| 2022 | receipt.error = Some(reason.label()); |
| 2023 | } |
| 2024 | Some(_) => { |
| 2025 | receipt.outcome = "failed"; |
| 2026 | receipt.error = Some("cache_write_failed"); |
| 2027 | } |
| 2028 | } |
| 2029 | } |
| 2030 | Err(reason) => { |
| 2031 | crate::provider_catalog_live::record_failure_if_current( |
| 2032 | &ticket, |
| 2033 | identity.key.as_str(), |
| 2034 | &fingerprint, |
| 2035 | reason, |
| 2036 | ); |
| 2037 | receipt.outcome = "failed"; |
| 2038 | receipt.error = Some(reason.label()); |
| 2039 | } |
| 2040 | } |
| 2041 | let outcome = receipt.outcome; |
| 2042 | let failure = receipt.error; |
| 2043 | receipt = cached_receipt(&route_config, identity); |
| 2044 | receipt.outcome = outcome; |
| 2045 | if outcome == "failed" { |
| 2046 | receipt.error = failure.or(receipt.error); |
| 2047 | } |
| 2048 | receipt |
| 2049 | } |
| 2050 | |
| 2051 | pub async fn refresh_local_ollama_catalog(config: &Config, identity: &ProviderIdentity) { |
| 2052 | #[cfg(any( |
| 2053 | test, |
| 2054 | feature = "test-support", |
| 2055 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 2056 | ))] |
| 2057 | let _ = (config, identity); |
| 2058 | #[cfg(not(any( |
| 2059 | test, |
| 2060 | feature = "test-support", |
| 2061 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 2062 | )))] |
| 2063 | { |
| 2064 | if identity.provider != ProviderKind::Ollama { |
| 2065 | return; |
| 2066 | } |
| 2067 | static REFRESH_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| 2068 | let queued_at = codewhale_config::catalog::now_unix(); |
| 2069 | let refresh_guard = REFRESH_LOCK.lock().await; |
| 2070 | let handle = tokio::runtime::Handle::current(); |
| 2071 | let config = config.clone(); |
| 2072 | let identity = identity.clone(); |
| 2073 | let _ = tokio::task::spawn_blocking(move || { |
| 2074 | let _refresh_guard = refresh_guard; |
| 2075 | let now = codewhale_config::catalog::now_unix(); |
| 2076 | let base_url = config.base_url_for_route(&identity); |
| 2077 | let recent = crate::provider_catalog_live::with_cached_entry_for_route( |
| 2078 | identity.provider, |
| 2079 | identity.key.as_str(), |
| 2080 | &base_url, |
| 2081 | |entry| { |
| 2082 | entry.is_fresh(now) |
| 2083 | && matches!( |
| 2084 | entry.status, |
| 2085 | codewhale_config::catalog::CatalogStatus::Fresh |
| 2086 | ) |
| 2087 | && entry.fetched_at >= queued_at |
| 2088 | && entry.fetched_at <= now |
| 2089 | && entry.offerings.iter().any(|row| row.default_for_provider) |
| 2090 | }, |
| 2091 | ) |
| 2092 | .ok() |
| 2093 | .flatten() |
| 2094 | .unwrap_or(false); |
| 2095 | if recent |
| 2096 | && runtime_catalog_resolver_for_identity( |
| 2097 | identity.provider, |
| 2098 | Some(identity.key.as_str()), |
| 2099 | &base_url, |
| 2100 | codewhale_config::catalog::CatalogStatus::Fresh, |
| 2101 | ) |
| 2102 | .endpoint_catalog_authoritative |
| 2103 | { |
| 2104 | return; |
| 2105 | } |
| 2106 | handle.block_on(update_provider_catalog(&config, &identity)); |
| 2107 | }) |
| 2108 | .await; |
| 2109 | } |
| 2110 | } |
| 2111 | |
| 2112 | pub async fn refresh_unverified_local_context( |
| 2113 | config: &Config, |
| 2114 | identity: &ProviderIdentity, |
| 2115 | model: &str, |
| 2116 | ) { |
| 2117 | if identity.provider != ProviderKind::Ollama { |
| 2118 | return; |
| 2119 | } |
| 2120 | let base_url = config.base_url_for_route(identity); |
| 2121 | let known = || { |
| 2122 | let provider = identity.provider; |
| 2123 | let key = identity.key.as_str().to_string(); |
| 2124 | let base_url = base_url.clone(); |
| 2125 | let model = model.to_string(); |
| 2126 | async move { |
| 2127 | tokio::task::spawn_blocking(move || { |
| 2128 | catalog_offering_for_route(provider, &key, &base_url, &model) |
| 2129 | .and_then(|row| row.limit) |
| 2130 | .and_then(|limit| limit.context) |
| 2131 | .is_some() |
| 2132 | }) |
| 2133 | .await |
| 2134 | .unwrap_or(false) |
| 2135 | } |
| 2136 | }; |
| 2137 | let refresh = || { |
| 2138 | tokio::time::timeout( |
| 2139 | std::time::Duration::from_secs(3), |
| 2140 | refresh_local_ollama_catalog(config, identity), |
| 2141 | ) |
| 2142 | }; |
| 2143 | if known().await { |
| 2144 | return; |
| 2145 | } |
| 2146 | let _ = refresh().await; |
| 2147 | #[cfg(not(any( |
| 2148 | test, |
| 2149 | feature = "test-support", |
| 2150 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 2151 | )))] |
| 2152 | if !known().await |
| 2153 | && crate::client::ollama_catalog::load_model( |
| 2154 | &crate::client::ollama_catalog::ollama_native_origin(&base_url), |
| 2155 | model, |
| 2156 | ) |
| 2157 | .await |
| 2158 | { |
| 2159 | let _ = refresh().await; |
| 2160 | } |
| 2161 | } |
| 2162 | |
| 2163 | pub async fn refresh_account_catalog_before_first_request(config: &Config) -> bool { |
| 2164 | let Ok(identity) = config.active_provider_identity() else { |
| 2165 | return false; |
| 2166 | }; |
| 2167 | if !crate::provider_catalog_live::route_is_account_scoped(config, &identity) |
| 2168 | || live_catalog_unavailable(config, &identity) |
| 2169 | { |
| 2170 | return false; |
| 2171 | } |
| 2172 | let handle = tokio::runtime::Handle::current(); |
| 2173 | let refresh_config = config.clone(); |
| 2174 | let refresh_identity = identity.clone(); |
| 2175 | let receipt = tokio::task::spawn_blocking(move || { |
| 2176 | handle.block_on(update_provider_catalog(&refresh_config, &refresh_identity)) |
| 2177 | }) |
| 2178 | .await |
| 2179 | .ok(); |
| 2180 | let status = crate::provider_catalog_live::status_for_route( |
| 2181 | identity.provider, |
| 2182 | identity.key.as_str(), |
| 2183 | &config.active_route_base_url(), |
| 2184 | ); |
| 2185 | if !matches!(status, CatalogStatus::Fresh) { |
| 2186 | let reason = match &status { |
| 2187 | CatalogStatus::Failed { reason } => reason.label(), |
| 2188 | _ => receipt.map_or("refresh_failed", |receipt| { |
| 2189 | receipt.error.unwrap_or(receipt.outcome) |
| 2190 | }), |
| 2191 | }; |
| 2192 | tracing::warn!( |
| 2193 | target: "provider_catalog", |
| 2194 | provider = %identity.key, |
| 2195 | reason, |
| 2196 | "account model listing unavailable before the first request" |
| 2197 | ); |
| 2198 | if identity.provider == ProviderKind::OpencodeGo |
| 2199 | && crate::client::opencode_catalog::official_listing(&config.active_route_base_url()) |
| 2200 | { |
| 2201 | eprintln!( |
| 2202 | "codewhale: could not read the {} account model listing ({reason}); refresh the exact connection before dispatch.", |
| 2203 | identity.key |
| 2204 | ); |
| 2205 | } else { |
| 2206 | eprintln!( |
| 2207 | "codewhale: could not read the {} account model listing ({reason}); requesting with built-in model limits.", |
| 2208 | identity.key |
| 2209 | ); |
| 2210 | } |
| 2211 | } |
| 2212 | true |
| 2213 | } |
| 2214 | |
| 2215 | pub async fn run_models( |
| 2216 | config: &Config, |
| 2217 | update: bool, |
| 2218 | selected: Option<&str>, |
| 2219 | json: bool, |
| 2220 | ) -> anyhow::Result<()> { |
| 2221 | use codewhale_localization::{MessageId, resolve_locale, tr}; |
| 2222 | let locale = resolve_locale( |
| 2223 | &codewhale_runtime::settings::Settings::load_persisted() |
| 2224 | .unwrap_or_default() |
| 2225 | .locale, |
| 2226 | ); |
| 2227 | let identities = catalog_identities(config, selected, update)?; |
| 2228 | crate::models_dev_live::maybe_load_persisted_cache(); |
| 2229 | if update { |
| 2230 | let mut receipts = Vec::new(); |
| 2231 | if selected.is_none() { |
| 2232 | let result = crate::models_dev_live::refresh(true).await; |
| 2233 | let status = crate::models_dev_live::status(); |
| 2234 | receipts.push(CatalogUpdateReceipt { |
| 2235 | provider: "models.dev".to_string(), |
| 2236 | source: "models.dev", |
| 2237 | outcome: if result.is_ok() { "updated" } else { "failed" }, |
| 2238 | status: if result.is_ok() { |
| 2239 | CatalogStatus::Fresh |
| 2240 | } else { |
| 2241 | CatalogStatus::Unknown |
| 2242 | }, |
| 2243 | fetched_at: status.fetched_at, |
| 2244 | observed_at: None, |
| 2245 | base_url_fingerprint: None, |
| 2246 | model_count: status.offering_count, |
| 2247 | error: result.err().map(|error| match error { |
| 2248 | crate::models_dev_live::ModelsDevRefreshError::Disabled => "fetch_disabled", |
| 2249 | crate::models_dev_live::ModelsDevRefreshError::Network(_) => "network", |
| 2250 | crate::models_dev_live::ModelsDevRefreshError::HttpStatus(_) => "http_status", |
| 2251 | crate::models_dev_live::ModelsDevRefreshError::InvalidResponse(_) => { |
| 2252 | "invalid_response" |
| 2253 | } |
| 2254 | crate::models_dev_live::ModelsDevRefreshError::EmptyCatalog => "empty_catalog", |
| 2255 | crate::models_dev_live::ModelsDevRefreshError::Io(_) => "cache_io", |
| 2256 | }), |
| 2257 | }); |
| 2258 | } |
| 2259 | use futures_util::StreamExt; |
| 2260 | receipts.extend( |
| 2261 | futures_util::stream::iter(&identities) |
| 2262 | .map(|identity| update_provider_catalog(config, identity)) |
| 2263 | .buffered(4) |
| 2264 | .collect::<Vec<_>>() |
| 2265 | .await, |
| 2266 | ); |
| 2267 | let updated = receipts |
| 2268 | .iter() |
| 2269 | .filter(|receipt| receipt.outcome == "updated") |
| 2270 | .count(); |
| 2271 | let loaded = receipts |
| 2272 | .iter() |
| 2273 | .filter(|receipt| receipt.outcome == "loaded") |
| 2274 | .count(); |
| 2275 | let failed = receipts |
| 2276 | .iter() |
| 2277 | .filter(|receipt| receipt.outcome == "failed") |
| 2278 | .count(); |
| 2279 | let skipped = receipts |
| 2280 | .iter() |
| 2281 | .filter(|receipt| receipt.outcome == "skipped") |
| 2282 | .count(); |
| 2283 | if json { |
| 2284 | println!( |
| 2285 | "{}", |
| 2286 | serde_json::to_string_pretty(&serde_json::json!({ |
| 2287 | "updated": updated, "loaded": loaded, "failed": failed, "skipped": skipped, |
| 2288 | "catalogs": receipts, |
| 2289 | }))? |
| 2290 | ); |
| 2291 | } else { |
| 2292 | println!( |
| 2293 | "{}", |
| 2294 | tr(locale, MessageId::ModelsUpdateSummary) |
| 2295 | .replace("{updated}", &updated.to_string()) |
| 2296 | .replace("{loaded}", &loaded.to_string()) |
| 2297 | .replace("{failed}", &failed.to_string()) |
| 2298 | .replace("{skipped}", &skipped.to_string()) |
| 2299 | ); |
| 2300 | let now_secs = codewhale_config::catalog::now_unix(); |
| 2301 | for receipt in &receipts { |
| 2302 | let freshness = format_receipt_freshness_fields( |
| 2303 | receipt.fetched_at, |
| 2304 | receipt.observed_at, |
| 2305 | now_secs, |
| 2306 | ); |
| 2307 | println!( |
| 2308 | "{}\t{}\tmodels={}\t{}\tsource={}\tstatus={}{}", |
| 2309 | receipt.provider, |
| 2310 | receipt.outcome, |
| 2311 | receipt.model_count, |
| 2312 | freshness, |
| 2313 | receipt.source, |
| 2314 | serde_json::to_string(&receipt.status)?, |
| 2315 | receipt |
| 2316 | .error |
| 2317 | .map_or_else(String::new, |error| format!("\terror={error}")) |
| 2318 | ); |
| 2319 | } |
| 2320 | } |
| 2321 | if failed > 0 { |
| 2322 | anyhow::bail!("{}", tr(locale, MessageId::ModelsUpdatePartial)); |
| 2323 | } |
| 2324 | return Ok(()); |
| 2325 | } |
| 2326 | let identity = &identities[0]; |
| 2327 | let mut route_config = config.clone(); |
| 2328 | route_config |
| 2329 | .scope_to_provider_identity(identity) |
| 2330 | .map_err(anyhow::Error::msg)?; |
| 2331 | let models = listed_models_for_route(&route_config, identity); |
| 2332 | let default_model = route_config.default_model(); |
| 2333 | if json { |
| 2334 | let chatgpt_roster = (identity.provider == ProviderKind::OpenaiCodex) |
| 2335 | .then(|| codex_model_cache::model_roster_for(&route_config)); |
| 2336 | let rows: Vec<_> = models |
| 2337 | .iter() |
| 2338 | .map(|id| { |
| 2339 | let metadata = chatgpt_roster |
| 2340 | .as_ref() |
| 2341 | .and_then(|roster| roster.metadata_for(id)); |
| 2342 | crate::client::AvailableModel { |
| 2343 | id: id.clone(), |
| 2344 | display_name: metadata.and_then(|model| model.display_name.clone()), |
| 2345 | owned_by: None, |
| 2346 | created: None, |
| 2347 | context_window: metadata.and_then(|model| model.context_window), |
| 2348 | effective_context_window_percent: None, |
| 2349 | reasoning: metadata.and_then(|model| model.reasoning), |
| 2350 | efforts: metadata |
| 2351 | .map(|model| model.efforts.clone()) |
| 2352 | .unwrap_or_default(), |
| 2353 | } |
| 2354 | }) |
| 2355 | .collect(); |
| 2356 | println!("{}", serde_json::to_string_pretty(&rows)?); |
| 2357 | } else { |
| 2358 | println!( |
| 2359 | "{}", |
| 2360 | tr(locale, MessageId::ModelsListHeader) |
| 2361 | .replace("{provider}", identity.key.as_str()) |
| 2362 | .replace("{model}", &default_model) |
| 2363 | ); |
| 2364 | let receipt = if identity.provider == ProviderKind::OpenaiCodex { |
| 2365 | codex_receipt(&route_config, identity) |
| 2366 | } else { |
| 2367 | roster_receipt(&route_config, identity, models.len()) |
| 2368 | }; |
| 2369 | let now_secs = codewhale_config::catalog::now_unix(); |
| 2370 | let freshness = |
| 2371 | format_receipt_freshness_fields(receipt.fetched_at, receipt.observed_at, now_secs); |
| 2372 | println!( |
| 2373 | "source={}\tstatus={}\t{}", |
| 2374 | receipt.source, |
| 2375 | serde_json::to_string(&receipt.status)?, |
| 2376 | freshness, |
| 2377 | ); |
| 2378 | if receipt.model_count == 0 { |
| 2379 | println!("{}", tr(locale, MessageId::ModelsSourceFallback)); |
| 2380 | } |
| 2381 | for model in models { |
| 2382 | println!("{} {model}", if model == default_model { "*" } else { " " }); |
| 2383 | } |
| 2384 | println!("{}", tr(locale, MessageId::ModelsListHint)); |
| 2385 | } |
| 2386 | Ok(()) |
| 2387 | } |
| 2388 | |
| 2389 | fn format_epoch_freshness(epoch_secs: u64, now_secs: u64) -> String { |
| 2390 | let utc = i64::try_from(epoch_secs) |
| 2391 | .ok() |
| 2392 | .and_then(|secs| chrono::DateTime::from_timestamp(secs, 0)) |
| 2393 | .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string()) |
| 2394 | .unwrap_or_else(|| epoch_secs.to_string()); |
| 2395 | let age = if now_secs >= epoch_secs { |
| 2396 | let diff = now_secs - epoch_secs; |
| 2397 | if diff < 60 { |
| 2398 | format!("{diff}s ago") |
| 2399 | } else if diff < 3600 { |
| 2400 | format!("{}m ago", diff / 60) |
| 2401 | } else if diff < 86_400 { |
| 2402 | format!("{}h ago", diff / 3600) |
| 2403 | } else { |
| 2404 | format!("{}d ago", diff / 86_400) |
| 2405 | } |
| 2406 | } else { |
| 2407 | "in future".to_string() |
| 2408 | }; |
| 2409 | format!("{utc} ({age})") |
| 2410 | } |
| 2411 | |
| 2412 | fn format_receipt_freshness_fields( |
| 2413 | fetched_at: Option<u64>, |
| 2414 | observed_at: Option<u64>, |
| 2415 | now_secs: u64, |
| 2416 | ) -> String { |
| 2417 | let mut parts = Vec::new(); |
| 2418 | match fetched_at { |
| 2419 | Some(ts) => parts.push(format!( |
| 2420 | "fetched_at={}", |
| 2421 | format_epoch_freshness(ts, now_secs) |
| 2422 | )), |
| 2423 | None => parts.push("fetched_at=unknown".to_string()), |
| 2424 | } |
| 2425 | if let Some(ts) = observed_at { |
| 2426 | parts.push(format!( |
| 2427 | "observed_at={}", |
| 2428 | format_epoch_freshness(ts, now_secs) |
| 2429 | )); |
| 2430 | } |
| 2431 | parts.join("\t") |
| 2432 | } |
| 2433 | |
| 2434 | // ============================================================================ |
| 2435 | // Provider Capability Matrix |
| 2436 | // ============================================================================ |
| 2437 | |
| 2438 | /// Known capabilities for a provider + resolved-model combination. |
| 2439 | /// |
| 2440 | /// Returned by [`provider_capability`] to describe what a given provider |
| 2441 | /// supports for the resolved model string. All fields are derived from |
| 2442 | /// static knowledge (release docs, API guides) rather than live API probes. |
| 2443 | #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)] |
| 2444 | pub struct ProviderCapability { |
| 2445 | /// Canonical provider identifier. |
| 2446 | pub provider: ProviderKind, |
| 2447 | /// Resolved model identifier that will be sent in the API payload. |
| 2448 | pub resolved_model: String, |
| 2449 | /// Context window in tokens (the maximum input the model can accept). |
| 2450 | pub context_window: u32, |
| 2451 | /// Known output ceiling for this provider/model metadata path, when one is |
| 2452 | /// actually known. |
| 2453 | /// |
| 2454 | /// `None` means "this route publishes no output maximum we can stand |
| 2455 | /// behind" — for example the Kimi Code membership ids, whose limits live in |
| 2456 | /// the membership catalog rather than the static model catalogue. Unknown |
| 2457 | /// must stay unknown: callers may **not** substitute a placeholder ceiling, |
| 2458 | /// and in particular [`crate::route_budget`] does not clamp a requested |
| 2459 | /// `max_tokens` against an unknown compatibility cap. |
| 2460 | /// |
| 2461 | /// When `Some`, the value is a documented exact-route maximum or a |
| 2462 | /// deliberately conservative provider ceiling (Anthropic's 64K floor, the |
| 2463 | /// Codex OAuth route). It is metadata for diagnostics and CI policy; normal |
| 2464 | /// turns use a separate, more conservative request cap in the engine. |
| 2465 | #[serde(skip_serializing_if = "Option::is_none")] |
| 2466 | pub max_output: Option<u32>, |
| 2467 | /// Whether the provider+model supports thinking/reasoning mode. |
| 2468 | pub thinking_supported: bool, |
| 2469 | /// Whether the provider returns prompt-cache telemetry fields. |
| 2470 | pub cache_telemetry_supported: bool, |
| 2471 | /// Which request-payload dialect the provider uses. |
| 2472 | pub request_payload_mode: RequestPayloadMode, |
| 2473 | /// Deprecation metadata for compatibility aliases that are still accepted. |
| 2474 | #[serde(skip_serializing_if = "Option::is_none")] |
| 2475 | pub alias_deprecation: Option<codewhale_runtime::config::ModelAliasDeprecation>, |
| 2476 | } |
| 2477 | |
| 2478 | /// Which request-payload dialect the provider speaks. |
| 2479 | #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq)] |
| 2480 | pub enum RequestPayloadMode { |
| 2481 | /// Standard OpenAI-compatible `/v1/chat/completions` payload. |
| 2482 | ChatCompletions, |
| 2483 | /// OpenAI Responses API payload. |
| 2484 | Responses, |
| 2485 | /// Native Anthropic Messages API `/v1/messages` payload (#3014). |
| 2486 | AnthropicMessages, |
| 2487 | GenerateContent, |
| 2488 | } |
| 2489 | |
| 2490 | /// Resolve the provider capability for a given [`ProviderKind`] and resolved |
| 2491 | /// model string. |
| 2492 | /// |
| 2493 | /// The `resolved_model` should be the final model identifier that will appear |
| 2494 | /// in the API payload (after normalization / provider-specific mapping). |
| 2495 | #[must_use] |
| 2496 | pub fn provider_capability(provider: ProviderKind, resolved_model: &str) -> ProviderCapability { |
| 2497 | provider_capability_with_wire(provider, resolved_model, None) |
| 2498 | } |
| 2499 | |
| 2500 | const fn payload_mode_for_wire( |
| 2501 | format: codewhale_config::provider::WireFormat, |
| 2502 | ) -> RequestPayloadMode { |
| 2503 | match format { |
| 2504 | codewhale_config::provider::WireFormat::ChatCompletions => { |
| 2505 | RequestPayloadMode::ChatCompletions |
| 2506 | } |
| 2507 | codewhale_config::provider::WireFormat::Responses => RequestPayloadMode::Responses, |
| 2508 | codewhale_config::provider::WireFormat::AnthropicMessages => { |
| 2509 | RequestPayloadMode::AnthropicMessages |
| 2510 | } |
| 2511 | codewhale_config::provider::WireFormat::GenerateContent => { |
| 2512 | RequestPayloadMode::GenerateContent |
| 2513 | } |
| 2514 | } |
| 2515 | } |
| 2516 | |
| 2517 | pub(crate) fn provider_uses_anthropic_messages_floor(provider: ProviderKind) -> bool { |
| 2518 | let descriptor = codewhale_config::route::ProviderDescriptor::for_kind(provider); |
| 2519 | descriptor.wire_policy() |
| 2520 | == codewhale_config::provider::WirePolicy::Fixed( |
| 2521 | codewhale_config::provider::WireFormat::AnthropicMessages, |
| 2522 | ) |
| 2523 | && matches!(descriptor.family(), "anthropic" | "minimax" | "openmodel") |
| 2524 | } |
| 2525 | |
| 2526 | fn prioritized_catalog_limit( |
| 2527 | offering: Option<&CatalogOffering>, |
| 2528 | field: &str, |
| 2529 | catalog_value: Option<u32>, |
| 2530 | route_value: Option<u32>, |
| 2531 | intrinsic_value: Option<u32>, |
| 2532 | ) -> Option<u32> { |
| 2533 | match offering.map(|row| row.fact_source(field)) { |
| 2534 | Some(CatalogSource::Bundled) | None => intrinsic_value.or(route_value).or(catalog_value), |
| 2535 | Some(CatalogSource::ModelsDevLive { .. }) => { |
| 2536 | intrinsic_value.or(catalog_value).or(route_value) |
| 2537 | } |
| 2538 | Some(_) => catalog_value.or(route_value).or(intrinsic_value), |
| 2539 | } |
| 2540 | } |
| 2541 | |
| 2542 | pub(crate) fn catalog_max_output_for_route(provider: ProviderKind, model: &str) -> Option<u32> { |
| 2543 | let resolved = codewhale_config::route::resolve_model(provider, model, None) |
| 2544 | .ok() |
| 2545 | .filter(|row| !row.is_auto); |
| 2546 | let wire_id = resolved |
| 2547 | .as_ref() |
| 2548 | .map_or_else(|| model.trim(), |row| row.wire_id.as_str()); |
| 2549 | let logical = resolved.as_ref().map(|row| row.logical.as_str()); |
| 2550 | let canonical = resolved |
| 2551 | .as_ref() |
| 2552 | .and_then(|row| row.model.as_ref()) |
| 2553 | .map(|id| id.as_str()); |
| 2554 | let route_offering = resolved.as_ref().and_then(|row| row.offering.as_ref()); |
| 2555 | let catalog_offering = catalog_offering_for_model(provider, wire_id); |
| 2556 | let catalog_output = catalog_offering |
| 2557 | .as_ref() |
| 2558 | .and_then(|offering| offering.limit.as_ref()) |
| 2559 | .and_then(|limit| limit.output) |
| 2560 | .and_then(|limit| u32::try_from(limit).ok()); |
| 2561 | let route_output = route_offering |
| 2562 | .and_then(|offering| offering.limits.output_tokens) |
| 2563 | .and_then(|limit| u32::try_from(limit).ok()); |
| 2564 | let intrinsic_output = codewhale_models::max_output_tokens_for_model(wire_id) |
| 2565 | .or_else(|| logical.and_then(codewhale_models::max_output_tokens_for_model)) |
| 2566 | .or_else(|| canonical.and_then(codewhale_models::max_output_tokens_for_model)); |
| 2567 | |
| 2568 | prioritized_catalog_limit( |
| 2569 | catalog_offering.as_ref(), |
| 2570 | "limit.output", |
| 2571 | catalog_output, |
| 2572 | route_output, |
| 2573 | intrinsic_output, |
| 2574 | ) |
| 2575 | } |
| 2576 | |
| 2577 | #[must_use] |
| 2578 | pub fn provider_capability_with_wire( |
| 2579 | provider: ProviderKind, |
| 2580 | resolved_model: &str, |
| 2581 | wire: Option<&str>, |
| 2582 | ) -> ProviderCapability { |
| 2583 | let descriptor = codewhale_config::route::ProviderDescriptor::for_kind(provider); |
| 2584 | let resolved = codewhale_config::route::resolve_model(provider, resolved_model, None) |
| 2585 | .ok() |
| 2586 | .filter(|row| !row.is_auto); |
| 2587 | let wire_id = resolved |
| 2588 | .as_ref() |
| 2589 | .map_or_else(|| resolved_model.trim(), |row| row.wire_id.as_str()); |
| 2590 | let logical = resolved.as_ref().map(|row| row.logical.as_str()); |
| 2591 | let canonical = resolved |
| 2592 | .as_ref() |
| 2593 | .and_then(|row| row.model.as_ref()) |
| 2594 | .map(|id| id.as_str()); |
| 2595 | let route_offering = resolved.as_ref().and_then(|row| row.offering.as_ref()); |
| 2596 | let catalog_offering = catalog_offering_for_model(provider, wire_id); |
| 2597 | |
| 2598 | let request_payload_mode = if provider == ProviderKind::Custom { |
| 2599 | if codewhale_config::provider::wire_dialect_prefers_anthropic(wire) { |
| 2600 | RequestPayloadMode::AnthropicMessages |
| 2601 | } else if codewhale_config::provider::wire_dialect_prefers_responses(wire) { |
| 2602 | RequestPayloadMode::Responses |
| 2603 | } else if codewhale_config::provider::wire_dialect_prefers_generate_content(wire) { |
| 2604 | RequestPayloadMode::GenerateContent |
| 2605 | } else { |
| 2606 | RequestPayloadMode::ChatCompletions |
| 2607 | } |
| 2608 | } else { |
| 2609 | match descriptor.wire_policy() { |
| 2610 | codewhale_config::provider::WirePolicy::Fixed(format) => payload_mode_for_wire(format), |
| 2611 | codewhale_config::provider::WirePolicy::ModelAware => { |
| 2612 | let endpoint_key = route_offering |
| 2613 | .map(|offering| offering.endpoint_key.as_str()) |
| 2614 | .or_else(|| { |
| 2615 | catalog_offering |
| 2616 | .as_ref() |
| 2617 | .map(|offering| offering.endpoint_key.as_str()) |
| 2618 | }) |
| 2619 | .or_else(|| { |
| 2620 | (provider == ProviderKind::Codewhale).then(|| { |
| 2621 | codewhale_config::route::codewhale_endpoint_key_for_model(wire_id) |
| 2622 | }) |
| 2623 | }) |
| 2624 | .or_else(|| { |
| 2625 | (provider == ProviderKind::OpencodeZen |
| 2626 | && wire_id.to_ascii_lowercase().contains("muse-spark")) |
| 2627 | .then_some("responses") |
| 2628 | }); |
| 2629 | endpoint_key |
| 2630 | .and_then(|key| descriptor.protocol_for_endpoint(key)) |
| 2631 | .map_or(RequestPayloadMode::ChatCompletions, payload_mode_for_wire) |
| 2632 | } |
| 2633 | } |
| 2634 | }; |
| 2635 | |
| 2636 | if provider == ProviderKind::OpenaiCodex { |
| 2637 | return ProviderCapability { |
| 2638 | provider, |
| 2639 | resolved_model: resolved_model.to_string(), |
| 2640 | context_window: codewhale_runtime::config::OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS, |
| 2641 | max_output: Some(4096), |
| 2642 | thinking_supported: true, |
| 2643 | cache_telemetry_supported: false, |
| 2644 | request_payload_mode, |
| 2645 | alias_deprecation: None, |
| 2646 | }; |
| 2647 | } |
| 2648 | |
| 2649 | let model_lower = resolved_model.to_ascii_lowercase(); |
| 2650 | let alias_deprecation = if descriptor.family() == "deepseek" { |
| 2651 | codewhale_runtime::config::deepseek_alias_deprecation(&model_lower) |
| 2652 | } else { |
| 2653 | None |
| 2654 | }; |
| 2655 | |
| 2656 | let anthropic_floor = provider_uses_anthropic_messages_floor(provider); |
| 2657 | let intrinsic_window = |candidate: &str| { |
| 2658 | codewhale_models::context_window_for_model(candidate) |
| 2659 | .filter(|_| codewhale_models::name_suffix_context_window_hint(candidate).is_none()) |
| 2660 | }; |
| 2661 | let context_window = if provider == ProviderKind::Ollama { |
| 2662 | route_offering |
| 2663 | .and_then(|offering| offering.limits.context_tokens) |
| 2664 | .and_then(|window| u32::try_from(window).ok()) |
| 2665 | .or_else(|| { |
| 2666 | catalog_offering |
| 2667 | .as_ref() |
| 2668 | .and_then(|offering| offering.limit.as_ref()) |
| 2669 | .and_then(|limit| limit.context.or(limit.input)) |
| 2670 | .and_then(|window| u32::try_from(window).ok()) |
| 2671 | }) |
| 2672 | .unwrap_or(8192) |
| 2673 | } else { |
| 2674 | let catalog_context = catalog_offering |
| 2675 | .as_ref() |
| 2676 | .and_then(|offering| offering.limit.as_ref()) |
| 2677 | .and_then(|limit| limit.context.or(limit.input)) |
| 2678 | .and_then(|window| u32::try_from(window).ok()); |
| 2679 | let route_context = route_offering |
| 2680 | .and_then(|offering| offering.limits.context_tokens) |
| 2681 | .and_then(|window| u32::try_from(window).ok()); |
| 2682 | let intrinsic = intrinsic_window(wire_id) |
| 2683 | .or_else(|| logical.and_then(intrinsic_window)) |
| 2684 | .or_else(|| canonical.and_then(intrinsic_window)); |
| 2685 | let prioritized = prioritized_catalog_limit( |
| 2686 | catalog_offering.as_ref(), |
| 2687 | "limit.context", |
| 2688 | catalog_context, |
| 2689 | route_context, |
| 2690 | intrinsic, |
| 2691 | ); |
| 2692 | prioritized |
| 2693 | .or_else(|| codewhale_models::name_suffix_context_window_hint(wire_id)) |
| 2694 | .unwrap_or(if anthropic_floor { |
| 2695 | 200_000 |
| 2696 | } else { |
| 2697 | codewhale_models::LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS |
| 2698 | }) |
| 2699 | }; |
| 2700 | |
| 2701 | let max_output = catalog_max_output_for_route(provider, resolved_model) |
| 2702 | .or_else(|| anthropic_floor.then_some(64_000)); |
| 2703 | |
| 2704 | let thinking_supported = route_offering |
| 2705 | .is_some_and(|offering| offering.capabilities.reasoning.is_supported()) |
| 2706 | || catalog_offering |
| 2707 | .as_ref() |
| 2708 | .is_some_and(|offering| offering.reasoning == Some(true)) |
| 2709 | || codewhale_config::catalog::reviewed::selection_supports_reasoning( |
| 2710 | provider.as_str(), |
| 2711 | wire_id, |
| 2712 | ) |
| 2713 | || logical.is_some_and(|id| { |
| 2714 | codewhale_config::catalog::reviewed::selection_supports_reasoning(provider.as_str(), id) |
| 2715 | }) |
| 2716 | || codewhale_models::model_supports_reasoning(wire_id) |
| 2717 | || logical.is_some_and(codewhale_models::model_supports_reasoning) |
| 2718 | || canonical.is_some_and(codewhale_models::model_supports_reasoning); |
| 2719 | |
| 2720 | let cache_telemetry_supported = catalog_offering |
| 2721 | .as_ref() |
| 2722 | .and_then(|offering| offering.cost.as_ref()) |
| 2723 | .is_some_and(|cost| cost.cache_read.is_some()) |
| 2724 | || matches!( |
| 2725 | provider, |
| 2726 | ProviderKind::Anthropic |
| 2727 | | ProviderKind::Deepseek |
| 2728 | | ProviderKind::NvidiaNim |
| 2729 | | ProviderKind::Volcengine |
| 2730 | | ProviderKind::Openai |
| 2731 | | ProviderKind::OpenaiCodex |
| 2732 | | ProviderKind::Google |
| 2733 | | ProviderKind::Moonshot |
| 2734 | | ProviderKind::Zai |
| 2735 | | ProviderKind::Stepfun |
| 2736 | | ProviderKind::Minimax |
| 2737 | | ProviderKind::XiaomiMimo |
| 2738 | | ProviderKind::Xai |
| 2739 | | ProviderKind::Openrouter |
| 2740 | | ProviderKind::Orcarouter |
| 2741 | ); |
| 2742 | |
| 2743 | ProviderCapability { |
| 2744 | provider, |
| 2745 | resolved_model: resolved_model.to_string(), |
| 2746 | context_window, |
| 2747 | max_output, |
| 2748 | thinking_supported, |
| 2749 | cache_telemetry_supported, |
| 2750 | request_payload_mode, |
| 2751 | alias_deprecation, |
| 2752 | } |
| 2753 | } |
| 2754 | |
| 2755 | #[cfg(test)] |
| 2756 | mod tests { |
| 2757 | use super::*; |
| 2758 | use codewhale_config::catalog::CatalogSource; |
| 2759 | use codewhale_config::descriptors::defaults::{ |
| 2760 | DEFAULT_TOGETHER_FLASH_MODEL, DEFAULT_TOGETHER_MODEL, |
| 2761 | }; |
| 2762 | |
| 2763 | #[test] |
| 2764 | fn wire_model_lookup_is_exact_first_and_never_guesses_between_case_variants() { |
| 2765 | let row = |id: &str| CatalogOffering { |
| 2766 | provider: "p".to_string(), |
| 2767 | wire_model_id: id.to_string(), |
| 2768 | ..Default::default() |
| 2769 | }; |
| 2770 | let rows = vec![row("org/Model-A"), row("org/model-a"), row("org/Model-B")]; |
| 2771 | let found = |
| 2772 | |needle: &str| find_wire_model(&rows, needle).map(|row| row.wire_model_id.clone()); |
| 2773 | assert_eq!(found("org/model-a").as_deref(), Some("org/model-a")); |
| 2774 | assert_eq!(found("org/Model-A").as_deref(), Some("org/Model-A")); |
| 2775 | assert_eq!(found("ORG/MODEL-A"), None, "two distinct ids fold together"); |
| 2776 | assert_eq!(found("org/model-b").as_deref(), Some("org/Model-B")); |
| 2777 | |
| 2778 | // Listing keeps both case variants: each is a distinct, pickable id. |
| 2779 | let listed = catalog_models_from_offerings(rows.iter()); |
| 2780 | assert!( |
| 2781 | listed.contains(&"org/Model-A".to_string()) |
| 2782 | && listed.contains(&"org/model-a".to_string()), |
| 2783 | "case variants of a wire id are distinct models: {listed:?}" |
| 2784 | ); |
| 2785 | } |
| 2786 | |
| 2787 | fn catalog_test_config(first_url: &str, second_url: &str) -> Config { |
| 2788 | use codewhale_runtime::config::{ProviderConfig, ProvidersConfig}; |
| 2789 | { |
| 2790 | let __cw_config_init_0_0 = Some("catalog-first".to_string()); |
| 2791 | let __cw_config_init_0_1 = Some(ProvidersConfig { |
| 2792 | custom: [ |
| 2793 | ("catalog-first", first_url, "first-route-test-key"), |
| 2794 | ("catalog-second", second_url, "second-route-test-key"), |
| 2795 | ] |
| 2796 | .into_iter() |
| 2797 | .map(|(name, base_url, key)| { |
| 2798 | ( |
| 2799 | name.to_string(), |
| 2800 | ProviderConfig { |
| 2801 | kind: Some("openai-compatible".to_string()), |
| 2802 | base_url: Some(base_url.to_string()), |
| 2803 | api_key: Some(key.to_string()), |
| 2804 | model: Some("saved-model".to_string()), |
| 2805 | ..Default::default() |
| 2806 | }, |
| 2807 | ) |
| 2808 | }) |
| 2809 | .collect(), |
| 2810 | ..Default::default() |
| 2811 | }); |
| 2812 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 2813 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 2814 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 2815 | __cw_config_init_0_value |
| 2816 | } |
| 2817 | } |
| 2818 | |
| 2819 | async fn catalog_mock( |
| 2820 | server: &wiremock::MockServer, |
| 2821 | key: &str, |
| 2822 | status: u16, |
| 2823 | body: serde_json::Value, |
| 2824 | ) { |
| 2825 | use wiremock::matchers::{header, method, path}; |
| 2826 | wiremock::Mock::given(method("GET")) |
| 2827 | .and(path("/v1/models")) |
| 2828 | .and(header("Authorization", format!("Bearer {key}"))) |
| 2829 | .respond_with(wiremock::ResponseTemplate::new(status).set_body_json(body)) |
| 2830 | .expect(1) |
| 2831 | .mount(server) |
| 2832 | .await; |
| 2833 | } |
| 2834 | |
| 2835 | #[tokio::test] |
| 2836 | async fn models_update_refuses_credentials_changed_during_request() { |
| 2837 | let _env = crate::test_support::lock_test_env(); |
| 2838 | let home = tempfile::tempdir().unwrap(); |
| 2839 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2840 | let _cli = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2841 | let _key = |
| 2842 | crate::test_support::EnvVarGuard::set("CWC_CATALOG_TEST_KEY", "first-route-test-key"); |
| 2843 | let upstream = wiremock::MockServer::start().await; |
| 2844 | let mut config = catalog_test_config(&upstream.uri(), &upstream.uri()); |
| 2845 | let entry = config |
| 2846 | .providers |
| 2847 | .as_mut() |
| 2848 | .unwrap() |
| 2849 | .custom |
| 2850 | .get_mut("catalog-first") |
| 2851 | .unwrap(); |
| 2852 | entry.api_key = None; |
| 2853 | entry.api_key_env = Some("CWC_CATALOG_TEST_KEY".into()); |
| 2854 | let identity = config.resolve_provider_identity("catalog-first").unwrap(); |
| 2855 | crate::provider_catalog_live::reset_cache_for_test(); |
| 2856 | wiremock::Mock::given(wiremock::matchers::method("GET")) |
| 2857 | .respond_with( |
| 2858 | wiremock::ResponseTemplate::new(200) |
| 2859 | .set_delay(std::time::Duration::from_millis(100)) |
| 2860 | .set_body_json( |
| 2861 | serde_json::json!({"data":[{"id":"old-account-private-model"}]}), |
| 2862 | ), |
| 2863 | ) |
| 2864 | .expect(1) |
| 2865 | .mount(&upstream) |
| 2866 | .await; |
| 2867 | let change = async { |
| 2868 | tokio::time::timeout(std::time::Duration::from_secs(2), async { |
| 2869 | while upstream.received_requests().await.unwrap().is_empty() { |
| 2870 | tokio::task::yield_now().await; |
| 2871 | } |
| 2872 | }) |
| 2873 | .await |
| 2874 | .unwrap(); |
| 2875 | // This guard stays alive until after the delayed refresh completes. |
| 2876 | crate::test_support::EnvVarGuard::set("CWC_CATALOG_TEST_KEY", "other-account-test-key") |
| 2877 | }; |
| 2878 | let (receipt, _changed) = tokio::join!(update_provider_catalog(&config, &identity), change); |
| 2879 | assert_eq!(receipt.outcome, "skipped"); |
| 2880 | assert_eq!(receipt.error, Some("refresh_credentials_changed")); |
| 2881 | assert!( |
| 2882 | crate::provider_catalog_live::cached_entry_for_route( |
| 2883 | ProviderKind::Custom, |
| 2884 | identity.key.as_str(), |
| 2885 | &upstream.uri() |
| 2886 | ) |
| 2887 | .unwrap() |
| 2888 | .is_none() |
| 2889 | ); |
| 2890 | } |
| 2891 | |
| 2892 | #[tokio::test] |
| 2893 | async fn models_update_persists_exact_routes_and_keeps_prior_rows_after_failure() { |
| 2894 | let _env = crate::test_support::lock_test_env(); |
| 2895 | let _live = lock_live_snapshot(); |
| 2896 | let home = tempfile::tempdir().unwrap(); |
| 2897 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2898 | crate::provider_catalog_live::reset_cache_for_test(); |
| 2899 | let _cli_key = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2900 | let first = wiremock::MockServer::start().await; |
| 2901 | let second = wiremock::MockServer::start().await; |
| 2902 | let mut config = catalog_test_config(&first.uri(), &second.uri()); |
| 2903 | let first_id = config.resolve_provider_identity("catalog-first").unwrap(); |
| 2904 | let second_id = config.resolve_provider_identity("catalog-second").unwrap(); |
| 2905 | let second_route = config.provider_config_for_mut(&second_id).unwrap(); |
| 2906 | second_route.api_key = None; |
| 2907 | second_route.auth_mode = Some("none".into()); |
| 2908 | catalog_mock( |
| 2909 | &first, |
| 2910 | "first-route-test-key", |
| 2911 | 200, |
| 2912 | serde_json::json!({"data":[{"id":"new-first-model"}]}), |
| 2913 | ) |
| 2914 | .await; |
| 2915 | wiremock::Mock::given(wiremock::matchers::method("GET")) |
| 2916 | .and(wiremock::matchers::path("/v1/models")) |
| 2917 | .respond_with( |
| 2918 | wiremock::ResponseTemplate::new(200) |
| 2919 | .set_body_json(serde_json::json!({"data":[{"id":"new-second-model"}]})), |
| 2920 | ) |
| 2921 | .expect(1) |
| 2922 | .mount(&second) |
| 2923 | .await; |
| 2924 | assert_eq!( |
| 2925 | update_provider_catalog(&config, &first_id).await.outcome, |
| 2926 | "updated" |
| 2927 | ); |
| 2928 | assert_eq!( |
| 2929 | update_provider_catalog(&config, &second_id).await.outcome, |
| 2930 | "updated" |
| 2931 | ); |
| 2932 | assert_eq!(config.provider.as_deref(), Some("catalog-first")); |
| 2933 | assert_eq!(config.default_model(), "saved-model"); |
| 2934 | let anonymous_requests = second.received_requests().await.unwrap(); |
| 2935 | assert_eq!(anonymous_requests.len(), 1); |
| 2936 | assert!(!anonymous_requests[0].headers.contains_key("authorization")); |
| 2937 | assert_eq!( |
| 2938 | catalog_models_for_route(ProviderKind::Custom, "catalog-first", &first.uri()), |
| 2939 | ["new-first-model"] |
| 2940 | ); |
| 2941 | assert_eq!( |
| 2942 | catalog_models_for_route(ProviderKind::Custom, "catalog-second", &second.uri()), |
| 2943 | ["new-second-model"] |
| 2944 | ); |
| 2945 | assert!( |
| 2946 | catalog_models_for_route(ProviderKind::Custom, "catalog-first", &second.uri()) |
| 2947 | .is_empty() |
| 2948 | ); |
| 2949 | let prior = cached_receipt(&config, &first_id).fetched_at; |
| 2950 | assert!(prior.is_some()); |
| 2951 | first.reset().await; |
| 2952 | catalog_mock( |
| 2953 | &first, |
| 2954 | "first-route-test-key", |
| 2955 | 401, |
| 2956 | serde_json::json!({"error":"first-route-test-key"}), |
| 2957 | ) |
| 2958 | .await; |
| 2959 | let receipt = update_provider_catalog(&config, &first_id).await; |
| 2960 | assert_eq!(receipt.outcome, "failed"); |
| 2961 | assert_eq!(receipt.fetched_at, prior); |
| 2962 | assert!(matches!( |
| 2963 | receipt.status, |
| 2964 | CatalogStatus::Failed { |
| 2965 | reason: codewhale_config::catalog::CatalogRefreshError::Unauthorized |
| 2966 | } |
| 2967 | )); |
| 2968 | assert_eq!( |
| 2969 | catalog_models_for_route(ProviderKind::Custom, "catalog-first", &first.uri()), |
| 2970 | ["new-first-model"] |
| 2971 | ); |
| 2972 | let body = |
| 2973 | std::fs::read_to_string(crate::provider_catalog_live::cache_path().unwrap()).unwrap(); |
| 2974 | assert!(body.contains("new-second-model")); |
| 2975 | assert!(!body.contains("new-first-model")); |
| 2976 | assert!(!body.contains("first-route-test-key")); |
| 2977 | assert!(!body.contains(&first.uri())); |
| 2978 | assert!(!body.contains(&second.uri())); |
| 2979 | crate::provider_catalog_live::reset_cache_for_test(); |
| 2980 | clear_live_snapshot(); |
| 2981 | assert!( |
| 2982 | catalog_models_for_route(ProviderKind::Custom, "catalog-first", &first.uri()) |
| 2983 | .is_empty() |
| 2984 | ); |
| 2985 | assert!( |
| 2986 | catalog_models_for_route(ProviderKind::Custom, "catalog-first", &second.uri()) |
| 2987 | .is_empty() |
| 2988 | ); |
| 2989 | assert_eq!( |
| 2990 | catalog_models_for_route(ProviderKind::Custom, "catalog-second", &second.uri()), |
| 2991 | ["new-second-model"] |
| 2992 | ); |
| 2993 | assert!( |
| 2994 | !serde_json::to_string(&receipt) |
| 2995 | .unwrap() |
| 2996 | .contains("first-route-test-key") |
| 2997 | ); |
| 2998 | } |
| 2999 | |
| 3000 | #[tokio::test] |
| 3001 | async fn models_update_removes_withdrawn_ids_and_rejects_secret_or_control_ids() { |
| 3002 | let _env = crate::test_support::lock_test_env(); |
| 3003 | let home = tempfile::tempdir().unwrap(); |
| 3004 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3005 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3006 | let _cli_key = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 3007 | let server = wiremock::MockServer::start().await; |
| 3008 | let config = catalog_test_config(&server.uri(), &server.uri()); |
| 3009 | let identity = config.resolve_provider_identity("catalog-first").unwrap(); |
| 3010 | for model in [ |
| 3011 | "old-model", |
| 3012 | "new-model", |
| 3013 | "first-route-test-key", |
| 3014 | "bad\u{1b}[31m-model", |
| 3015 | ] { |
| 3016 | server.reset().await; |
| 3017 | catalog_mock( |
| 3018 | &server, |
| 3019 | "first-route-test-key", |
| 3020 | 200, |
| 3021 | serde_json::json!({"data":[{"id": model}]}), |
| 3022 | ) |
| 3023 | .await; |
| 3024 | let receipt = update_provider_catalog(&config, &identity).await; |
| 3025 | if model.starts_with("old-") || model.starts_with("new-") { |
| 3026 | assert_eq!(receipt.outcome, "updated"); |
| 3027 | assert_eq!( |
| 3028 | catalog_models_for_route( |
| 3029 | ProviderKind::Custom, |
| 3030 | identity.key.as_str(), |
| 3031 | &server.uri() |
| 3032 | ), |
| 3033 | [model] |
| 3034 | ); |
| 3035 | } else { |
| 3036 | assert_eq!(receipt.outcome, "failed"); |
| 3037 | assert_eq!( |
| 3038 | catalog_models_for_route( |
| 3039 | ProviderKind::Custom, |
| 3040 | identity.key.as_str(), |
| 3041 | &server.uri() |
| 3042 | ), |
| 3043 | ["new-model"] |
| 3044 | ); |
| 3045 | } |
| 3046 | } |
| 3047 | server.reset().await; |
| 3048 | catalog_mock( |
| 3049 | &server, |
| 3050 | "first-route-test-key", |
| 3051 | 200, |
| 3052 | serde_json::json!({"data":[]}), |
| 3053 | ) |
| 3054 | .await; |
| 3055 | let receipt = update_provider_catalog(&config, &identity).await; |
| 3056 | assert_eq!(receipt.outcome, "updated"); |
| 3057 | assert_eq!(receipt.status, CatalogStatus::Fresh); |
| 3058 | assert_eq!(receipt.model_count, 0); |
| 3059 | assert!( |
| 3060 | catalog_models_for_route(ProviderKind::Custom, identity.key.as_str(), &server.uri()) |
| 3061 | .is_empty() |
| 3062 | ); |
| 3063 | } |
| 3064 | |
| 3065 | #[tokio::test] |
| 3066 | async fn chatgpt_catalog_refresh_rejects_unregistered_legacy_credentials() { |
| 3067 | let _env = crate::test_support::lock_test_env(); |
| 3068 | let _token = crate::test_support::EnvVarGuard::set("CODEX_ACCESS_TOKEN", "legacy-token"); |
| 3069 | let config = { |
| 3070 | let __cw_config_init_1_0 = Some("openai-codex".to_string()); |
| 3071 | let mut __cw_config_init_1_value: Config = Default::default(); |
| 3072 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 3073 | __cw_config_init_1_value |
| 3074 | }; |
| 3075 | let identity = config.resolve_provider_identity("openai-codex").unwrap(); |
| 3076 | let receipt = update_provider_catalog(&config, &identity).await; |
| 3077 | assert_eq!(receipt.outcome, "failed"); |
| 3078 | assert_eq!(receipt.error, Some("chatgpt_plan_permission_required")); |
| 3079 | assert_eq!(receipt.model_count, 0); |
| 3080 | } |
| 3081 | |
| 3082 | #[test] |
| 3083 | fn codex_live_roster_receipt_discloses_skipped_persistence() { |
| 3084 | let identity = Config::default() |
| 3085 | .resolve_provider_identity("openai-codex") |
| 3086 | .unwrap(); |
| 3087 | let roster = codewhale_runtime::codex_model_roster::CodexModelRoster { |
| 3088 | models: Vec::new(), |
| 3089 | freshness: codewhale_runtime::codex_model_roster::CodexModelCacheFreshness::Fresh, |
| 3090 | fetched_at: None, |
| 3091 | observed_at: Some(chrono::Utc::now()), |
| 3092 | source: "chatgpt_plan_api", |
| 3093 | observation_persisted: false, |
| 3094 | }; |
| 3095 | let receipt = codex_roster_receipt(&identity, &roster); |
| 3096 | assert_eq!(receipt.status, CatalogStatus::Fresh); |
| 3097 | assert_eq!(receipt.error, Some("chatgpt_catalog_not_persisted")); |
| 3098 | assert_eq!(receipt.fetched_at, None); |
| 3099 | assert!(receipt.observed_at.is_some()); |
| 3100 | } |
| 3101 | |
| 3102 | #[tokio::test] |
| 3103 | async fn models_listing_is_offline_and_update_never_forwards_another_routes_cli_key() { |
| 3104 | let _env = crate::test_support::lock_test_env(); |
| 3105 | let home = tempfile::tempdir().unwrap(); |
| 3106 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3107 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3108 | let _source = |
| 3109 | crate::test_support::EnvVarGuard::set(codewhale_config::CLI_API_KEY_SOURCE_ENV, "cli"); |
| 3110 | let _key = crate::test_support::EnvVarGuard::set( |
| 3111 | codewhale_config::CLI_API_KEY_ENV, |
| 3112 | "active-route-cli-key", |
| 3113 | ); |
| 3114 | let server = wiremock::MockServer::start().await; |
| 3115 | let config = catalog_test_config(&server.uri(), &server.uri()); |
| 3116 | run_models(&config, false, Some("catalog-first"), true) |
| 3117 | .await |
| 3118 | .unwrap(); |
| 3119 | let other = config.resolve_provider_identity("catalog-second").unwrap(); |
| 3120 | let receipt = update_provider_catalog(&config, &other).await; |
| 3121 | assert_eq!(receipt.outcome, "skipped"); |
| 3122 | assert_eq!(receipt.error, Some("cli_key_is_scoped_to_active_provider")); |
| 3123 | assert!(server.received_requests().await.unwrap().is_empty()); |
| 3124 | assert!(!crate::provider_catalog_live::cache_path().unwrap().exists()); |
| 3125 | } |
| 3126 | |
| 3127 | #[tokio::test] |
| 3128 | async fn models_update_reports_io_failure_without_claiming_persistence() { |
| 3129 | let _env = crate::test_support::lock_test_env(); |
| 3130 | let home = tempfile::tempdir().unwrap(); |
| 3131 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 3132 | crate::provider_catalog_live::reset_cache_for_test(); |
| 3133 | let _cli_key = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 3134 | let server = wiremock::MockServer::start().await; |
| 3135 | let config = catalog_test_config(&server.uri(), &server.uri()); |
| 3136 | let identity = config.resolve_provider_identity("catalog-first").unwrap(); |
| 3137 | let path = crate::provider_catalog_live::cache_path().unwrap(); |
| 3138 | std::fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 3139 | std::fs::write(&path, b"broken cache").unwrap(); |
| 3140 | let receipt = update_provider_catalog(&config, &identity).await; |
| 3141 | assert_eq!(receipt.outcome, "failed"); |
| 3142 | assert_eq!(receipt.error, Some("cache_read_failed")); |
| 3143 | assert_eq!(std::fs::read(&path).unwrap(), b"broken cache"); |
| 3144 | assert!(server.received_requests().await.unwrap().is_empty()); |
| 3145 | } |
| 3146 | |
| 3147 | #[test] |
| 3148 | fn models_update_scope_includes_every_named_identity_once() { |
| 3149 | let _env = crate::test_support::lock_test_env(); |
| 3150 | let config = catalog_test_config("http://localhost:1", "http://localhost:2"); |
| 3151 | let identities = catalog_identities(&config, None, true).unwrap(); |
| 3152 | for name in ["catalog-first", "catalog-second"] { |
| 3153 | assert_eq!( |
| 3154 | identities |
| 3155 | .iter() |
| 3156 | .filter(|identity| identity.key.as_str() == name) |
| 3157 | .count(), |
| 3158 | 1 |
| 3159 | ); |
| 3160 | } |
| 3161 | assert_eq!( |
| 3162 | catalog_identities(&config, Some("catalog-second"), true) |
| 3163 | .unwrap() |
| 3164 | .len(), |
| 3165 | 1 |
| 3166 | ); |
| 3167 | } |
| 3168 | |
| 3169 | #[test] |
| 3170 | fn together_catalog_includes_flash_from_bundled_asset() { |
| 3171 | let _live = lock_live_snapshot(); |
| 3172 | clear_live_snapshot(); |
| 3173 | let models = all_catalog_models_for_provider(ProviderKind::Together); |
| 3174 | assert!( |
| 3175 | models.contains(&DEFAULT_TOGETHER_MODEL.to_string()), |
| 3176 | "missing Together pro: {models:?}" |
| 3177 | ); |
| 3178 | assert!( |
| 3179 | models.contains(&DEFAULT_TOGETHER_FLASH_MODEL.to_string()), |
| 3180 | "missing Together flash: {models:?}" |
| 3181 | ); |
| 3182 | } |
| 3183 | |
| 3184 | #[test] |
| 3185 | fn configured_providers_matches_provider_predicate() { |
| 3186 | let _env_lock = crate::test_support::lock_test_env(); |
| 3187 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 3188 | let _auth_file = crate::test_support::EnvVarGuard::set( |
| 3189 | "OPENAI_CODEX_AUTH_FILE", |
| 3190 | tmp.path().join("missing-auth.json"), |
| 3191 | ); |
| 3192 | let _openai_token = crate::test_support::EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN"); |
| 3193 | let _codex_token = crate::test_support::EnvVarGuard::remove("CODEX_ACCESS_TOKEN"); |
| 3194 | let config = Config::default(); |
| 3195 | let active = config.active_provider_identity().unwrap(); |
| 3196 | let expected: Vec<_> = config |
| 3197 | .provider_identities() |
| 3198 | .into_iter() |
| 3199 | .filter(|identity| { |
| 3200 | crate::provider_readiness::provider_is_configured_for_active( |
| 3201 | &config, identity, &active, |
| 3202 | ) |
| 3203 | }) |
| 3204 | .collect(); |
| 3205 | assert_eq!(configured_providers(&config), expected); |
| 3206 | } |
| 3207 | |
| 3208 | #[test] |
| 3209 | fn models_for_provider_filters_unconfigured_gateways() { |
| 3210 | let _env_lock = crate::test_support::lock_test_env(); |
| 3211 | let _together = crate::test_support::EnvVarGuard::remove("TOGETHER_API_KEY"); |
| 3212 | let config = Config::default(); |
| 3213 | assert!( |
| 3214 | models_for_provider( |
| 3215 | &config, |
| 3216 | &config.test_identity_for_kind(ProviderKind::Together) |
| 3217 | ) |
| 3218 | .is_empty() |
| 3219 | ); |
| 3220 | assert!( |
| 3221 | !models_for_provider( |
| 3222 | &config, |
| 3223 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 3224 | ) |
| 3225 | .is_empty() |
| 3226 | ); |
| 3227 | } |
| 3228 | |
| 3229 | /// #4116 CRITICAL (no-narrowing guarantee for the migrated consumer): the |
| 3230 | /// catalog-backed facade must return a NON-EMPTY enumeration for every |
| 3231 | /// provider that has a non-empty legacy `model_completion_names_for_provider` |
| 3232 | /// table. `all_catalog_models_for_provider` falls back to that legacy table |
| 3233 | /// whenever the merged catalog has no rows for the provider, so this holds by |
| 3234 | /// construction — and it proves that the raw-legacy tail removed from the |
| 3235 | /// subagent `operator_model_for_subagent` consumer (which only ran when the |
| 3236 | /// facade was empty) was unreachable whenever legacy was non-empty. The |
| 3237 | /// migrated consumer is therefore behavior-preserving: it always has a |
| 3238 | /// catalog-sourced model to pick and never narrows to fewer choices than the |
| 3239 | /// legacy path offered. |
| 3240 | /// |
| 3241 | /// Note: the facade is intentionally *catalog-authoritative* (live > |
| 3242 | /// bundled > legacy fallback, #4188), so for some providers whose catalog |
| 3243 | /// supersedes stale entries in the legacy placeholder table (e.g. |
| 3244 | /// OpenRouter/MiniMax revisions), the facade is not a strict superset of |
| 3245 | /// every legacy id. That divergence does not affect subagent model |
| 3246 | /// *acceptance*, which is gated by `validate_route` and the route |
| 3247 | /// resolver, not by this list. |
| 3248 | #[test] |
| 3249 | fn catalog_facade_covers_every_provider_with_a_legacy_table() { |
| 3250 | let _env = crate::test_support::lock_test_env(); |
| 3251 | let codex_home = tempfile::tempdir().expect("temporary CODEX_HOME"); |
| 3252 | let _codex_home = crate::test_support::EnvVarGuard::set("CODEX_HOME", codex_home.path()); |
| 3253 | let _live = lock_live_snapshot(); |
| 3254 | clear_live_snapshot(); |
| 3255 | for &provider in ProviderKind::all() { |
| 3256 | let legacy_len = model_completion_names_for_provider(provider).len(); |
| 3257 | if legacy_len == 0 || provider == ProviderKind::OpenaiCodex { |
| 3258 | continue; |
| 3259 | } |
| 3260 | assert!( |
| 3261 | !all_catalog_models_for_provider(provider).is_empty(), |
| 3262 | "catalog facade returned no models for {provider:?} despite a \ |
| 3263 | non-empty legacy table ({legacy_len} entries): the operator-route \ |
| 3264 | consumer would have nothing to enumerate" |
| 3265 | ); |
| 3266 | } |
| 3267 | } |
| 3268 | |
| 3269 | /// #4188: CodeWhale-only / local providers keep defaults via the legacy |
| 3270 | /// fallback when Models.dev (live or bundled) has no rows for them. |
| 3271 | #[test] |
| 3272 | fn codewhale_only_providers_keep_legacy_defaults() { |
| 3273 | let _env = crate::test_support::lock_test_env(); |
| 3274 | let codex_home = tempfile::tempdir().expect("temporary CODEX_HOME"); |
| 3275 | let _codex_home = crate::test_support::EnvVarGuard::set("CODEX_HOME", codex_home.path()); |
| 3276 | let _live = lock_live_snapshot(); |
| 3277 | clear_live_snapshot(); |
| 3278 | // A public model table cannot attest account plan permission. |
| 3279 | assert!(all_catalog_models_for_provider(ProviderKind::OpenaiCodex).is_empty()); |
| 3280 | |
| 3281 | // Ollama intentionally has an empty legacy table (user-supplied ids); |
| 3282 | // the lake must still return empty rather than inventing rows. |
| 3283 | assert!(all_catalog_models_for_provider(ProviderKind::Ollama).is_empty()); |
| 3284 | assert!(model_completion_names_for_provider(ProviderKind::Ollama).is_empty()); |
| 3285 | assert!(live_per_provider_models(ProviderKind::Ollama).is_empty()); |
| 3286 | } |
| 3287 | |
| 3288 | #[test] |
| 3289 | fn ollama_live_default_uses_per_provider_tags_not_models_dev() { |
| 3290 | let _live = lock_live_snapshot(); |
| 3291 | clear_live_snapshot(); |
| 3292 | |
| 3293 | set_live_snapshot( |
| 3294 | CatalogSnapshot { |
| 3295 | offerings: vec![CatalogOffering { |
| 3296 | provider: "ollama".to_string(), |
| 3297 | wire_model_id: "deepseek-v4-flash".to_string(), |
| 3298 | endpoint_key: "chat".to_string(), |
| 3299 | default_for_provider: true, |
| 3300 | ..Default::default() |
| 3301 | }], |
| 3302 | }, |
| 3303 | LiveSource::ModelsDev, |
| 3304 | ); |
| 3305 | assert!( |
| 3306 | live_per_provider_models(ProviderKind::Ollama).is_empty(), |
| 3307 | "Models.dev must not satisfy a local Ollama default" |
| 3308 | ); |
| 3309 | |
| 3310 | merge_live_offerings(vec![CatalogOffering { |
| 3311 | provider: "ollama".to_string(), |
| 3312 | wire_model_id: "qwen2.5:0.5b".to_string(), |
| 3313 | endpoint_key: "chat".to_string(), |
| 3314 | default_for_provider: true, |
| 3315 | ..Default::default() |
| 3316 | }]); |
| 3317 | assert_eq!( |
| 3318 | live_per_provider_models(ProviderKind::Ollama), |
| 3319 | vec!["qwen2.5:0.5b".to_string()] |
| 3320 | ); |
| 3321 | clear_live_snapshot(); |
| 3322 | } |
| 3323 | |
| 3324 | /// #4116 / #4188 (AC): a provider with no bundled/live catalog coverage must |
| 3325 | /// fall back to the legacy table verbatim, so CodeWhale-only routes stay |
| 3326 | /// usable. We assert this for every currently-unbundled provider that still |
| 3327 | /// carries a non-empty legacy list, and require at least one such provider |
| 3328 | /// to exist so the fallback path is actually exercised. |
| 3329 | #[test] |
| 3330 | fn unbundled_provider_falls_back_to_legacy_table() { |
| 3331 | let _live = lock_live_snapshot(); |
| 3332 | clear_live_snapshot(); |
| 3333 | let merged = merged_snapshot(); |
| 3334 | let mut exercised = 0usize; |
| 3335 | for &provider in ProviderKind::all() { |
| 3336 | // OpenAI Codex deliberately owns an account-scoped cache source; |
| 3337 | // its fallback behavior is covered separately above. |
| 3338 | if provider == ProviderKind::OpenaiCodex { |
| 3339 | continue; |
| 3340 | } |
| 3341 | let catalog_id = catalog_provider_id(provider); |
| 3342 | let has_catalog_rows = !merged.offerings_for_provider(catalog_id).is_empty(); |
| 3343 | let legacy = model_completion_names_for_provider(provider); |
| 3344 | if has_catalog_rows || legacy.is_empty() { |
| 3345 | continue; |
| 3346 | } |
| 3347 | // Unbundled + non-empty legacy: the facade must echo the legacy list. |
| 3348 | let facade = all_catalog_models_for_provider(provider); |
| 3349 | let expected: Vec<String> = legacy.iter().map(|m| m.to_string()).collect(); |
| 3350 | assert_eq!( |
| 3351 | facade, expected, |
| 3352 | "unbundled provider {provider:?} did not fall back to the legacy table" |
| 3353 | ); |
| 3354 | exercised += 1; |
| 3355 | } |
| 3356 | assert!( |
| 3357 | exercised > 0, |
| 3358 | "expected at least one unbundled provider to exercise the legacy fallback path" |
| 3359 | ); |
| 3360 | } |
| 3361 | |
| 3362 | /// #4188: live Models.dev rows win over bundled on identity, and clearing |
| 3363 | /// live restores the offline bundled snapshot (offline startup still works). |
| 3364 | #[test] |
| 3365 | fn live_snapshot_merges_over_bundled() { |
| 3366 | let _live = lock_live_snapshot(); |
| 3367 | clear_live_snapshot(); |
| 3368 | // With no live snapshot, we get bundled models. |
| 3369 | let bundled = all_catalog_models_for_provider(ProviderKind::Deepseek); |
| 3370 | assert!(!bundled.is_empty()); |
| 3371 | |
| 3372 | // Set a live snapshot that adds a synthetic model. |
| 3373 | let live = CatalogSnapshot { |
| 3374 | offerings: vec![CatalogOffering { |
| 3375 | provider: "deepseek".to_string(), |
| 3376 | wire_model_id: "deepseek-v4-synthetic".to_string(), |
| 3377 | endpoint_key: "chat".to_string(), |
| 3378 | ..Default::default() |
| 3379 | }], |
| 3380 | }; |
| 3381 | set_live_snapshot(live, LiveSource::ModelsDev); |
| 3382 | let merged = all_catalog_models_for_provider(ProviderKind::Deepseek); |
| 3383 | assert!(merged.contains(&"deepseek-v4-synthetic".to_string())); |
| 3384 | // The bundled model is still present. |
| 3385 | assert!(merged.iter().any(|m| bundled.contains(m))); |
| 3386 | |
| 3387 | clear_live_snapshot(); |
| 3388 | let after_clear = all_catalog_models_for_provider(ProviderKind::Deepseek); |
| 3389 | assert_eq!(after_clear, bundled); |
| 3390 | } |
| 3391 | |
| 3392 | #[test] |
| 3393 | fn provider_owned_roster_replaces_bundled_and_models_dev_rows() { |
| 3394 | let _live = lock_live_snapshot(); |
| 3395 | clear_live_snapshot(); |
| 3396 | let bundled = all_catalog_models_for_provider(ProviderKind::Openrouter); |
| 3397 | assert!( |
| 3398 | !bundled.is_empty(), |
| 3399 | "OpenRouter must have an offline fallback roster" |
| 3400 | ); |
| 3401 | |
| 3402 | set_live_snapshot( |
| 3403 | CatalogSnapshot { |
| 3404 | offerings: vec![CatalogOffering { |
| 3405 | provider: "openrouter".to_string(), |
| 3406 | wire_model_id: "models-dev-only-openrouter-model".to_string(), |
| 3407 | endpoint_key: "chat".to_string(), |
| 3408 | ..Default::default() |
| 3409 | }], |
| 3410 | }, |
| 3411 | LiveSource::ModelsDev, |
| 3412 | ); |
| 3413 | set_live_snapshot( |
| 3414 | CatalogSnapshot { |
| 3415 | offerings: vec![CatalogOffering { |
| 3416 | provider: "openrouter".to_string(), |
| 3417 | wire_model_id: "provider-owned-openrouter-model".to_string(), |
| 3418 | endpoint_key: "chat".to_string(), |
| 3419 | ..Default::default() |
| 3420 | }], |
| 3421 | }, |
| 3422 | LiveSource::PerProvider, |
| 3423 | ); |
| 3424 | |
| 3425 | assert_eq!( |
| 3426 | all_catalog_models_for_provider(ProviderKind::Openrouter), |
| 3427 | vec!["provider-owned-openrouter-model".to_string()], |
| 3428 | "a successful provider-owned refresh must remove stale bundled and Models.dev ids" |
| 3429 | ); |
| 3430 | |
| 3431 | replace_provider_live_snapshot("openrouter", CatalogSnapshot::default()); |
| 3432 | let restored_cross_provider = all_catalog_models_for_provider(ProviderKind::Openrouter); |
| 3433 | assert!( |
| 3434 | restored_cross_provider.contains(&"models-dev-only-openrouter-model".to_string()), |
| 3435 | "clearing the exact partition must restore the cross-provider fallback" |
| 3436 | ); |
| 3437 | assert!( |
| 3438 | restored_cross_provider |
| 3439 | .iter() |
| 3440 | .any(|model| bundled.contains(model)), |
| 3441 | "clearing the exact partition must restore bundled fallbacks" |
| 3442 | ); |
| 3443 | |
| 3444 | clear_live_snapshot(); |
| 3445 | assert_eq!( |
| 3446 | all_catalog_models_for_provider(ProviderKind::Openrouter), |
| 3447 | bundled |
| 3448 | ); |
| 3449 | } |
| 3450 | |
| 3451 | #[test] |
| 3452 | fn named_custom_catalogs_keep_exact_identity_without_compiled_seeds() { |
| 3453 | let _live = lock_live_snapshot(); |
| 3454 | clear_live_snapshot(); |
| 3455 | |
| 3456 | // No live rows, no bundled rows, no configured rows: an ordinary |
| 3457 | // custom route offers nothing rather than a compiled default (#6289). |
| 3458 | for identity in ["baseten", "another-custom-host"] { |
| 3459 | assert!( |
| 3460 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some(identity)) |
| 3461 | .is_empty(), |
| 3462 | "{identity} must not invent models offline" |
| 3463 | ); |
| 3464 | } |
| 3465 | |
| 3466 | set_live_snapshot( |
| 3467 | CatalogSnapshot { |
| 3468 | offerings: vec![CatalogOffering { |
| 3469 | provider: "baseten".to_string(), |
| 3470 | wire_model_id: "synthetic-live-baseten-model".to_string(), |
| 3471 | endpoint_key: "chat".to_string(), |
| 3472 | source: CatalogSource::Live { |
| 3473 | base_url_fingerprint: "baseten-fp".to_string(), |
| 3474 | fetched_at: 42, |
| 3475 | }, |
| 3476 | ..Default::default() |
| 3477 | }], |
| 3478 | }, |
| 3479 | LiveSource::PerProvider, |
| 3480 | ); |
| 3481 | |
| 3482 | assert_eq!( |
| 3483 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("baseten")), |
| 3484 | vec!["synthetic-live-baseten-model".to_string()] |
| 3485 | ); |
| 3486 | let case_distinct = |
| 3487 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("BASETEN")); |
| 3488 | assert!( |
| 3489 | case_distinct.is_empty(), |
| 3490 | "a case variant shares neither seeds nor another exact table's live roster" |
| 3491 | ); |
| 3492 | assert!( |
| 3493 | catalog_offering_for_model_identity( |
| 3494 | ProviderKind::Custom, |
| 3495 | Some("baseten"), |
| 3496 | "synthetic-live-baseten-model", |
| 3497 | ) |
| 3498 | .is_some() |
| 3499 | ); |
| 3500 | assert!( |
| 3501 | catalog_offering_for_model(ProviderKind::Custom, "synthetic-live-baseten-model",) |
| 3502 | .is_none(), |
| 3503 | "the generic custom bucket must not see Baseten rows" |
| 3504 | ); |
| 3505 | |
| 3506 | clear_live_snapshot(); |
| 3507 | } |
| 3508 | |
| 3509 | #[test] |
| 3510 | fn case_colliding_and_builtin_named_custom_catalogs_stay_isolated() { |
| 3511 | let _live = lock_live_snapshot(); |
| 3512 | clear_live_snapshot(); |
| 3513 | |
| 3514 | for (provider, model) in [("CustomA", "upper-model"), ("customa", "lower-model")] { |
| 3515 | replace_provider_live_snapshot( |
| 3516 | provider, |
| 3517 | CatalogSnapshot { |
| 3518 | offerings: vec![CatalogOffering { |
| 3519 | provider: provider.to_string(), |
| 3520 | wire_model_id: model.to_string(), |
| 3521 | endpoint_key: "chat".to_string(), |
| 3522 | ..Default::default() |
| 3523 | }], |
| 3524 | }, |
| 3525 | ); |
| 3526 | } |
| 3527 | |
| 3528 | assert_eq!( |
| 3529 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("CustomA")), |
| 3530 | vec!["upper-model".to_string()] |
| 3531 | ); |
| 3532 | assert_eq!( |
| 3533 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("customa")), |
| 3534 | vec!["lower-model".to_string()] |
| 3535 | ); |
| 3536 | let built_in_openai = all_catalog_models_for_provider(ProviderKind::Openai); |
| 3537 | assert!(!built_in_openai.is_empty()); |
| 3538 | assert!( |
| 3539 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("openai")) |
| 3540 | .is_empty(), |
| 3541 | "a custom table named openai must not borrow the first-class OpenAI template" |
| 3542 | ); |
| 3543 | for model in &built_in_openai { |
| 3544 | assert!( |
| 3545 | catalog_offering_for_model_identity(ProviderKind::Custom, Some("openai"), model) |
| 3546 | .is_none(), |
| 3547 | "an exact custom table named openai must not inherit built-in model {model}" |
| 3548 | ); |
| 3549 | } |
| 3550 | |
| 3551 | let custom_model = "custom-openai-only-model"; |
| 3552 | replace_provider_live_snapshot_for_identity( |
| 3553 | ProviderKind::Custom, |
| 3554 | "openai", |
| 3555 | CatalogSnapshot { |
| 3556 | offerings: vec![CatalogOffering { |
| 3557 | provider: "openai".to_string(), |
| 3558 | wire_model_id: custom_model.to_string(), |
| 3559 | endpoint_key: "chat".to_string(), |
| 3560 | ..Default::default() |
| 3561 | }], |
| 3562 | }, |
| 3563 | ); |
| 3564 | assert_eq!( |
| 3565 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("openai")), |
| 3566 | vec![custom_model.to_string()], |
| 3567 | "the exact custom table must retrieve its own built-in-looking roster" |
| 3568 | ); |
| 3569 | assert_eq!( |
| 3570 | all_catalog_models_for_provider(ProviderKind::Openai), |
| 3571 | built_in_openai, |
| 3572 | "publishing custom openai must not replace or suppress built-in OpenAI" |
| 3573 | ); |
| 3574 | assert!( |
| 3575 | catalog_offering_for_model(ProviderKind::Openai, custom_model).is_none(), |
| 3576 | "the built-in OpenAI route must not see the custom table's row" |
| 3577 | ); |
| 3578 | |
| 3579 | let built_in_live_model = "built-in-openai-only-model"; |
| 3580 | replace_provider_live_snapshot_for_identity( |
| 3581 | ProviderKind::Openai, |
| 3582 | "openai", |
| 3583 | CatalogSnapshot { |
| 3584 | offerings: vec![CatalogOffering { |
| 3585 | provider: "openai".to_string(), |
| 3586 | wire_model_id: built_in_live_model.to_string(), |
| 3587 | endpoint_key: "chat".to_string(), |
| 3588 | ..Default::default() |
| 3589 | }], |
| 3590 | }, |
| 3591 | ); |
| 3592 | assert_eq!( |
| 3593 | all_catalog_models_for_provider(ProviderKind::Openai), |
| 3594 | vec![built_in_live_model.to_string()] |
| 3595 | ); |
| 3596 | assert_eq!( |
| 3597 | all_catalog_models_for_provider_identity(ProviderKind::Custom, Some("openai")), |
| 3598 | vec![custom_model.to_string()], |
| 3599 | "publishing built-in OpenAI must not replace the custom table's roster" |
| 3600 | ); |
| 3601 | |
| 3602 | clear_live_snapshot(); |
| 3603 | } |
| 3604 | |
| 3605 | #[test] |
| 3606 | fn live_catalog_origin_prefers_per_provider_over_models_dev() { |
| 3607 | let _live = lock_live_snapshot(); |
| 3608 | clear_live_snapshot(); |
| 3609 | let wire = "accounts/fireworks/models/deepseek-v4-flash-0731"; |
| 3610 | assert_eq!(live_catalog_origin(ProviderKind::Fireworks, wire), None); |
| 3611 | |
| 3612 | set_live_snapshot( |
| 3613 | CatalogSnapshot { |
| 3614 | offerings: vec![CatalogOffering { |
| 3615 | provider: "fireworks".to_string(), |
| 3616 | wire_model_id: wire.to_string(), |
| 3617 | endpoint_key: "chat".to_string(), |
| 3618 | ..Default::default() |
| 3619 | }], |
| 3620 | }, |
| 3621 | LiveSource::ModelsDev, |
| 3622 | ); |
| 3623 | assert_eq!( |
| 3624 | live_catalog_origin(ProviderKind::Fireworks, wire), |
| 3625 | Some(LiveSource::ModelsDev) |
| 3626 | ); |
| 3627 | |
| 3628 | set_live_snapshot( |
| 3629 | CatalogSnapshot { |
| 3630 | offerings: vec![CatalogOffering { |
| 3631 | provider: "fireworks".to_string(), |
| 3632 | wire_model_id: wire.to_string(), |
| 3633 | endpoint_key: "chat".to_string(), |
| 3634 | ..Default::default() |
| 3635 | }], |
| 3636 | }, |
| 3637 | LiveSource::PerProvider, |
| 3638 | ); |
| 3639 | assert_eq!( |
| 3640 | live_catalog_origin(ProviderKind::Fireworks, wire), |
| 3641 | Some(LiveSource::PerProvider) |
| 3642 | ); |
| 3643 | clear_live_snapshot(); |
| 3644 | } |
| 3645 | |
| 3646 | /// Footprint: the merge holds `Arc`s into the bundled and Models.dev |
| 3647 | /// layers, so only rows it rewrites exist twice in memory. |
| 3648 | #[test] |
| 3649 | fn merged_snapshot_shares_rows_with_its_layers_instead_of_copying_them() { |
| 3650 | let _live = lock_live_snapshot(); |
| 3651 | clear_live_snapshot(); |
| 3652 | |
| 3653 | let live_id = "deepseek-shared-row-probe"; |
| 3654 | set_live_snapshot( |
| 3655 | CatalogSnapshot { |
| 3656 | offerings: vec![CatalogOffering { |
| 3657 | provider: "deepseek".to_string(), |
| 3658 | wire_model_id: live_id.to_string(), |
| 3659 | endpoint_key: "chat".to_string(), |
| 3660 | ..Default::default() |
| 3661 | }], |
| 3662 | }, |
| 3663 | LiveSource::ModelsDev, |
| 3664 | ); |
| 3665 | let merged = merged_snapshot(); |
| 3666 | let live_row = { |
| 3667 | let live = LIVE_SNAPSHOT.read().expect("live snapshot"); |
| 3668 | let models_dev = live.models_dev.as_ref().expect("models.dev partition"); |
| 3669 | Arc::clone(&models_dev.offerings[0]) |
| 3670 | }; |
| 3671 | let merged_live_row = merged |
| 3672 | .offerings |
| 3673 | .iter() |
| 3674 | .find(|row| row.wire_model_id == live_id) |
| 3675 | .expect("live row merged"); |
| 3676 | assert!( |
| 3677 | Arc::ptr_eq(merged_live_row, &live_row), |
| 3678 | "the merge must share the Models.dev row, not hold a second copy" |
| 3679 | ); |
| 3680 | |
| 3681 | let bundled = bundled_snapshot(); |
| 3682 | let shared_bundled = merged |
| 3683 | .offerings |
| 3684 | .iter() |
| 3685 | .filter(|row| bundled.offerings.iter().any(|b| Arc::ptr_eq(b, row))) |
| 3686 | .count(); |
| 3687 | let untouched_bundled = bundled |
| 3688 | .offerings |
| 3689 | .iter() |
| 3690 | .filter(|row| { |
| 3691 | ProviderKind::parse(&row.provider) != Some(ProviderKind::OpencodeGo) |
| 3692 | && !(row.provider == "deepseek" && row.wire_model_id == live_id) |
| 3693 | }) |
| 3694 | .count(); |
| 3695 | assert_eq!( |
| 3696 | shared_bundled, untouched_bundled, |
| 3697 | "every bundled row the merge does not rewrite must be shared" |
| 3698 | ); |
| 3699 | |
| 3700 | clear_live_snapshot(); |
| 3701 | } |
| 3702 | |
| 3703 | /// Memoization: repeated `merged_snapshot()` calls return the cached merge |
| 3704 | /// (same `Arc` allocation), and publishing or clearing a live snapshot |
| 3705 | /// invalidates the cache so new content becomes visible. |
| 3706 | #[test] |
| 3707 | fn merged_snapshot_cache_invalidates_on_live_snapshot_change() { |
| 3708 | let _live = lock_live_snapshot(); |
| 3709 | clear_live_snapshot(); |
| 3710 | |
| 3711 | let bundled_only = merged_snapshot(); |
| 3712 | assert!( |
| 3713 | Arc::ptr_eq(&bundled_only, &merged_snapshot()), |
| 3714 | "repeated merged_snapshot() calls must return the cached Arc" |
| 3715 | ); |
| 3716 | let probe = "deepseek-cache-probe-model"; |
| 3717 | assert!( |
| 3718 | !bundled_only |
| 3719 | .offerings |
| 3720 | .iter() |
| 3721 | .any(|row| row.wire_model_id == probe), |
| 3722 | "probe model must not pre-exist in the bundled snapshot" |
| 3723 | ); |
| 3724 | |
| 3725 | set_live_snapshot( |
| 3726 | CatalogSnapshot { |
| 3727 | offerings: vec![CatalogOffering { |
| 3728 | provider: "deepseek".to_string(), |
| 3729 | wire_model_id: probe.to_string(), |
| 3730 | endpoint_key: "chat".to_string(), |
| 3731 | ..Default::default() |
| 3732 | }], |
| 3733 | }, |
| 3734 | LiveSource::ModelsDev, |
| 3735 | ); |
| 3736 | let with_live = merged_snapshot(); |
| 3737 | assert!( |
| 3738 | !Arc::ptr_eq(&bundled_only, &with_live), |
| 3739 | "set_live_snapshot must invalidate the memoized merge" |
| 3740 | ); |
| 3741 | assert!( |
| 3742 | with_live |
| 3743 | .offerings |
| 3744 | .iter() |
| 3745 | .any(|row| row.wire_model_id == probe), |
| 3746 | "new live content must be visible after set_live_snapshot" |
| 3747 | ); |
| 3748 | |
| 3749 | clear_live_snapshot(); |
| 3750 | let after_clear = merged_snapshot(); |
| 3751 | assert!( |
| 3752 | !after_clear |
| 3753 | .offerings |
| 3754 | .iter() |
| 3755 | .any(|row| row.wire_model_id == probe), |
| 3756 | "clear_live_snapshot must invalidate the memoized merge" |
| 3757 | ); |
| 3758 | assert_eq!( |
| 3759 | after_clear.offerings, bundled_only.offerings, |
| 3760 | "clearing live must restore the bundled-only merge content" |
| 3761 | ); |
| 3762 | } |
| 3763 | |
| 3764 | #[test] |
| 3765 | fn official_go_requires_current_account_proof_after_empty_or_denied_refresh() { |
| 3766 | use codewhale_config::catalog::CatalogRefreshError; |
| 3767 | use codewhale_config::route::{LogicalModelRef, RouteRequest}; |
| 3768 | |
| 3769 | let _live = lock_live_snapshot(); |
| 3770 | clear_live_snapshot(); |
| 3771 | let provider = ProviderKind::OpencodeGo; |
| 3772 | let base = "https://opencode.ai/inference/go/v1"; |
| 3773 | let request = RouteRequest { |
| 3774 | explicit_provider: Some(provider), |
| 3775 | model_selector: Some(LogicalModelRef::from(provider.provider().default_model())), |
| 3776 | saved_provider_model: None, |
| 3777 | base_url_override: Some(base.to_string()), |
| 3778 | limit_overrides: Vec::new(), |
| 3779 | wire_override: None, |
| 3780 | responses_profile_override: None, |
| 3781 | }; |
| 3782 | for status in [ |
| 3783 | CatalogStatus::Fresh, |
| 3784 | CatalogStatus::Stale { age_secs: 1 }, |
| 3785 | CatalogStatus::Failed { |
| 3786 | reason: CatalogRefreshError::Forbidden, |
| 3787 | }, |
| 3788 | ] { |
| 3789 | let catalog = runtime_catalog_resolver_for_identity(provider, None, base, status); |
| 3790 | assert!(catalog.resolver.resolve(&request).is_err()); |
| 3791 | } |
| 3792 | } |
| 3793 | |
| 3794 | #[test] |
| 3795 | fn opencode_go_lake_corrects_stale_protocols_in_saved_and_live_rows() { |
| 3796 | let _live = lock_live_snapshot(); |
| 3797 | clear_live_snapshot(); |
| 3798 | |
| 3799 | let mut offerings: Vec<_> = codewhale_config::opencode_go_models() |
| 3800 | .iter() |
| 3801 | .map(|model| CatalogOffering { |
| 3802 | provider: "opencode_go".to_string(), |
| 3803 | wire_model_id: if *model |
| 3804 | == codewhale_config::descriptors::defaults::DEFAULT_OPENCODE_GO_MODEL |
| 3805 | { |
| 3806 | format!("opencode-go/{model}") |
| 3807 | } else { |
| 3808 | (*model).to_string() |
| 3809 | }, |
| 3810 | endpoint_key: "chat".to_string(), |
| 3811 | ..Default::default() |
| 3812 | }) |
| 3813 | .collect(); |
| 3814 | offerings.extend(["minimax-m3", "qwen3.7-max"].map(|model| CatalogOffering { |
| 3815 | provider: "opencode-go".to_string(), |
| 3816 | wire_model_id: model.to_string(), |
| 3817 | endpoint_key: "messages".to_string(), |
| 3818 | ..Default::default() |
| 3819 | })); |
| 3820 | set_live_snapshot(CatalogSnapshot { offerings }, LiveSource::ModelsDev); |
| 3821 | |
| 3822 | let models: std::collections::BTreeSet<_> = |
| 3823 | all_catalog_models_for_provider(ProviderKind::OpencodeGo) |
| 3824 | .into_iter() |
| 3825 | .collect(); |
| 3826 | let expected: std::collections::BTreeSet<_> = codewhale_config::opencode_go_models() |
| 3827 | .iter() |
| 3828 | .map(|model| (*model).to_string()) |
| 3829 | .collect(); |
| 3830 | assert_eq!(models, expected); |
| 3831 | for (model, endpoint) in [("minimax-m3", "messages"), ("grok-4.6", "responses")] { |
| 3832 | let row = catalog_offering_for_model(ProviderKind::OpencodeGo, model) |
| 3833 | .expect("documented model survives refresh"); |
| 3834 | assert_eq!(row.endpoint_key, endpoint); |
| 3835 | } |
| 3836 | assert!( |
| 3837 | catalog_offering_for_model( |
| 3838 | ProviderKind::OpencodeGo, |
| 3839 | codewhale_config::descriptors::defaults::DEFAULT_OPENCODE_GO_MODEL, |
| 3840 | ) |
| 3841 | .is_some() |
| 3842 | ); |
| 3843 | |
| 3844 | clear_live_snapshot(); |
| 3845 | } |
| 3846 | |
| 3847 | /// #4188: live > bundled > legacy fallback precedence, including live |
| 3848 | /// override of a bundled wire id and no duplicate rows after alias |
| 3849 | /// normalization (`moonshotai` → `moonshot`). |
| 3850 | #[test] |
| 3851 | fn live_over_bundled_over_legacy_precedence_and_alias_dedupe() { |
| 3852 | let _live = lock_live_snapshot(); |
| 3853 | clear_live_snapshot(); |
| 3854 | |
| 3855 | let bundled_moonshot = all_catalog_models_for_provider(ProviderKind::Moonshot); |
| 3856 | assert!( |
| 3857 | !bundled_moonshot.is_empty(), |
| 3858 | "offline bundled Moonshot seed required: {bundled_moonshot:?}" |
| 3859 | ); |
| 3860 | |
| 3861 | // Live rows use the Models.dev alias id; lake merge must normalize onto |
| 3862 | // CodeWhale `moonshot` and not leave a parallel `moonshotai` bucket. |
| 3863 | let live = CatalogSnapshot { |
| 3864 | offerings: vec![ |
| 3865 | CatalogOffering { |
| 3866 | provider: "moonshot".to_string(), |
| 3867 | wire_model_id: "kimi-k2.5-live".to_string(), |
| 3868 | endpoint_key: "chat".to_string(), |
| 3869 | default_for_provider: true, |
| 3870 | ..Default::default() |
| 3871 | }, |
| 3872 | // Same identity as a typical bundled Moonshot default — live wins. |
| 3873 | CatalogOffering { |
| 3874 | provider: "moonshot".to_string(), |
| 3875 | wire_model_id: bundled_moonshot[0].clone(), |
| 3876 | endpoint_key: "chat".to_string(), |
| 3877 | family: Some("live-override".to_string()), |
| 3878 | ..Default::default() |
| 3879 | }, |
| 3880 | ], |
| 3881 | }; |
| 3882 | set_live_snapshot(live, LiveSource::ModelsDev); |
| 3883 | |
| 3884 | let merged = merged_snapshot(); |
| 3885 | let moonshot_rows = merged.offerings_for_provider("moonshot"); |
| 3886 | assert!( |
| 3887 | moonshot_rows |
| 3888 | .iter() |
| 3889 | .any(|r| r.wire_model_id == "kimi-k2.5-live"), |
| 3890 | "live-only Moonshot row missing: {moonshot_rows:?}" |
| 3891 | ); |
| 3892 | let overridden = moonshot_rows |
| 3893 | .iter() |
| 3894 | .find(|r| r.wire_model_id == bundled_moonshot[0]) |
| 3895 | .expect("bundled Moonshot id should still exist after live merge"); |
| 3896 | assert_eq!( |
| 3897 | overridden.family.as_deref(), |
| 3898 | Some("live-override"), |
| 3899 | "live row must replace bundled facts on the same wire id" |
| 3900 | ); |
| 3901 | assert!( |
| 3902 | merged.offerings_for_provider("moonshotai").is_empty(), |
| 3903 | "alias-normalized providers must not leave a duplicate moonshotai bucket" |
| 3904 | ); |
| 3905 | |
| 3906 | let models = all_catalog_models_for_provider(ProviderKind::Moonshot); |
| 3907 | let mut seen = std::collections::BTreeSet::new(); |
| 3908 | for model in &models { |
| 3909 | assert!( |
| 3910 | seen.insert(model.to_ascii_lowercase()), |
| 3911 | "duplicate Moonshot model row after alias merge: {model}" |
| 3912 | ); |
| 3913 | } |
| 3914 | assert!(models.contains(&"kimi-k2.5-live".to_string())); |
| 3915 | |
| 3916 | // Legacy fallback is skipped when catalog rows exist (even if legacy |
| 3917 | // lists additional ids) — catalog is authoritative once non-empty. |
| 3918 | assert!( |
| 3919 | !model_completion_names_for_provider(ProviderKind::Moonshot).is_empty(), |
| 3920 | "legacy Moonshot table should still exist as fallback documentation" |
| 3921 | ); |
| 3922 | |
| 3923 | clear_live_snapshot(); |
| 3924 | assert_eq!( |
| 3925 | all_catalog_models_for_provider(ProviderKind::Moonshot), |
| 3926 | bundled_moonshot, |
| 3927 | "clearing live must restore offline bundled Moonshot rows" |
| 3928 | ); |
| 3929 | } |
| 3930 | |
| 3931 | /// #4188: when live Models.dev emits both an alias id and the CodeWhale id |
| 3932 | /// for the same provider, compiling through `live_offerings_from_models_dev` |
| 3933 | /// then merging into the lake must not produce duplicate model rows. |
| 3934 | #[test] |
| 3935 | fn alias_normalized_live_rows_do_not_duplicate_in_lake() { |
| 3936 | let _live = lock_live_snapshot(); |
| 3937 | clear_live_snapshot(); |
| 3938 | let body = r#"{ |
| 3939 | "models": {}, |
| 3940 | "providers": { |
| 3941 | "moonshotai": { |
| 3942 | "id": "moonshotai", |
| 3943 | "models": { |
| 3944 | "kimi-k2.5": { |
| 3945 | "id": "kimi-k2.5", |
| 3946 | "modalities": { "input": ["text"], "output": ["text"] } |
| 3947 | } |
| 3948 | } |
| 3949 | }, |
| 3950 | "moonshot": { |
| 3951 | "id": "moonshot", |
| 3952 | "models": { |
| 3953 | "kimi-k2.5": { |
| 3954 | "id": "kimi-k2.5", |
| 3955 | "modalities": { "input": ["text"], "output": ["text"] }, |
| 3956 | "limit": { "context": 262144, "output": 8192 } |
| 3957 | }, |
| 3958 | "kimi-k2.7-code": { |
| 3959 | "id": "kimi-k2.7-code", |
| 3960 | "modalities": { "input": ["text"], "output": ["text"] } |
| 3961 | } |
| 3962 | } |
| 3963 | } |
| 3964 | } |
| 3965 | }"#; |
| 3966 | let catalog = |
| 3967 | codewhale_config::models_dev::ModelsDevCatalog::parse_json(body).expect("parse"); |
| 3968 | let live_rows = |
| 3969 | codewhale_config::catalog::live_offerings_from_models_dev(&catalog, 1_700_000_000); |
| 3970 | assert!( |
| 3971 | live_rows.iter().all(|r| r.provider == "moonshot"), |
| 3972 | "both moonshotai and moonshot must normalize onto moonshot: {:?}", |
| 3973 | live_rows |
| 3974 | .iter() |
| 3975 | .map(|r| r.provider.as_str()) |
| 3976 | .collect::<Vec<_>>() |
| 3977 | ); |
| 3978 | set_live_snapshot( |
| 3979 | CatalogSnapshot { |
| 3980 | offerings: live_rows, |
| 3981 | }, |
| 3982 | LiveSource::ModelsDev, |
| 3983 | ); |
| 3984 | |
| 3985 | let models = all_catalog_models_for_provider(ProviderKind::Moonshot); |
| 3986 | let kimi_count = models.iter().filter(|m| m.as_str() == "kimi-k2.5").count(); |
| 3987 | assert_eq!( |
| 3988 | kimi_count, 1, |
| 3989 | "alias-normalized providers must not duplicate kimi-k2.5: {models:?}" |
| 3990 | ); |
| 3991 | assert!( |
| 3992 | merged_snapshot() |
| 3993 | .offerings_for_provider("moonshotai") |
| 3994 | .is_empty() |
| 3995 | ); |
| 3996 | clear_live_snapshot(); |
| 3997 | } |
| 3998 | |
| 3999 | // ── Source-scoped partition tests (#4188 race fix) ────────────────────── |
| 4000 | |
| 4001 | #[test] |
| 4002 | fn provider_live_snapshots_are_scoped_per_provider() { |
| 4003 | let _live = lock_live_snapshot(); |
| 4004 | clear_live_snapshot(); |
| 4005 | |
| 4006 | set_live_snapshot( |
| 4007 | CatalogSnapshot { |
| 4008 | offerings: vec![CatalogOffering { |
| 4009 | provider: "telecomjs".to_string(), |
| 4010 | wire_model_id: "deepseek-v4-pro".to_string(), |
| 4011 | endpoint_key: "chat".to_string(), |
| 4012 | ..Default::default() |
| 4013 | }], |
| 4014 | }, |
| 4015 | LiveSource::PerProvider, |
| 4016 | ); |
| 4017 | let telecom_only = merged_snapshot(); |
| 4018 | assert_eq!(telecom_only.offerings_for_provider("telecomjs").len(), 1); |
| 4019 | |
| 4020 | set_live_snapshot( |
| 4021 | CatalogSnapshot { |
| 4022 | offerings: vec![CatalogOffering { |
| 4023 | provider: "another-gateway".to_string(), |
| 4024 | wire_model_id: "another-model".to_string(), |
| 4025 | endpoint_key: "chat".to_string(), |
| 4026 | ..Default::default() |
| 4027 | }], |
| 4028 | }, |
| 4029 | LiveSource::PerProvider, |
| 4030 | ); |
| 4031 | |
| 4032 | let merged = merged_snapshot(); |
| 4033 | assert_eq!(merged.offerings_for_provider("telecomjs").len(), 1); |
| 4034 | assert_eq!(merged.offerings_for_provider("another-gateway").len(), 1); |
| 4035 | assert!( |
| 4036 | !Arc::ptr_eq(&telecom_only, &merged), |
| 4037 | "publishing a second provider must invalidate the cached merge" |
| 4038 | ); |
| 4039 | |
| 4040 | clear_live_snapshot(); |
| 4041 | } |
| 4042 | |
| 4043 | /// Models.dev→TelecomJS completion order: Models.dev sets its snapshot first, |
| 4044 | /// then TelecomJS merges per-provider rows. Both sets must be present in the |
| 4045 | /// final merged view. |
| 4046 | #[test] |
| 4047 | fn models_dev_first_then_telecomjs_both_preserved() { |
| 4048 | let _live = lock_live_snapshot(); |
| 4049 | clear_live_snapshot(); |
| 4050 | |
| 4051 | // 1) Models.dev publishes its cross-provider snapshot. |
| 4052 | let models_dev_rows = vec![ |
| 4053 | CatalogOffering { |
| 4054 | provider: "deepseek".to_string(), |
| 4055 | wire_model_id: "deepseek-chat".to_string(), |
| 4056 | endpoint_key: "chat".to_string(), |
| 4057 | family: Some("deepseek".to_string()), |
| 4058 | source: CatalogSource::Live { |
| 4059 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4060 | fetched_at: 1000, |
| 4061 | }, |
| 4062 | ..Default::default() |
| 4063 | }, |
| 4064 | CatalogOffering { |
| 4065 | provider: "zai".to_string(), |
| 4066 | wire_model_id: "glm-4".to_string(), |
| 4067 | endpoint_key: "chat".to_string(), |
| 4068 | family: Some("glm".to_string()), |
| 4069 | source: CatalogSource::Live { |
| 4070 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4071 | fetched_at: 1000, |
| 4072 | }, |
| 4073 | ..Default::default() |
| 4074 | }, |
| 4075 | ]; |
| 4076 | set_live_snapshot( |
| 4077 | CatalogSnapshot { |
| 4078 | offerings: models_dev_rows, |
| 4079 | }, |
| 4080 | LiveSource::ModelsDev, |
| 4081 | ); |
| 4082 | let before_provider_refresh = merged_snapshot(); |
| 4083 | assert!( |
| 4084 | before_provider_refresh |
| 4085 | .offerings_for_provider("telecomjs") |
| 4086 | .is_empty() |
| 4087 | ); |
| 4088 | |
| 4089 | // 2) TelecomJS merges its per-provider rows (after Models.dev completes). |
| 4090 | let telecomjs_rows = vec![ |
| 4091 | CatalogOffering { |
| 4092 | provider: "telecomjs".to_string(), |
| 4093 | wire_model_id: "deepseek-chat".to_string(), |
| 4094 | endpoint_key: "chat".to_string(), |
| 4095 | family: Some("deepseek".to_string()), |
| 4096 | source: CatalogSource::Live { |
| 4097 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4098 | fetched_at: 2000, |
| 4099 | }, |
| 4100 | ..Default::default() |
| 4101 | }, |
| 4102 | CatalogOffering { |
| 4103 | provider: "telecomjs".to_string(), |
| 4104 | wire_model_id: "glm-4".to_string(), |
| 4105 | endpoint_key: "chat".to_string(), |
| 4106 | family: Some("glm".to_string()), |
| 4107 | source: CatalogSource::Live { |
| 4108 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4109 | fetched_at: 2000, |
| 4110 | }, |
| 4111 | ..Default::default() |
| 4112 | }, |
| 4113 | ]; |
| 4114 | merge_live_offerings(telecomjs_rows); |
| 4115 | assert_eq!( |
| 4116 | merged_snapshot().offerings_for_provider("telecomjs").len(), |
| 4117 | 2, |
| 4118 | "provider refresh should invalidate the cached Models.dev-only view" |
| 4119 | ); |
| 4120 | |
| 4121 | // 3) Both sources' rows are present in the merged snapshot. |
| 4122 | let merged = merged_snapshot(); |
| 4123 | let deepseek_rows = merged.offerings_for_provider("deepseek"); |
| 4124 | assert!( |
| 4125 | deepseek_rows |
| 4126 | .iter() |
| 4127 | .any(|r| r.wire_model_id == "deepseek-chat"), |
| 4128 | "Models.dev deepseek row missing: {deepseek_rows:?}" |
| 4129 | ); |
| 4130 | let zai_rows = merged.offerings_for_provider("zai"); |
| 4131 | assert!( |
| 4132 | zai_rows.iter().any(|r| r.wire_model_id == "glm-4"), |
| 4133 | "Models.dev zai row missing: {zai_rows:?}" |
| 4134 | ); |
| 4135 | let telecomjs_rows_merged = merged.offerings_for_provider("telecomjs"); |
| 4136 | assert_eq!( |
| 4137 | telecomjs_rows_merged.len(), |
| 4138 | 2, |
| 4139 | "TelecomJS rows missing: {telecomjs_rows_merged:?}" |
| 4140 | ); |
| 4141 | assert!( |
| 4142 | telecomjs_rows_merged |
| 4143 | .iter() |
| 4144 | .any(|r| r.wire_model_id == "deepseek-chat"), |
| 4145 | "TelecomJS deepseek-chat row missing" |
| 4146 | ); |
| 4147 | assert!( |
| 4148 | telecomjs_rows_merged |
| 4149 | .iter() |
| 4150 | .any(|r| r.wire_model_id == "glm-4"), |
| 4151 | "TelecomJS glm-4 row missing" |
| 4152 | ); |
| 4153 | |
| 4154 | clear_live_snapshot(); |
| 4155 | } |
| 4156 | |
| 4157 | /// TelecomJS→Models.dev completion order: TelecomJS merges first, then |
| 4158 | /// Models.dev replaces the cross-provider snapshot. TelecomJS rows must |
| 4159 | /// survive the Models.dev refresh (they live in a separate partition). |
| 4160 | #[test] |
| 4161 | fn telecomjs_first_then_models_dev_both_preserved() { |
| 4162 | let _live = lock_live_snapshot(); |
| 4163 | clear_live_snapshot(); |
| 4164 | |
| 4165 | // 1) TelecomJS merges its per-provider rows first. |
| 4166 | let telecomjs_rows = vec![ |
| 4167 | CatalogOffering { |
| 4168 | provider: "telecomjs".to_string(), |
| 4169 | wire_model_id: "deepseek-chat".to_string(), |
| 4170 | endpoint_key: "chat".to_string(), |
| 4171 | family: Some("deepseek".to_string()), |
| 4172 | source: CatalogSource::Live { |
| 4173 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4174 | fetched_at: 2000, |
| 4175 | }, |
| 4176 | ..Default::default() |
| 4177 | }, |
| 4178 | CatalogOffering { |
| 4179 | provider: "telecomjs".to_string(), |
| 4180 | wire_model_id: "glm-4".to_string(), |
| 4181 | endpoint_key: "chat".to_string(), |
| 4182 | family: Some("glm".to_string()), |
| 4183 | source: CatalogSource::Live { |
| 4184 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4185 | fetched_at: 2000, |
| 4186 | }, |
| 4187 | ..Default::default() |
| 4188 | }, |
| 4189 | ]; |
| 4190 | merge_live_offerings(telecomjs_rows); |
| 4191 | assert_eq!( |
| 4192 | merged_snapshot().offerings_for_provider("telecomjs").len(), |
| 4193 | 2, |
| 4194 | "provider rows should be visible before Models.dev completes" |
| 4195 | ); |
| 4196 | |
| 4197 | // 2) Models.dev refreshes and replaces its cross-provider snapshot. |
| 4198 | // Before the source-scoped fix, this would have wiped TelecomJS rows. |
| 4199 | let models_dev_rows = vec![CatalogOffering { |
| 4200 | provider: "deepseek".to_string(), |
| 4201 | wire_model_id: "deepseek-chat".to_string(), |
| 4202 | endpoint_key: "chat".to_string(), |
| 4203 | family: Some("deepseek".to_string()), |
| 4204 | source: CatalogSource::Live { |
| 4205 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4206 | fetched_at: 3000, |
| 4207 | }, |
| 4208 | ..Default::default() |
| 4209 | }]; |
| 4210 | set_live_snapshot( |
| 4211 | CatalogSnapshot { |
| 4212 | offerings: models_dev_rows, |
| 4213 | }, |
| 4214 | LiveSource::ModelsDev, |
| 4215 | ); |
| 4216 | |
| 4217 | // 3) Both sources' rows are present — TelecomJS rows were NOT erased. |
| 4218 | let merged = merged_snapshot(); |
| 4219 | let telecomjs_rows_merged = merged.offerings_for_provider("telecomjs"); |
| 4220 | assert_eq!( |
| 4221 | telecomjs_rows_merged.len(), |
| 4222 | 2, |
| 4223 | "TelecomJS rows were erased by Models.dev refresh: {telecomjs_rows_merged:?}" |
| 4224 | ); |
| 4225 | assert!( |
| 4226 | telecomjs_rows_merged |
| 4227 | .iter() |
| 4228 | .any(|r| r.wire_model_id == "deepseek-chat"), |
| 4229 | "TelecomJS deepseek-chat row erased" |
| 4230 | ); |
| 4231 | assert!( |
| 4232 | telecomjs_rows_merged |
| 4233 | .iter() |
| 4234 | .any(|r| r.wire_model_id == "glm-4"), |
| 4235 | "TelecomJS glm-4 row erased" |
| 4236 | ); |
| 4237 | let deepseek_rows = merged.offerings_for_provider("deepseek"); |
| 4238 | assert!( |
| 4239 | deepseek_rows |
| 4240 | .iter() |
| 4241 | .any(|r| r.wire_model_id == "deepseek-chat"), |
| 4242 | "Models.dev deepseek row missing: {deepseek_rows:?}" |
| 4243 | ); |
| 4244 | |
| 4245 | clear_live_snapshot(); |
| 4246 | } |
| 4247 | |
| 4248 | /// Catalog refresh never deletes previously published rows: a Models.dev |
| 4249 | /// refresh that adds new rows must preserve existing per-provider rows, |
| 4250 | /// and a per-provider merge must preserve existing Models.dev rows. |
| 4251 | #[test] |
| 4252 | fn catalog_refresh_never_deletes_previously_published_rows() { |
| 4253 | let _live = lock_live_snapshot(); |
| 4254 | clear_live_snapshot(); |
| 4255 | |
| 4256 | // 1) Initial state: Models.dev publishes rows for deepseek + zai. |
| 4257 | let initial_models_dev = vec![ |
| 4258 | CatalogOffering { |
| 4259 | provider: "deepseek".to_string(), |
| 4260 | wire_model_id: "deepseek-chat".to_string(), |
| 4261 | endpoint_key: "chat".to_string(), |
| 4262 | source: CatalogSource::Live { |
| 4263 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4264 | fetched_at: 1000, |
| 4265 | }, |
| 4266 | ..Default::default() |
| 4267 | }, |
| 4268 | CatalogOffering { |
| 4269 | provider: "zai".to_string(), |
| 4270 | wire_model_id: "glm-4".to_string(), |
| 4271 | endpoint_key: "chat".to_string(), |
| 4272 | source: CatalogSource::Live { |
| 4273 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4274 | fetched_at: 1000, |
| 4275 | }, |
| 4276 | ..Default::default() |
| 4277 | }, |
| 4278 | ]; |
| 4279 | set_live_snapshot( |
| 4280 | CatalogSnapshot { |
| 4281 | offerings: initial_models_dev, |
| 4282 | }, |
| 4283 | LiveSource::ModelsDev, |
| 4284 | ); |
| 4285 | |
| 4286 | // 2) TelecomJS merges its rows. |
| 4287 | let telecomjs_rows = vec![CatalogOffering { |
| 4288 | provider: "telecomjs".to_string(), |
| 4289 | wire_model_id: "deepseek-chat".to_string(), |
| 4290 | endpoint_key: "chat".to_string(), |
| 4291 | source: CatalogSource::Live { |
| 4292 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4293 | fetched_at: 2000, |
| 4294 | }, |
| 4295 | ..Default::default() |
| 4296 | }]; |
| 4297 | merge_live_offerings(telecomjs_rows); |
| 4298 | |
| 4299 | // Record what we have before the second refresh. |
| 4300 | let before_refresh = merged_snapshot(); |
| 4301 | let before_providers: std::collections::BTreeSet<_> = before_refresh |
| 4302 | .offerings |
| 4303 | .iter() |
| 4304 | .map(|r| (r.provider.clone(), r.wire_model_id.clone())) |
| 4305 | .collect(); |
| 4306 | assert!( |
| 4307 | before_providers.contains(&("deepseek".to_string(), "deepseek-chat".to_string())), |
| 4308 | "deepseek row should exist before refresh" |
| 4309 | ); |
| 4310 | assert!( |
| 4311 | before_providers.contains(&("telecomjs".to_string(), "deepseek-chat".to_string())), |
| 4312 | "telecomjs row should exist before refresh" |
| 4313 | ); |
| 4314 | |
| 4315 | // 3) Models.dev refreshes again with an updated snapshot (adds a new row). |
| 4316 | let updated_models_dev = vec![ |
| 4317 | CatalogOffering { |
| 4318 | provider: "deepseek".to_string(), |
| 4319 | wire_model_id: "deepseek-chat".to_string(), |
| 4320 | endpoint_key: "chat".to_string(), |
| 4321 | source: CatalogSource::Live { |
| 4322 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4323 | fetched_at: 3000, |
| 4324 | }, |
| 4325 | ..Default::default() |
| 4326 | }, |
| 4327 | CatalogOffering { |
| 4328 | provider: "zai".to_string(), |
| 4329 | wire_model_id: "glm-4".to_string(), |
| 4330 | endpoint_key: "chat".to_string(), |
| 4331 | source: CatalogSource::Live { |
| 4332 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4333 | fetched_at: 3000, |
| 4334 | }, |
| 4335 | ..Default::default() |
| 4336 | }, |
| 4337 | // New row added by the refresh. |
| 4338 | CatalogOffering { |
| 4339 | provider: "moonshot".to_string(), |
| 4340 | wire_model_id: "kimi-k2.5".to_string(), |
| 4341 | endpoint_key: "chat".to_string(), |
| 4342 | source: CatalogSource::Live { |
| 4343 | base_url_fingerprint: "modelsdev-fp".to_string(), |
| 4344 | fetched_at: 3000, |
| 4345 | }, |
| 4346 | ..Default::default() |
| 4347 | }, |
| 4348 | ]; |
| 4349 | set_live_snapshot( |
| 4350 | CatalogSnapshot { |
| 4351 | offerings: updated_models_dev, |
| 4352 | }, |
| 4353 | LiveSource::ModelsDev, |
| 4354 | ); |
| 4355 | |
| 4356 | // 4) The TelecomJS row is STILL present — it was not deleted. |
| 4357 | let after_refresh = merged_snapshot(); |
| 4358 | let after_telecomjs: Vec<_> = after_refresh |
| 4359 | .offerings_for_provider("telecomjs") |
| 4360 | .iter() |
| 4361 | .map(|r| r.wire_model_id.clone()) |
| 4362 | .collect(); |
| 4363 | assert!( |
| 4364 | after_telecomjs.iter().any(|id| id == "deepseek-chat"), |
| 4365 | "TelecomJS row was deleted by Models.dev refresh! Remaining: {after_telecomjs:?}" |
| 4366 | ); |
| 4367 | |
| 4368 | // 5) New Models.dev row is also present. |
| 4369 | let after_moonshot: Vec<_> = after_refresh |
| 4370 | .offerings_for_provider("moonshot") |
| 4371 | .iter() |
| 4372 | .map(|r| r.wire_model_id.clone()) |
| 4373 | .collect(); |
| 4374 | assert!( |
| 4375 | after_moonshot.iter().any(|id| id == "kimi-k2.5"), |
| 4376 | "New Models.dev moonshot row missing: {after_moonshot:?}" |
| 4377 | ); |
| 4378 | |
| 4379 | // 6) Also verify: a per-provider merge does not delete Models.dev rows. |
| 4380 | let extra_telecomjs = vec![CatalogOffering { |
| 4381 | provider: "telecomjs".to_string(), |
| 4382 | wire_model_id: "glm-4".to_string(), |
| 4383 | endpoint_key: "chat".to_string(), |
| 4384 | source: CatalogSource::Live { |
| 4385 | base_url_fingerprint: "telecomjs-fp".to_string(), |
| 4386 | fetched_at: 4000, |
| 4387 | }, |
| 4388 | ..Default::default() |
| 4389 | }]; |
| 4390 | merge_live_offerings(extra_telecomjs); |
| 4391 | |
| 4392 | let final_merged = merged_snapshot(); |
| 4393 | let final_deepseek: Vec<_> = final_merged |
| 4394 | .offerings_for_provider("deepseek") |
| 4395 | .iter() |
| 4396 | .map(|r| r.wire_model_id.clone()) |
| 4397 | .collect(); |
| 4398 | assert!( |
| 4399 | final_deepseek.iter().any(|id| id == "deepseek-chat"), |
| 4400 | "Models.dev deepseek row was deleted by per-provider merge! Remaining: {final_deepseek:?}" |
| 4401 | ); |
| 4402 | let final_moonshot: Vec<_> = final_merged |
| 4403 | .offerings_for_provider("moonshot") |
| 4404 | .iter() |
| 4405 | .map(|r| r.wire_model_id.clone()) |
| 4406 | .collect(); |
| 4407 | assert!( |
| 4408 | final_moonshot.iter().any(|id| id == "kimi-k2.5"), |
| 4409 | "Models.dev moonshot row was deleted by per-provider merge! Remaining: {final_moonshot:?}" |
| 4410 | ); |
| 4411 | |
| 4412 | clear_live_snapshot(); |
| 4413 | } |
| 4414 | |
| 4415 | #[test] |
| 4416 | fn cloud_generation_updates_exact_catalog_defaults_and_disable_restores_baseline() { |
| 4417 | use codewhale_config::cloud_facts::{ |
| 4418 | CloudFactsStatus, ModelFact, ProviderDefaultFact, ScopedFacts, overlay, |
| 4419 | }; |
| 4420 | let _live = lock_live_snapshot(); |
| 4421 | let home = tempfile::tempdir().unwrap(); |
| 4422 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 4423 | let _enabled = crate::test_support::EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS"); |
| 4424 | struct Reset; |
| 4425 | impl Drop for Reset { |
| 4426 | fn drop(&mut self) { |
| 4427 | overlay::clear(); |
| 4428 | clear_live_snapshot(); |
| 4429 | crate::provider_catalog_live::reset_cache_for_test(); |
| 4430 | } |
| 4431 | } |
| 4432 | let _reset = Reset; |
| 4433 | overlay::clear(); |
| 4434 | clear_live_snapshot(); |
| 4435 | crate::provider_catalog_live::reset_cache_for_test(); |
| 4436 | let provider = ProviderKind::Openai; |
| 4437 | let base = provider.provider().default_base_url(); |
| 4438 | let model = "cloud-catalog-fixture"; |
| 4439 | let config = { |
| 4440 | let __cw_config_init_2_0 = Some("openai".into()); |
| 4441 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 4442 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 4443 | __cw_config_init_2_value |
| 4444 | }; |
| 4445 | let baseline = crate::route_runtime::resolve_runtime_route(&config, provider, None) |
| 4446 | .unwrap() |
| 4447 | .model; |
| 4448 | assert!( |
| 4449 | !catalog_models_for_route(provider, "openai", base) |
| 4450 | .iter() |
| 4451 | .any(|id| id == model) |
| 4452 | ); |
| 4453 | let ticket = overlay::configure(true, "catalog-generation-test").unwrap(); |
| 4454 | let mut facts = ScopedFacts { |
| 4455 | channel: "catalog-generation-test".into(), |
| 4456 | facts_version: 1, |
| 4457 | key_id: "cwf-test-only".into(), |
| 4458 | models: vec![ModelFact { |
| 4459 | provider: "openai".into(), |
| 4460 | id: model.into(), |
| 4461 | context_window: Some(31_337), |
| 4462 | ..Default::default() |
| 4463 | }], |
| 4464 | provider_defaults: BTreeMap::from([( |
| 4465 | "openai".into(), |
| 4466 | ProviderDefaultFact { |
| 4467 | default_model: Some(model.into()), |
| 4468 | ..Default::default() |
| 4469 | }, |
| 4470 | )]), |
| 4471 | ..Default::default() |
| 4472 | }; |
| 4473 | assert!(overlay::publish( |
| 4474 | &ticket, |
| 4475 | Some(facts.clone()), |
| 4476 | CloudFactsStatus::default() |
| 4477 | )); |
| 4478 | assert!( |
| 4479 | catalog_models_for_route(provider, "openai", base) |
| 4480 | .iter() |
| 4481 | .any(|id| id == model) |
| 4482 | ); |
| 4483 | assert!( |
| 4484 | catalog_models_for_route(provider, "openai", "https://catalog-proxy.invalid/v1") |
| 4485 | .is_empty() |
| 4486 | ); |
| 4487 | let route = crate::route_runtime::resolve_runtime_route(&config, provider, None).unwrap(); |
| 4488 | assert_eq!(route.model, model); |
| 4489 | assert_eq!(route.candidate.limits().context_tokens, Some(31_337)); |
| 4490 | assert_eq!( |
| 4491 | crate::route_runtime::resolve_runtime_route(&config, provider, Some(&baseline)) |
| 4492 | .unwrap() |
| 4493 | .model, |
| 4494 | baseline |
| 4495 | ); |
| 4496 | facts.facts_version = 2; |
| 4497 | facts.models[0].context_window = Some(62_674); |
| 4498 | assert!(overlay::publish( |
| 4499 | &ticket, |
| 4500 | Some(facts), |
| 4501 | CloudFactsStatus::default() |
| 4502 | )); |
| 4503 | assert_eq!( |
| 4504 | crate::route_runtime::resolve_runtime_route(&config, provider, None) |
| 4505 | .unwrap() |
| 4506 | .candidate |
| 4507 | .limits() |
| 4508 | .context_tokens, |
| 4509 | Some(62_674) |
| 4510 | ); |
| 4511 | overlay::clear(); |
| 4512 | assert_eq!( |
| 4513 | crate::route_runtime::resolve_runtime_route(&config, provider, None) |
| 4514 | .unwrap() |
| 4515 | .model, |
| 4516 | baseline |
| 4517 | ); |
| 4518 | assert!( |
| 4519 | !catalog_models_for_route(provider, "openai", base) |
| 4520 | .iter() |
| 4521 | .any(|id| id == model) |
| 4522 | ); |
| 4523 | } |
| 4524 | |
| 4525 | /// Test scaffolding shared by the signed-catalog cases: an isolated home, |
| 4526 | /// cloud facts enabled, and every process-wide layer reset on the way out. |
| 4527 | /// |
| 4528 | /// Field order is the drop order and is load-bearing: the env guards must |
| 4529 | /// restore their variables while this thread still holds the test env |
| 4530 | /// barrier that [`lock_live_snapshot`] took, so `_live` is declared last. |
| 4531 | struct CloudFactsTestEnv { |
| 4532 | _enabled: crate::test_support::EnvVarGuard, |
| 4533 | _home: crate::test_support::EnvVarGuard, |
| 4534 | _home_dir: tempfile::TempDir, |
| 4535 | _live: LiveSnapshotLock, |
| 4536 | } |
| 4537 | |
| 4538 | impl Drop for CloudFactsTestEnv { |
| 4539 | fn drop(&mut self) { |
| 4540 | codewhale_config::cloud_facts::overlay::clear(); |
| 4541 | clear_live_snapshot(); |
| 4542 | crate::provider_catalog_live::reset_cache_for_test(); |
| 4543 | } |
| 4544 | } |
| 4545 | |
| 4546 | fn cloud_facts_test_env() -> CloudFactsTestEnv { |
| 4547 | let live = lock_live_snapshot(); |
| 4548 | let home_dir = tempfile::tempdir().unwrap(); |
| 4549 | let home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home_dir.path()); |
| 4550 | let enabled = crate::test_support::EnvVarGuard::remove("CODEWHALE_DISABLE_CLOUD_FACTS"); |
| 4551 | codewhale_config::cloud_facts::overlay::clear(); |
| 4552 | clear_live_snapshot(); |
| 4553 | crate::provider_catalog_live::reset_cache_for_test(); |
| 4554 | CloudFactsTestEnv { |
| 4555 | _enabled: enabled, |
| 4556 | _home: home, |
| 4557 | _home_dir: home_dir, |
| 4558 | _live: live, |
| 4559 | } |
| 4560 | } |
| 4561 | |
| 4562 | fn publish_test_facts( |
| 4563 | channel: &str, |
| 4564 | version: u64, |
| 4565 | valid_until: Option<u64>, |
| 4566 | models: Vec<codewhale_config::cloud_facts::ModelFact>, |
| 4567 | ) { |
| 4568 | use codewhale_config::cloud_facts::{CloudFactsStatus, ScopedFacts, overlay}; |
| 4569 | let ticket = overlay::configure(true, channel).unwrap(); |
| 4570 | assert!(overlay::publish( |
| 4571 | &ticket, |
| 4572 | Some(ScopedFacts { |
| 4573 | channel: channel.into(), |
| 4574 | facts_version: version, |
| 4575 | key_id: "cwf-test-only".into(), |
| 4576 | valid_until, |
| 4577 | models, |
| 4578 | ..Default::default() |
| 4579 | }), |
| 4580 | CloudFactsStatus::default() |
| 4581 | )); |
| 4582 | } |
| 4583 | |
| 4584 | fn upsert_fact( |
| 4585 | provider: &str, |
| 4586 | id: &str, |
| 4587 | context_window: u64, |
| 4588 | ) -> codewhale_config::cloud_facts::ModelFact { |
| 4589 | codewhale_config::cloud_facts::ModelFact { |
| 4590 | provider: provider.into(), |
| 4591 | id: id.into(), |
| 4592 | context_window: Some(context_window), |
| 4593 | ..Default::default() |
| 4594 | } |
| 4595 | } |
| 4596 | |
| 4597 | /// An id-only unlisted assertion: the signer says this exact id exists on |
| 4598 | /// the provider's official endpoint and states nothing else about it. |
| 4599 | fn attested_fact(provider: &str, id: &str) -> codewhale_config::cloud_facts::ModelFact { |
| 4600 | codewhale_config::cloud_facts::ModelFact { |
| 4601 | provider: provider.into(), |
| 4602 | id: id.into(), |
| 4603 | allow_unlisted: true, |
| 4604 | ..Default::default() |
| 4605 | } |
| 4606 | } |
| 4607 | |
| 4608 | /// `scoped_view` only keeps an assertion in a payload that expires; mirror |
| 4609 | /// that here so these tests publish what the client can actually receive. |
| 4610 | fn bounded() -> Option<u64> { |
| 4611 | Some(codewhale_config::catalog::now_unix() + 3_600) |
| 4612 | } |
| 4613 | |
| 4614 | fn record_roster(base: &str, offerings: Vec<CatalogOffering>) { |
| 4615 | use codewhale_config::catalog::ProviderCatalogDelta; |
| 4616 | crate::provider_catalog_live::record_success(ProviderCatalogDelta { |
| 4617 | provider: "deepseek".to_string(), |
| 4618 | base_url_fingerprint: base_url_fingerprint(base), |
| 4619 | fetched_at: codewhale_config::catalog::now_unix(), |
| 4620 | offerings, |
| 4621 | }); |
| 4622 | } |
| 4623 | |
| 4624 | fn roster_row(base: &str, id: &str) -> CatalogOffering { |
| 4625 | CatalogOffering { |
| 4626 | provider: "deepseek".to_string(), |
| 4627 | wire_model_id: id.to_string(), |
| 4628 | endpoint_key: "chat".to_string(), |
| 4629 | source: CatalogSource::Live { |
| 4630 | base_url_fingerprint: base_url_fingerprint(base), |
| 4631 | fetched_at: codewhale_config::catalog::now_unix(), |
| 4632 | }, |
| 4633 | ..Default::default() |
| 4634 | } |
| 4635 | } |
| 4636 | |
| 4637 | /// A provider roster owns the ids it lists **and its own omissions**. This |
| 4638 | /// client keeps no roster history, so nothing it holds locally — bundled or |
| 4639 | /// otherwise — is evidence about what the provider once served: only an |
| 4640 | /// explicit signed assertion may name an id the roster omits, and it does so |
| 4641 | /// for a bundled id and an unknown id alike. |
| 4642 | #[test] |
| 4643 | fn roster_omission_stands_unless_the_payload_explicitly_attests_the_id() { |
| 4644 | let _env = cloud_facts_test_env(); |
| 4645 | |
| 4646 | let provider = ProviderKind::Deepseek; |
| 4647 | let base = provider.provider().default_base_url(); |
| 4648 | // One id the bundled catalog knows, one it has never heard of. Neither |
| 4649 | // fact changes what the roster is authoritative about. |
| 4650 | let bundled = "deepseek-v4-flash"; |
| 4651 | let unknown = "deepseek-v4-nano-preview"; |
| 4652 | let listed = "deepseek-v4-pro"; |
| 4653 | assert!(bundled_catalog_offering_for_model(provider, bundled).is_some()); |
| 4654 | assert!(bundled_catalog_offering_for_model(provider, unknown).is_none()); |
| 4655 | record_roster(base, vec![roster_row(base, listed)]); |
| 4656 | |
| 4657 | // No assertion: the roster's omission stands for both ids. |
| 4658 | publish_test_facts( |
| 4659 | "roster-dominance-test", |
| 4660 | 1, |
| 4661 | bounded(), |
| 4662 | vec![ |
| 4663 | upsert_fact("deepseek", bundled, 999_999), |
| 4664 | upsert_fact("deepseek", unknown, 131_072), |
| 4665 | ], |
| 4666 | ); |
| 4667 | let models = catalog_models_for_route(provider, "deepseek", base); |
| 4668 | assert!(models.iter().any(|id| id == listed), "{models:?}"); |
| 4669 | for id in [bundled, unknown] { |
| 4670 | assert!( |
| 4671 | !models.iter().any(|row| row == id), |
| 4672 | "an unattested patch must not survive the roster's omission: {models:?}" |
| 4673 | ); |
| 4674 | assert!( |
| 4675 | catalog_offering_for_route(provider, "deepseek", base, id).is_none(), |
| 4676 | "{id} must not answer with signed facts either" |
| 4677 | ); |
| 4678 | assert!( |
| 4679 | !all_catalog_models_for_provider(provider) |
| 4680 | .iter() |
| 4681 | .any(|row| row == id), |
| 4682 | "the merged view must not read it back out either" |
| 4683 | ); |
| 4684 | } |
| 4685 | |
| 4686 | // Same ids, now explicitly attested. The bundled one carries no stated |
| 4687 | // limits, so it must not inherit the bundled row's. |
| 4688 | publish_test_facts( |
| 4689 | "roster-dominance-test", |
| 4690 | 2, |
| 4691 | bounded(), |
| 4692 | vec![ |
| 4693 | attested_fact("deepseek", bundled), |
| 4694 | codewhale_config::cloud_facts::ModelFact { |
| 4695 | allow_unlisted: true, |
| 4696 | ..upsert_fact("deepseek", unknown, 131_072) |
| 4697 | }, |
| 4698 | ], |
| 4699 | ); |
| 4700 | let models = catalog_models_for_route(provider, "deepseek", base); |
| 4701 | let merged = all_catalog_models_for_provider(provider); |
| 4702 | for id in [listed, bundled, unknown] { |
| 4703 | assert!(models.iter().any(|row| row == id), "{models:?}"); |
| 4704 | assert!(merged.iter().any(|row| row == id), "{merged:?}"); |
| 4705 | } |
| 4706 | let attested = catalog_offering_for_route(provider, "deepseek", base, bundled) |
| 4707 | .expect("an attested id resolves its own facts"); |
| 4708 | assert_eq!( |
| 4709 | attested.limit, None, |
| 4710 | "an id-only assertion must not borrow limits from the bundled layer" |
| 4711 | ); |
| 4712 | assert_eq!(attested.cost, None); |
| 4713 | assert_eq!(attested.tool_call, None); |
| 4714 | assert_eq!(attested.modalities, None); |
| 4715 | assert_eq!(attested.attachment, None); |
| 4716 | let offering = catalog_offering_for_route(provider, "deepseek", base, unknown) |
| 4717 | .expect("an attested id resolves its own facts"); |
| 4718 | assert_eq!(offering.wire_model_id, unknown, "the exact id, verbatim"); |
| 4719 | assert_eq!( |
| 4720 | offering.limit.and_then(|limit| limit.context), |
| 4721 | Some(131_072) |
| 4722 | ); |
| 4723 | |
| 4724 | // The executor reads the same list the picker does. |
| 4725 | let config = { |
| 4726 | let __cw_config_init_3_0 = Some("deepseek".into()); |
| 4727 | let mut __cw_config_init_3_value: Config = Default::default(); |
| 4728 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 4729 | __cw_config_init_3_value |
| 4730 | }; |
| 4731 | assert_eq!( |
| 4732 | crate::route_runtime::resolve_runtime_route(&config, provider, Some(unknown)) |
| 4733 | .unwrap() |
| 4734 | .candidate |
| 4735 | .limits() |
| 4736 | .context_tokens, |
| 4737 | Some(131_072) |
| 4738 | ); |
| 4739 | |
| 4740 | // Signed rows never reach a proxied endpoint, attested or not. |
| 4741 | assert!( |
| 4742 | !catalog_models_for_route(provider, "deepseek", "https://deepseek-proxy.invalid/v1") |
| 4743 | .iter() |
| 4744 | .any(|id| id == unknown) |
| 4745 | ); |
| 4746 | } |
| 4747 | |
| 4748 | /// Every retraction path is the signer's, and none needs a provider |
| 4749 | /// request: `hide` removes a bundled row, an elapsed validity bound drops |
| 4750 | /// the whole overlay on read (including the hide it carried), and dropping |
| 4751 | /// an upsert withdraws the row it created. |
| 4752 | #[test] |
| 4753 | fn signed_hide_expiry_and_dropped_upsert_retract_rows_without_a_provider_request() { |
| 4754 | use codewhale_config::catalog::now_unix; |
| 4755 | use codewhale_config::cloud_facts::{ModelFact, ModelOp}; |
| 4756 | let _env = cloud_facts_test_env(); |
| 4757 | |
| 4758 | let provider = ProviderKind::Deepseek; |
| 4759 | let base = provider.provider().default_base_url(); |
| 4760 | let hidden = "deepseek-v4-flash"; |
| 4761 | let preview = "deepseek-v4-nano-preview"; |
| 4762 | let before = catalog_models_for_route(provider, "deepseek", base); |
| 4763 | assert!(before.iter().any(|id| id == hidden), "{before:?}"); |
| 4764 | |
| 4765 | publish_test_facts( |
| 4766 | "retraction-test", |
| 4767 | 1, |
| 4768 | None, |
| 4769 | vec![ |
| 4770 | ModelFact { |
| 4771 | provider: "deepseek".into(), |
| 4772 | id: hidden.into(), |
| 4773 | op: ModelOp::Hide, |
| 4774 | ..Default::default() |
| 4775 | }, |
| 4776 | upsert_fact("deepseek", preview, 131_072), |
| 4777 | ], |
| 4778 | ); |
| 4779 | let hidden_view = catalog_models_for_route(provider, "deepseek", base); |
| 4780 | assert!( |
| 4781 | !hidden_view.iter().any(|id| id == hidden), |
| 4782 | "hide must remove the bundled row: {hidden_view:?}" |
| 4783 | ); |
| 4784 | assert!( |
| 4785 | hidden_view.iter().any(|id| id == preview), |
| 4786 | "{hidden_view:?}" |
| 4787 | ); |
| 4788 | |
| 4789 | // Expiry is evaluated on read: no refresh, no provider request, and no |
| 4790 | // setting change is needed for the payload to stop being authority. |
| 4791 | publish_test_facts( |
| 4792 | "retraction-test", |
| 4793 | 2, |
| 4794 | Some(now_unix().saturating_sub(1)), |
| 4795 | vec![ |
| 4796 | ModelFact { |
| 4797 | provider: "deepseek".into(), |
| 4798 | id: hidden.into(), |
| 4799 | op: ModelOp::Hide, |
| 4800 | ..Default::default() |
| 4801 | }, |
| 4802 | upsert_fact("deepseek", preview, 131_072), |
| 4803 | ], |
| 4804 | ); |
| 4805 | let expired = catalog_models_for_route(provider, "deepseek", base); |
| 4806 | assert!( |
| 4807 | expired.iter().any(|id| id == hidden), |
| 4808 | "an expired payload cannot keep hiding a bundled row: {expired:?}" |
| 4809 | ); |
| 4810 | assert!( |
| 4811 | !expired.iter().any(|id| id == preview), |
| 4812 | "an expired payload cannot keep offering its own row: {expired:?}" |
| 4813 | ); |
| 4814 | |
| 4815 | // The third retraction: publish the same channel without the upsert. |
| 4816 | // An attested row is offered past a roster, so this is the path that |
| 4817 | // withdraws one without waiting for `not_after`. |
| 4818 | record_roster(base, vec![roster_row(base, "deepseek-v4-pro")]); |
| 4819 | publish_test_facts( |
| 4820 | "retraction-test", |
| 4821 | 3, |
| 4822 | bounded(), |
| 4823 | vec![attested_fact("deepseek", preview)], |
| 4824 | ); |
| 4825 | assert!( |
| 4826 | catalog_models_for_route(provider, "deepseek", base) |
| 4827 | .iter() |
| 4828 | .any(|id| id == preview) |
| 4829 | ); |
| 4830 | publish_test_facts("retraction-test", 4, bounded(), Vec::new()); |
| 4831 | let withdrawn = catalog_models_for_route(provider, "deepseek", base); |
| 4832 | assert!( |
| 4833 | !withdrawn.iter().any(|id| id == preview), |
| 4834 | "dropping the upsert must withdraw the row: {withdrawn:?}" |
| 4835 | ); |
| 4836 | assert!( |
| 4837 | withdrawn.iter().any(|id| id == "deepseek-v4-pro"), |
| 4838 | "the roster is untouched by the withdrawal: {withdrawn:?}" |
| 4839 | ); |
| 4840 | } |
| 4841 | |
| 4842 | /// A signed row names one canonical identity on one official endpoint. |
| 4843 | /// Catalog partitions deliberately collapse regional and dual-wire aliases |
| 4844 | /// onto a vendor primary, and that collapse must not become a channel for |
| 4845 | /// facts to reach an endpoint the signer did not name. |
| 4846 | #[test] |
| 4847 | fn signed_rows_do_not_cross_regional_wire_or_proxied_routes() { |
| 4848 | let _env = cloud_facts_test_env(); |
| 4849 | |
| 4850 | let preview = "deepseek-v4-nano-preview"; |
| 4851 | let siliconflow_preview = "sf-preview-not-in-any-catalog"; |
| 4852 | publish_test_facts( |
| 4853 | "route-scope-test", |
| 4854 | 1, |
| 4855 | bounded(), |
| 4856 | vec![ |
| 4857 | // Attested: the assertion must not widen the endpoint or |
| 4858 | // identity boundary either. |
| 4859 | codewhale_config::cloud_facts::ModelFact { |
| 4860 | allow_unlisted: true, |
| 4861 | pricing: Some(codewhale_config::cloud_facts::PricingFact { |
| 4862 | input_per_m: Some(0.25), |
| 4863 | output_per_m: Some(1.0), |
| 4864 | ..Default::default() |
| 4865 | }), |
| 4866 | ..upsert_fact("deepseek", preview, 131_072) |
| 4867 | }, |
| 4868 | upsert_fact("siliconflow", siliconflow_preview, 65_536), |
| 4869 | ], |
| 4870 | ); |
| 4871 | let offers = |provider: ProviderKind, identity: &str, model: &str| { |
| 4872 | catalog_models_for_route(provider, identity, provider.provider().default_base_url()) |
| 4873 | .iter() |
| 4874 | .any(|id| id == model) |
| 4875 | }; |
| 4876 | |
| 4877 | assert!( |
| 4878 | offers(ProviderKind::Deepseek, "deepseek", preview), |
| 4879 | "the exact signed route must offer the row" |
| 4880 | ); |
| 4881 | // Same host, but a TUI-only legacy alias with no canonical identity. |
| 4882 | assert!( |
| 4883 | !offers(ProviderKind::Deepseek, "deepseek-cn", preview), |
| 4884 | "the legacy CN alias inherits nothing from the primary identity" |
| 4885 | ); |
| 4886 | // Reads the `deepseek` partition, but is a separate endpoint contract. |
| 4887 | assert!( |
| 4888 | !offers( |
| 4889 | ProviderKind::DeepseekAnthropic, |
| 4890 | "deepseek-anthropic", |
| 4891 | preview |
| 4892 | ), |
| 4893 | "the Anthropic-wire endpoint is not the identity the signer named" |
| 4894 | ); |
| 4895 | // A regional sibling that shares a catalog partition, not an identity. |
| 4896 | assert!( |
| 4897 | offers( |
| 4898 | ProviderKind::Siliconflow, |
| 4899 | "siliconflow", |
| 4900 | siliconflow_preview |
| 4901 | ), |
| 4902 | "the exact signed SiliconFlow route must offer the row" |
| 4903 | ); |
| 4904 | assert!( |
| 4905 | !offers( |
| 4906 | ProviderKind::SiliconflowCN, |
| 4907 | "siliconflow-CN", |
| 4908 | siliconflow_preview |
| 4909 | ), |
| 4910 | "the China endpoint is a different identity, even where the host allowlist overlaps" |
| 4911 | ); |
| 4912 | // A proxy or redirect on the right identity is still the wrong endpoint. |
| 4913 | assert!( |
| 4914 | !catalog_models_for_route( |
| 4915 | ProviderKind::Deepseek, |
| 4916 | "deepseek", |
| 4917 | "https://deepseek-proxy.invalid/v1" |
| 4918 | ) |
| 4919 | .iter() |
| 4920 | .any(|id| id == preview), |
| 4921 | "a custom base URL never inherits signed rows" |
| 4922 | ); |
| 4923 | |
| 4924 | // The price travels with the row and no further. A signed rate that |
| 4925 | // renders somewhere it cannot be billed is the failure this layer must |
| 4926 | // not have, so the offered row and the dispatch quote answer together. |
| 4927 | let quote = |provider: ProviderKind, identity: &str, base: &str| { |
| 4928 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 4929 | provider, |
| 4930 | identity, |
| 4931 | preview, |
| 4932 | base, |
| 4933 | codewhale_config::catalog::now_unix(), |
| 4934 | ) |
| 4935 | }; |
| 4936 | assert!( |
| 4937 | quote( |
| 4938 | ProviderKind::Deepseek, |
| 4939 | "deepseek", |
| 4940 | ProviderKind::Deepseek.provider().default_base_url() |
| 4941 | ) |
| 4942 | .is_some(), |
| 4943 | "a signed price on the exact signed route is billable — this is what \ |
| 4944 | makes a rate change data rather than a release" |
| 4945 | ); |
| 4946 | for (provider, identity) in [ |
| 4947 | (ProviderKind::Deepseek, "deepseek-cn"), |
| 4948 | (ProviderKind::DeepseekAnthropic, "deepseek-anthropic"), |
| 4949 | ] { |
| 4950 | assert!( |
| 4951 | quote(provider, identity, provider.provider().default_base_url()).is_none(), |
| 4952 | "{identity} must not mint a quote from another endpoint's facts" |
| 4953 | ); |
| 4954 | } |
| 4955 | assert!( |
| 4956 | quote( |
| 4957 | ProviderKind::Deepseek, |
| 4958 | "deepseek", |
| 4959 | "https://deepseek-proxy.invalid/v1" |
| 4960 | ) |
| 4961 | .is_none(), |
| 4962 | "and neither may a proxied base URL" |
| 4963 | ); |
| 4964 | assert!( |
| 4965 | quote( |
| 4966 | ProviderKind::Deepseek, |
| 4967 | "deepseek-custom-table", |
| 4968 | ProviderKind::Deepseek.provider().default_base_url() |
| 4969 | ) |
| 4970 | .is_none(), |
| 4971 | "a differently-named provider table is a separate billing relationship" |
| 4972 | ); |
| 4973 | } |
| 4974 | |
| 4975 | /// A roster that answers with ids alone has not said its models have no |
| 4976 | /// limits. Signed facts complete that silence for the picker, the metadata |
| 4977 | /// lookup and the executor alike — and lose every field the provider did |
| 4978 | /// state. A completed price keeps its signed source separately from the |
| 4979 | /// provider roster's existence claim. |
| 4980 | #[test] |
| 4981 | fn provider_id_only_rows_take_signed_limits_while_provider_facts_and_prices_win() { |
| 4982 | use codewhale_config::cloud_facts::{ModelFact, PricingFact}; |
| 4983 | use codewhale_config::models_dev::ModelsDevLimit; |
| 4984 | let _env = cloud_facts_test_env(); |
| 4985 | |
| 4986 | let provider = ProviderKind::Deepseek; |
| 4987 | let base = provider.provider().default_base_url(); |
| 4988 | let id_only = "deepseek-roster-bare"; |
| 4989 | let detailed = "deepseek-roster-detailed"; |
| 4990 | let narrow = "deepseek-roster-narrow"; |
| 4991 | let future = "deepseek-roster-future"; |
| 4992 | record_roster( |
| 4993 | base, |
| 4994 | vec![ |
| 4995 | roster_row(base, id_only), |
| 4996 | CatalogOffering { |
| 4997 | limit: Some(ModelsDevLimit { |
| 4998 | context: Some(12_345), |
| 4999 | ..Default::default() |
| 5000 | }), |
| 5001 | reasoning: Some(false), |
| 5002 | ..roster_row(base, detailed) |
| 5003 | }, |
| 5004 | CatalogOffering { |
| 5005 | reasoning_options: vec![ |
| 5006 | serde_json::json!({"type": "toggle"}), |
| 5007 | serde_json::json!({"type": "effort", "values": ["low", "max"], "default": "max"}), |
| 5008 | ], |
| 5009 | reasoning_options_present: true, |
| 5010 | ..roster_row(base, narrow) |
| 5011 | }, |
| 5012 | CatalogOffering { |
| 5013 | reasoning_options: vec![ |
| 5014 | serde_json::json!({"type": "toggle"}), |
| 5015 | serde_json::json!({"type": "effort", "values": []}), |
| 5016 | ], |
| 5017 | reasoning_options_present: true, |
| 5018 | ..roster_row(base, future) |
| 5019 | }, |
| 5020 | ], |
| 5021 | ); |
| 5022 | use crate::reasoning_preference::ReasoningEffort; |
| 5023 | assert_eq!( |
| 5024 | ReasoningEffort::High.normalize_for_route(provider, base, narrow), |
| 5025 | ReasoningEffort::Max |
| 5026 | ); |
| 5027 | assert_eq!( |
| 5028 | ReasoningEffort::Off.normalize_for_route(provider, base, narrow), |
| 5029 | ReasoningEffort::Off |
| 5030 | ); |
| 5031 | assert_eq!( |
| 5032 | ReasoningEffort::High.normalize_for_route(provider, base, future), |
| 5033 | ReasoningEffort::Auto |
| 5034 | ); |
| 5035 | assert_eq!( |
| 5036 | ReasoningEffort::High.normalize_for_route(provider, "https://proxy.example/v1", narrow), |
| 5037 | ReasoningEffort::High |
| 5038 | ); |
| 5039 | let signed = |id: &str| ModelFact { |
| 5040 | max_output: Some(8_192), |
| 5041 | reasoning: Some(true), |
| 5042 | pricing: Some(PricingFact { |
| 5043 | input_per_m: Some(1.0), |
| 5044 | output_per_m: Some(2.0), |
| 5045 | ..Default::default() |
| 5046 | }), |
| 5047 | ..upsert_fact("deepseek", id, 131_072) |
| 5048 | }; |
| 5049 | publish_test_facts( |
| 5050 | "roster-completion-test", |
| 5051 | 1, |
| 5052 | bounded(), |
| 5053 | vec![signed(id_only), signed(detailed)], |
| 5054 | ); |
| 5055 | |
| 5056 | let bare = catalog_offering_for_route(provider, "deepseek", base, id_only) |
| 5057 | .expect("the roster row is still there"); |
| 5058 | let limit = bare.limit.clone().expect("signed limits complete it"); |
| 5059 | assert_eq!(limit.context, Some(131_072)); |
| 5060 | assert_eq!(limit.output, Some(8_192)); |
| 5061 | assert_eq!(bare.reasoning, Some(true)); |
| 5062 | assert!( |
| 5063 | matches!(bare.source, CatalogSource::Live { .. }), |
| 5064 | "the row is still the provider's: {:?}", |
| 5065 | bare.source |
| 5066 | ); |
| 5067 | assert_eq!(bare.cost.as_ref().and_then(|cost| cost.input), Some(1.0)); |
| 5068 | assert_eq!(bare.cost.as_ref().and_then(|cost| cost.output), Some(2.0)); |
| 5069 | assert!( |
| 5070 | matches!(bare.pricing_source(), CatalogSource::CloudFacts { .. }), |
| 5071 | "the estimate must retain its signed price authority" |
| 5072 | ); |
| 5073 | assert!( |
| 5074 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 5075 | provider, |
| 5076 | "deepseek", |
| 5077 | id_only, |
| 5078 | base, |
| 5079 | codewhale_config::catalog::now_unix(), |
| 5080 | ) |
| 5081 | .is_none(), |
| 5082 | "a completed estimate must not become a provider-confirmed quote" |
| 5083 | ); |
| 5084 | |
| 5085 | let stated = catalog_offering_for_route(provider, "deepseek", base, detailed) |
| 5086 | .expect("the roster row is still there"); |
| 5087 | let limit = stated.limit.clone().expect("provider limits are kept"); |
| 5088 | assert_eq!( |
| 5089 | limit.context, |
| 5090 | Some(12_345), |
| 5091 | "the provider's own context must win" |
| 5092 | ); |
| 5093 | assert_eq!(limit.output, Some(8_192), "only the silence is filled"); |
| 5094 | assert_eq!(stated.reasoning, Some(false), "and its own capability wins"); |
| 5095 | |
| 5096 | // The same completion reaches the merged picker view and the executor. |
| 5097 | assert_eq!( |
| 5098 | catalog_offering_for_model(provider, id_only) |
| 5099 | .and_then(|row| row.limit) |
| 5100 | .and_then(|limit| limit.context), |
| 5101 | Some(131_072) |
| 5102 | ); |
| 5103 | let config = { |
| 5104 | let __cw_config_init_4_0 = Some("deepseek".into()); |
| 5105 | let mut __cw_config_init_4_value: Config = Default::default(); |
| 5106 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 5107 | __cw_config_init_4_value |
| 5108 | }; |
| 5109 | let limits = |model: &str| { |
| 5110 | crate::route_runtime::resolve_runtime_route(&config, provider, Some(model)) |
| 5111 | .unwrap() |
| 5112 | .candidate |
| 5113 | .limits() |
| 5114 | .context_tokens |
| 5115 | }; |
| 5116 | assert_eq!(limits(id_only), Some(131_072)); |
| 5117 | assert_eq!(limits(detailed), Some(12_345)); |
| 5118 | } |
| 5119 | |
| 5120 | /// The population this layer exists to serve. Most models a user sees are |
| 5121 | /// described by a Models.dev refresh rather than by their provider, and a |
| 5122 | /// stale window or a changed rate on one of those is exactly what a signed |
| 5123 | /// correction must fix — arriving as data, not as a reinstall. The rows are |
| 5124 | /// published through the real producer, so this is also the runtime proof |
| 5125 | /// that external enrichment sits below the signed layer. |
| 5126 | #[test] |
| 5127 | fn signed_facts_correct_models_dev_enrichment_on_the_exact_route() { |
| 5128 | use codewhale_config::cloud_facts::{ModelFact, PricingFact}; |
| 5129 | let _env = cloud_facts_test_env(); |
| 5130 | |
| 5131 | let provider = ProviderKind::Deepseek; |
| 5132 | let base = provider.provider().default_base_url(); |
| 5133 | let model = "deepseek-enriched-only"; |
| 5134 | let body = format!( |
| 5135 | r#"{{ |
| 5136 | "models": {{}}, |
| 5137 | "providers": {{ |
| 5138 | "deepseek": {{ |
| 5139 | "id": "deepseek", |
| 5140 | "models": {{ |
| 5141 | "{model}": {{ |
| 5142 | "id": "{model}", |
| 5143 | "modalities": {{ "input": ["text"], "output": ["text"] }}, |
| 5144 | "limit": {{ "context": 65536, "output": 4096 }}, |
| 5145 | "cost": {{ "input": 2.0, "output": 8.0 }} |
| 5146 | }} |
| 5147 | }} |
| 5148 | }} |
| 5149 | }} |
| 5150 | }}"# |
| 5151 | ); |
| 5152 | let catalog = |
| 5153 | codewhale_config::models_dev::ModelsDevCatalog::parse_json(&body).expect("parse"); |
| 5154 | set_live_snapshot( |
| 5155 | CatalogSnapshot { |
| 5156 | offerings: codewhale_config::catalog::live_offerings_from_models_dev( |
| 5157 | &catalog, |
| 5158 | codewhale_config::catalog::now_unix(), |
| 5159 | ), |
| 5160 | }, |
| 5161 | LiveSource::ModelsDev, |
| 5162 | ); |
| 5163 | |
| 5164 | // A refreshed row describes a model, not an endpoint, so the route |
| 5165 | // resolves it without an endpoint fingerprint to match against. |
| 5166 | let enriched = catalog_offering_for_route(provider, "deepseek", base, model) |
| 5167 | .expect("the enriched row answers on the provider's own endpoint"); |
| 5168 | assert_eq!( |
| 5169 | enriched.limit.as_ref().and_then(|limit| limit.context), |
| 5170 | Some(65_536) |
| 5171 | ); |
| 5172 | |
| 5173 | publish_test_facts( |
| 5174 | "models-dev-correction-test", |
| 5175 | 1, |
| 5176 | bounded(), |
| 5177 | vec![ModelFact { |
| 5178 | pricing: Some(PricingFact { |
| 5179 | input_per_m: Some(0.5), |
| 5180 | output_per_m: Some(1.5), |
| 5181 | ..Default::default() |
| 5182 | }), |
| 5183 | ..upsert_fact("deepseek", model, 131_072) |
| 5184 | }], |
| 5185 | ); |
| 5186 | |
| 5187 | let corrected = catalog_offering_for_route(provider, "deepseek", base, model) |
| 5188 | .expect("the corrected row is still offered"); |
| 5189 | let limit = corrected.limit.clone().expect("limits are kept"); |
| 5190 | assert_eq!( |
| 5191 | limit.context, |
| 5192 | Some(131_072), |
| 5193 | "the stale window is corrected" |
| 5194 | ); |
| 5195 | assert_eq!( |
| 5196 | limit.output, |
| 5197 | Some(4_096), |
| 5198 | "and only what the payload states is replaced" |
| 5199 | ); |
| 5200 | assert_eq!( |
| 5201 | corrected.cost.as_ref().and_then(|cost| cost.input), |
| 5202 | Some(0.5), |
| 5203 | "the signed rate replaces the enriched one" |
| 5204 | ); |
| 5205 | assert!(matches!( |
| 5206 | corrected.pricing_source(), |
| 5207 | CatalogSource::CloudFacts { .. } |
| 5208 | )); |
| 5209 | |
| 5210 | // The executor reads the same correction the picker does. |
| 5211 | let config = { |
| 5212 | let __cw_config_init_5_0 = Some("deepseek".into()); |
| 5213 | let mut __cw_config_init_5_value: Config = Default::default(); |
| 5214 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 5215 | __cw_config_init_5_value |
| 5216 | }; |
| 5217 | assert_eq!( |
| 5218 | crate::route_runtime::resolve_runtime_route(&config, provider, Some(model)) |
| 5219 | .unwrap() |
| 5220 | .candidate |
| 5221 | .limits() |
| 5222 | .context_tokens, |
| 5223 | Some(131_072) |
| 5224 | ); |
| 5225 | |
| 5226 | // A corrected rate is only worth rendering where it is billable, and |
| 5227 | // only on the endpoint and identity the signer named. |
| 5228 | let quote = |identity: &str, endpoint: &str| { |
| 5229 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 5230 | provider, |
| 5231 | identity, |
| 5232 | model, |
| 5233 | endpoint, |
| 5234 | codewhale_config::catalog::now_unix(), |
| 5235 | ) |
| 5236 | }; |
| 5237 | assert!( |
| 5238 | quote("deepseek", base).is_some(), |
| 5239 | "the corrected rate bills on the exact signed route" |
| 5240 | ); |
| 5241 | assert!( |
| 5242 | quote("deepseek", "https://deepseek-proxy.invalid/v1").is_none(), |
| 5243 | "a proxied base URL never inherits it" |
| 5244 | ); |
| 5245 | assert!( |
| 5246 | quote("deepseek-custom-table", base).is_none(), |
| 5247 | "a differently-named provider table is a separate billing relationship" |
| 5248 | ); |
| 5249 | |
| 5250 | // A fresh roster is still the authority for the ids it lists: it |
| 5251 | // suppresses the enrichment and the correction that rode on it. |
| 5252 | record_roster(base, vec![roster_row(base, "deepseek-v4-pro")]); |
| 5253 | assert!( |
| 5254 | catalog_offering_for_route(provider, "deepseek", base, model).is_none(), |
| 5255 | "an unattested correction cannot survive the roster's omission" |
| 5256 | ); |
| 5257 | } |
| 5258 | |
| 5259 | /// #6705: through the production runtime resolver, a curated Zen |
| 5260 | /// transport row wins over a Models.dev row for the same id, a |
| 5261 | /// catalog-only row routes on the wire its row declares, and a deprecated |
| 5262 | /// catalog row stays unroutable. |
| 5263 | #[test] |
| 5264 | fn opencode_zen_runtime_resolver_keeps_curated_wire_over_models_dev_row() { |
| 5265 | use codewhale_config::models_dev::ModelsDevCatalog; |
| 5266 | use codewhale_config::route::{LogicalModelRef, RequestProtocol, RouteError, RouteRequest}; |
| 5267 | |
| 5268 | let _live = lock_live_snapshot(); |
| 5269 | clear_live_snapshot(); |
| 5270 | let raw = r#"{ |
| 5271 | "providers": { |
| 5272 | "opencode": { |
| 5273 | "id": "opencode", |
| 5274 | "npm": "@ai-sdk/openai-compatible", |
| 5275 | "models": { |
| 5276 | "gpt-5.6-sol": { "id": "gpt-5.6-sol", "provider": { "npm": "@ai-sdk/anthropic" } }, |
| 5277 | "claude-opus-9": { "id": "claude-opus-9", "provider": { "npm": "@ai-sdk/anthropic" } }, |
| 5278 | "claude-2-retired": { |
| 5279 | "id": "claude-2-retired", |
| 5280 | "status": "deprecated", |
| 5281 | "provider": { "npm": "@ai-sdk/anthropic" } |
| 5282 | } |
| 5283 | } |
| 5284 | } |
| 5285 | } |
| 5286 | }"#; |
| 5287 | let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses"); |
| 5288 | set_live_snapshot( |
| 5289 | CatalogSnapshot { |
| 5290 | offerings: codewhale_config::catalog::live_offerings_from_models_dev(&catalog, 1), |
| 5291 | }, |
| 5292 | LiveSource::ModelsDev, |
| 5293 | ); |
| 5294 | |
| 5295 | let provider = ProviderKind::OpencodeZen; |
| 5296 | let resolver = runtime_catalog_resolver_for_identity( |
| 5297 | provider, |
| 5298 | None, |
| 5299 | provider.provider().default_base_url(), |
| 5300 | CatalogStatus::Unknown, |
| 5301 | ) |
| 5302 | .resolver; |
| 5303 | let resolve = |model: &str| { |
| 5304 | resolver.resolve(&RouteRequest { |
| 5305 | explicit_provider: Some(provider), |
| 5306 | model_selector: Some(LogicalModelRef::from(model)), |
| 5307 | saved_provider_model: None, |
| 5308 | base_url_override: None, |
| 5309 | limit_overrides: Vec::new(), |
| 5310 | wire_override: None, |
| 5311 | responses_profile_override: None, |
| 5312 | }) |
| 5313 | }; |
| 5314 | |
| 5315 | let curated = resolve("gpt-5.6-sol").expect("curated Zen row resolves"); |
| 5316 | assert_eq!( |
| 5317 | curated.protocol(), |
| 5318 | RequestProtocol::Responses, |
| 5319 | "the curated transport row must win over the catalog's conflicting row" |
| 5320 | ); |
| 5321 | let catalog_only = resolve("claude-opus-9").expect("catalog-proven Zen row resolves"); |
| 5322 | assert_eq!(catalog_only.protocol(), RequestProtocol::AnthropicMessages); |
| 5323 | match resolve("claude-2-retired") { |
| 5324 | Err(RouteError::UnsupportedModelProtocol { endpoint_key, .. }) => { |
| 5325 | assert_eq!(endpoint_key, "deprecated"); |
| 5326 | } |
| 5327 | other => panic!("a deprecated Zen row must fail closed, got {other:?}"), |
| 5328 | } |
| 5329 | |
| 5330 | clear_live_snapshot(); |
| 5331 | } |
| 5332 | |
| 5333 | #[test] |
| 5334 | fn provider_capability_reads_resolved_route_facts_and_wire_policy() { |
| 5335 | let google_prefixed = provider_capability(ProviderKind::Google, "models/gemini-4-hydrogen"); |
| 5336 | let google_bare = provider_capability(ProviderKind::Google, "gemini-4-hydrogen"); |
| 5337 | assert_eq!(google_prefixed.context_window, 1_048_576); |
| 5338 | assert_eq!(google_prefixed.max_output, Some(65_536)); |
| 5339 | assert!(google_prefixed.thinking_supported); |
| 5340 | assert_eq!(google_prefixed.context_window, google_bare.context_window); |
| 5341 | assert_eq!(google_prefixed.max_output, google_bare.max_output); |
| 5342 | |
| 5343 | assert_eq!( |
| 5344 | provider_capability(ProviderKind::Deepseek, "deepseek-flash").request_payload_mode, |
| 5345 | RequestPayloadMode::Responses |
| 5346 | ); |
| 5347 | assert_eq!( |
| 5348 | provider_capability(ProviderKind::Deepseek, "deepseek-v4-pro").request_payload_mode, |
| 5349 | RequestPayloadMode::ChatCompletions |
| 5350 | ); |
| 5351 | assert_eq!( |
| 5352 | provider_capability(ProviderKind::OpencodeZen, "claude-opus-5").request_payload_mode, |
| 5353 | RequestPayloadMode::AnthropicMessages |
| 5354 | ); |
| 5355 | assert_eq!( |
| 5356 | provider_capability(ProviderKind::Concentrate, "deepseek-v4-pro").request_payload_mode, |
| 5357 | RequestPayloadMode::Responses |
| 5358 | ); |
| 5359 | } |
| 5360 | |
| 5361 | #[test] |
| 5362 | fn provider_capability_prefers_live_limits_and_preserves_ollama_show_context() { |
| 5363 | let _live = lock_live_snapshot(); |
| 5364 | clear_live_snapshot(); |
| 5365 | |
| 5366 | merge_live_offerings(vec![ |
| 5367 | CatalogOffering { |
| 5368 | provider: "ollama".to_string(), |
| 5369 | wire_model_id: "qwen3:32b".to_string(), |
| 5370 | endpoint_key: "chat".to_string(), |
| 5371 | default_for_provider: true, |
| 5372 | limit: Some(codewhale_config::models_dev::ModelsDevLimit { |
| 5373 | context: Some(131_072), |
| 5374 | input: Some(131_072), |
| 5375 | output: None, |
| 5376 | }), |
| 5377 | reasoning: Some(true), |
| 5378 | source: CatalogSource::Live { |
| 5379 | base_url_fingerprint: "ollama-fp".to_string(), |
| 5380 | fetched_at: 1, |
| 5381 | }, |
| 5382 | ..Default::default() |
| 5383 | }, |
| 5384 | CatalogOffering { |
| 5385 | provider: "sglang".to_string(), |
| 5386 | wire_model_id: "deepseek-ai/DeepSeek-V4-Pro".to_string(), |
| 5387 | endpoint_key: "chat".to_string(), |
| 5388 | limit: Some(codewhale_config::models_dev::ModelsDevLimit { |
| 5389 | context: Some(131_072), |
| 5390 | input: None, |
| 5391 | output: Some(16_384), |
| 5392 | }), |
| 5393 | source: CatalogSource::Live { |
| 5394 | base_url_fingerprint: "sglang-fp".to_string(), |
| 5395 | fetched_at: 1, |
| 5396 | }, |
| 5397 | ..Default::default() |
| 5398 | }, |
| 5399 | ]); |
| 5400 | |
| 5401 | let ollama_cap = provider_capability(ProviderKind::Ollama, "qwen3:32b"); |
| 5402 | assert_eq!(ollama_cap.context_window, 131_072); |
| 5403 | assert!(ollama_cap.thinking_supported); |
| 5404 | |
| 5405 | let mut stale_ps_row = CatalogOffering { |
| 5406 | provider: "ollama".to_string(), |
| 5407 | wire_model_id: "qwen3:32b".to_string(), |
| 5408 | endpoint_key: "chat".to_string(), |
| 5409 | limit: Some(codewhale_config::models_dev::ModelsDevLimit { |
| 5410 | context: Some(16_384), |
| 5411 | input: Some(131_072), |
| 5412 | output: None, |
| 5413 | }), |
| 5414 | source: CatalogSource::Live { |
| 5415 | base_url_fingerprint: "ollama-fp".to_string(), |
| 5416 | fetched_at: 1, |
| 5417 | }, |
| 5418 | ..Default::default() |
| 5419 | }; |
| 5420 | stale_ps_row |
| 5421 | .fact_sources |
| 5422 | .insert("limit.context.ps".to_string(), stale_ps_row.source.clone()); |
| 5423 | let expired_ps = current_local_context(ProviderKind::Ollama, stale_ps_row); |
| 5424 | assert_eq!( |
| 5425 | expired_ps.limit.as_ref().and_then(|limit| limit.context), |
| 5426 | Some(131_072) |
| 5427 | ); |
| 5428 | |
| 5429 | let show_only_row = CatalogOffering { |
| 5430 | provider: "ollama".to_string(), |
| 5431 | wire_model_id: "qwen3:32b".to_string(), |
| 5432 | endpoint_key: "chat".to_string(), |
| 5433 | limit: Some(codewhale_config::models_dev::ModelsDevLimit { |
| 5434 | context: Some(131_072), |
| 5435 | input: Some(131_072), |
| 5436 | output: None, |
| 5437 | }), |
| 5438 | source: CatalogSource::Live { |
| 5439 | base_url_fingerprint: "ollama-fp".to_string(), |
| 5440 | fetched_at: 1, |
| 5441 | }, |
| 5442 | ..Default::default() |
| 5443 | }; |
| 5444 | let retained_show = current_local_context(ProviderKind::Ollama, show_only_row); |
| 5445 | assert_eq!( |
| 5446 | retained_show.limit.as_ref().and_then(|limit| limit.context), |
| 5447 | Some(131_072) |
| 5448 | ); |
| 5449 | |
| 5450 | let sglang_live_cap = provider_capability(ProviderKind::Sglang, "deepseek-v4-pro"); |
| 5451 | assert_eq!(sglang_live_cap.context_window, 131_072); |
| 5452 | assert_eq!(sglang_live_cap.max_output, Some(16_384)); |
| 5453 | |
| 5454 | set_live_snapshot( |
| 5455 | CatalogSnapshot { |
| 5456 | offerings: vec![CatalogOffering { |
| 5457 | provider: "google".to_string(), |
| 5458 | wire_model_id: "gemma-4-31b-it".to_string(), |
| 5459 | endpoint_key: "chat".to_string(), |
| 5460 | limit: Some(codewhale_config::models_dev::ModelsDevLimit { |
| 5461 | context: Some(524_288), |
| 5462 | input: None, |
| 5463 | output: Some(65_536), |
| 5464 | }), |
| 5465 | source: CatalogSource::ModelsDevLive { fetched_at: 10 }, |
| 5466 | ..Default::default() |
| 5467 | }], |
| 5468 | }, |
| 5469 | LiveSource::ModelsDev, |
| 5470 | ); |
| 5471 | let models_dev_live_cap = provider_capability(ProviderKind::Google, "gemma-4-31b-it"); |
| 5472 | assert_eq!(models_dev_live_cap.context_window, 524_288); |
| 5473 | assert_eq!(models_dev_live_cap.max_output, Some(65_536)); |
| 5474 | |
| 5475 | clear_live_snapshot(); |
| 5476 | } |
| 5477 | |
| 5478 | #[test] |
| 5479 | fn format_receipt_freshness_renders_utc_age_and_omits_unknown_observed_at() { |
| 5480 | let epoch = 1_796_107_052; |
| 5481 | let now = epoch + 300; |
| 5482 | let only_fetched = format_receipt_freshness_fields(Some(epoch), None, now); |
| 5483 | assert_eq!(only_fetched, "fetched_at=2026-12-01T06:37:32Z (5m ago)"); |
| 5484 | assert!(!only_fetched.contains("observed_at")); |
| 5485 | |
| 5486 | let both = format_receipt_freshness_fields(Some(epoch), Some(epoch + 240), now); |
| 5487 | assert_eq!( |
| 5488 | both, |
| 5489 | "fetched_at=2026-12-01T06:37:32Z (5m ago)\tobserved_at=2026-12-01T06:41:32Z (1m ago)" |
| 5490 | ); |
| 5491 | |
| 5492 | let unknown = format_receipt_freshness_fields(None, None, now); |
| 5493 | assert_eq!(unknown, "fetched_at=unknown"); |
| 5494 | } |
| 5495 | } |
| 5496 |