返回 CodeWhale
catalog_parity.rs
根目录 / crates / app-server / src / runtime_api / tests / catalog_parity.rs
1 use super::*;
2 use codewhale_config::catalog::{
3 CatalogOffering, CatalogSource, CatalogStatus, ProviderCatalogDelta, base_url_fingerprint,
4 now_unix,
5 };
6 use codewhale_engine::cost_status::EffectiveRouteEnvelope;
7 use codewhale_engine::model_inventory::ModelInventory;
8 use codewhale_runtime::config::ProviderIdentity;
9 use sha2::{Digest, Sha256};
10 use std::collections::BTreeMap;
11
12 const SINGULAR: &str = "model list / model resolve";
13 const PLURAL: &str = "models";
14 const RUNTIME: &str = "runtime api";
15 const ROUTING: &str = "routing inventory";
16 const COST: &str = "cost";
17 const UNKNOWN: &str = "unknown";
18
19 const ROSTER: &[&str] = &["claude-opus-5", "claude-haiku-4-5", "claude-parity-probe-1"];
20
21 type Readings = BTreeMap<(String, String, &'static str), BTreeMap<&'static str, String>>;
22
23 struct Route {
24 label: &'static str,
25 api_path: &'static str,
26 identity: ProviderIdentity,
27 base_url: String,
28 models: &'static [&'static str],
29 }
30
31 fn cold_process() {
32 codewhale_engine::provider_catalog_live::reset_cache_for_test();
33 codewhale_engine::provider_lake::clear_live_snapshot();
34 }
35
36 fn known<T: ToString>(value: Option<T>) -> String {
37 value.map_or_else(|| UNKNOWN.to_string(), |value| value.to_string())
38 }
39
40 fn rate(value: &Value) -> String {
41 let number = match value {
42 Value::Number(number) => number.as_f64(),
43 Value::String(text) => text.parse::<f64>().ok(),
44 _ => None,
45 };
46 known(number)
47 }
48
49 fn roster(mut models: Vec<String>) -> String {
50 models.sort();
51 models.dedup();
52 models.join(",")
53 }
54
55 fn read(
56 readings: &mut Readings,
57 route: &Route,
58 model: &str,
59 field: &'static str,
60 surface: &'static str,
61 value: String,
62 ) {
63 readings
64 .entry((route.label.to_string(), model.to_string(), field))
65 .or_default()
66 .insert(surface, value);
67 }
68
69 fn persist_id_only_roster(identity: &ProviderIdentity, base_url: &str) {
70 let fingerprint = base_url_fingerprint(base_url);
71 let fetched_at = now_unix();
72 let ticket = codewhale_engine::provider_catalog_live::begin_refresh_for_identity(
73 identity.provider,
74 identity.key.as_str(),
75 base_url,
76 );
77 assert_eq!(
78 codewhale_engine::provider_catalog_live::record_success_if_current(
79 &ticket,
80 ProviderCatalogDelta {
81 provider: identity.key.to_string(),
82 base_url_fingerprint: fingerprint.clone(),
83 fetched_at,
84 offerings: ROSTER
85 .iter()
86 .map(|id| CatalogOffering {
87 provider: identity.key.to_string(),
88 wire_model_id: (*id).to_string(),
89 endpoint_key: "chat".into(),
90 source: CatalogSource::Live {
91 base_url_fingerprint: fingerprint.clone(),
92 fetched_at,
93 },
94 ..Default::default()
95 })
96 .collect(),
97 },
98 ),
99 Some(CatalogStatus::Fresh)
100 );
101 }
102
103 fn read_singular(readings: &mut Readings, config_path: &Path, route: &Route) -> Result<()> {
104 cold_process();
105 let store = codewhale_config::ConfigStore::load(Some(config_path.to_path_buf()))?;
106 let listed =
107 codewhale_engine::route_preferences::list_models(&store, Some(route.identity.provider))?
108 .into_iter()
109 .find(|(listed, _)| listed == route.identity.key.as_str())
110 .map(|(_, models)| roster(models));
111 read(
112 readings,
113 route,
114 "*",
115 "roster",
116 SINGULAR,
117 listed.unwrap_or_else(|| "route not listed".into()),
118 );
119 for model in route.models {
120 let limits = codewhale_engine::route_preferences::resolve_model(
121 config_path,
122 route.identity.key.as_str(),
123 &route.base_url,
124 Some(model),
125 )
126 .map(|candidate| candidate.limits());
127 let (context, output) = match limits {
128 Ok(limits) => (known(limits.context_tokens), known(limits.output_tokens)),
129 Err(error) => (format!("refused: {error}"), format!("refused: {error}")),
130 };
131 read(readings, route, model, "limit.context", SINGULAR, context);
132 read(readings, route, model, "limit.output", SINGULAR, output);
133 }
134 Ok(())
135 }
136
137 fn read_plural(readings: &mut Readings, config: &Config, route: &Route) -> Result<()> {
138 cold_process();
139 codewhale_engine::models_dev_live::maybe_load_persisted_cache();
140 let mut route_config = config.clone();
141 route_config
142 .scope_to_provider_identity(&route.identity)
143 .map_err(anyhow::Error::msg)?;
144 read(
145 readings,
146 route,
147 "*",
148 "roster",
149 PLURAL,
150 roster(codewhale_engine::provider_lake::listed_models_for_route(
151 &route_config,
152 &route.identity,
153 )),
154 );
155 Ok(())
156 }
157
158 async fn read_runtime(
159 readings: &mut Readings,
160 client: &reqwest::Client,
161 addr: &SocketAddr,
162 route: &Route,
163 ) -> Result<()> {
164 let body: Value = client
165 .get(format!("http://{addr}/v1/providers/{}", route.api_path))
166 .send()
167 .await?
168 .error_for_status()?
169 .json()
170 .await?;
171 let models = body["models"].as_array().context("models array")?;
172 read(
173 readings,
174 route,
175 "*",
176 "roster",
177 RUNTIME,
178 roster(
179 models
180 .iter()
181 .filter_map(|model| model["id"].as_str().map(str::to_string))
182 .collect(),
183 ),
184 );
185 for model in route.models {
186 let facts = models
187 .iter()
188 .find(|entry| entry["id"] == *model)
189 .map_or(&Value::Null, |entry| &entry["facts"]);
190 read(
191 readings,
192 route,
193 model,
194 "limit.context",
195 RUNTIME,
196 known(facts["effective_limits"]["context_tokens"].as_u64()),
197 );
198 read(
199 readings,
200 route,
201 model,
202 "limit.output",
203 RUNTIME,
204 known(facts["effective_limits"]["output_tokens"].as_u64()),
205 );
206 read(
207 readings,
208 route,
209 model,
210 "window",
211 RUNTIME,
212 known(facts["effective_context"]["tokens"].as_u64()),
213 );
214 read(
215 readings,
216 route,
217 model,
218 "window.source",
219 RUNTIME,
220 known(facts["effective_context"]["source"].as_str()),
221 );
222 read(
223 readings,
224 route,
225 model,
226 "price.input",
227 RUNTIME,
228 rate(&facts["pricing"]["input_per_million"]),
229 );
230 read(
231 readings,
232 route,
233 model,
234 "price.output",
235 RUNTIME,
236 rate(&facts["pricing"]["output_per_million"]),
237 );
238 read(
239 readings,
240 route,
241 model,
242 "price.basis",
243 RUNTIME,
244 format!(
245 "provenance={} status={} source={}",
246 facts["pricing"]["provenance"], facts["pricing_status"], facts["source"]
247 ),
248 );
249 }
250 Ok(())
251 }
252
253 fn read_routing(readings: &mut Readings, config: &Config, route: &Route) -> Result<()> {
254 let inventory = ModelInventory::from_config(config).map_err(anyhow::Error::msg)?;
255 let candidates: Vec<_> = inventory
256 .candidates
257 .iter()
258 .filter(|candidate| candidate.identity == route.identity)
259 .collect();
260 read(
261 readings,
262 route,
263 "*",
264 "roster",
265 ROUTING,
266 roster(
267 candidates
268 .iter()
269 .map(|candidate| candidate.model.clone())
270 .collect(),
271 ),
272 );
273 for model in route.models {
274 let candidate = candidates
275 .iter()
276 .find(|candidate| candidate.model == *model);
277 read(
278 readings,
279 route,
280 model,
281 "window",
282 ROUTING,
283 known(candidate.map(|candidate| candidate.context_window)),
284 );
285 read(
286 readings,
287 route,
288 model,
289 "window.source",
290 ROUTING,
291 known(candidate.map(|candidate| {
292 if candidate.context_window_unverified {
293 "unverified"
294 } else {
295 "verified"
296 }
297 })),
298 );
299 read(
300 readings,
301 route,
302 model,
303 "limit.output",
304 ROUTING,
305 known(candidate.and_then(|candidate| candidate.max_output)),
306 );
307 }
308 Ok(())
309 }
310
311 fn read_cost(readings: &mut Readings, config: &Config, route: &Route) {
312 let usage = Usage {
313 input_tokens: 100_000,
314 output_tokens: 10_000,
315 ..Default::default()
316 };
317 for model in route.models {
318 let envelope = EffectiveRouteEnvelope::from_admitted(
319 Some(config),
320 &route.identity,
321 *model,
322 Some(&route.base_url),
323 chrono::Utc::now(),
324 );
325 let quote = envelope.provider_live_pricing.as_ref();
326 let audit = envelope.audit(&usage);
327 read(
328 readings,
329 route,
330 model,
331 "price.input",
332 COST,
333 quote
334 .and_then(|quote| quote.input_per_million.as_deref())
335 .map_or_else(|| UNKNOWN.to_string(), |text| rate(&json!(text))),
336 );
337 read(
338 readings,
339 route,
340 model,
341 "price.output",
342 COST,
343 quote
344 .and_then(|quote| quote.output_per_million.as_deref())
345 .map_or_else(|| UNKNOWN.to_string(), |text| rate(&json!(text))),
346 );
347 read(
348 readings,
349 route,
350 model,
351 "price.basis",
352 COST,
353 format!(
354 "provenance={:?} billing={:?} charge_usd={} unpriced={:?}",
355 quote.map(|quote| quote.provenance.clone()),
356 envelope.billing_mode,
357 known(audit.exact_usd.as_deref()),
358 audit.unpriced_reason,
359 ),
360 );
361 }
362 }
363
364 #[tokio::test]
365 async fn one_captured_catalog_reads_the_same_on_every_model_surface() -> Result<()> {
366 let _env = lock_test_env();
367 let _live = codewhale_engine::provider_lake::lock_live_snapshot();
368 let root = tempfile::tempdir()?;
369 let captured = codewhale_config::catalog::BUNDLED_MODELS_DEV_JSON;
370 let catalog_path = root.path().join("captured-models-dev.json");
371 fs::write(&catalog_path, captured)?;
372 let _catalog = EnvVarGuard::set("CODEWHALE_MODELS_DEV_PATH", &catalog_path);
373 let _home = EnvVarGuard::set("CODEWHALE_HOME", root.path());
374 let _config_path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
375 let _legacy_config_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
376 let _cli = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV);
377 cold_process();
378
379 let config_path = root.path().join("config.toml");
380 fs::write(
381 &config_path,
382 r#"provider = "anthropic"
383
384 [providers.anthropic]
385 auth_mode = "none"
386 model = "claude-opus-5"
387
388 [providers.zai]
389 api_key = "parity-fixture-key"
390 model = "GLM-5.3"
391
392 [providers.lab]
393 kind = "openai-compatible"
394 base_url = "http://127.0.0.1:9/v1"
395 api_key = "parity-fixture-key"
396 model = "claude-haiku-4-5"
397 "#,
398 )?;
399 let config = Config::load(Some(config_path.clone()), None)?;
400 let route = |label: &'static str,
401 api_path: &'static str,
402 key: &str,
403 models: &'static [&'static str]|
404 -> Result<Route> {
405 let identity = config
406 .resolve_provider_pin_identity(key)
407 .map_err(anyhow::Error::msg)?;
408 Ok(Route {
409 label,
410 api_path,
411 base_url: config.base_url_for_route(&identity),
412 identity,
413 models,
414 })
415 };
416 let routes = [
417 route(
418 "anthropic (official, id-only roster)",
419 "anthropic/models",
420 "anthropic",
421 ROSTER,
422 )?,
423 route(
424 "lab (custom endpoint, same spelling)",
425 "custom/models?model_provider_id=lab",
426 "lab",
427 &["claude-haiku-4-5"],
428 )?,
429 route(
430 "zai (plan endpoint)",
431 "zai/models",
432 "zai",
433 &["GLM-5.3", "GLM-5.2"],
434 )?,
435 ];
436
437 assert!(
438 codewhale_engine::models_dev_live::refresh(false)
439 .await
440 .map_err(|error| anyhow::anyhow!("{error}"))?
441 > 0
442 );
443 persist_id_only_roster(&routes[0].identity, &routes[0].base_url);
444
445 let mut readings = Readings::new();
446 for route in &routes {
447 read_singular(&mut readings, &config_path, route)?;
448 read_plural(&mut readings, &config, route)?;
449 }
450 cold_process();
451 let (addr, _, handle) = spawn_test_server_with_config_path(config_path.clone())
452 .await?
453 .expect("loopback server required");
454 let client = codewhale_release::tls::reqwest_client();
455 for route in &routes {
456 read_runtime(&mut readings, &client, &addr, route).await?;
457 read_routing(&mut readings, &config, route)?;
458 read_cost(&mut readings, &config, route);
459 }
460 handle.abort();
461 cold_process();
462
463 println!(
464 "PARITY captured_catalog sha256={} bytes={}",
465 Sha256::digest(captured.as_bytes())
466 .iter()
467 .map(|byte| format!("{byte:02x}"))
468 .collect::<String>(),
469 captured.len()
470 );
471 let mut differing = Vec::new();
472 let mut known_differences: Vec<String> = Vec::new();
473 for ((route, model, field), surfaces) in &readings {
474 let mut values: Vec<String> = surfaces
475 .values()
476 .map(|value| {
477 if *field == "roster" {
478 roster(
479 value
480 .to_ascii_lowercase()
481 .split(',')
482 .map(str::to_string)
483 .collect(),
484 )
485 } else {
486 value.clone()
487 }
488 })
489 .collect();
490 values.sort();
491 values.dedup();
492 let compared = !matches!(*field, "price.basis" | "window.source");
493 let borrowed_window = *field == "window"
494 && surfaces.get(RUNTIME).map(String::as_str) == Some(UNKNOWN)
495 && readings
496 .get(&(route.clone(), model.clone(), "window.source"))
497 .and_then(|sources| sources.get(ROUTING))
498 .map(String::as_str)
499 == Some("unverified");
500 let verdict = if !compared {
501 "info"
502 } else if borrowed_window {
503 known_differences.push(format!("{route} | {model} | {surfaces:?}"));
504 "KNOWN-DIFFERENCE"
505 } else if values.len() == 1 {
506 "agree"
507 } else {
508 differing.push(format!("{route} | {model} | {field} | {surfaces:?}"));
509 "DIFFER"
510 };
511 println!("PARITY {verdict} | {route} | {model} | {field} | {surfaces:?}");
512 }
513 let value = |route: &Route, model: &str, field: &'static str, surface: &'static str| {
514 readings
515 .get(&(route.label.to_string(), model.to_string(), field))
516 .and_then(|surfaces| surfaces.get(surface))
517 .cloned()
518 .unwrap_or_default()
519 };
520 assert_eq!(
521 value(&routes[0], "*", "roster", SINGULAR),
522 "claude-haiku-4-5,claude-opus-5,claude-parity-probe-1",
523 "the singular command lists the route's own roster, not every bundled row"
524 );
525 assert_eq!(
526 value(&routes[0], "claude-opus-5", "limit.context", RUNTIME),
527 "1000000"
528 );
529 assert_eq!(
530 value(&routes[0], "claude-haiku-4-5", "limit.context", RUNTIME),
531 "200000"
532 );
533 assert_eq!(value(&routes[0], "claude-opus-5", "price.input", COST), "5");
534 assert_eq!(
535 value(&routes[0], "claude-haiku-4-5", "price.output", COST),
536 "5"
537 );
538 for field in ["limit.context", "limit.output", "price.input"] {
539 assert_eq!(
540 value(&routes[1], "claude-haiku-4-5", field, RUNTIME),
541 UNKNOWN,
542 "a custom endpoint borrows no fact from a same-named model: {field}"
543 );
544 }
545 assert_eq!(
546 value(&routes[1], "claude-haiku-4-5", "window.source", ROUTING),
547 "unverified",
548 "routing never presents a same-named model's window as this endpoint's"
549 );
550 assert_eq!(
551 value(&routes[1], "claude-haiku-4-5", "limit.output", ROUTING),
552 UNKNOWN
553 );
554 for model in ["GLM-5.3", "GLM-5.2"] {
555 let basis = value(&routes[2], model, "price.basis", COST);
556 assert!(
557 basis.contains("NotMoneyMetered") && basis.contains("charge_usd=unknown"),
558 "a plan route is never billed per token: {model}: {basis}"
559 );
560 }
561 for (model, rate) in [("GLM-5.3", UNKNOWN), ("GLM-5.2", "1.4")] {
562 for surface in [COST, RUNTIME] {
563 assert_eq!(
564 value(&routes[2], model, "price.input", surface),
565 rate,
566 "the list rate is shown the same everywhere and never turned into a charge: {model} {surface}"
567 );
568 }
569 }
570 let basis = value(&routes[1], "claude-haiku-4-5", "price.basis", COST);
571 assert!(
572 basis.contains("UnknownBillingBasis") && basis.contains("charge_usd=unknown"),
573 "a custom endpoint is never given a charge: {basis}"
574 );
575 for surface in [COST, RUNTIME] {
576 assert_eq!(
577 value(&routes[0], "claude-parity-probe-1", "price.input", surface),
578 UNKNOWN,
579 "a metered first-party model with no price row reads unknown: {surface}"
580 );
581 }
582 let basis = value(&routes[0], "claude-parity-probe-1", "price.basis", COST);
583 assert!(
584 basis.contains("charge_usd=unknown") && !basis.contains("unpriced=None"),
585 "an unpriced model produces no charge and says why: {basis}"
586 );
587 assert_eq!(
588 known_differences,
589 vec![
590 "lab (custom endpoint, same spelling) | claude-haiku-4-5 | {\"routing inventory\": \"200000\", \"runtime api\": \"unknown\"}"
591 ],
592 "the only named difference is the custom endpoint's borrowed routing window"
593 );
594 assert!(
595 differing.is_empty(),
596 "surfaces disagree on the same captured catalog:\n{}",
597 differing.join("\n")
598 );
599 Ok(())
600 }
601
601 lines RUST