返回 CodeWhale
tests.rs
根目录 / crates / config / src / catalog / tests.rs
1 //! Behavior tests for the Models.dev-backed catalog cache (#3385).
2 //!
3 //! Fixtures use synthetic ids for anti-hardcoding guards, plus the GLM-5.2 and
4 //! hosted-DeepSeek rows the issue explicitly asks to exercise. No full hosted
5 //! provider model list is copied here.
6
7 use super::*;
8
9 /// Zhipu canonical + Zhipu/Z.AI provider offerings, and a hosted DeepSeek row
10 /// served by an aggregator under a prefixed wire id with an explicit canonical
11 /// `base_model` join.
12 const FIXTURE: &str = r#"{
13 "models": {
14 "zhipuai/glm-5.2": {
15 "id": "zhipuai/glm-5.2",
16 "family": "glm",
17 "reasoning": true,
18 "modalities": { "input": ["text"], "output": ["text"] },
19 "limit": { "context": 1000000, "output": 131072 }
20 }
21 },
22 "providers": {
23 "zhipuai": {
24 "id": "zhipuai",
25 "models": {
26 "glm-5.2": {
27 "id": "glm-5.2",
28 "family": "glm",
29 "default": true,
30 "attachment": false,
31 "reasoning": true,
32 "reasoning_options": [{ "type": "effort", "values": ["high", "max"] }],
33 "tool_call": true,
34 "structured_output": true,
35 "modalities": { "input": ["text"], "output": ["text"] },
36 "limit": { "context": 1000000, "output": 131072 },
37 "cost": { "input": 1.4, "output": 4.4, "cache_read": 0.26 }
38 },
39 "glm-voice": {
40 "id": "glm-voice",
41 "modalities": { "input": ["text"], "output": ["audio"] }
42 }
43 }
44 },
45 "together": {
46 "id": "together",
47 "models": {
48 "deepseek-ai/DeepSeek-V4-Pro": {
49 "id": "deepseek-ai/DeepSeek-V4-Pro",
50 "base_model": "deepseek-v4-pro",
51 "family": "deepseek",
52 "reasoning": false,
53 "modalities": { "input": ["text"], "output": ["text"] },
54 "cost": { "input": 0.9, "output": 0.9 }
55 }
56 }
57 }
58 }
59 }"#;
60
61 fn fixture() -> ModelsDevCatalog {
62 ModelsDevCatalog::parse_json(FIXTURE).expect("fixture parses")
63 }
64
65 fn find<'a>(rows: &'a [CatalogOffering], provider: &str, wire: &str) -> &'a CatalogOffering {
66 rows.iter()
67 .find(|r| r.provider == provider && r.wire_model_id == wire)
68 .unwrap_or_else(|| panic!("offering {provider}/{wire} not found"))
69 }
70
71 #[test]
72 fn hydrates_models_dev_offerings_preserving_offering_facts() {
73 let rows = bundled_offerings_from_models_dev(&fixture());
74
75 // glm-voice (audio output) is excluded; two chat offerings remain.
76 assert_eq!(rows.len(), 2, "audio-only rows are not chat offerings");
77
78 let glm = find(&rows, "zhipuai", "glm-5.2");
79 assert!(glm.default_for_provider);
80 assert_eq!(glm.family.as_deref(), Some("glm"));
81 assert_eq!(glm.reasoning, Some(true));
82 assert_eq!(glm.attachment, Some(false));
83 assert_eq!(glm.tool_call, Some(true));
84 assert_eq!(glm.structured_output, Some(true));
85 // Provider-scoped reasoning options are preserved, not collapsed.
86 assert_eq!(glm.reasoning_options.len(), 1);
87 assert_eq!(glm.limit.as_ref().and_then(|l| l.context), Some(1_000_000));
88 assert_eq!(glm.cost.as_ref().and_then(|c| c.cache_read), Some(0.26));
89 // Provider row carried no base_model link → no inferred canonical model.
90 assert_eq!(glm.canonical_model, None);
91 assert_eq!(glm.source, CatalogSource::Bundled);
92 }
93
94 #[test]
95 fn hosted_offering_keeps_prefixed_wire_id_and_explicit_canonical_join() {
96 let rows = bundled_offerings_from_models_dev(&fixture());
97 let hosted = find(&rows, "together", "deepseek-ai/DeepSeek-V4-Pro");
98
99 // The prefixed wire id is preserved verbatim under the serving provider.
100 assert_eq!(hosted.wire_model_id, "deepseek-ai/DeepSeek-V4-Pro");
101 assert_eq!(hosted.provider, "together");
102 // Canonical link comes only from the explicit base_model.
103 assert_eq!(hosted.canonical_model.as_deref(), Some("deepseek-v4-pro"));
104 assert_eq!(hosted.reasoning, Some(false));
105 }
106
107 #[test]
108 fn model_only_rows_use_namespaced_keys_and_preserve_unpriced_facts() {
109 let catalog = ModelsDevCatalog::parse_json(
110 r#"{
111 "models": {
112 "moonshotai/synthetic/chat": {
113 "id": "",
114 "family": "synthetic",
115 "attachment": true,
116 "reasoning": true,
117 "tool_call": true,
118 "structured_output": false,
119 "limit": { "context": 123456, "output": 7890 },
120 "modalities": { "input": ["text", "image"], "output": ["text"] }
121 },
122 "new-vendor/solo": {},
123 "xiaomi/synthetic-chat": {},
124 "bare-model": {},
125 "/missing-provider": {},
126 "missing-model/": {},
127 "new-vendor/voice": {
128 "modalities": { "input": ["text"], "output": ["audio"] }
129 }
130 }
131 }"#,
132 )
133 .expect("fixture parses");
134
135 for live in [false, true] {
136 let (rows, provider, source) = if live {
137 (
138 live_offerings_from_models_dev(&catalog, 1_700),
139 "moonshot",
140 CatalogSource::ModelsDevLive { fetched_at: 1_700 },
141 )
142 } else {
143 (
144 bundled_offerings_from_models_dev(&catalog),
145 "moonshot",
146 CatalogSource::Bundled,
147 )
148 };
149 assert_eq!(
150 rows.len(),
151 3,
152 "unqualified and audio-only rows stay excluded"
153 );
154 let row = find(&rows, provider, "synthetic/chat");
155 assert_eq!(
156 row.canonical_model.as_deref(),
157 Some("moonshotai/synthetic/chat")
158 );
159 assert_eq!(row.endpoint_key, "chat");
160 assert_eq!(row.family.as_deref(), Some("synthetic"));
161 assert_eq!(
162 row.limit.as_ref().and_then(|limit| limit.context),
163 Some(123456)
164 );
165 assert_eq!(
166 row.limit.as_ref().and_then(|limit| limit.output),
167 Some(7890)
168 );
169 assert_eq!(row.attachment, Some(true));
170 assert_eq!(row.reasoning, Some(true));
171 assert_eq!(row.tool_call, Some(true));
172 assert_eq!(row.structured_output, Some(false));
173 assert_eq!(row.modalities.as_ref().unwrap().input, ["text", "image"]);
174 assert_eq!(row.source, source);
175 assert!(rows.iter().all(|row| {
176 row.cost.is_none()
177 // A MiMo row's price is withheld by a Codewhale correction.
178 && (row.cost_source.is_none()
179 || matches!(row.cost_source, Some(CatalogSource::CodewhaleBundled { .. })))
180 && !row.default_for_provider
181 && row.reasoning_options.is_empty()
182 }));
183 // Vendor namespaces normalize offline too (#6396 slice B).
184 find(&rows, "xiaomi-mimo", "synthetic-chat");
185 find(&rows, "new-vendor", "solo");
186 assert!(crate::ProviderKind::parse("new-vendor").is_none());
187 }
188 }
189
190 #[test]
191 fn model_only_rows_yield_to_provider_facts_and_non_chat_exclusions() {
192 let catalog = ModelsDevCatalog::parse_json(
193 r#"{
194 "models": {
195 "moonshotai/chat": { "reasoning": true },
196 "moonshotai/voice": {},
197 "moonshot/duplicate": {},
198 "moonshotai/duplicate": {}
199 },
200 "providers": {
201 "moonshot": {
202 "id": "moonshot",
203 "models": {
204 "chat": {
205 "id": "chat",
206 "base_model": "explicit/chat",
207 "reasoning": false,
208 "reasoning_options": [{ "type": "effort", "values": ["high"] }],
209 "default": true,
210 "cost": { "input": 2.0 }
211 },
212 "voice": {
213 "id": "voice",
214 "modalities": { "input": ["text"], "output": ["audio"] }
215 }
216 }
217 }
218 }
219 }"#,
220 )
221 .expect("fixture parses");
222 let rows = live_offerings_from_models_dev(&catalog, 1_700);
223 assert_eq!(
224 rows.len(),
225 2,
226 "aliases deduplicate; provider exclusions win"
227 );
228 let row = find(&rows, "moonshot", "chat");
229 assert_eq!(row.canonical_model.as_deref(), Some("explicit/chat"));
230 assert_eq!(row.reasoning, Some(false));
231 assert!(row.default_for_provider);
232 assert_eq!(row.cost.as_ref().and_then(|cost| cost.input), Some(2.0));
233 assert_eq!(row.reasoning_options.len(), 1);
234 find(&rows, "moonshot", "duplicate");
235 }
236
237 #[test]
238 fn provider_map_keys_preserve_precedence_when_model_ids_are_missing() {
239 let catalog = ModelsDevCatalog::parse_json(
240 r#"{
241 "models": {
242 "moonshotai/chat": { "reasoning": true },
243 "moonshotai/voice": {},
244 "moonshotai/explicit": { "reasoning": true }
245 },
246 "providers": {
247 "moonshotai": {
248 "models": {
249 " chat ": { "id": " ", "reasoning": false },
250 "voice": { "modalities": { "output": ["audio"] } },
251 "different-map-key": { "id": " explicit ", "reasoning": false },
252 " ": {}
253 }
254 }
255 }
256 }"#,
257 )
258 .expect("fixture parses");
259
260 for (rows, provider) in [
261 (live_offerings_from_models_dev(&catalog, 1_700), "moonshot"),
262 (bundled_offerings_from_models_dev(&catalog), "moonshotai"),
263 ] {
264 assert_eq!(rows.len(), 2, "provider identities and exclusions win");
265 for wire_model_id in ["chat", "explicit"] {
266 let row = find(&rows, provider, wire_model_id);
267 assert_eq!(row.reasoning, Some(false));
268 assert_eq!(row.canonical_model, None);
269 }
270 }
271 }
272
273 #[test]
274 fn to_offering_projects_routing_identity_and_limits() {
275 let rows = bundled_offerings_from_models_dev(&fixture());
276 let glm = find(&rows, "zhipuai", "glm-5.2").to_offering();
277
278 assert_eq!(glm.provider.as_str(), "zhipuai");
279 assert_eq!(glm.wire_model_id.as_str(), "glm-5.2");
280 assert_eq!(glm.canonical_model, None);
281 assert_eq!(glm.endpoint_key, "chat");
282 assert_eq!(glm.limits.context_tokens, Some(1_000_000));
283 assert_eq!(glm.limits.output_tokens, Some(131_072));
284 assert_eq!(
285 glm.capabilities.attachments,
286 crate::route::CapabilityState::Unsupported
287 );
288 assert_eq!(
289 glm.capabilities.reasoning,
290 crate::route::CapabilityState::Supported
291 );
292 assert_eq!(
293 glm.capabilities.native_tool_calls,
294 crate::route::CapabilityState::Supported
295 );
296 assert_eq!(
297 glm.capabilities.structured_output,
298 crate::route::CapabilityState::Supported
299 );
300 assert_eq!(
301 glm.capabilities.streaming,
302 crate::route::CapabilityState::Unknown
303 );
304 }
305
306 #[test]
307 fn compiler_merges_layers_with_override_precedence() {
308 // Bundled default for synthetic provider "acme".
309 let bundled = vec![CatalogOffering {
310 provider: "acme".into(),
311 wire_model_id: "synth-chat-1".into(),
312 endpoint_key: "chat".into(),
313 default_for_provider: true,
314 family: Some("synth".into()),
315 source: CatalogSource::Bundled,
316 ..Default::default()
317 }];
318 // Live refresh adds a new row AND restates the bundled one with a cost.
319 let live = vec![
320 CatalogOffering {
321 provider: "acme".into(),
322 wire_model_id: "synth-chat-1".into(),
323 endpoint_key: "chat".into(),
324 cost: Some(ModelsDevCost {
325 input: Some(2.0),
326 ..Default::default()
327 }),
328 source: CatalogSource::Live {
329 base_url_fingerprint: "fp".into(),
330 fetched_at: 100,
331 },
332 ..Default::default()
333 },
334 CatalogOffering {
335 provider: "acme".into(),
336 wire_model_id: "synth-chat-2".into(),
337 endpoint_key: "chat".into(),
338 source: CatalogSource::Live {
339 base_url_fingerprint: "fp".into(),
340 fetched_at: 100,
341 },
342 ..Default::default()
343 },
344 ];
345 // User override pins a custom canonical model on synth-chat-1.
346 let overrides = vec![CatalogOffering {
347 provider: "acme".into(),
348 wire_model_id: "synth-chat-1".into(),
349 canonical_model: Some("acme-canonical".into()),
350 endpoint_key: "chat".into(),
351 source: CatalogSource::UserOverride,
352 ..Default::default()
353 }];
354
355 let snapshot = CatalogCompiler::new()
356 .with_bundled(bundled)
357 .with_live(live)
358 .with_overrides(overrides)
359 .compile();
360
361 // Two distinct (provider, wire) identities survive de-duplication.
362 assert_eq!(snapshot.offerings.len(), 2);
363
364 let one = find(&snapshot.offerings, "acme", "synth-chat-1");
365 // Highest-precedence layer (override) wins the identity collision.
366 assert_eq!(one.source, CatalogSource::UserOverride);
367 assert_eq!(one.canonical_model.as_deref(), Some("acme-canonical"));
368
369 let two = find(&snapshot.offerings, "acme", "synth-chat-2");
370 assert!(matches!(two.source, CatalogSource::Live { .. }));
371 }
372
373 #[test]
374 fn compiler_layer_order_and_policy_deny_never_overridden() {
375 let row = |source: CatalogSource, model: &str, family: &str| CatalogOffering {
376 provider: "zai-coding-cn".into(),
377 wire_model_id: model.into(),
378 endpoint_key: "chat".into(),
379 family: Some(family.into()),
380 source,
381 ..Default::default()
382 };
383 let policy = crate::route::CatalogPolicy {
384 rules: vec![crate::route::PolicyRule {
385 effect: crate::route::PolicyEffect::Deny,
386 action: crate::route::PolicyAction::ModelUse,
387 resource: "*-cn/*".to_string(),
388 }],
389 };
390 let snapshot = CatalogCompiler::new()
391 .with_bundled(vec![row(CatalogSource::Bundled, "glm-5", "bundled")])
392 .with_models_dev_live(vec![row(
393 CatalogSource::ModelsDevLive { fetched_at: 1 },
394 "glm-5",
395 "models-dev",
396 )])
397 .with_provider_live(vec![row(
398 CatalogSource::Live {
399 base_url_fingerprint: "fp".into(),
400 fetched_at: 2,
401 },
402 "glm-5",
403 "provider",
404 )])
405 .with_config(vec![row(CatalogSource::ConfigOverride, "glm-5", "config")])
406 .with_overrides(vec![row(CatalogSource::UserOverride, "glm-5", "user")])
407 .with_policy(policy)
408 .compile();
409
410 assert!(
411 snapshot.offerings.is_empty(),
412 "policy DENY after every layer must drop the row; layers cannot override it"
413 );
414
415 let allowed = CatalogCompiler::new()
416 .with_bundled(vec![row(CatalogSource::Bundled, "glm-5", "bundled")])
417 .with_overrides(vec![row(CatalogSource::UserOverride, "glm-5", "user")])
418 .compile();
419 let kept = find(&allowed.offerings, "zai-coding-cn", "glm-5");
420 assert_eq!(kept.source, CatalogSource::UserOverride);
421 assert_eq!(kept.family.as_deref(), Some("user"));
422 }
423
424 #[test]
425 fn cache_scopes_by_provider_and_base_url_fingerprint() {
426 let fp_a = base_url_fingerprint("https://api.example.com/v1");
427 let fp_b = base_url_fingerprint("https://other.example.com/v1");
428 assert_ne!(fp_a, fp_b, "different hosts must not share a fingerprint");
429
430 let mut cache = ProviderCatalogCache::new();
431 let row = |id: &str| CatalogOffering {
432 provider: "acme".into(),
433 wire_model_id: id.into(),
434 endpoint_key: "chat".into(),
435 ..Default::default()
436 };
437
438 // Same provider, two different base URLs.
439 cache.record_success(
440 ProviderCatalogDelta {
441 provider: "acme".into(),
442 base_url_fingerprint: fp_a.clone(),
443 fetched_at: 1_000,
444 offerings: vec![row("from-a")],
445 },
446 3_600,
447 );
448 cache.record_success(
449 ProviderCatalogDelta {
450 provider: "acme".into(),
451 base_url_fingerprint: fp_b.clone(),
452 fetched_at: 1_000,
453 offerings: vec![row("from-b")],
454 },
455 3_600,
456 );
457 // Different provider, SAME base URL as fp_a.
458 cache.record_success(
459 ProviderCatalogDelta {
460 provider: "beta".into(),
461 base_url_fingerprint: fp_a.clone(),
462 fetched_at: 1_000,
463 offerings: vec![row("from-beta")],
464 },
465 3_600,
466 );
467
468 let a = cache.fresh_offerings("acme", &fp_a, 1_100);
469 assert_eq!(a.len(), 1);
470 assert_eq!(a[0].wire_model_id, "from-a");
471 // Same provider, different base URL must not leak rows across.
472 let b = cache.fresh_offerings("acme", &fp_b, 1_100);
473 assert_eq!(b[0].wire_model_id, "from-b");
474 // Different provider on the same base URL must not share rows either.
475 let beta = cache.fresh_offerings("beta", &fp_a, 1_100);
476 assert_eq!(beta[0].wire_model_id, "from-beta");
477 assert_eq!(cache.entries.len(), 3);
478 }
479
480 #[test]
481 fn fingerprint_folds_cosmetic_base_url_differences() {
482 let canonical = base_url_fingerprint("https://API.Example.com/v1");
483 assert_eq!(canonical.len(), 64, "endpoint fingerprints use SHA-256");
484 assert_eq!(
485 canonical,
486 base_url_fingerprint("https://api.example.com/v1/"),
487 "trailing slash + host case must not change the cache scope"
488 );
489 assert_eq!(
490 canonical,
491 base_url_fingerprint(" https://api.example.com:443/v1 "),
492 "default https port + surrounding whitespace must fold away"
493 );
494 // Path case is significant (providers can be case-sensitive on the path).
495 assert_ne!(
496 canonical,
497 base_url_fingerprint("https://api.example.com/V1")
498 );
499
500 // Port stripping is scheme-aware: :80 is http's default (folds away), but
501 // :443 on http is a non-default port and must stay distinct from bare http.
502 assert_eq!(
503 base_url_fingerprint("http://h.example.com:80/v1"),
504 base_url_fingerprint("http://h.example.com/v1"),
505 "http default port :80 must fold away"
506 );
507 assert_ne!(
508 base_url_fingerprint("http://h.example.com:443/v1"),
509 base_url_fingerprint("http://h.example.com/v1"),
510 ":443 is not http's default port and must not fold"
511 );
512 }
513
514 #[test]
515 fn fingerprint_never_hashes_secret_bearing_url_text() {
516 let expected = base_url_fingerprint("https://api.example.com/v1");
517 for url in [
518 "https://user:secret@api.example.com/v1",
519 "https://api.example.com/v1?api_key=secret",
520 "https://api.example.com/v1#secret",
521 ] {
522 assert_eq!(base_url_fingerprint(url), expected, "{url}");
523 }
524 }
525
526 #[test]
527 fn fingerprint_strips_userinfo_from_a_scheme_less_base_url() {
528 // A base_url typed without a scheme took the fall-through branch, which
529 // only split off `?`/`#` — so `user:pass@host` went into SHA-256 verbatim,
530 // against the documented "userinfo never enters the digest function".
531 let expected = base_url_fingerprint("api.example.com/v1");
532 for url in [
533 "user:secret@api.example.com/v1",
534 "user:other-secret@api.example.com/v1",
535 "token@api.example.com/v1",
536 ] {
537 assert_eq!(base_url_fingerprint(url), expected, "{url}");
538 }
539 }
540
541 #[test]
542 fn fingerprint_of_an_empty_base_url_is_the_redacted_constant() {
543 // The fall-through's `unwrap_or(REDACTED)` never fired — `split` always
544 // yields at least one (possibly empty) piece — so an empty base URL
545 // fingerprinted the empty string instead of the redacted sentinel.
546 let redacted = base_url_fingerprint("ftp://api.example.com");
547 for url in ["", " ", "?api_key=secret"] {
548 assert_eq!(base_url_fingerprint(url), redacted, "{url:?}");
549 }
550 // SHA-256("") is what empty/whitespace hashed to before the sentinel
551 // mapping. That digest is a persisted cache/receipt key, so flipping it
552 // back would be another undeclared persisted-key change.
553 const EMPTY_SHA256: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
554 assert_ne!(redacted, EMPTY_SHA256);
555 }
556
557 #[test]
558 fn ttl_marks_entries_stale_and_excludes_them_from_fresh() {
559 let fp = base_url_fingerprint("https://api.example.com");
560 let mut cache = ProviderCatalogCache::new();
561 cache.record_success(
562 ProviderCatalogDelta {
563 provider: "acme".into(),
564 base_url_fingerprint: fp.clone(),
565 fetched_at: 1_000,
566 offerings: vec![CatalogOffering {
567 provider: "acme".into(),
568 wire_model_id: "synth-chat-1".into(),
569 endpoint_key: "chat".into(),
570 ..Default::default()
571 }],
572 },
573 100, // ttl
574 );
575
576 // Within TTL: fresh.
577 assert_eq!(cache.status("acme", &fp, 1_050), CatalogStatus::Fresh);
578 assert_eq!(cache.fresh_offerings("acme", &fp, 1_050).len(), 1);
579
580 // Past TTL: stale, and excluded from fresh offerings.
581 match cache.status("acme", &fp, 1_200) {
582 CatalogStatus::Stale { age_secs } => assert_eq!(age_secs, 200),
583 other => panic!("expected stale, got {other:?}"),
584 }
585 assert!(cache.fresh_offerings("acme", &fp, 1_200).is_empty());
586 // But the rows are still present in the cache for explicit fallback display.
587 assert_eq!(cache.get("acme", &fp).unwrap().offerings.len(), 1);
588 }
589
590 #[test]
591 fn future_catalog_timestamps_cannot_extend_freshness() {
592 let fp = base_url_fingerprint("https://api.example.com");
593 let mut cache = ProviderCatalogCache::new();
594 cache.record_success(
595 ProviderCatalogDelta {
596 provider: "acme".into(),
597 base_url_fingerprint: fp.clone(),
598 fetched_at: 1_300,
599 offerings: vec![CatalogOffering {
600 provider: "acme".into(),
601 wire_model_id: "synth-chat-1".into(),
602 ..Default::default()
603 }],
604 },
605 100,
606 );
607 assert_eq!(cache.fresh_offerings("acme", &fp, 1_000).len(), 1);
608 assert!(cache.fresh_offerings("acme", &fp, 999).is_empty());
609 assert!(matches!(
610 cache.status("acme", &fp, 999),
611 CatalogStatus::Stale { .. }
612 ));
613 assert_eq!(cache.get("acme", &fp).unwrap().offerings.len(), 1);
614 let entry = cache.entries.values_mut().next().unwrap();
615 entry.fetched_at = u64::MAX;
616 assert!(!entry.is_fresh(1_000));
617 entry.fetched_at = u64::MAX - 1;
618 assert!(entry.is_fresh(u64::MAX - 2));
619 }
620
621 #[test]
622 fn ttl_zero_is_always_stale() {
623 let fp = base_url_fingerprint("https://api.example.com");
624 let mut cache = ProviderCatalogCache::new();
625 cache.record_success(
626 ProviderCatalogDelta {
627 provider: "acme".into(),
628 base_url_fingerprint: fp.clone(),
629 fetched_at: 1_000,
630 offerings: vec![],
631 },
632 0,
633 );
634 assert!(cache.get("acme", &fp).unwrap().is_stale(1_000));
635 }
636
637 #[test]
638 fn unknown_scope_reports_unknown_status() {
639 let cache = ProviderCatalogCache::new();
640 let fp = base_url_fingerprint("https://api.example.com");
641 assert_eq!(cache.status("acme", &fp, 1_000), CatalogStatus::Unknown);
642 assert!(cache.fresh_offerings("acme", &fp, 1_000).is_empty());
643 }
644
645 #[test]
646 fn refresh_failure_preserves_prior_rows_and_marks_failed() {
647 let fp = base_url_fingerprint("https://api.example.com");
648 let mut cache = ProviderCatalogCache::new();
649 cache.record_success(
650 ProviderCatalogDelta {
651 provider: "acme".into(),
652 base_url_fingerprint: fp.clone(),
653 fetched_at: 1_000,
654 offerings: vec![CatalogOffering {
655 provider: "acme".into(),
656 wire_model_id: "synth-chat-1".into(),
657 endpoint_key: "chat".into(),
658 ..Default::default()
659 }],
660 },
661 3_600,
662 );
663
664 for reason in [
665 CatalogRefreshError::Unauthorized,
666 CatalogRefreshError::Forbidden,
667 CatalogRefreshError::NotFound,
668 CatalogRefreshError::RateLimited,
669 CatalogRefreshError::InvalidResponse,
670 CatalogRefreshError::EmptyList,
671 CatalogRefreshError::Network,
672 ] {
673 cache.record_failure("acme", &fp, reason);
674 let entry = cache.get("acme", &fp).expect("entry survives failure");
675 // Prior successful rows remain available after a failed refresh.
676 assert_eq!(entry.offerings.len(), 1, "{reason:?} dropped prior rows");
677 assert_eq!(entry.status, CatalogStatus::Failed { reason });
678 // fetched_at is NOT bumped by a failure.
679 assert_eq!(entry.fetched_at, 1_000);
680 // ...but a Failed entry must NOT contribute to fresh offerings even
681 // while still within its TTL window (now=1_100, ttl=3_600). The rows
682 // are reachable only via get() for explicit fallback display.
683 assert!(
684 cache.fresh_offerings("acme", &fp, 1_100).is_empty(),
685 "{reason:?}: failed entry served fresh offerings within TTL"
686 );
687 assert!(cache.all_fresh_offerings(1_100).is_empty());
688 assert_eq!(
689 cache.status("acme", &fp, 1_100),
690 CatalogStatus::Failed { reason }
691 );
692 }
693 }
694
695 #[test]
696 fn failure_without_prior_creates_observable_empty_entry() {
697 let fp = base_url_fingerprint("https://api.example.com");
698 let mut cache = ProviderCatalogCache::new();
699 cache.record_failure("acme", &fp, CatalogRefreshError::Unauthorized);
700
701 let entry = cache.get("acme", &fp).expect("failure is observable");
702 assert!(entry.offerings.is_empty());
703 assert_eq!(
704 entry.status,
705 CatalogStatus::Failed {
706 reason: CatalogRefreshError::Unauthorized
707 }
708 );
709 }
710
711 #[test]
712 fn record_success_stamps_live_provenance_on_rows() {
713 let fp = base_url_fingerprint("https://api.example.com");
714 let mut cache = ProviderCatalogCache::new();
715 // Row arrives mislabeled as Bundled; ingest must normalize provenance.
716 cache.record_success(
717 ProviderCatalogDelta {
718 provider: "acme".into(),
719 base_url_fingerprint: fp.clone(),
720 fetched_at: 4_242,
721 offerings: vec![CatalogOffering {
722 provider: "acme".into(),
723 wire_model_id: "synth-chat-1".into(),
724 endpoint_key: "chat".into(),
725 source: CatalogSource::Bundled,
726 ..Default::default()
727 }],
728 },
729 3_600,
730 );
731 let entry = cache.get("acme", &fp).unwrap();
732 assert_eq!(
733 entry.offerings[0].source,
734 CatalogSource::Live {
735 base_url_fingerprint: fp,
736 fetched_at: 4_242,
737 }
738 );
739 }
740
741 #[test]
742 fn cache_serialization_round_trips_and_contains_no_secrets() {
743 let fp = base_url_fingerprint("https://api.example.com/v1");
744 let mut cache = ProviderCatalogCache::new();
745 cache.record_success(
746 ProviderCatalogDelta {
747 provider: "zhipuai".into(),
748 base_url_fingerprint: fp.clone(),
749 fetched_at: 1_700,
750 offerings: bundled_offerings_from_models_dev(&fixture()),
751 },
752 3_600,
753 );
754
755 let json = serde_json::to_string_pretty(&cache).expect("cache serializes");
756 let round: ProviderCatalogCache = serde_json::from_str(&json).expect("cache round-trips");
757 assert_eq!(round, cache);
758
759 // The persisted shape carries model facts but has no field that could hold
760 // a credential. Guard against a future field reintroducing one.
761 let lower = json.to_lowercase();
762 for needle in [
763 "api_key",
764 "apikey",
765 "api-key",
766 "authorization",
767 "secret",
768 "password",
769 "bearer",
770 "access_token",
771 ] {
772 assert!(
773 !lower.contains(needle),
774 "cache JSON unexpectedly contains `{needle}`"
775 );
776 }
777 // Sanity: it did serialize meaningful provider/model facts.
778 assert!(json.contains("glm-5.2"));
779 assert!(json.contains("base_url_fingerprint"));
780 }
781
782 #[test]
783 fn all_fresh_offerings_spans_providers_and_skips_stale() {
784 let fp = base_url_fingerprint("https://api.example.com");
785 let mut cache = ProviderCatalogCache::new();
786 cache.record_success(
787 ProviderCatalogDelta {
788 provider: "acme".into(),
789 base_url_fingerprint: fp.clone(),
790 fetched_at: 1_000,
791 offerings: vec![CatalogOffering {
792 provider: "acme".into(),
793 wire_model_id: "fresh-row".into(),
794 endpoint_key: "chat".into(),
795 ..Default::default()
796 }],
797 },
798 3_600,
799 );
800 cache.record_success(
801 ProviderCatalogDelta {
802 provider: "beta".into(),
803 base_url_fingerprint: fp.clone(),
804 fetched_at: 0,
805 offerings: vec![CatalogOffering {
806 provider: "beta".into(),
807 wire_model_id: "stale-row".into(),
808 endpoint_key: "chat".into(),
809 ..Default::default()
810 }],
811 },
812 10, // tiny ttl → stale at now=1_100
813 );
814
815 let fresh = cache.all_fresh_offerings(1_100);
816 assert_eq!(fresh.len(), 1);
817 assert_eq!(fresh[0].wire_model_id, "fresh-row");
818
819 // #4139: pickers still see stale rows; only the fresh helper drops them.
820 let visible = cache.all_visible_offerings(1_100);
821 assert_eq!(visible.len(), 2);
822 assert!(visible.iter().any(|row| row.wire_model_id == "fresh-row"));
823 assert!(visible.iter().any(|row| row.wire_model_id == "stale-row"));
824 }
825
826 #[test]
827 fn snapshot_feeds_route_resolver_offerings() {
828 // The compiled snapshot projects into the exact type RouteResolver consumes,
829 // proving catalog rows reach routing only through the offering seam.
830 let snapshot = CatalogCompiler::new().with_models_dev(&fixture()).compile();
831 let offerings = snapshot.to_offerings();
832
833 let glm = offerings
834 .iter()
835 .find(|o| o.provider.as_str() == "zhipuai" && o.wire_model_id.as_str() == "glm-5.2")
836 .expect("GLM offering reaches the route resolver seam");
837 assert_eq!(glm.limits.context_tokens, Some(1_000_000));
838 assert_eq!(glm.limits.output_tokens, Some(131_072));
839 // Audio-only row never becomes a routing offering.
840 assert!(
841 !offerings
842 .iter()
843 .any(|o| o.wire_model_id.as_str() == "glm-voice")
844 );
845 }
846
847 // ---------------------------------------------------------------------------
848 // #3385 / #4188: the committed offline/stale bundled Models.dev asset.
849 // ---------------------------------------------------------------------------
850
851 #[test]
852 fn bundled_asset_parses() {
853 // The committed asset must `include_str!`-load and deserialize into the
854 // parser's `ModelsDevCatalog` shape. This is the build-time guard that keeps
855 // `bundled_models_dev_catalog()` panic-free in shipped builds.
856 let catalog = ModelsDevCatalog::parse_json(BUNDLED_MODELS_DEV_JSON)
857 .expect("committed bundled asset must be valid Models.dev JSON");
858 assert!(
859 !catalog.providers.is_empty(),
860 "bundled asset must carry provider rows"
861 );
862 assert!(catalog.reviewed.revision.is_empty());
863 let bundled = bundled_models_dev_catalog();
864 assert_eq!(bundled.providers, catalog.providers);
865 assert_eq!(bundled.models, catalog.models);
866 assert_eq!(
867 bundled.reviewed,
868 super::corrections::bundled_corrections().reviewed
869 );
870 }
871
872 #[test]
873 fn bundled_deepseek_flash_routes_support_image_input() {
874 // #6421: the official Vision guide documents deepseek-flash; the pricing
875 // guide maps both legacy Flash names to it (verified 2026-09-23).
876 // https://api-docs.deepseek.com/guides/vision/
877 // https://api-docs.deepseek.com/quick_start/pricing/
878 let rows = bundled_catalog_offerings();
879 for model in [
880 "deepseek-flash",
881 "deepseek-v4-flash",
882 "deepseek-v4-flash-vision-exp",
883 ] {
884 let row = find(&rows, "deepseek", model);
885 assert_eq!(
886 crate::models_dev::image_input_support(row.modalities.as_ref()),
887 crate::route::CapabilityState::Supported,
888 "native DeepSeek route {model} must retain its documented vision capability"
889 );
890 }
891 let text_only = find(&rows, "deepseek", "deepseek-v4-pro");
892 assert_eq!(
893 crate::models_dev::image_input_support(text_only.modalities.as_ref()),
894 crate::route::CapabilityState::Unsupported,
895 "a Flash correction must not widen other routes"
896 );
897 }
898
899 #[test]
900 fn bundled_seed_canonical_entries_use_upstream_keys_and_yield_to_provider_rows() {
901 // #6396 slice B: canonical entries carry upstream `vendor/model` keys. The
902 // xiaomi-mimo provider rows still win offline, and a vendor namespace
903 // never leaks out as its own (non-route) provider.
904 let catalog = bundled_models_dev_catalog();
905 for key in ["xiaomi/mimo-v2.6-pro", "xiaomi/mimo-v2.6-flash"] {
906 assert!(catalog.model(key).is_some(), "{key} canonical entry");
907 }
908 let rows = bundled_catalog_offerings();
909 assert!(
910 rows.iter().all(|row| row.provider != "xiaomi"),
911 "vendor namespace must normalize onto xiaomi-mimo"
912 );
913 for model in ["mimo-v2.6-pro", "mimo-v2.6-flash"] {
914 let row = find(&rows, "xiaomi-mimo", model);
915 assert_eq!(
916 row.canonical_model.as_deref(),
917 Some(format!("xiaomi/{model}").as_str()),
918 "{model} keeps the canonical join upstream now states on the provider row"
919 );
920 // The text-only hold is gone (#6396): upstream lists image input,
921 // and a wrong claim costs one rejected, retried request.
922 assert_eq!(
923 row.to_offering().capabilities.image_input,
924 crate::route::CapabilityState::Supported,
925 "{model} carries upstream's image input"
926 );
927 }
928 }
929
930 #[test]
931 fn bundled_seed_cold_start_joins_namespaced_entries_without_provider_rows() {
932 // #6396: with the provider rows gone, the upstream-shaped canonical
933 // entries alone still put MiMo 2.6 on the xiaomi-mimo route offline.
934 let mut catalog = bundled_models_dev_catalog().clone();
935 let mimo = catalog
936 .providers
937 .get_mut("xiaomi-mimo")
938 .expect("xiaomi-mimo provider");
939 mimo.models.remove("mimo-v2.6-pro");
940 mimo.models.remove("mimo-v2.6-flash");
941 let rows = bundled_offerings_from_models_dev(&catalog);
942 for model in ["mimo-v2.6-pro", "mimo-v2.6-flash"] {
943 let row = find(&rows, "xiaomi-mimo", model);
944 let canonical = format!("xiaomi/{model}");
945 assert_eq!(row.canonical_model.as_deref(), Some(canonical.as_str()));
946 assert_eq!(row.source, CatalogSource::Bundled);
947 assert_eq!(row.reasoning, Some(true));
948 assert_eq!(row.tool_call, Some(true));
949 assert!(row.cost.is_none(), "MiMo stays unpriced offline");
950 assert!(!row.default_for_provider);
951 }
952 }
953
954 /// The bundled Claude row as it read before the seed was generated: text-only.
955 fn stale_text_only_seed_row() -> CatalogOffering {
956 let mut row = find(&bundled_catalog_offerings(), "anthropic", "claude-opus-5").clone();
957 row.modalities = Some(ModelsDevModalities {
958 input: vec!["text".into()],
959 output: vec!["text".into()],
960 });
961 row
962 }
963
964 #[test]
965 fn bundled_text_only_rows_leave_image_input_unknown_not_unsupported() {
966 // #6396: the hand-kept seed listed every Anthropic row as `input: [text]`
967 // while the provider accepts images, and a cold start stripped them. The
968 // seed is generated now, but it still lags providers, so simulate a stale
969 // text-only row: it must not strip the user's images.
970 let seed = &stale_text_only_seed_row();
971 assert_eq!(seed.source, CatalogSource::Bundled);
972 assert_eq!(
973 crate::models_dev::image_input_support(seed.modalities.as_ref()),
974 crate::route::CapabilityState::Unsupported,
975 "fixture premise: the seed row is text-only"
976 );
977 assert_eq!(
978 seed.to_offering().capabilities.image_input,
979 crate::route::CapabilityState::Unknown
980 );
981
982 // The same statement from a live catalog is a real refusal.
983 let live = CatalogOffering {
984 source: CatalogSource::ModelsDevLive { fetched_at: 1 },
985 ..seed.clone()
986 };
987 assert_eq!(
988 live.to_offering().capabilities.image_input,
989 crate::route::CapabilityState::Unsupported
990 );
991
992 // A layer that re-sources the row without restating modalities keeps the
993 // seed's low trust for them.
994 let re_sourced = CatalogOffering {
995 source: CatalogSource::Live {
996 base_url_fingerprint: "fp".into(),
997 fetched_at: 1,
998 },
999 modalities_source: Some(CatalogSource::Bundled),
1000 ..seed.clone()
1001 };
1002 assert_eq!(
1003 re_sourced.to_offering().capabilities.image_input,
1004 crate::route::CapabilityState::Unknown
1005 );
1006 }
1007
1008 #[test]
1009 fn offline_resolver_keeps_images_for_a_text_only_seed_row() {
1010 let route = crate::route::RouteResolver::new()
1011 .resolve(&crate::route::RouteRequest {
1012 explicit_provider: Some(crate::ProviderKind::Anthropic),
1013 model_selector: Some(crate::route::LogicalModelRef::from("claude-opus-5")),
1014 saved_provider_model: None,
1015 base_url_override: None,
1016 limit_overrides: Vec::new(),
1017 wire_override: None,
1018 responses_profile_override: None,
1019 })
1020 .expect("bundled Anthropic route resolves offline");
1021 assert_ne!(
1022 route.capabilities().image_input,
1023 crate::route::CapabilityState::Unsupported
1024 );
1025 }
1026
1027 #[test]
1028 fn signed_patch_keeps_the_seed_as_the_modality_authority() {
1029 let seed = stale_text_only_seed_row();
1030 let key = seed.merge_key();
1031 let mut rows = BTreeMap::from([(key.clone(), seed)]);
1032 let facts = crate::cloud_facts::ScopedFacts {
1033 facts_version: 1,
1034 key_id: "cwf-test-only".into(),
1035 models: vec![crate::cloud_facts::ModelFact {
1036 provider: key.0.clone(),
1037 id: key.1.clone(),
1038 context_window: Some(9000),
1039 ..Default::default()
1040 }],
1041 ..Default::default()
1042 };
1043 crate::cloud_facts::catalog_patch::apply_model_patches(&mut rows, &facts, 1);
1044 let row = &rows[&key];
1045 assert!(matches!(row.source, CatalogSource::CloudFacts { .. }));
1046 assert_eq!(row.modalities_source(), &CatalogSource::Bundled);
1047 assert_eq!(
1048 row.to_offering().capabilities.image_input,
1049 crate::route::CapabilityState::Unknown
1050 );
1051 }
1052
1053 #[test]
1054 fn bundled_asset_meta_describes_offline_fallback_not_competing_truth() {
1055 // #4188: the asset must document itself as offline/stale fallback, not a
1056 // competing curated source of truth alongside live Models.dev.
1057 let raw: serde_json::Value =
1058 serde_json::from_str(BUNDLED_MODELS_DEV_JSON).expect("bundled JSON");
1059 let meta = raw
1060 .get("_meta")
1061 .and_then(|m| m.as_object())
1062 .expect("_meta object");
1063 let role = meta
1064 .get("role")
1065 .and_then(|v| v.as_str())
1066 .unwrap_or_default();
1067 assert!(
1068 role.to_ascii_lowercase().contains("not a competing"),
1069 "_meta.role must demote the bundled asset: {role}"
1070 );
1071 assert!(
1072 role.to_ascii_lowercase().contains("live"),
1073 "_meta.role must point at live Models.dev preference: {role}"
1074 );
1075 }
1076
1077 #[test]
1078 fn bundled_asset_yields_real_chat_offerings_for_key_models() {
1079 let rows = bundled_catalog_offerings();
1080 assert!(
1081 rows.len() >= 20,
1082 "expected dozens of bundled chat offerings, got {}",
1083 rows.len()
1084 );
1085
1086 // A GLM and a Kimi row carry their real (non-default) context windows,
1087 // proving real facts flow rather than `RouteLimits::default()` (unknown).
1088 let glm = find(&rows, "zai", "GLM-5.2");
1089 assert_eq!(glm.limit.as_ref().and_then(|l| l.context), Some(1_000_000));
1090 assert!(
1091 !glm.default_for_provider,
1092 "GLM-5.2 is no longer the Z.ai default"
1093 );
1094
1095 // GLM-5.3 is the Z.ai default (matching DEFAULT_ZAI_MODEL); its limits
1096 // still inherit from glm-5.2 until Z.ai publishes distinct 5.3 numbers.
1097 let glm53 = find(&rows, "zai", "GLM-5.3");
1098 assert_eq!(
1099 glm53.limit.as_ref().and_then(|l| l.context),
1100 glm.limit.as_ref().and_then(|l| l.context)
1101 );
1102 assert_eq!(
1103 glm53.limit.as_ref().and_then(|l| l.output),
1104 glm.limit.as_ref().and_then(|l| l.output)
1105 );
1106 assert!(
1107 glm53.default_for_provider,
1108 "GLM-5.3 must be the Z.ai default"
1109 );
1110
1111 let glm54 = find(&rows, "zai", "GLM-5.4");
1112 assert_eq!(
1113 glm54.limit.as_ref().and_then(|l| l.context),
1114 Some(1_000_000)
1115 );
1116 assert_eq!(glm54.limit.as_ref().and_then(|l| l.output), Some(131_072));
1117 assert!(
1118 !glm54.default_for_provider,
1119 "GLM-5.4 must not replace GLM-5.3 as the Z.ai default"
1120 );
1121 assert!(
1122 glm54
1123 .modalities
1124 .as_ref()
1125 .is_some_and(|m| m.input.contains(&"image".to_string())),
1126 "GLM-5.4 must carry vision (image) input"
1127 );
1128 assert!(
1129 glm54.cost.is_none(),
1130 "GLM-5.4 has no USD PAYG row: Coding Plan credit multipliers only"
1131 );
1132
1133 let kimi_k27 = find(&rows, "moonshot", "kimi-k2.7-code");
1134 assert_eq!(
1135 kimi_k27.limit.as_ref().and_then(|l| l.context),
1136 Some(262_144)
1137 );
1138
1139 let kimi_k3 = find(&rows, "moonshot", "kimi-k3");
1140 assert_eq!(
1141 kimi_k3.limit.as_ref().and_then(|l| l.context),
1142 Some(1_048_576)
1143 );
1144 // Upstream's output figure; requests stay capped at 131,072 by the
1145 // compatibility limit table in crates/models (intersected at dispatch).
1146 assert_eq!(
1147 kimi_k3.limit.as_ref().and_then(|l| l.output),
1148 Some(1_048_576)
1149 );
1150 let kimi_k3_input_modalities = kimi_k3
1151 .modalities
1152 .as_ref()
1153 .expect("K3 modalities")
1154 .input
1155 .iter()
1156 .map(String::as_str)
1157 .collect::<Vec<_>>();
1158 assert_eq!(kimi_k3_input_modalities, ["text", "image", "video"]);
1159
1160 let minimax_m3 = find(&rows, "minimax-anthropic", "MiniMax-M3");
1161 assert_eq!(
1162 minimax_m3.limit.as_ref().and_then(|limit| limit.context),
1163 Some(1_000_000)
1164 );
1165 let input_modalities = minimax_m3
1166 .modalities
1167 .as_ref()
1168 .expect("M3 modalities")
1169 .input
1170 .iter()
1171 .map(String::as_str)
1172 .collect::<Vec<_>>();
1173 assert_eq!(input_modalities, ["text", "image", "video"]);
1174 // Codewhale's recorded controls, applied by a correction (#6396).
1175 assert_eq!(
1176 minimax_m3.reasoning_options[0]
1177 .get("default")
1178 .and_then(serde_json::Value::as_str),
1179 Some("disabled")
1180 );
1181
1182 let grok_47 = find(&rows, "xai", "grok-4.7");
1183 assert!(grok_47.default_for_provider);
1184 let grok_46 = find(&rows, "xai", "grok-4.6");
1185 assert!(!grok_46.default_for_provider);
1186 assert_eq!(
1187 grok_46.limit.as_ref().and_then(|limit| limit.context),
1188 Some(500_000)
1189 );
1190 assert_eq!(grok_46.attachment, Some(true));
1191 assert_eq!(grok_46.structured_output, Some(true));
1192 let grok_input_modalities = grok_46
1193 .modalities
1194 .as_ref()
1195 .expect("Grok 4.6 modalities")
1196 .input
1197 .iter()
1198 .map(String::as_str)
1199 .collect::<Vec<_>>();
1200 assert_eq!(grok_input_modalities, ["text", "image", "pdf"]);
1201 assert_eq!(
1202 grok_46.reasoning_options[0]
1203 .get("default")
1204 .and_then(serde_json::Value::as_str),
1205 Some("high")
1206 );
1207 let grok_45 = find(&rows, "xai", "grok-4.5");
1208 assert_eq!(
1209 grok_45.reasoning_options[0]
1210 .get("default")
1211 .and_then(serde_json::Value::as_str),
1212 Some("high")
1213 );
1214 let grok_45_values = grok_45.reasoning_options[0]
1215 .get("values")
1216 .and_then(serde_json::Value::as_array)
1217 .expect("Grok 4.5 effort values");
1218 assert_eq!(
1219 grok_45_values
1220 .iter()
1221 .filter_map(|value| value.as_str())
1222 .collect::<Vec<_>>(),
1223 ["low", "medium", "high"]
1224 );
1225
1226 let minimax_m2_7 = find(&rows, "minimax-anthropic", "MiniMax-M2.7");
1227 assert_eq!(
1228 minimax_m2_7.limit.as_ref().and_then(|limit| limit.context),
1229 Some(204_800)
1230 );
1231 assert_eq!(
1232 minimax_m2_7.reasoning_options[0]
1233 .get("default")
1234 .and_then(serde_json::Value::as_str),
1235 Some("always_on")
1236 );
1237
1238 // Audio/TTS rows are absent (the asset only ships chat models, but assert
1239 // the filter contract anyway).
1240 assert!(
1241 rows.iter().all(|r| !r.wire_model_id.contains("tts")),
1242 "no TTS rows should reach the offering layer"
1243 );
1244 }
1245
1246 #[test]
1247 fn bundled_asset_pricing_is_honest() {
1248 let rows = bundled_catalog_offerings();
1249
1250 // DeepSeek-native rows are intentionally unpriced here (priced via the
1251 // time-aware DeepSeek table elsewhere); pricing them would also break the
1252 // route layer's `unpriced_offering_stays_unknown` invariant.
1253 let deepseek = find(&rows, "deepseek", "deepseek-v4-pro");
1254 assert!(
1255 deepseek.cost.is_none(),
1256 "DeepSeek-native rows must stay unpriced in the bundled asset"
1257 );
1258
1259 // Any row that *does* carry a cost must expose a usable input/output rate
1260 // (the honesty rule: no cache-only / empty cost objects that would render as
1261 // a rate-less Token at the route layer).
1262 for row in &rows {
1263 if let Some(cost) = row.cost.as_ref() {
1264 assert!(
1265 cost.input.is_some() || cost.output.is_some(),
1266 "{}/{}: priced row must have an input or output rate",
1267 row.provider,
1268 row.wire_model_id
1269 );
1270 }
1271 }
1272
1273 // A sampled priced row matches the in-repo USD table (crates/tui pricing):
1274 // GLM-5.1 at the 2026-07-09 Z.ai published rates.
1275 let glm51 = find(&rows, "zai", "glm-5.1");
1276 let cost = glm51.cost.as_ref().expect("glm-5.1 is priced");
1277 assert_eq!(cost.input, Some(1.40));
1278 assert_eq!(cost.output, Some(4.40));
1279 assert_eq!(cost.cache_read, Some(0.26));
1280
1281 // The default Z.ai route is the GLM Coding Plan, which bills credit
1282 // multipliers, so a Codewhale correction keeps GLM-5.3 unpriced there even
1283 // though Models.dev lists a USD rate (#6396).
1284 let glm53 = find(&rows, "zai", "GLM-5.3");
1285 assert!(glm53.cost.is_none());
1286
1287 let glm53_flash = find(&rows, "zai", "GLM-5.3-Flash");
1288 let cost = glm53_flash
1289 .cost
1290 .as_ref()
1291 .expect("GLM-5.3-Flash must ship priced at durable list rates");
1292 assert_eq!(cost.input, Some(0.15));
1293 assert_eq!(cost.output, Some(0.50));
1294 assert_eq!(cost.cache_read, Some(0.03));
1295 assert_eq!(
1296 glm53_flash.limit.as_ref().and_then(|l| l.context),
1297 Some(1_000_000)
1298 );
1299 assert!(
1300 !glm53_flash.default_for_provider,
1301 "GLM-5.3-Flash is a picker row, not the Z.ai default"
1302 );
1303
1304 // OpenRouter qwen3.8-flash lists durable (non-promo) rates on models.dev
1305 // as of 2026-08-26. Unlike GLM-5.3-Flash's explicit 50% promo, this row
1306 // must ship priced. It is not a family default.
1307 let qwen38_flash = find(&rows, "openrouter", "qwen/qwen3.8-flash");
1308 assert!(
1309 !qwen38_flash.default_for_provider,
1310 "qwen3.8-flash is a suffix variant and must not be the OpenRouter default"
1311 );
1312 let cost = qwen38_flash
1313 .cost
1314 .as_ref()
1315 .expect("qwen/qwen3.8-flash must ship priced (durable list rates, no promo)");
1316 // The rates are upstream's, pinned by the seed lock; a re-lock that moves
1317 // them shows up in `seed lock`'s review report, not here.
1318 assert!(cost.input.is_some_and(|rate| rate > 0.0));
1319 assert!(cost.output.is_some_and(|rate| rate > 0.0));
1320 assert_eq!(
1321 qwen38_flash.limit.as_ref().and_then(|l| l.context),
1322 Some(1_000_000)
1323 );
1324 assert_eq!(
1325 qwen38_flash.limit.as_ref().and_then(|l| l.output),
1326 Some(131_072)
1327 );
1328
1329 // M3 publishes a context tier at 512K tokens. The row ships priced only
1330 // because the tier travels with it; dropping the tier would underbill.
1331 let minimax_m3 = find(&rows, "minimax-anthropic", "MiniMax-M3");
1332 let cost = minimax_m3
1333 .cost
1334 .as_ref()
1335 .expect("M3 is priced with its tier");
1336 assert_eq!(cost.input, Some(0.30));
1337 assert_eq!(cost.output, Some(1.20));
1338 let tiers = cost.tiers.as_ref().expect("M3 keeps its context tier");
1339 assert!(tiers.iter().any(|t| t.tier.size == 512_000));
1340
1341 // Grok 4.6 also has a prompt-length tier, starting at 200K input tokens.
1342 // It likewise ships priced with the tier preserved for usage-aware pricing.
1343 let grok_46 = find(&rows, "xai", "grok-4.6");
1344 let cost = grok_46
1345 .cost
1346 .as_ref()
1347 .expect("Grok 4.6 is priced with its tier");
1348 assert_eq!(cost.input, Some(2.0));
1349 assert_eq!(cost.output, Some(6.0));
1350 let tiers = cost
1351 .tiers
1352 .as_ref()
1353 .expect("Grok 4.6 keeps its context tier");
1354 assert!(tiers.iter().any(|t| t.tier.size == 200_000));
1355
1356 let minimax_m2_7 = find(&rows, "minimax-anthropic", "MiniMax-M2.7");
1357 let cost = minimax_m2_7.cost.as_ref().expect("M2.7 is priced");
1358 assert_eq!(cost.input, Some(0.30));
1359 assert_eq!(cost.output, Some(1.20));
1360 assert_eq!(cost.cache_read, Some(0.06));
1361 assert_eq!(cost.cache_write, Some(0.375));
1362 }
1363
1364 #[test]
1365 fn live_offerings_normalize_models_dev_provider_aliases() {
1366 // Live Models.dev ids that must map onto CodeWhale kinds (#4186/#4187).
1367 let raw = r#"{
1368 "models": {},
1369 "providers": {
1370 "moonshotai": {
1371 "id": "moonshotai",
1372 "models": {
1373 "kimi-k2.5": {
1374 "id": "kimi-k2.5",
1375 "modalities": { "input": ["text"], "output": ["text"] }
1376 }
1377 }
1378 },
1379 "togetherai": {
1380 "id": "togetherai",
1381 "models": {
1382 "deepseek-ai/DeepSeek-V4-Pro": {
1383 "id": "deepseek-ai/DeepSeek-V4-Pro",
1384 "modalities": { "input": ["text"], "output": ["text"] }
1385 }
1386 }
1387 },
1388 "zhipuai": {
1389 "id": "zhipuai",
1390 "models": {
1391 "glm-5.2": {
1392 "id": "glm-5.2",
1393 "modalities": { "input": ["text"], "output": ["text"] }
1394 }
1395 }
1396 },
1397 "brand-new-gateway": {
1398 "id": "brand-new-gateway",
1399 "models": {
1400 "x-1": {
1401 "id": "x-1",
1402 "modalities": { "input": ["text"], "output": ["text"] }
1403 }
1404 }
1405 }
1406 }
1407 }"#;
1408 let catalog = ModelsDevCatalog::parse_json(raw).expect("fixture parses");
1409 let rows = live_offerings_from_models_dev(&catalog, 1_700);
1410
1411 // Layer 10, and no endpoint fingerprint: a models.dev row is external
1412 // enrichment about a model, not a provider's statement about an endpoint.
1413 // Stamping `Live` here put every enriched row above the signed layer that
1414 // is supposed to be able to correct it.
1415 assert_eq!(
1416 find(&rows, "moonshot", "kimi-k2.5").source,
1417 CatalogSource::ModelsDevLive { fetched_at: 1_700 }
1418 );
1419 find(&rows, "together", "deepseek-ai/DeepSeek-V4-Pro");
1420 find(&rows, "zai", "glm-5.2");
1421 // Unknown upstream providers keep their Models.dev id.
1422 find(&rows, "brand-new-gateway", "x-1");
1423 assert!(rows.iter().all(|r| r.provider != "moonshotai"));
1424 assert!(rows.iter().all(|r| r.provider != "togetherai"));
1425 assert!(rows.iter().all(|r| r.provider != "zhipuai"));
1426 }
1427
1428 fn offering(provider: &str, wire: &str, source: CatalogSource) -> CatalogOffering {
1429 CatalogOffering {
1430 provider: provider.to_string(),
1431 wire_model_id: wire.to_string(),
1432 endpoint_key: "chat".to_string(),
1433 source,
1434 ..CatalogOffering::default()
1435 }
1436 }
1437
1438 /// The layer-25 "signed CWC catalog" this test used to pin is gone: it never
1439 /// had a fetcher, and signed cloud facts (layer 15, under the provider roster)
1440 /// is the client's one online catalog authority. What still has to hold on the
1441 /// same wire is that the provider's own roster outranks models.dev.
1442 #[test]
1443 fn provider_live_beats_models_dev_on_the_same_wire() {
1444 let snapshot = CatalogCompiler::new()
1445 .with_bundled(vec![offering(
1446 "command-code",
1447 "deepseek/deepseek-v4-flash",
1448 CatalogSource::Bundled,
1449 )])
1450 .with_models_dev_live(vec![offering(
1451 "command-code",
1452 "deepseek/deepseek-v4-flash",
1453 CatalogSource::ModelsDevLive { fetched_at: 1 },
1454 )])
1455 .with_provider_live(vec![offering(
1456 "command-code",
1457 "deepseek/deepseek-v4-flash",
1458 CatalogSource::Live {
1459 base_url_fingerprint: "fixture".into(),
1460 fetched_at: 2,
1461 },
1462 )])
1463 .compile();
1464 let row = find(
1465 &snapshot.offerings,
1466 "command-code",
1467 "deepseek/deepseek-v4-flash",
1468 );
1469 assert!(matches!(
1470 row.source,
1471 CatalogSource::Live { ref base_url_fingerprint, fetched_at: 2 }
1472 if base_url_fingerprint == "fixture"
1473 ));
1474 }
1475
1476 #[test]
1477 fn endpoint_is_baseten_recognizes_the_host_not_the_spelling() {
1478 assert!(endpoint_is_baseten(BASETEN_BASE_URL));
1479 assert!(endpoint_is_baseten(&format!("{BASETEN_BASE_URL}/")));
1480 assert!(endpoint_is_baseten("HTTPS://INFERENCE.BASETEN.CO/v1"));
1481 assert!(!endpoint_is_baseten("https://api.groq.com/openai/v1"));
1482 assert!(!endpoint_is_baseten("https://127.0.0.1:9/v1"));
1483 assert!(!endpoint_is_baseten(""));
1484 }
1485
1486 #[test]
1487 fn endpoint_is_prime_intellect_recognizes_the_host_not_the_spelling() {
1488 assert!(endpoint_is_prime_intellect(PRIME_INTELLECT_BASE_URL));
1489 assert!(endpoint_is_prime_intellect(&format!(
1490 "{PRIME_INTELLECT_BASE_URL}/"
1491 )));
1492 assert!(endpoint_is_prime_intellect(
1493 "HTTPS://API.PINFERENCE.AI/api/v1"
1494 ));
1495 assert!(!endpoint_is_prime_intellect(
1496 "https://api.groq.com/openai/v1"
1497 ));
1498 assert!(!endpoint_is_prime_intellect(""));
1499 }
1500
1501 #[test]
1502 fn stepfun_bundled_coding_models_preserve_default_and_plan_pricing_boundary() {
1503 let rows: Vec<_> = bundled_catalog_offerings()
1504 .into_iter()
1505 .filter(|row| row.provider == "stepfun")
1506 .collect();
1507 assert_eq!(rows.len(), 5);
1508 assert_eq!(
1509 rows.iter()
1510 .find(|row| row.default_for_provider)
1511 .unwrap()
1512 .wire_model_id,
1513 "step-5"
1514 );
1515 for row in &rows {
1516 assert_eq!(row.reasoning, Some(true));
1517 assert_eq!(row.tool_call, Some(true));
1518 assert!(row.cost.is_none(), "Step Plan shares ids, not PAYG billing");
1519 assert_eq!(row.modalities.as_ref().unwrap().output, ["text"]);
1520 }
1521 for model_id in ["step-5", "step-5-preview"] {
1522 let step5 = rows
1523 .iter()
1524 .find(|row| row.wire_model_id == model_id)
1525 .unwrap();
1526 assert_eq!(step5.limit.as_ref().unwrap().context, Some(1_000_000));
1527 assert_eq!(step5.limit.as_ref().unwrap().output, Some(65_536));
1528 assert_eq!(
1529 step5.modalities.as_ref().unwrap().input,
1530 ["text", "image", "video"]
1531 );
1532 assert_eq!(
1533 step5.reasoning_options[0]["values"],
1534 serde_json::json!(["low", "medium", "high"])
1535 );
1536 }
1537 let march = rows
1538 .iter()
1539 .find(|row| row.wire_model_id == "step-3.5-flash-2603")
1540 .unwrap();
1541 assert_eq!(
1542 march.reasoning_options[0]["values"],
1543 serde_json::json!(["low", "high"])
1544 );
1545 assert_eq!(march.limit.as_ref().unwrap().output, Some(256_000));
1546 }
1547
1548 // ---- Codewhale corrections (#6396) -------------------------------------
1549
1550 const LIVE_CORRECTION_FIXTURE: &str = r#"{
1551 "providers": {
1552 "xiaomi": {
1553 "id": "xiaomi",
1554 "models": {
1555 "mimo-v2.6-pro": {
1556 "id": "mimo-v2.6-pro",
1557 "modalities": { "input": ["text", "image"], "output": ["text"] },
1558 "limit": { "context": 1048576, "output": 131072 },
1559 "cost": { "input": 0.435, "output": 0.87, "cache_read": 0.0036 }
1560 }
1561 }
1562 },
1563 "alibaba-token-plan": {
1564 "id": "alibaba-token-plan",
1565 "models": {
1566 "qwen3.8-max": {
1567 "id": "qwen3.8-max",
1568 "limit": { "context": 1000000, "output": 131072 },
1569 "cost": { "input": 0, "output": 0, "cache_read": 0, "cache_write": 0 }
1570 }
1571 }
1572 },
1573 "deepseek": {
1574 "id": "deepseek",
1575 "models": {
1576 "deepseek-v4-pro": {
1577 "id": "deepseek-v4-pro",
1578 "limit": { "context": 1000000, "output": 393216 },
1579 "cost": { "input": 0.435, "output": 0.87 }
1580 }
1581 }
1582 },
1583 "anthropic": {
1584 "id": "anthropic",
1585 "models": {
1586 "claude-opus-5": {
1587 "id": "claude-opus-5",
1588 "limit": { "context": 1000000, "output": 128000 },
1589 "cost": { "input": 5, "output": 25 }
1590 }
1591 }
1592 }
1593 }
1594 }"#;
1595
1596 fn live_corrected_rows() -> Vec<CatalogOffering> {
1597 let catalog = ModelsDevCatalog::parse_json(LIVE_CORRECTION_FIXTURE).expect("fixture parses");
1598 live_offerings_from_models_dev(&catalog, 1_700_000_000)
1599 }
1600
1601 fn codewhale_source() -> CatalogSource {
1602 CatalogSource::CodewhaleBundled {
1603 revision: corrections::bundled_corrections().revision.clone(),
1604 }
1605 }
1606
1607 #[test]
1608 fn committed_corrections_parse_and_name_rows_codewhale_carries() {
1609 let parsed = corrections::CatalogCorrections::parse(corrections::CATALOG_CORRECTIONS_JSON)
1610 .expect("committed corrections are valid");
1611 let seed = bundled_offerings_from_models_dev(bundled_models_dev_catalog());
1612 for rule in &parsed.providers {
1613 assert!(
1614 seed.iter().any(|row| row.provider == rule.provider),
1615 "provider rule {} names no seed provider",
1616 rule.provider
1617 );
1618 }
1619 for correction in &parsed.models {
1620 let fact = &correction.fact;
1621 find(&seed, &fact.provider, &fact.id);
1622 }
1623 }
1624
1625 #[test]
1626 fn live_refresh_cannot_undo_a_withheld_price() {
1627 let rows = live_corrected_rows();
1628 for (provider, model) in [
1629 ("xiaomi-mimo", "mimo-v2.6-pro"),
1630 ("modelstudio-token-plan", "qwen3.8-max"),
1631 ("deepseek", "deepseek-v4-pro"),
1632 ] {
1633 let row = find(&rows, provider, model);
1634 assert_eq!(row.cost, None, "{provider}/{model} keeps no flat price");
1635 assert!(
1636 matches!(row.source, CatalogSource::ModelsDevLive { .. }),
1637 "a corrected row stays on its own layer"
1638 );
1639 assert_eq!(row.pricing_source(), &codewhale_source());
1640 assert_eq!(
1641 row.to_offering().pricing,
1642 crate::route::PricingSku::UnknownOrStale,
1643 "{provider}/{model} must read as unknown, never as a rate or free"
1644 );
1645 }
1646 // Facts the correction does not touch stay the live layer's.
1647 let mimo = find(&rows, "xiaomi-mimo", "mimo-v2.6-pro");
1648 assert_eq!(
1649 mimo.modalities_source(),
1650 &CatalogSource::ModelsDevLive {
1651 fetched_at: 1_700_000_000
1652 }
1653 );
1654 assert_eq!(
1655 mimo.to_offering().capabilities.image_input,
1656 crate::route::CapabilityState::Supported
1657 );
1658 assert_eq!(mimo.limit.as_ref().and_then(|l| l.context), Some(1_048_576));
1659
1660 // Rows no correction names are untouched.
1661 let claude = find(&rows, "anthropic", "claude-opus-5");
1662 assert!(matches!(claude.source, CatalogSource::ModelsDevLive { .. }));
1663 assert_eq!(claude.cost.as_ref().and_then(|c| c.input), Some(5.0));
1664 }
1665
1666 #[test]
1667 fn deepseek_output_limit_correction_holds_live_and_yields_to_signed_facts() {
1668 let rows = live_corrected_rows();
1669 let row = find(&rows, "deepseek", "deepseek-v4-pro").clone();
1670 assert_eq!(row.limit.as_ref().and_then(|l| l.output), Some(384_000));
1671 assert_eq!(row.to_offering().limits.output_tokens, Some(384_000));
1672
1673 let key = row.merge_key();
1674 let mut map = BTreeMap::from([(key.clone(), row)]);
1675 let facts = crate::cloud_facts::ScopedFacts {
1676 facts_version: 1,
1677 key_id: "cwf-test-only".into(),
1678 models: vec![crate::cloud_facts::ModelFact {
1679 provider: key.0.clone(),
1680 id: key.1.clone(),
1681 max_output: Some(393_216),
1682 pricing: Some(crate::cloud_facts::PricingFact {
1683 input_per_m: Some(0.435),
1684 output_per_m: Some(0.87),
1685 ..Default::default()
1686 }),
1687 ..Default::default()
1688 }],
1689 ..Default::default()
1690 };
1691 crate::cloud_facts::catalog_patch::apply_model_patches(&mut map, &facts, 1);
1692 let signed = &map[&key];
1693 assert!(matches!(signed.source, CatalogSource::CloudFacts { .. }));
1694 assert_eq!(signed.limit.as_ref().and_then(|l| l.output), Some(393_216));
1695 assert!(matches!(
1696 signed.to_offering().pricing,
1697 crate::route::PricingSku::Token { .. }
1698 ));
1699 }
1700
1701 #[test]
1702 fn offline_seed_rows_carry_the_same_corrections() {
1703 let rows = bundled_catalog_offerings();
1704 let deepseek = find(&rows, "deepseek", "deepseek-v4-pro");
1705 assert_eq!(deepseek.source, CatalogSource::Bundled);
1706 assert_eq!(deepseek.pricing_source(), &codewhale_source());
1707 assert_eq!(deepseek.cost, None);
1708 assert_eq!(
1709 deepseek.limit.as_ref().and_then(|l| l.output),
1710 Some(384_000)
1711 );
1712 // The seed still owns the modality statement, so its low trust holds.
1713 assert_eq!(deepseek.modalities_source(), &CatalogSource::Bundled);
1714 assert_eq!(deepseek.modalities_source, None);
1715
1716 let claude = find(&rows, "anthropic", "claude-opus-5");
1717 assert_eq!(claude.source, CatalogSource::Bundled);
1718 }
1719
1720 #[test]
1721 fn corrections_never_add_or_hide_rows() {
1722 let parsed = corrections::CatalogCorrections::parse(
1723 r#"{
1724 "revision": "test",
1725 "models": [
1726 { "provider": "nobody", "id": "ghost", "context_window": 9000, "reason": "r" }
1727 ]
1728 }"#,
1729 )
1730 .expect("valid");
1731 let mut rows = bundled_offerings_from_models_dev(bundled_models_dev_catalog());
1732 let before = rows.len();
1733 parsed.apply_to(&mut rows);
1734 assert_eq!(rows.len(), before);
1735 assert!(!rows.iter().any(|row| row.wire_model_id == "ghost"));
1736
1737 for (json, why) in [
1738 (
1739 r#"{"revision":"t","models":[{"provider":"p","id":"m","op":"hide","pricing_withheld":"x"}]}"#,
1740 "hide",
1741 ),
1742 (
1743 r#"{"revision":"t","models":[{"provider":"p","id":"m","allow_unlisted":true,"context_window":1,"reason":"x"}]}"#,
1744 "allow_unlisted",
1745 ),
1746 (
1747 r#"{"revision":"t","models":[{"provider":"p","id":"m","max_output":1}]}"#,
1748 "missing reason",
1749 ),
1750 (
1751 r#"{"revision":"t","models":[{"provider":"p","id":"m","reason":"x"}]}"#,
1752 "changes nothing",
1753 ),
1754 (
1755 r#"{"revision":"t","models":[{"provider":"p","id":"m","note":"n","pricing_withheld":"x"}]}"#,
1756 "annotation",
1757 ),
1758 (
1759 r#"{"revision":"t","providers":[{"provider":"p","pricing_withheld":""}]}"#,
1760 "empty provider reason",
1761 ),
1762 (r#"{"revision":"","models":[]}"#, "empty revision"),
1763 ] {
1764 assert!(
1765 corrections::CatalogCorrections::parse(json).is_err(),
1766 "{why} must be refused"
1767 );
1768 }
1769 }
1770
1771 #[test]
1772 fn pricing_withheld_round_trips_and_older_payloads_still_parse() {
1773 let fact = crate::cloud_facts::ModelFact {
1774 provider: "p".into(),
1775 id: "m".into(),
1776 pricing_withheld: Some("tiered".into()),
1777 ..Default::default()
1778 };
1779 let json = serde_json::to_string(&fact).expect("serializes");
1780 assert!(json.contains("pricing_withheld"));
1781 let back: crate::cloud_facts::ModelFact = serde_json::from_str(&json).expect("parses");
1782 assert_eq!(back, fact);
1783
1784 let older: crate::cloud_facts::ModelFact =
1785 serde_json::from_str(r#"{"provider":"p","id":"m","context_window":9000}"#)
1786 .expect("payload without the field parses");
1787 assert_eq!(older.pricing_withheld, None);
1788 let plain = serde_json::to_string(&older).expect("serializes");
1789 assert!(!plain.contains("pricing_withheld"));
1790 }
1791
1792 #[test]
1793 fn reasoning_controls_correction_holds_on_a_live_row() {
1794 let catalog = ModelsDevCatalog::parse_json(
1795 r#"{
1796 "providers": {
1797 "xai": {
1798 "id": "xai",
1799 "models": {
1800 "grok-4.6": {
1801 "id": "grok-4.6",
1802 "reasoning": true,
1803 "reasoning_options": [
1804 { "type": "effort", "values": ["low", "medium", "high", "xhigh"] }
1805 ]
1806 }
1807 }
1808 }
1809 }
1810 }"#,
1811 )
1812 .expect("fixture parses");
1813 let rows = live_offerings_from_models_dev(&catalog, 1);
1814 let grok = find(&rows, "xai", "grok-4.6");
1815 assert_eq!(
1816 grok.reasoning_options[0]
1817 .get("default")
1818 .and_then(serde_json::Value::as_str),
1819 Some("high"),
1820 "Codewhale's documented default survives a live refresh"
1821 );
1822 assert!(matches!(grok.source, CatalogSource::ModelsDevLive { .. }));
1823
1824 // A signed annotation already on the row is kept alongside the controls.
1825 let mut row = grok.clone();
1826 row.reasoning_options
1827 .push(serde_json::json!({ "cloud_facts": { "op": "upsert" } }));
1828 let key = row.merge_key();
1829 let mut map = BTreeMap::from([(key.clone(), row)]);
1830 let options = vec![serde_json::json!({ "type": "effort", "values": ["high"] })];
1831 crate::cloud_facts::catalog_patch::apply_model_patches(
1832 &mut map,
1833 &crate::cloud_facts::ScopedFacts {
1834 facts_version: 1,
1835 key_id: "cwf-test-only".into(),
1836 models: vec![crate::cloud_facts::ModelFact {
1837 provider: key.0.clone(),
1838 id: key.1.clone(),
1839 reasoning_options: Some(options.clone()),
1840 ..Default::default()
1841 }],
1842 ..Default::default()
1843 },
1844 1,
1845 );
1846 let patched = &map[&key].reasoning_options;
1847 assert_eq!(patched[0], options[0]);
1848 assert!(
1849 patched
1850 .iter()
1851 .any(|value| value.get("cloud_facts").is_some())
1852 );
1853
1854 assert!(
1855 corrections::CatalogCorrections::parse(
1856 r#"{"revision":"t","models":[{"provider":"p","id":"m","reasoning_options":[]}]}"#
1857 )
1858 .is_err(),
1859 "a reasoning correction needs a reason"
1860 );
1861 }
1862
1862 lines RUST