| 1 | use super::test_support::{EnvGuard, no_managed_config}; |
| 2 | use super::*; |
| 3 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 4 | use codewhale_config::catalog::bundled_catalog_offerings; |
| 5 | use codewhale_config::catalog::reviewed::bundled_reviewed; |
| 6 | use codewhale_config::descriptors::{bundled_provider_descriptors, compatibility_for_kind}; |
| 7 | use codewhale_config::route::offering::bundled_offerings; |
| 8 | use codewhale_config::route::{ |
| 9 | LogicalModelRef, ProviderDescriptor as RouteProviderDescriptor, RouteError, RouteRequest, |
| 10 | RouteResolver, |
| 11 | }; |
| 12 | use std::collections::{BTreeMap, BTreeSet}; |
| 13 | use std::fs; |
| 14 | use std::path::Path; |
| 15 | |
| 16 | const GOLDEN_PATH: &str = concat!( |
| 17 | env!("CARGO_MANIFEST_DIR"), |
| 18 | "/src/config/model_resolution.golden.tsv" |
| 19 | ); |
| 20 | |
| 21 | const REGENERATE_COMMAND: &str = "WRITE_GOLDEN=1 CODEWHALE_SCCACHE=1 python3 scripts/build-lock.py \ |
| 22 | /tmp/codewhale-build.lock -- sh scripts/with-hermetic-test-home.sh sh scripts/dev-cargo.sh test \ |
| 23 | --locked -p codewhale-runtime --lib config::model_resolution_golden"; |
| 24 | |
| 25 | const COLUMNS: [&str; 14] = [ |
| 26 | "provider", |
| 27 | "input", |
| 28 | "input_kind", |
| 29 | "runtime_canonical", |
| 30 | "runtime_normalized", |
| 31 | "runtime_wire", |
| 32 | "runtime_requested", |
| 33 | "tui_default_model", |
| 34 | "cli_model", |
| 35 | "route_canonical", |
| 36 | "route_wire", |
| 37 | "route_endpoint", |
| 38 | "route_context", |
| 39 | "disagree", |
| 40 | ]; |
| 41 | |
| 42 | const IDENTITY_COLUMNS: [(&str, usize); 7] = [ |
| 43 | ("runtime_normalized", 4), |
| 44 | ("runtime_wire", 5), |
| 45 | ("runtime_requested", 6), |
| 46 | ("tui_default_model", 7), |
| 47 | ("cli_model", 8), |
| 48 | ("route_canonical", 9), |
| 49 | ("route_wire", 10), |
| 50 | ]; |
| 51 | |
| 52 | const PROVIDER_ENV_SUFFIXES: [&str; 8] = [ |
| 53 | "_MODEL", |
| 54 | "_BASE_URL", |
| 55 | "_API_BASE", |
| 56 | "_PROVIDER", |
| 57 | "_MODE", |
| 58 | "_HTTP_HEADERS", |
| 59 | "_DEFAULT_TEXT_MODEL", |
| 60 | "_PROFILE", |
| 61 | ]; |
| 62 | |
| 63 | struct Target { |
| 64 | label: String, |
| 65 | kind: ProviderKind, |
| 66 | catalog_provider_id: String, |
| 67 | config_identity: String, |
| 68 | config_table: String, |
| 69 | custom_base_url: Option<String>, |
| 70 | default_model: String, |
| 71 | } |
| 72 | |
| 73 | impl Target { |
| 74 | fn builtin(kind: ProviderKind) -> Self { |
| 75 | Self { |
| 76 | label: kind.as_str().to_string(), |
| 77 | kind, |
| 78 | catalog_provider_id: kind.as_str().to_string(), |
| 79 | config_identity: kind.as_str().to_string(), |
| 80 | config_table: compatibility_for_kind(kind).config_key.to_string(), |
| 81 | custom_base_url: None, |
| 82 | default_model: RouteProviderDescriptor::for_kind(kind) |
| 83 | .default_wire_model() |
| 84 | .as_str() |
| 85 | .to_string(), |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn data_only(descriptor: &codewhale_config::descriptors::ProviderDescriptor) -> Self { |
| 90 | Self { |
| 91 | label: format!("descriptor:{}", descriptor.id), |
| 92 | kind: ProviderKind::Custom, |
| 93 | catalog_provider_id: descriptor.id.clone(), |
| 94 | config_identity: descriptor.id.clone(), |
| 95 | config_table: descriptor.id.clone(), |
| 96 | custom_base_url: Some(descriptor.base_url.clone()), |
| 97 | default_model: descriptor.default_model.clone(), |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn config_body(&self, model: &str) -> String { |
| 102 | let model = toml::Value::String(model.to_string()).to_string(); |
| 103 | let identity = toml::Value::String(self.config_identity.clone()).to_string(); |
| 104 | let table = &self.config_table; |
| 105 | match &self.custom_base_url { |
| 106 | None => format!( |
| 107 | "provider = {identity}\n\n[providers.{table}]\napi_key = \"k\"\nmodel = {model}\n" |
| 108 | ), |
| 109 | Some(base_url) => { |
| 110 | let base_url = toml::Value::String(base_url.clone()).to_string(); |
| 111 | format!( |
| 112 | "provider = {identity}\n\n[providers.{table}]\nkind = \"openai-compatible\"\n\ |
| 113 | base_url = {base_url}\napi_key = \"k\"\nmodel = {model}\n" |
| 114 | ) |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn targets() -> Vec<Target> { |
| 121 | ProviderKind::ALL |
| 122 | .iter() |
| 123 | .copied() |
| 124 | .map(Target::builtin) |
| 125 | .chain(bundled_provider_descriptors().iter().map(Target::data_only)) |
| 126 | .collect() |
| 127 | } |
| 128 | |
| 129 | fn provider_model_rules(provider_id: &str) -> Option<serde_json::Value> { |
| 130 | let descriptors: serde_json::Value = serde_json::from_str(include_str!(concat!( |
| 131 | env!("CARGO_MANIFEST_DIR"), |
| 132 | "/../config/assets/provider_descriptors.json" |
| 133 | ))) |
| 134 | .expect("provider_descriptors.json parses"); |
| 135 | descriptors["providers"] |
| 136 | .as_array() |
| 137 | .expect("provider rows") |
| 138 | .iter() |
| 139 | .find(|row| row["id"] == provider_id) |
| 140 | .map(|row| row["models"].clone()) |
| 141 | } |
| 142 | |
| 143 | fn offering_ids_by_provider() -> BTreeMap<String, BTreeSet<String>> { |
| 144 | let mut ids: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); |
| 145 | let reviewed = bundled_offerings(); |
| 146 | let asset = bundled_catalog_offerings() |
| 147 | .iter() |
| 148 | .map(|row| row.to_offering()) |
| 149 | .collect::<Vec<_>>(); |
| 150 | for offering in reviewed.iter().chain(asset.iter()) { |
| 151 | ids.entry(offering.provider.as_str().to_string()) |
| 152 | .or_default() |
| 153 | .insert(offering.wire_model_id.as_str().to_string()); |
| 154 | } |
| 155 | ids |
| 156 | } |
| 157 | |
| 158 | fn committed_inputs() -> BTreeMap<String, BTreeSet<String>> { |
| 159 | let mut inputs: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); |
| 160 | let text = fs::read_to_string(GOLDEN_PATH).unwrap_or_default(); |
| 161 | for line in text.lines().skip(1) { |
| 162 | let mut cells = line.split('\t'); |
| 163 | let (Some(provider), Some(input)) = (cells.next(), cells.next()) else { |
| 164 | continue; |
| 165 | }; |
| 166 | let input = if input.starts_with('"') { |
| 167 | serde_json::from_str::<String>(input).expect("quoted golden input") |
| 168 | } else { |
| 169 | input.to_string() |
| 170 | }; |
| 171 | inputs |
| 172 | .entry(provider.to_string()) |
| 173 | .or_default() |
| 174 | .insert(input); |
| 175 | } |
| 176 | inputs |
| 177 | } |
| 178 | |
| 179 | fn inputs_for( |
| 180 | target: &Target, |
| 181 | offerings: &BTreeMap<String, BTreeSet<String>>, |
| 182 | committed: &BTreeMap<String, BTreeSet<String>>, |
| 183 | ) -> BTreeMap<String, BTreeSet<&'static str>> { |
| 184 | let mut inputs: BTreeMap<String, BTreeSet<&'static str>> = BTreeMap::new(); |
| 185 | let mut add = |input: &str, kind: &'static str| { |
| 186 | inputs.entry(input.to_string()).or_default().insert(kind); |
| 187 | }; |
| 188 | let reviewed = bundled_reviewed(); |
| 189 | let is_builtin = target.custom_base_url.is_none(); |
| 190 | |
| 191 | add(&target.default_model, "default"); |
| 192 | let provider_offerings = offerings.get(&target.catalog_provider_id); |
| 193 | for id in provider_offerings.into_iter().flatten() { |
| 194 | add(id, "offering"); |
| 195 | } |
| 196 | |
| 197 | if is_builtin && let Some(rules) = provider_model_rules(&target.catalog_provider_id) { |
| 198 | for table in ["aliases", "wire_slugs"] { |
| 199 | for (key, value) in rules[table].as_object().expect("models table") { |
| 200 | add(key, "alias-key"); |
| 201 | add(value.as_str().expect("models target"), "alias-target"); |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | if is_builtin { |
| 206 | for selection in reviewed |
| 207 | .selections |
| 208 | .iter() |
| 209 | .filter(|selection| selection.provider == target.catalog_provider_id) |
| 210 | { |
| 211 | add(&selection.id, "alias-target"); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | let variant_bases = std::iter::once(target.default_model.clone()).chain( |
| 216 | provider_offerings |
| 217 | .into_iter() |
| 218 | .flatten() |
| 219 | .find(|id| **id != target.default_model) |
| 220 | .cloned(), |
| 221 | ); |
| 222 | for base in variant_bases.collect::<Vec<_>>() { |
| 223 | add(&base.to_uppercase(), "variant-uppercase"); |
| 224 | add(&format!("models/{base}"), "variant-models-prefix"); |
| 225 | add( |
| 226 | &format!("{}/{base}", target.catalog_provider_id), |
| 227 | "variant-provider-prefix", |
| 228 | ); |
| 229 | add(&format!(" {base} "), "variant-whitespace"); |
| 230 | } |
| 231 | |
| 232 | add("auto", "sentinel-auto"); |
| 233 | add("totally-unknown-model-x", "unknown"); |
| 234 | if !matches!( |
| 235 | target.kind, |
| 236 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 237 | ) { |
| 238 | add("deepseek-v4-pro", "foreign-deepseek"); |
| 239 | } |
| 240 | for input in committed.get(&target.label).into_iter().flatten() { |
| 241 | inputs |
| 242 | .entry(input.clone()) |
| 243 | .or_insert_with(|| BTreeSet::from(["carried"])); |
| 244 | } |
| 245 | inputs |
| 246 | } |
| 247 | |
| 248 | fn optional_cell(value: Option<String>) -> String { |
| 249 | match value { |
| 250 | Some(value) if !value.is_empty() => value, |
| 251 | _ => "-".to_string(), |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | fn route_error_tag(error: &RouteError) -> &'static str { |
| 256 | match error { |
| 257 | RouteError::EmptyModel => "-!empty-model", |
| 258 | RouteError::InvalidProvider(_) => "-!invalid-provider", |
| 259 | RouteError::AmbiguousModel(_) => "-!ambiguous-model", |
| 260 | RouteError::ForeignModelForDirectProvider { .. } => "-!foreign-model", |
| 261 | RouteError::ResponsesProfile { .. } => "-!responses-profile", |
| 262 | RouteError::UnsupportedModelProtocol { .. } => "-!unsupported-protocol", |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn route_cells(target: &Target, input: &str) -> [String; 4] { |
| 267 | let request = RouteRequest { |
| 268 | explicit_provider: Some(target.kind), |
| 269 | model_selector: Some(LogicalModelRef::from(input)), |
| 270 | base_url_override: target.custom_base_url.clone(), |
| 271 | ..RouteRequest::default() |
| 272 | }; |
| 273 | match RouteResolver::bundled().resolve(&request) { |
| 274 | Ok(candidate) => [ |
| 275 | optional_cell( |
| 276 | candidate |
| 277 | .canonical_model() |
| 278 | .map(|id| id.as_str().to_string()), |
| 279 | ), |
| 280 | optional_cell(Some(candidate.wire_model_id().as_str().to_string())), |
| 281 | optional_cell(Some(candidate.endpoint().endpoint_key.clone())), |
| 282 | optional_cell( |
| 283 | candidate |
| 284 | .limits() |
| 285 | .context_tokens |
| 286 | .map(|tokens| tokens.to_string()), |
| 287 | ), |
| 288 | ], |
| 289 | Err(error) => std::array::from_fn(|_| route_error_tag(&error).to_string()), |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | fn configured_chain_cells(target: &Target, input: &str, config_path: &Path) -> [String; 2] { |
| 294 | fs::write(config_path, target.config_body(input)).expect("write golden fixture config"); |
| 295 | let tui = match Config::load(Some(config_path.to_path_buf()), None) { |
| 296 | Ok(config) => optional_cell(Some(config.default_model())), |
| 297 | Err(_) => "-!load".to_string(), |
| 298 | }; |
| 299 | let cli = match codewhale_config::ConfigStore::load(Some(config_path.to_path_buf())) { |
| 300 | Ok(store) => { |
| 301 | let resolved = store |
| 302 | .config |
| 303 | .resolve_runtime_options(&codewhale_config::CliRuntimeOverrides::default()); |
| 304 | if resolved.model_error.is_some() { |
| 305 | "-!load".to_string() |
| 306 | } else { |
| 307 | optional_cell(Some(resolved.model)) |
| 308 | } |
| 309 | } |
| 310 | Err(_) => "-!load".to_string(), |
| 311 | }; |
| 312 | [tui, cli] |
| 313 | } |
| 314 | |
| 315 | fn tsv_cell(value: &str) -> String { |
| 316 | if value != value.trim() || value.contains(['\t', '\n', '\r']) { |
| 317 | format!("{value:?}") |
| 318 | } else { |
| 319 | value.to_string() |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | fn render_row(cells: &[String]) -> String { |
| 324 | cells |
| 325 | .iter() |
| 326 | .map(|cell| tsv_cell(cell)) |
| 327 | .collect::<Vec<_>>() |
| 328 | .join("\t") |
| 329 | } |
| 330 | |
| 331 | fn golden_table(config_path: &Path) -> String { |
| 332 | let offerings = offering_ids_by_provider(); |
| 333 | let committed = committed_inputs(); |
| 334 | let mut targets = targets(); |
| 335 | targets.sort_by(|a, b| a.label.cmp(&b.label)); |
| 336 | |
| 337 | let mut out = COLUMNS.join("\t"); |
| 338 | out.push('\n'); |
| 339 | for target in &targets { |
| 340 | for (input, kinds) in inputs_for(target, &offerings, &committed) { |
| 341 | let mut cells: Vec<String> = Vec::with_capacity(COLUMNS.len()); |
| 342 | cells.push(target.label.clone()); |
| 343 | cells.push(input.clone()); |
| 344 | cells.push(kinds.into_iter().collect::<Vec<_>>().join("+")); |
| 345 | let resolved = codewhale_config::route::resolve_model(target.kind, &input, None).ok(); |
| 346 | let trimmed = input.trim(); |
| 347 | let fallback_wire = (!trimmed.is_empty()).then(|| { |
| 348 | resolved |
| 349 | .as_ref() |
| 350 | .map_or_else(|| trimmed.to_string(), |r| r.wire_id.clone()) |
| 351 | }); |
| 352 | cells.push(optional_cell(resolved.as_ref().map(|r| r.logical.clone()))); |
| 353 | cells.push(optional_cell(resolved.as_ref().map(|r| r.wire_id.clone()))); |
| 354 | cells.push(optional_cell(fallback_wire)); |
| 355 | cells.push(optional_cell(resolved.as_ref().map(|r| r.logical.clone()))); |
| 356 | cells.extend(configured_chain_cells(target, &input, config_path)); |
| 357 | cells.extend(route_cells(target, &input)); |
| 358 | let canonical = &cells[3]; |
| 359 | let disagree = IDENTITY_COLUMNS |
| 360 | .iter() |
| 361 | .filter(|(_, index)| cells[*index] != *canonical) |
| 362 | .map(|(name, _)| *name) |
| 363 | .collect::<Vec<_>>() |
| 364 | .join(","); |
| 365 | cells.push(if disagree.is_empty() { |
| 366 | "-".to_string() |
| 367 | } else { |
| 368 | disagree |
| 369 | }); |
| 370 | out.push_str(&render_row(&cells)); |
| 371 | out.push('\n'); |
| 372 | } |
| 373 | } |
| 374 | out |
| 375 | } |
| 376 | |
| 377 | struct StrippedProviderEnv { |
| 378 | _guards: Vec<EnvVarGuard>, |
| 379 | } |
| 380 | |
| 381 | impl StrippedProviderEnv { |
| 382 | fn new() -> Self { |
| 383 | let mut names: BTreeSet<String> = ProviderKind::ALL |
| 384 | .iter() |
| 385 | .flat_map(|kind| RouteProviderDescriptor::for_kind(*kind).env_vars().iter()) |
| 386 | .map(|name| (*name).to_string()) |
| 387 | .collect(); |
| 388 | names.extend( |
| 389 | bundled_provider_descriptors() |
| 390 | .iter() |
| 391 | .map(|descriptor| descriptor.api_key_env.clone()), |
| 392 | ); |
| 393 | names.extend( |
| 394 | std::env::vars_os() |
| 395 | .filter_map(|(name, _)| name.into_string().ok()) |
| 396 | .filter(|name| { |
| 397 | PROVIDER_ENV_SUFFIXES |
| 398 | .iter() |
| 399 | .any(|suffix| name.ends_with(suffix)) |
| 400 | }), |
| 401 | ); |
| 402 | let guards = names |
| 403 | .into_iter() |
| 404 | .map(|name| EnvVarGuard::remove(Box::leak(name.into_boxed_str()))) |
| 405 | .collect(); |
| 406 | Self { _guards: guards } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | #[test] |
| 411 | fn model_resolution_matches_the_committed_golden() { |
| 412 | let _lock = lock_test_env(); |
| 413 | let _stripped = StrippedProviderEnv::new(); |
| 414 | let root = tempfile::tempdir().expect("golden tempdir"); |
| 415 | let _guard = EnvGuard::new(root.path()); |
| 416 | let _managed = no_managed_config(root.path()); |
| 417 | let config_path = root.path().join(".deepseek").join("config.toml"); |
| 418 | fs::create_dir_all(config_path.parent().expect("config dir")).expect("create config dir"); |
| 419 | |
| 420 | let actual = golden_table(&config_path); |
| 421 | if std::env::var("WRITE_GOLDEN").ok().as_deref() == Some("1") { |
| 422 | fs::write(GOLDEN_PATH, &actual).expect("write model resolution golden"); |
| 423 | return; |
| 424 | } |
| 425 | let expected = fs::read_to_string(GOLDEN_PATH) |
| 426 | .unwrap_or_default() |
| 427 | .replace("\r\n", "\n"); |
| 428 | if actual != expected { |
| 429 | let divergence = crate::test_support::first_divergence(&expected, &actual); |
| 430 | panic!( |
| 431 | "model resolution changed from {GOLDEN_PATH} (first divergence: {divergence:?}); \ |
| 432 | if the change is intended, regenerate with: {REGENERATE_COMMAND}" |
| 433 | ); |
| 434 | } |
| 435 | } |
| 436 |