| 1 | use super::*; |
| 2 | use crate::client::chat::{ |
| 3 | build_chat_messages, build_chat_messages_for_request, |
| 4 | build_chat_messages_for_request_and_provider, count_reasoning_replay_chars, parse_chat_message, |
| 5 | parse_sse_chunk, sanitize_thinking_mode_messages, |
| 6 | }; |
| 7 | use crate::client::responses::build_responses_body_for_provider; |
| 8 | use crate::tools::apply_patch::ApplyPatchTool; |
| 9 | use crate::tools::spec::ToolSpec; |
| 10 | use crate::tools::{ToolContext, ToolRegistryBuilder}; |
| 11 | use codewhale_app_server_protocol::runtime::DynamicToolSpec; |
| 12 | use codewhale_config::catalog::reviewed::constants::OPENROUTER_QWEN_3_6_FLASH_MODEL; |
| 13 | use codewhale_config::descriptors::defaults::{ |
| 14 | DEFAULT_CONCENTRATE_BASE_URL, DEFAULT_CONCENTRATE_MODEL, DEFAULT_EDENAI_MODEL, |
| 15 | DEFAULT_TELECOMJS_MODEL, |
| 16 | }; |
| 17 | use codewhale_models::{ |
| 18 | ContentBlock, ContentBlockStart, Delta, Message, MessageRequest, MessageResponse, StreamEvent, |
| 19 | Tool, |
| 20 | }; |
| 21 | use codewhale_runtime::config::{ProviderConfig, ProvidersConfig}; |
| 22 | use serde_json::json; |
| 23 | use wiremock::matchers::{header, method, path}; |
| 24 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 25 | |
| 26 | /// OpenRouter app attribution: the headers that put an app on |
| 27 | /// openrouter.ai's rankings are sent for OpenRouter routes only, and a |
| 28 | /// user-configured header of the same name wins. |
| 29 | #[test] |
| 30 | fn openrouter_routes_carry_app_attribution_headers() { |
| 31 | let headers = build_default_headers( |
| 32 | "sk-or-key", |
| 33 | &HashMap::new(), |
| 34 | ProviderKind::Openrouter, |
| 35 | "https://openrouter.ai/api/v1", |
| 36 | WireFormat::ChatCompletions, |
| 37 | false, |
| 38 | AuthHeaderSurface::Inference, |
| 39 | ) |
| 40 | .expect("headers"); |
| 41 | assert_eq!( |
| 42 | headers.get("http-referer").and_then(|v| v.to_str().ok()), |
| 43 | Some("https://codewhale.net") |
| 44 | ); |
| 45 | assert_eq!( |
| 46 | headers.get("x-title").and_then(|v| v.to_str().ok()), |
| 47 | Some("Codewhale") |
| 48 | ); |
| 49 | // The current display-name header, alongside the legacy one. |
| 50 | assert_eq!( |
| 51 | headers |
| 52 | .get("x-openrouter-title") |
| 53 | .and_then(|v| v.to_str().ok()), |
| 54 | Some("Codewhale") |
| 55 | ); |
| 56 | // Marketplace categories must match OpenRouter's spelling exactly: |
| 57 | // unrecognised values are dropped silently, so a typo here is |
| 58 | // invisible in production and only shows up as a missing listing. |
| 59 | assert_eq!( |
| 60 | headers |
| 61 | .get("x-openrouter-categories") |
| 62 | .and_then(|v| v.to_str().ok()), |
| 63 | Some("cli-agent,personal-agent") |
| 64 | ); |
| 65 | |
| 66 | // Attribution identifies this app to OpenRouter's rankings and has |
| 67 | // no business on any other route, whichever provider that is. |
| 68 | for provider in [ |
| 69 | ProviderKind::Deepseek, |
| 70 | ProviderKind::Moonshot, |
| 71 | ProviderKind::Zai, |
| 72 | ProviderKind::Openai, |
| 73 | ProviderKind::Custom, |
| 74 | ] { |
| 75 | let other = build_default_headers( |
| 76 | "sk-key", |
| 77 | &HashMap::new(), |
| 78 | provider, |
| 79 | "https://example.invalid/v1", |
| 80 | WireFormat::ChatCompletions, |
| 81 | false, |
| 82 | AuthHeaderSurface::Inference, |
| 83 | ) |
| 84 | .expect("headers"); |
| 85 | assert!( |
| 86 | other.get("http-referer").is_none() |
| 87 | && other.get("x-title").is_none() |
| 88 | && other.get("x-openrouter-title").is_none(), |
| 89 | "{provider:?} must not receive OpenRouter attribution headers" |
| 90 | ); |
| 91 | } |
| 92 | |
| 93 | let overridden = build_default_headers( |
| 94 | "sk-or-key", |
| 95 | &HashMap::from([("X-Title".to_string(), "My Fork".to_string())]), |
| 96 | ProviderKind::Openrouter, |
| 97 | "https://openrouter.ai/api/v1", |
| 98 | WireFormat::ChatCompletions, |
| 99 | false, |
| 100 | AuthHeaderSurface::Inference, |
| 101 | ) |
| 102 | .expect("headers"); |
| 103 | // A user title on the legacy header alone must follow onto the |
| 104 | // current one, or OpenRouter would still show "Codewhale". |
| 105 | for name in ["x-title", "x-openrouter-title"] { |
| 106 | assert_eq!( |
| 107 | overridden.get(name).and_then(|v| v.to_str().ok()), |
| 108 | Some("My Fork"), |
| 109 | "{name} must carry the user's title" |
| 110 | ); |
| 111 | } |
| 112 | |
| 113 | // And the other way round: setting only the current header also |
| 114 | // renames the legacy one, so the two never disagree. |
| 115 | let current_only = build_default_headers( |
| 116 | "sk-or-key", |
| 117 | &HashMap::from([("X-OpenRouter-Title".to_string(), "My Fork".to_string())]), |
| 118 | ProviderKind::Openrouter, |
| 119 | "https://openrouter.ai/api/v1", |
| 120 | WireFormat::ChatCompletions, |
| 121 | false, |
| 122 | AuthHeaderSurface::Inference, |
| 123 | ) |
| 124 | .expect("headers"); |
| 125 | for name in ["x-title", "x-openrouter-title"] { |
| 126 | assert_eq!( |
| 127 | current_only.get(name).and_then(|v| v.to_str().ok()), |
| 128 | Some("My Fork"), |
| 129 | "{name} must carry the user's title" |
| 130 | ); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | #[test] |
| 135 | fn openrouter_pricing_maps_cache_write_per_token_to_per_million() { |
| 136 | let payload = r#"{"data":[{ |
| 137 | "id":"anthropic/claude-sonnet-4-6", |
| 138 | "pricing":{ |
| 139 | "prompt":"0.000003", |
| 140 | "completion":"0.000015", |
| 141 | "input_cache_read":"0.0000003", |
| 142 | "input_cache_write":"0.00000375" |
| 143 | } |
| 144 | },{ |
| 145 | "id":"some/no-write-row", |
| 146 | "pricing":{"prompt":"0.000001","completion":"0.000002"} |
| 147 | }]}"#; |
| 148 | |
| 149 | let items = parse_openrouter_models_response(payload).expect("parses"); |
| 150 | let priced = openrouter_to_catalog_offering(&items[0], "openrouter", "fp", 42) |
| 151 | .expect("valid priced row"); |
| 152 | let cost = priced.cost.as_ref().expect("pricing row"); |
| 153 | assert_eq!(cost.input, Some(3.0)); |
| 154 | assert_eq!(cost.output, Some(15.0)); |
| 155 | assert_eq!(cost.cache_read, Some(0.3)); |
| 156 | assert_eq!(cost.cache_write, Some(3.75)); |
| 157 | |
| 158 | // A cache-write premium must actually reach the estimator: the same |
| 159 | // tokens cost more when they are cache-creation rather than cache-read. |
| 160 | let pricing = codewhale_config::pricing::OfferingPricing::from_catalog_offering(&priced) |
| 161 | .expect("priced offering"); |
| 162 | let write = codewhale_config::pricing::TokenUsage { |
| 163 | cache_write: 1_000_000, |
| 164 | ..Default::default() |
| 165 | }; |
| 166 | assert_eq!(pricing.estimate_cost(&write), Some(3.75)); |
| 167 | assert!(pricing.unpriced_used_classes(&write).is_empty()); |
| 168 | |
| 169 | // A row without a published write rate stays unknown, not zero, and |
| 170 | // fails closed for cache-creation turns. |
| 171 | let unwritten = openrouter_to_catalog_offering(&items[1], "openrouter", "fp", 42) |
| 172 | .expect("valid row without cache-write rate"); |
| 173 | assert_eq!( |
| 174 | unwritten.cost.as_ref().and_then(|cost| cost.cache_write), |
| 175 | None |
| 176 | ); |
| 177 | let unwritten = codewhale_config::pricing::OfferingPricing::from_catalog_offering(&unwritten) |
| 178 | .expect("priced offering"); |
| 179 | assert_eq!(unwritten.estimate_cost(&write), None); |
| 180 | assert_eq!( |
| 181 | unwritten.unpriced_used_classes(&write), |
| 182 | vec![codewhale_config::pricing::TokenClass::CacheWrite] |
| 183 | ); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn baseten_catalog_maps_provider_stated_prices_limits_and_features() { |
| 188 | // Exact current Baseten shape: pricing is captured from the official |
| 189 | // baseten-switch repository; Model APIs publishes context_length, |
| 190 | // max_completion_tokens, and supported_features including `vision`. |
| 191 | let payload = r#"{"data":[{ |
| 192 | "id":"deepseek-ai/DeepSeek-V4-Pro", |
| 193 | "context_length":"1048576", |
| 194 | "max_completion_tokens":262144, |
| 195 | "pricing":{ |
| 196 | "prompt":0.0000014, |
| 197 | "completion":"0.0000044", |
| 198 | "input_cache_read":0.00000014 |
| 199 | }, |
| 200 | "supported_features":["reasoning","vision"], |
| 201 | "reasoning_options":[{"type":"toggle"}] |
| 202 | }]}"#; |
| 203 | |
| 204 | let items = parse_baseten_models_response(payload).expect("Baseten catalog"); |
| 205 | let offering = |
| 206 | baseten_to_catalog_offering(&items[0], "baseten", "baseten-fp", 42).expect("row"); |
| 207 | assert_eq!(offering.provider, "baseten"); |
| 208 | assert_eq!( |
| 209 | offering.wire_model_id, |
| 210 | codewhale_config::catalog::BASETEN_DEFAULT_MODEL |
| 211 | ); |
| 212 | assert!(offering.default_for_provider); |
| 213 | let limit = offering.limit.expect("published limits"); |
| 214 | assert_eq!(limit.context, Some(1_048_576)); |
| 215 | assert_eq!(limit.input, Some(1_048_576)); |
| 216 | assert_eq!(limit.output, Some(262_144)); |
| 217 | let cost = offering.cost.expect("published pricing"); |
| 218 | assert_eq!(cost.input, Some(1.4)); |
| 219 | assert_eq!(cost.output, Some(4.4)); |
| 220 | assert_eq!(cost.cache_read, Some(0.14)); |
| 221 | assert_eq!(cost.cache_write, None); |
| 222 | assert_eq!(offering.reasoning, Some(true)); |
| 223 | assert_eq!(offering.tool_call, Some(true)); |
| 224 | assert_eq!(offering.structured_output, Some(true)); |
| 225 | assert_eq!(offering.attachment, Some(true)); |
| 226 | let modalities = offering.modalities.expect("vision feature modalities"); |
| 227 | assert_eq!(modalities.input, vec!["text", "image"]); |
| 228 | assert_eq!(modalities.output, vec!["text"]); |
| 229 | assert_eq!(offering.reasoning_options, vec![json!({"type":"toggle"})]); |
| 230 | assert!(matches!(offering.source, CatalogSource::Live { .. })); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn baseten_catalog_rejects_duplicate_ids_and_invalid_known_numbers() { |
| 235 | let duplicates = r#"{"data":[{"id":"same/model"},{"id":"same/model"}]}"#; |
| 236 | assert_eq!( |
| 237 | parse_baseten_models_response(duplicates).unwrap_err(), |
| 238 | CatalogRefreshError::InvalidResponse |
| 239 | ); |
| 240 | |
| 241 | let negative = r#"{"data":[{ |
| 242 | "id":"synthetic/model", |
| 243 | "pricing":{"prompt":-0.000001,"completion":0.000002} |
| 244 | }]}"#; |
| 245 | let items = parse_baseten_models_response(negative).expect("shape parses"); |
| 246 | assert_eq!( |
| 247 | baseten_to_catalog_offering(&items[0], "baseten", "fp", 1).unwrap_err(), |
| 248 | CatalogRefreshError::InvalidResponse |
| 249 | ); |
| 250 | } |
| 251 | |
| 252 | #[test] |
| 253 | fn provider_live_price_parsers_reject_present_bad_rates_but_keep_zero_and_omission() { |
| 254 | for invalid in ["not-a-number", "-0.1", "NaN", "inf", "1e308", "0.100001"] { |
| 255 | let openrouter = json!({ |
| 256 | "data": [{ |
| 257 | "id": "synthetic/openrouter-invalid-price", |
| 258 | "pricing": { "prompt": invalid, "completion": "0.000001" } |
| 259 | }] |
| 260 | }) |
| 261 | .to_string(); |
| 262 | let items = parse_openrouter_models_response(&openrouter).expect("OpenRouter shape"); |
| 263 | let offering = openrouter_to_catalog_offering(&items[0], "openrouter", "fp", 1); |
| 264 | if invalid.starts_with('-') { |
| 265 | // OpenRouter's negative sentinel means "no fixed rate" (#6690). |
| 266 | assert_eq!(offering.expect("variable-price row").cost, None); |
| 267 | } else { |
| 268 | assert_eq!( |
| 269 | offering.unwrap_err(), |
| 270 | CatalogRefreshError::InvalidResponse, |
| 271 | "OpenRouter must reject {invalid:?}" |
| 272 | ); |
| 273 | } |
| 274 | |
| 275 | let baseten = json!({ |
| 276 | "data": [{ |
| 277 | "id": "synthetic/baseten-invalid-price", |
| 278 | "pricing": { "prompt": invalid, "completion": "0.000001" } |
| 279 | }] |
| 280 | }) |
| 281 | .to_string(); |
| 282 | let items = parse_baseten_models_response(&baseten).expect("Baseten shape"); |
| 283 | assert_eq!( |
| 284 | baseten_to_catalog_offering(&items[0], "baseten", "fp", 1).unwrap_err(), |
| 285 | CatalogRefreshError::InvalidResponse, |
| 286 | "Baseten must reject {invalid:?}" |
| 287 | ); |
| 288 | } |
| 289 | |
| 290 | let openrouter = parse_openrouter_models_response( |
| 291 | r#"{"data":[{"id":"synthetic/openrouter-free","pricing":{"prompt":"0","completion":"0"}}]}"#, |
| 292 | ) |
| 293 | .expect("OpenRouter zero row"); |
| 294 | let openrouter = openrouter_to_catalog_offering(&openrouter[0], "openrouter", "fp", 1) |
| 295 | .expect("explicit zero is a valid published price"); |
| 296 | let cost = openrouter.cost.expect("published zero cost"); |
| 297 | assert_eq!(cost.input, Some(0.0)); |
| 298 | assert_eq!(cost.output, Some(0.0)); |
| 299 | assert_eq!(cost.cache_read, None); |
| 300 | assert_eq!(cost.cache_write, None); |
| 301 | |
| 302 | let baseten = parse_baseten_models_response( |
| 303 | r#"{"data":[{"id":"synthetic/baseten-free","pricing":{"prompt":"0","completion":0}}]}"#, |
| 304 | ) |
| 305 | .expect("Baseten zero row"); |
| 306 | let baseten = baseten_to_catalog_offering(&baseten[0], "baseten", "fp", 1) |
| 307 | .expect("explicit zero is a valid published price"); |
| 308 | let cost = baseten.cost.expect("published zero cost"); |
| 309 | assert_eq!(cost.input, Some(0.0)); |
| 310 | assert_eq!(cost.output, Some(0.0)); |
| 311 | assert_eq!(cost.cache_read, None); |
| 312 | assert_eq!(cost.cache_write, None); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn baseten_feature_names_require_exact_normalized_aliases() { |
| 317 | let payload = r#"{"data":[{ |
| 318 | "id":"synthetic/text-only", |
| 319 | "supported_features":["revision","pre_reasoning_filter"] |
| 320 | }]}"#; |
| 321 | let items = parse_baseten_models_response(payload).expect("Baseten catalog"); |
| 322 | let offering = baseten_to_catalog_offering(&items[0], "baseten", "fp", 1).expect("valid row"); |
| 323 | assert_eq!(offering.reasoning, Some(false)); |
| 324 | assert_eq!(offering.modalities, None); |
| 325 | assert_eq!(offering.attachment, None); |
| 326 | assert_eq!(offering.tool_call, Some(true)); |
| 327 | assert_eq!(offering.structured_output, Some(true)); |
| 328 | } |
| 329 | |
| 330 | fn test_tool(name: &str) -> Tool { |
| 331 | Tool { |
| 332 | tool_type: None, |
| 333 | name: name.to_string(), |
| 334 | description: format!("{name} test tool"), |
| 335 | input_schema: json!({ |
| 336 | "type": "object", |
| 337 | "properties": {}, |
| 338 | }), |
| 339 | allowed_callers: None, |
| 340 | defer_loading: Some(false), |
| 341 | input_examples: None, |
| 342 | strict: Some(true), |
| 343 | cache_control: None, |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | fn apply_patch_request_tool() -> Tool { |
| 348 | let spec = ApplyPatchTool; |
| 349 | Tool { |
| 350 | tool_type: None, |
| 351 | name: spec.name().to_string(), |
| 352 | description: spec.description().to_string(), |
| 353 | input_schema: spec.input_schema(), |
| 354 | allowed_callers: None, |
| 355 | defer_loading: Some(false), |
| 356 | input_examples: None, |
| 357 | strict: None, |
| 358 | cache_control: None, |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | fn deferred_dynamic_request_tool() -> Tool { |
| 363 | let registry = ToolRegistryBuilder::new() |
| 364 | .with_dynamic_tools(&[DynamicToolSpec { |
| 365 | namespace: Some("capture".to_string()), |
| 366 | name: "deferred_lookup".to_string(), |
| 367 | description: "Look up a record after deferred loading".to_string(), |
| 368 | input_schema: json!({ |
| 369 | "type": "object", |
| 370 | "properties": { |
| 371 | "mode": {"type": "string", "const": "fast"}, |
| 372 | "query": { |
| 373 | "anyOf": [ |
| 374 | {"type": "string"}, |
| 375 | {"type": "null"} |
| 376 | ] |
| 377 | } |
| 378 | }, |
| 379 | "required": ["mode"] |
| 380 | }), |
| 381 | defer_loading: true, |
| 382 | }]) |
| 383 | .build(ToolContext::new( |
| 384 | std::env::temp_dir().join("codewhale-k3-deferred-capture"), |
| 385 | )); |
| 386 | registry |
| 387 | .to_api_tools() |
| 388 | .into_iter() |
| 389 | .find(|tool| tool.name == "deferred_lookup") |
| 390 | .expect("dynamic tool remains model-visible") |
| 391 | } |
| 392 | |
| 393 | fn value_contains_key(value: &Value, needle: &str) -> bool { |
| 394 | match value { |
| 395 | Value::Object(object) => { |
| 396 | object.contains_key(needle) |
| 397 | || object |
| 398 | .values() |
| 399 | .any(|child| value_contains_key(child, needle)) |
| 400 | } |
| 401 | Value::Array(values) => values.iter().any(|child| value_contains_key(child, needle)), |
| 402 | _ => false, |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | fn captured_function<'a>(body: &'a Value, name: &str) -> &'a Value { |
| 407 | body["tools"] |
| 408 | .as_array() |
| 409 | .and_then(|tools| tools.iter().find(|tool| tool["function"]["name"] == name)) |
| 410 | .map(|tool| &tool["function"]) |
| 411 | .unwrap_or_else(|| panic!("captured tool catalog is missing {name}: {body}")) |
| 412 | } |
| 413 | |
| 414 | fn moonshot_request_boundary_client( |
| 415 | route_base_url: &str, |
| 416 | model: &str, |
| 417 | transport_base_url: String, |
| 418 | ) -> CodewhaleClient { |
| 419 | let mut client = CodewhaleClient::new(&{ |
| 420 | let __cw_config_init_0_0 = Some("moonshot".to_string()); |
| 421 | let __cw_config_init_0_1 = Some(ProvidersConfig { |
| 422 | moonshot: ProviderConfig { |
| 423 | api_key: Some("moonshot-request-boundary-key".to_string()), |
| 424 | base_url: Some(route_base_url.to_string()), |
| 425 | model: Some(model.to_string()), |
| 426 | ..ProviderConfig::default() |
| 427 | }, |
| 428 | ..ProvidersConfig::default() |
| 429 | }); |
| 430 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 431 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 432 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 433 | __cw_config_init_0_value |
| 434 | }) |
| 435 | .expect("Moonshot request-boundary client"); |
| 436 | assert_eq!(client.base_url, route_base_url); |
| 437 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 438 | client |
| 439 | } |
| 440 | |
| 441 | fn zai_request_boundary_client( |
| 442 | route_base_url: &str, |
| 443 | model: &str, |
| 444 | transport_base_url: String, |
| 445 | ) -> CodewhaleClient { |
| 446 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 447 | let mut client = CodewhaleClient::new(&{ |
| 448 | let __cw_config_init_1_0 = Some("zai".to_string()); |
| 449 | let __cw_config_init_1_1 = Some(ProvidersConfig { |
| 450 | zai: ProviderConfig { |
| 451 | api_key: Some("zai-request-boundary-key".to_string()), |
| 452 | base_url: Some(route_base_url.to_string()), |
| 453 | model: Some(model.to_string()), |
| 454 | ..ProviderConfig::default() |
| 455 | }, |
| 456 | ..ProvidersConfig::default() |
| 457 | }); |
| 458 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 459 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 460 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 461 | __cw_config_init_1_value |
| 462 | }) |
| 463 | .expect("Z.ai request-boundary client"); |
| 464 | assert_eq!(client.base_url, route_base_url); |
| 465 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 466 | client |
| 467 | } |
| 468 | |
| 469 | fn minimax_request_boundary_client( |
| 470 | route_base_url: &str, |
| 471 | model: &str, |
| 472 | transport_base_url: String, |
| 473 | ) -> CodewhaleClient { |
| 474 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 475 | let mut client = CodewhaleClient::new(&{ |
| 476 | let __cw_config_init_2_0 = Some("minimax".to_string()); |
| 477 | let __cw_config_init_2_1 = Some(ProvidersConfig { |
| 478 | minimax: ProviderConfig { |
| 479 | api_key: Some("minimax-request-boundary-key".to_string()), |
| 480 | base_url: Some(route_base_url.to_string()), |
| 481 | model: Some(model.to_string()), |
| 482 | ..ProviderConfig::default() |
| 483 | }, |
| 484 | ..ProvidersConfig::default() |
| 485 | }); |
| 486 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 487 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 488 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 489 | __cw_config_init_2_value |
| 490 | }) |
| 491 | .expect("MiniMax request-boundary client"); |
| 492 | assert_eq!(client.base_url, route_base_url); |
| 493 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 494 | client |
| 495 | } |
| 496 | |
| 497 | fn deepseek_request_boundary_client( |
| 498 | route_base_url: &str, |
| 499 | transport_base_url: String, |
| 500 | ) -> CodewhaleClient { |
| 501 | let mut client = CodewhaleClient::new( |
| 502 | &{ |
| 503 | let __cw_config_init_3_0 = Some("deepseek".to_string()); |
| 504 | let __cw_config_init_3_1 = Some("deepseek-v4-pro".to_string()); |
| 505 | let mut __cw_config_init_3_value: Config = Config::default(); |
| 506 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 507 | __cw_config_init_3_value.default_text_model = __cw_config_init_3_1; |
| 508 | __cw_config_init_3_value |
| 509 | } |
| 510 | .with_legacy_root( |
| 511 | Some("deepseek-request-boundary-key".to_string()), |
| 512 | Some(route_base_url.to_string()), |
| 513 | ), |
| 514 | ) |
| 515 | .expect("DeepSeek request-boundary client"); |
| 516 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 517 | client |
| 518 | } |
| 519 | |
| 520 | fn ollama_cloud_request_boundary_client(transport_base_url: String) -> CodewhaleClient { |
| 521 | let mut client = CodewhaleClient::new(&{ |
| 522 | let __cw_config_init_4_0 = Some("ollama-cloud".to_string()); |
| 523 | let __cw_config_init_4_1 = Some(ProvidersConfig { |
| 524 | ollama_cloud: ProviderConfig { |
| 525 | api_key: Some("ollama-cloud-request-boundary-key".to_string()), |
| 526 | base_url: Some( |
| 527 | codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_BASE_URL |
| 528 | .to_string(), |
| 529 | ), |
| 530 | model: Some("gpt-oss:120b".to_string()), |
| 531 | ..ProviderConfig::default() |
| 532 | }, |
| 533 | ..ProvidersConfig::default() |
| 534 | }); |
| 535 | let mut __cw_config_init_4_value: Config = Config::default(); |
| 536 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 537 | __cw_config_init_4_value.providers = __cw_config_init_4_1; |
| 538 | __cw_config_init_4_value |
| 539 | }) |
| 540 | .expect("Ollama Cloud request-boundary client"); |
| 541 | assert_eq!( |
| 542 | client.base_url, |
| 543 | codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_CLOUD_BASE_URL |
| 544 | ); |
| 545 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 546 | client |
| 547 | } |
| 548 | |
| 549 | /// Swap in a short non-streaming envelope for the test's duration, |
| 550 | /// restoring the previous value on drop. |
| 551 | struct NonStreamingEnvelopeGuard(u64); |
| 552 | |
| 553 | impl NonStreamingEnvelopeGuard { |
| 554 | fn millis(ms: u64) -> Self { |
| 555 | Self(TEST_NON_STREAMING_ENVELOPE_MS.swap(ms, std::sync::atomic::Ordering::SeqCst)) |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | impl Drop for NonStreamingEnvelopeGuard { |
| 560 | fn drop(&mut self) { |
| 561 | TEST_NON_STREAMING_ENVELOPE_MS.store(self.0, std::sync::atomic::Ordering::SeqCst); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | /// The provider accepts the connection but stalls far past the budgeted |
| 566 | /// envelope before answering: the non-streaming request must be cut off |
| 567 | /// with a timeout instead of wedging the caller (mid-turn compaction, |
| 568 | /// translate, provider-native search) indefinitely. |
| 569 | #[tokio::test] |
| 570 | async fn non_streaming_envelope_bounds_a_stalled_provider() { |
| 571 | // The injected budget is process-global; serialize against other tests |
| 572 | // (which may issue non-streaming requests with their own timing |
| 573 | // assumptions) through the shared test-env lock. |
| 574 | let _env_lock = crate::test_support::lock_test_env(); |
| 575 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 576 | let server = MockServer::start().await; |
| 577 | Mock::given(method("POST")) |
| 578 | .respond_with( |
| 579 | ResponseTemplate::new(200) |
| 580 | .set_body_json(json!({ |
| 581 | "id": "chatcmpl_envelope", |
| 582 | "object": "chat.completion", |
| 583 | "model": "deepseek-v4-pro", |
| 584 | "choices": [{ |
| 585 | "index": 0, |
| 586 | "message": {"role": "assistant", "content": "late"}, |
| 587 | "finish_reason": "stop" |
| 588 | }], |
| 589 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} |
| 590 | })) |
| 591 | .set_delay(Duration::from_secs(5)), |
| 592 | ) |
| 593 | .mount(&server) |
| 594 | .await; |
| 595 | |
| 596 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 597 | let err = client |
| 598 | .create_message(k3_request_fixture("deepseek-v4-pro", Some("off"), false)) |
| 599 | .await |
| 600 | .expect_err("a provider that never answers must hit the envelope"); |
| 601 | assert!( |
| 602 | err.to_string().to_lowercase().contains("timed out"), |
| 603 | "envelope timeout must be reported as such; got {err:#}" |
| 604 | ); |
| 605 | } |
| 606 | |
| 607 | #[tokio::test] |
| 608 | async fn retry_after_beyond_recovery_budget_returns_typed_refusal() { |
| 609 | let _env_lock = crate::test_support::lock_test_env(); |
| 610 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 611 | let server = MockServer::start().await; |
| 612 | Mock::given(method("POST")) |
| 613 | .respond_with( |
| 614 | ResponseTemplate::new(429) |
| 615 | .insert_header("retry-after", "3600") |
| 616 | .set_body_string("rate limited"), |
| 617 | ) |
| 618 | .mount(&server) |
| 619 | .await; |
| 620 | |
| 621 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 622 | let started = std::time::Instant::now(); |
| 623 | let err = client |
| 624 | .create_message(k3_request_fixture("deepseek-v4-pro", Some("off"), false)) |
| 625 | .await |
| 626 | .expect_err("a minimum beyond recovery budget must stop without sleeping"); |
| 627 | let error = err.downcast_ref::<LlmError>().expect("typed refusal"); |
| 628 | assert!(matches!(error, LlmError::QuotaWindow { .. })); |
| 629 | assert_eq!( |
| 630 | error.suggested_retry_delay(), |
| 631 | Some(Duration::from_secs(3600)) |
| 632 | ); |
| 633 | assert_eq!(server.received_requests().await.unwrap().len(), 1); |
| 634 | assert!( |
| 635 | started.elapsed() < Duration::from_secs(30), |
| 636 | "a 3600s Retry-After must not run past the envelope; took {:?}", |
| 637 | started.elapsed() |
| 638 | ); |
| 639 | codewhale_runtime::retry_status::clear(); |
| 640 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 641 | } |
| 642 | |
| 643 | /// The open answers past the injected non-streaming envelope. The |
| 644 | /// streaming-open path must not inherit any total: reqwest's per-request |
| 645 | /// timeout wraps the response body, so a total set on the open would ride |
| 646 | /// on the returned body and hard-cut a live stream mid-generation. |
| 647 | #[tokio::test] |
| 648 | async fn stream_open_retry_path_sets_no_total_deadline() { |
| 649 | let _env_lock = crate::test_support::lock_test_env(); |
| 650 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 651 | let server = MockServer::start().await; |
| 652 | Mock::given(method("POST")) |
| 653 | .respond_with( |
| 654 | ResponseTemplate::new(200) |
| 655 | .set_body_string("data: [DONE]\n\n") |
| 656 | .set_delay(Duration::from_millis(2500)), |
| 657 | ) |
| 658 | .mount(&server) |
| 659 | .await; |
| 660 | |
| 661 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 662 | let response = client |
| 663 | .send_stream_open_with_retry(|policy| { |
| 664 | super::stream_entry::client_for_policy( |
| 665 | &client.http_client, |
| 666 | client.http1_fallback_client(), |
| 667 | policy, |
| 668 | ) |
| 669 | .post(format!("{}/chat/completions", server.uri())) |
| 670 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 671 | .body("{}".to_string()) |
| 672 | }) |
| 673 | .await |
| 674 | .expect("stream open must not carry the non-streaming envelope"); |
| 675 | assert!(response.status().is_success()); |
| 676 | let text = response.text().await.expect("read stream-open body"); |
| 677 | assert_eq!(text, "data: [DONE]\n\n"); |
| 678 | } |
| 679 | |
| 680 | /// A caller that pins its own, larger per-attempt total (`list_models` |
| 681 | /// pins 30s) must keep it: `.timeout()` on the builder is a pure |
| 682 | /// overwrite, so an unconditional envelope would silently replace the |
| 683 | /// pinned budget with the injected 2s and fail this 2.5s-late response. |
| 684 | #[tokio::test] |
| 685 | async fn pinned_request_total_survives_the_shared_retry_envelope() { |
| 686 | let _env_lock = crate::test_support::lock_test_env(); |
| 687 | let _envelope = NonStreamingEnvelopeGuard::millis(2000); |
| 688 | let server = MockServer::start().await; |
| 689 | Mock::given(method("GET")) |
| 690 | .respond_with( |
| 691 | ResponseTemplate::new(200) |
| 692 | .set_body_string("{}") |
| 693 | .set_delay(Duration::from_millis(2500)), |
| 694 | ) |
| 695 | .mount(&server) |
| 696 | .await; |
| 697 | |
| 698 | let client = deepseek_request_boundary_client(&server.uri(), server.uri()); |
| 699 | let response = client |
| 700 | .send_with_retry_total_error_body( |
| 701 | Duration::from_secs(5), |
| 702 | || client.http_client.get(format!("{}/models", server.uri())), |
| 703 | &ErrorBodyDisclosure::Full, |
| 704 | crate::llm_client::RetryOperation::ReadOnly, |
| 705 | ) |
| 706 | .await |
| 707 | .expect("caller-pinned total must not be overwritten by the envelope"); |
| 708 | assert!(response.status().is_success()); |
| 709 | } |
| 710 | |
| 711 | /// The per-chunk line cap is backpressure relief, not a data budget. When |
| 712 | /// one transport chunk carries more SSE lines than the cap, the drain loop |
| 713 | /// stops mid-buffer and the outer loop waits for the *next* chunk before |
| 714 | /// draining any more — so whatever is still buffered when the stream ends |
| 715 | /// never reaches the decoder. `flush_sse_line` cannot rescue it: it treats |
| 716 | /// the whole remainder as one unterminated line. A long stream of small |
| 717 | /// deltas (or provider heartbeats) therefore loses its tail — the last |
| 718 | /// tokens, `finish_reason`, and usage — silently. |
| 719 | #[tokio::test] |
| 720 | async fn chat_stream_drains_chunks_carrying_more_lines_than_the_per_chunk_cap() { |
| 721 | // Comment lines are counted by the drain loop and are cheap enough |
| 722 | // that one transport read holds far more than SSE_MAX_LINES_PER_CHUNK. |
| 723 | let heartbeats = ": ping\n".repeat(20 * SSE_MAX_LINES_PER_CHUNK * 4); |
| 724 | let body = format!( |
| 725 | "{heartbeats}data: {}\n\ndata: [DONE]\n\n", |
| 726 | json!({ |
| 727 | "choices": [{ |
| 728 | "index": 0, |
| 729 | "delta": {"content": "pong"}, |
| 730 | "finish_reason": "stop" |
| 731 | }] |
| 732 | }) |
| 733 | ); |
| 734 | |
| 735 | let server = MockServer::start().await; |
| 736 | Mock::given(method("POST")) |
| 737 | .respond_with( |
| 738 | ResponseTemplate::new(200) |
| 739 | .insert_header("content-type", "text/event-stream") |
| 740 | .set_body_string(body), |
| 741 | ) |
| 742 | .expect(1) |
| 743 | .mount(&server) |
| 744 | .await; |
| 745 | |
| 746 | let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 747 | let request = MessageRequest { |
| 748 | model: "deepseek-v4-pro".to_string(), |
| 749 | messages: vec![Message { |
| 750 | role: Role::User, |
| 751 | content: vec![ContentBlock::Text { |
| 752 | text: "sse drain regression".to_string(), |
| 753 | cache_control: None, |
| 754 | }], |
| 755 | }], |
| 756 | max_tokens: 64, |
| 757 | system: None, |
| 758 | tools: None, |
| 759 | tool_choice: None, |
| 760 | metadata: None, |
| 761 | thinking: None, |
| 762 | reasoning_effort: Some("off".to_string()), |
| 763 | stream: Some(true), |
| 764 | temperature: None, |
| 765 | top_p: None, |
| 766 | safety_check: None, |
| 767 | title: None, |
| 768 | }; |
| 769 | |
| 770 | let mut stream = client |
| 771 | .create_message_stream(request) |
| 772 | .await |
| 773 | .expect("streaming request succeeds"); |
| 774 | let mut text = String::new(); |
| 775 | while let Some(event) = stream.next().await { |
| 776 | if let StreamEvent::ContentBlockDelta { |
| 777 | delta: Delta::TextDelta { text: chunk }, |
| 778 | .. |
| 779 | } = event.expect("heartbeat-padded SSE stays valid") |
| 780 | { |
| 781 | text.push_str(&chunk); |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | assert_eq!( |
| 786 | text, "pong", |
| 787 | "the data frame after the heartbeat flood must still be decoded" |
| 788 | ); |
| 789 | } |
| 790 | |
| 791 | #[tokio::test] |
| 792 | async fn chat_stream_eof_without_done_or_finish_reason_is_error() { |
| 793 | let server = MockServer::start().await; |
| 794 | Mock::given(method("POST")) |
| 795 | .respond_with( |
| 796 | ResponseTemplate::new(200) |
| 797 | .insert_header("content-type", "text/event-stream") |
| 798 | .set_body_string(": provider heartbeat\n\n"), |
| 799 | ) |
| 800 | .expect(1) |
| 801 | .mount(&server) |
| 802 | .await; |
| 803 | |
| 804 | let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 805 | let request = MessageRequest { |
| 806 | model: "deepseek-v4-pro".to_string(), |
| 807 | messages: vec![Message { |
| 808 | role: Role::User, |
| 809 | content: vec![ContentBlock::Text { |
| 810 | text: "premature EOF regression".to_string(), |
| 811 | cache_control: None, |
| 812 | }], |
| 813 | }], |
| 814 | max_tokens: 64, |
| 815 | system: None, |
| 816 | tools: None, |
| 817 | tool_choice: None, |
| 818 | metadata: None, |
| 819 | thinking: None, |
| 820 | reasoning_effort: Some("off".to_string()), |
| 821 | stream: Some(true), |
| 822 | temperature: None, |
| 823 | top_p: None, |
| 824 | safety_check: None, |
| 825 | title: None, |
| 826 | }; |
| 827 | |
| 828 | let mut stream = client |
| 829 | .create_message_stream(request) |
| 830 | .await |
| 831 | .expect("HTTP request succeeds before the stream closes"); |
| 832 | let mut saw_stop = false; |
| 833 | let mut failure = None; |
| 834 | while let Some(event) = stream.next().await { |
| 835 | match event { |
| 836 | Ok(StreamEvent::MessageStop) => saw_stop = true, |
| 837 | Ok(_) => {} |
| 838 | Err(error) => failure = Some(error.to_string()), |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | assert!( |
| 843 | !saw_stop, |
| 844 | "premature EOF must not be reported as MessageStop" |
| 845 | ); |
| 846 | assert!( |
| 847 | failure |
| 848 | .as_deref() |
| 849 | .is_some_and(|message| message.contains("before [DONE] or finish_reason")), |
| 850 | "premature EOF must remain a typed stream failure: {failure:?}" |
| 851 | ); |
| 852 | } |
| 853 | |
| 854 | #[tokio::test] |
| 855 | async fn chat_stream_finish_reason_without_done_is_terminal() { |
| 856 | let server = MockServer::start().await; |
| 857 | Mock::given(method("POST")) |
| 858 | .respond_with( |
| 859 | ResponseTemplate::new(200) |
| 860 | .insert_header("content-type", "text/event-stream") |
| 861 | .set_body_string(concat!( |
| 862 | "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":null}]}\n\n", |
| 863 | "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", |
| 864 | )), |
| 865 | ) |
| 866 | .expect(1) |
| 867 | .mount(&server) |
| 868 | .await; |
| 869 | |
| 870 | let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 871 | let request = MessageRequest { |
| 872 | model: "deepseek-v4-pro".to_string(), |
| 873 | messages: vec![Message { |
| 874 | role: Role::User, |
| 875 | content: vec![ContentBlock::Text { |
| 876 | text: "finish reason regression".to_string(), |
| 877 | cache_control: None, |
| 878 | }], |
| 879 | }], |
| 880 | max_tokens: 64, |
| 881 | system: None, |
| 882 | tools: None, |
| 883 | tool_choice: None, |
| 884 | metadata: None, |
| 885 | thinking: None, |
| 886 | reasoning_effort: Some("off".to_string()), |
| 887 | stream: Some(true), |
| 888 | temperature: None, |
| 889 | top_p: None, |
| 890 | safety_check: None, |
| 891 | title: None, |
| 892 | }; |
| 893 | |
| 894 | let mut stream = client |
| 895 | .create_message_stream(request) |
| 896 | .await |
| 897 | .expect("streaming request succeeds"); |
| 898 | let mut saw_stop = false; |
| 899 | while let Some(event) = stream.next().await { |
| 900 | if matches!( |
| 901 | event.expect("terminal stream stays valid"), |
| 902 | StreamEvent::MessageStop |
| 903 | ) { |
| 904 | saw_stop = true; |
| 905 | } |
| 906 | } |
| 907 | assert!( |
| 908 | saw_stop, |
| 909 | "finish_reason is valid terminal proof without [DONE]" |
| 910 | ); |
| 911 | } |
| 912 | |
| 913 | async fn capture_deepseek_chat_request( |
| 914 | route_base_url: &str, |
| 915 | strict: bool, |
| 916 | streaming: bool, |
| 917 | ) -> (String, Value) { |
| 918 | let server = MockServer::start().await; |
| 919 | let response = if streaming { |
| 920 | ResponseTemplate::new(200) |
| 921 | .insert_header("content-type", "text/event-stream") |
| 922 | .set_body_string("data: [DONE]\n\n") |
| 923 | } else { |
| 924 | ResponseTemplate::new(200).set_body_json(json!({ |
| 925 | "id": "chatcmpl-deepseek-request-boundary", |
| 926 | "object": "chat.completion", |
| 927 | "model": "deepseek-v4-pro", |
| 928 | "choices": [{ |
| 929 | "index": 0, |
| 930 | "message": {"role": "assistant", "content": "ok"}, |
| 931 | "finish_reason": "stop" |
| 932 | }], |
| 933 | "usage": { |
| 934 | "prompt_tokens": 1, |
| 935 | "completion_tokens": 1, |
| 936 | "total_tokens": 2 |
| 937 | } |
| 938 | })) |
| 939 | }; |
| 940 | Mock::given(method("POST")) |
| 941 | .respond_with(response) |
| 942 | .expect(1) |
| 943 | .mount(&server) |
| 944 | .await; |
| 945 | |
| 946 | let mut tool = test_tool("lookup"); |
| 947 | if !strict { |
| 948 | tool.strict = None; |
| 949 | } |
| 950 | let request = MessageRequest { |
| 951 | model: "deepseek-v4-pro".to_string(), |
| 952 | messages: vec![Message { |
| 953 | role: Role::User, |
| 954 | content: vec![ContentBlock::Text { |
| 955 | text: "provider-free DeepSeek route fixture".to_string(), |
| 956 | cache_control: None, |
| 957 | }], |
| 958 | }], |
| 959 | max_tokens: 64, |
| 960 | system: None, |
| 961 | tools: Some(vec![tool]), |
| 962 | tool_choice: Some(json!(if strict { "required" } else { "auto" })), |
| 963 | metadata: None, |
| 964 | thinking: None, |
| 965 | reasoning_effort: Some("off".to_string()), |
| 966 | stream: Some(streaming), |
| 967 | temperature: None, |
| 968 | top_p: None, |
| 969 | safety_check: None, |
| 970 | title: None, |
| 971 | }; |
| 972 | let client = deepseek_request_boundary_client(route_base_url, server.uri()); |
| 973 | |
| 974 | if streaming { |
| 975 | let mut stream = client |
| 976 | .create_message_stream(request) |
| 977 | .await |
| 978 | .expect("streaming request succeeds"); |
| 979 | while let Some(event) = stream.next().await { |
| 980 | event.expect("captured SSE response remains valid"); |
| 981 | } |
| 982 | } else { |
| 983 | client |
| 984 | .create_message(request) |
| 985 | .await |
| 986 | .expect("non-streaming request succeeds"); |
| 987 | } |
| 988 | |
| 989 | let requests = server.received_requests().await.expect("recorded request"); |
| 990 | assert_eq!(requests.len(), 1); |
| 991 | let path = requests[0].url.path().to_string(); |
| 992 | let body = serde_json::from_slice(&requests[0].body).expect("captured request JSON"); |
| 993 | (path, body) |
| 994 | } |
| 995 | |
| 996 | /// #6540: the compaction summary is the parent turn plus one trailing |
| 997 | /// user instruction. Rendered through the production wire builders, its |
| 998 | /// prompt must be byte-for-byte the parent's prompt followed by that one |
| 999 | /// item, with the same model, system/instructions, tools and reasoning |
| 1000 | /// controls — otherwise the provider cache misses the whole history. |
| 1001 | #[test] |
| 1002 | fn compaction_summary_request_extends_the_parent_turn_prompt_bytes() { |
| 1003 | fn text(role: Role, text: &str) -> Message { |
| 1004 | Message { |
| 1005 | role, |
| 1006 | content: vec![ContentBlock::Text { |
| 1007 | text: text.to_string(), |
| 1008 | cache_control: None, |
| 1009 | }], |
| 1010 | } |
| 1011 | } |
| 1012 | fn assert_extends(label: &str, parent: &Value, summary: &Value) { |
| 1013 | let parent_items = parent.as_array().expect("parent prompt items"); |
| 1014 | let summary_items = summary.as_array().expect("summary prompt items"); |
| 1015 | assert_eq!(summary_items.len(), parent_items.len() + 1, "{label}"); |
| 1016 | let parent_bytes = serde_json::to_string(parent).expect("serialize parent"); |
| 1017 | let summary_bytes = serde_json::to_string(summary).expect("serialize summary"); |
| 1018 | let open_prefix = parent_bytes.strip_suffix(']').expect("JSON array"); |
| 1019 | assert!( |
| 1020 | summary_bytes.starts_with(open_prefix), |
| 1021 | "{label}: summary prompt diverges from the parent prefix" |
| 1022 | ); |
| 1023 | } |
| 1024 | |
| 1025 | let model = "deepseek-v4-pro"; |
| 1026 | let history = vec![ |
| 1027 | text(Role::User, "fix the failing session_store test"), |
| 1028 | text(Role::Assistant, "Reading the test first."), |
| 1029 | text(Role::User, "keep the branch name"), |
| 1030 | ]; |
| 1031 | let system = SystemPrompt::Text("pinned system prompt".to_string()); |
| 1032 | let tools = vec![test_tool("read"), test_tool("bash")]; |
| 1033 | let config = crate::compaction::CompactionConfig { |
| 1034 | model: model.to_string(), |
| 1035 | ..Default::default() |
| 1036 | }; |
| 1037 | let mut summary_history = history.clone(); |
| 1038 | summary_history.push(text(Role::User, "write the handoff summary")); |
| 1039 | let parent_for = |target_model: &str, effort: Option<&str>| { |
| 1040 | codewhale_core::request::prepare_primary_turn_request( |
| 1041 | codewhale_core::request::PrimaryTurnRequest { |
| 1042 | model: target_model.to_string(), |
| 1043 | messages: history.clone(), |
| 1044 | max_tokens: 64_000, |
| 1045 | system: Some(system.clone()), |
| 1046 | tools: Some(tools.clone()), |
| 1047 | tool_choice: Some(crate::core::engine::tool_catalog::default_tool_choice( |
| 1048 | false, |
| 1049 | )), |
| 1050 | reasoning_effort: effort.map(str::to_string), |
| 1051 | }, |
| 1052 | ) |
| 1053 | }; |
| 1054 | let summary_for = |target_model: &str, effort: Option<&str>| { |
| 1055 | let mut target_config = config.clone(); |
| 1056 | target_config.model = target_model.to_string(); |
| 1057 | crate::compaction::compaction_summary_request( |
| 1058 | summary_history.clone(), |
| 1059 | &target_config, |
| 1060 | Some(&system), |
| 1061 | Some(&tools), |
| 1062 | effort, |
| 1063 | 8_192, |
| 1064 | ) |
| 1065 | }; |
| 1066 | |
| 1067 | let client = deepseek_request_boundary_client( |
| 1068 | "https://api.deepseek.com/v1", |
| 1069 | "http://127.0.0.1:9".into(), |
| 1070 | ); |
| 1071 | for effort in ["high", "off"] { |
| 1072 | let parent_body = client |
| 1073 | .prepare_outbound_request(parent_for(model, Some(effort)), true) |
| 1074 | .expect("parent prepares") |
| 1075 | .body; |
| 1076 | let summary_body = client |
| 1077 | .prepare_outbound_request(summary_for(model, Some(effort)), false) |
| 1078 | .expect("summary prepares") |
| 1079 | .body; |
| 1080 | assert_extends("chat", &parent_body["messages"], &summary_body["messages"]); |
| 1081 | for key in ["model", "tools", "tool_choice", "reasoning_effort", "thinking"] { |
| 1082 | assert_eq!( |
| 1083 | parent_body.get(key), |
| 1084 | summary_body.get(key), |
| 1085 | "chat {effort} {key}" |
| 1086 | ); |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | let custom_ds4_client = CodewhaleClient::new(&{ |
| 1091 | let mut config: Config = Config::default(); |
| 1092 | config.provider = Some("local-ds4".to_string()); |
| 1093 | config.providers = Some(ProvidersConfig { |
| 1094 | custom: std::collections::HashMap::from([( |
| 1095 | "local-ds4".to_string(), |
| 1096 | ProviderConfig { |
| 1097 | kind: Some("openai-compatible".to_string()), |
| 1098 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 1099 | api_key: Some("local-ds4-key".to_string()), |
| 1100 | model: Some(model.to_string()), |
| 1101 | wire: Some("chat-completions".to_string()), |
| 1102 | ..Default::default() |
| 1103 | }, |
| 1104 | )]), |
| 1105 | ..Default::default() |
| 1106 | }); |
| 1107 | config |
| 1108 | }) |
| 1109 | .expect("custom DS4 client"); |
| 1110 | for effort in ["high", "off"] { |
| 1111 | let parent_body = custom_ds4_client |
| 1112 | .prepare_outbound_request(parent_for(model, Some(effort)), true) |
| 1113 | .expect("custom parent prepares") |
| 1114 | .body; |
| 1115 | let summary_body = custom_ds4_client |
| 1116 | .prepare_outbound_request(summary_for(model, Some(effort)), false) |
| 1117 | .expect("custom summary prepares") |
| 1118 | .body; |
| 1119 | assert_extends( |
| 1120 | "custom-ds4", |
| 1121 | &parent_body["messages"], |
| 1122 | &summary_body["messages"], |
| 1123 | ); |
| 1124 | assert_eq!(summary_body.get("tool_choice"), Some(&json!("auto"))); |
| 1125 | for key in ["model", "tools", "tool_choice", "reasoning_effort", "thinking"] { |
| 1126 | assert_eq!( |
| 1127 | parent_body.get(key), |
| 1128 | summary_body.get(key), |
| 1129 | "custom-ds4 {effort} {key}" |
| 1130 | ); |
| 1131 | } |
| 1132 | } |
| 1133 | |
| 1134 | let openai_chat_client = CodewhaleClient::new(&{ |
| 1135 | let mut config: Config = Config::default(); |
| 1136 | config.provider = Some("openai".to_string()); |
| 1137 | config.providers = Some(ProvidersConfig { |
| 1138 | openai: ProviderConfig { |
| 1139 | api_key: Some("sk-openai-test".to_string()), |
| 1140 | model: Some("gpt-4.1".to_string()), |
| 1141 | ..Default::default() |
| 1142 | }, |
| 1143 | ..Default::default() |
| 1144 | }); |
| 1145 | config |
| 1146 | }) |
| 1147 | .expect("openai chat client"); |
| 1148 | let parent_body = openai_chat_client |
| 1149 | .prepare_outbound_request(parent_for("gpt-4.1", None), true) |
| 1150 | .expect("openai parent prepares") |
| 1151 | .body; |
| 1152 | let summary_body = openai_chat_client |
| 1153 | .prepare_outbound_request(summary_for("gpt-4.1", None), false) |
| 1154 | .expect("openai summary prepares") |
| 1155 | .body; |
| 1156 | assert_extends( |
| 1157 | "openai-chat", |
| 1158 | &parent_body["messages"], |
| 1159 | &summary_body["messages"], |
| 1160 | ); |
| 1161 | assert_eq!(summary_body.get("tool_choice"), Some(&json!("auto"))); |
| 1162 | for key in ["model", "tools", "tool_choice"] { |
| 1163 | assert_eq!( |
| 1164 | parent_body.get(key), |
| 1165 | summary_body.get(key), |
| 1166 | "openai-chat {key}" |
| 1167 | ); |
| 1168 | } |
| 1169 | |
| 1170 | for (provider_name, provider_model) in [ |
| 1171 | ("anthropic", "claude-sonnet-4-5"), |
| 1172 | ("deepseek-anthropic", "deepseek-v4"), |
| 1173 | ] { |
| 1174 | let mut providers = ProvidersConfig::default(); |
| 1175 | if provider_name == "anthropic" { |
| 1176 | providers.anthropic = ProviderConfig { |
| 1177 | api_key: Some("sk-ant-test".to_string()), |
| 1178 | model: Some(provider_model.to_string()), |
| 1179 | ..Default::default() |
| 1180 | }; |
| 1181 | } else { |
| 1182 | providers.deepseek_anthropic = ProviderConfig { |
| 1183 | api_key: Some("sk-ds-ant-test".to_string()), |
| 1184 | model: Some(provider_model.to_string()), |
| 1185 | ..Default::default() |
| 1186 | }; |
| 1187 | } |
| 1188 | let messages_client = CodewhaleClient::new(&{ |
| 1189 | let mut config: Config = Config::default(); |
| 1190 | config.provider = Some(provider_name.to_string()); |
| 1191 | config.providers = Some(providers); |
| 1192 | config |
| 1193 | }) |
| 1194 | .expect("messages client"); |
| 1195 | let parent_body = messages_client |
| 1196 | .prepare_outbound_request(parent_for(provider_model, Some("high")), true) |
| 1197 | .expect("messages parent prepares") |
| 1198 | .body; |
| 1199 | let summary_body = messages_client |
| 1200 | .prepare_outbound_request(summary_for(provider_model, Some("high")), false) |
| 1201 | .expect("messages summary prepares") |
| 1202 | .body; |
| 1203 | let strip_cache_control = |mut messages: Value| { |
| 1204 | if let Some(items) = messages.as_array_mut() { |
| 1205 | for item in items { |
| 1206 | if let Some(blocks) = item.get_mut("content").and_then(Value::as_array_mut) { |
| 1207 | for block in blocks { |
| 1208 | if let Some(object) = block.as_object_mut() { |
| 1209 | object.remove("cache_control"); |
| 1210 | } |
| 1211 | } |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | messages |
| 1216 | }; |
| 1217 | assert_extends( |
| 1218 | provider_name, |
| 1219 | &strip_cache_control(parent_body["messages"].clone()), |
| 1220 | &strip_cache_control(summary_body["messages"].clone()), |
| 1221 | ); |
| 1222 | assert_eq!( |
| 1223 | summary_body.get("tool_choice"), |
| 1224 | Some(&json!({"type": "auto"})), |
| 1225 | "{provider_name} tool_choice" |
| 1226 | ); |
| 1227 | for key in ["model", "system", "tools", "tool_choice"] { |
| 1228 | assert_eq!( |
| 1229 | parent_body.get(key), |
| 1230 | summary_body.get(key), |
| 1231 | "{provider_name} {key}" |
| 1232 | ); |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | let parent = parent_for(model, Some("high")); |
| 1237 | let summary = summary_for(model, Some("high")); |
| 1238 | assert_eq!( |
| 1239 | summary.tool_choice, |
| 1240 | Some(crate::core::engine::tool_catalog::default_tool_choice( |
| 1241 | false |
| 1242 | )) |
| 1243 | ); |
| 1244 | |
| 1245 | for provider in [ProviderKind::OpenaiCodex, ProviderKind::Concentrate] { |
| 1246 | let parent_body = responses::build_responses_body_for_provider(&parent, provider, None); |
| 1247 | let summary_body = responses::build_responses_body_for_provider(&summary, provider, None); |
| 1248 | assert_extends( |
| 1249 | provider.as_str(), |
| 1250 | &parent_body["input"], |
| 1251 | &summary_body["input"], |
| 1252 | ); |
| 1253 | assert_eq!( |
| 1254 | summary_body.get("tool_choice"), |
| 1255 | Some(&json!("auto")), |
| 1256 | "{} tool_choice", |
| 1257 | provider.as_str() |
| 1258 | ); |
| 1259 | for key in [ |
| 1260 | "model", |
| 1261 | "instructions", |
| 1262 | "tools", |
| 1263 | "tool_choice", |
| 1264 | "reasoning", |
| 1265 | "include", |
| 1266 | ] { |
| 1267 | assert_eq!( |
| 1268 | parent_body.get(key), |
| 1269 | summary_body.get(key), |
| 1270 | "{} {key}", |
| 1271 | provider.as_str() |
| 1272 | ); |
| 1273 | } |
| 1274 | assert!(parent_body.get("reasoning").is_some()); |
| 1275 | } |
| 1276 | } |
| 1277 | |
| 1278 | #[tokio::test] |
| 1279 | async fn core_primary_request_preparation_matches_captured_transport_bytes() { |
| 1280 | let server = MockServer::start().await; |
| 1281 | Mock::given(method("POST")) |
| 1282 | .respond_with( |
| 1283 | ResponseTemplate::new(200) |
| 1284 | .insert_header("content-type", "text/event-stream") |
| 1285 | .set_body_string("data: [DONE]\n\n"), |
| 1286 | ) |
| 1287 | .expect(1) |
| 1288 | .mount(&server) |
| 1289 | .await; |
| 1290 | |
| 1291 | let request = codewhale_core::request::prepare_primary_turn_request( |
| 1292 | codewhale_core::request::PrimaryTurnRequest { |
| 1293 | model: "deepseek-v4-pro".to_string(), |
| 1294 | messages: vec![Message { |
| 1295 | role: Role::User, |
| 1296 | content: vec![ContentBlock::Text { |
| 1297 | text: "core request boundary".to_string(), |
| 1298 | cache_control: None, |
| 1299 | }], |
| 1300 | }], |
| 1301 | max_tokens: 64, |
| 1302 | system: None, |
| 1303 | tools: Some(vec![Tool { |
| 1304 | input_schema: json!({ |
| 1305 | "zeta": {"type": "string"}, |
| 1306 | "alpha": {"type": "number"}, |
| 1307 | "type": "object", |
| 1308 | }), |
| 1309 | ..test_tool("lookup") |
| 1310 | }]), |
| 1311 | tool_choice: Some(json!({"type": "auto"})), |
| 1312 | reasoning_effort: Some("off".to_string()), |
| 1313 | }, |
| 1314 | ); |
| 1315 | let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 1316 | let prepared = client |
| 1317 | .prepare_outbound_request(request.clone(), true) |
| 1318 | .expect("core request prepares through the production seam"); |
| 1319 | let prepared_bytes = serde_json::to_vec(&prepared.body).expect("prepared body serializes"); |
| 1320 | |
| 1321 | let mut stream = client |
| 1322 | .create_message_stream(request) |
| 1323 | .await |
| 1324 | .expect("production transport accepts the core request"); |
| 1325 | while let Some(event) = stream.next().await { |
| 1326 | event.expect("captured SSE response remains valid"); |
| 1327 | } |
| 1328 | |
| 1329 | let requests = server.received_requests().await.expect("recorded request"); |
| 1330 | assert_eq!(requests.len(), 1); |
| 1331 | assert_eq!(requests[0].body, prepared_bytes); |
| 1332 | let captured = std::str::from_utf8(&requests[0].body).expect("request body is UTF-8 JSON"); |
| 1333 | assert!( |
| 1334 | captured.contains( |
| 1335 | r#""parameters":{"zeta":{"type":"string"},"alpha":{"type":"number"},"type":"object"}"# |
| 1336 | ), |
| 1337 | "nested core-owned JSON order drifted: {captured}" |
| 1338 | ); |
| 1339 | } |
| 1340 | |
| 1341 | #[tokio::test] |
| 1342 | async fn ollama_cloud_uses_authenticated_openai_compatible_v1_wire() { |
| 1343 | let server = MockServer::start().await; |
| 1344 | Mock::given(method("POST")) |
| 1345 | .and(path("/v1/chat/completions")) |
| 1346 | .and(header( |
| 1347 | "authorization", |
| 1348 | "Bearer ollama-cloud-request-boundary-key", |
| 1349 | )) |
| 1350 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 1351 | "id": "chatcmpl-ollama-cloud-request-boundary", |
| 1352 | "object": "chat.completion", |
| 1353 | "model": "gpt-oss:120b", |
| 1354 | "choices": [{ |
| 1355 | "index": 0, |
| 1356 | "message": {"role": "assistant", "content": "ok"}, |
| 1357 | "finish_reason": "stop" |
| 1358 | }], |
| 1359 | "usage": { |
| 1360 | "prompt_tokens": 1, |
| 1361 | "completion_tokens": 1, |
| 1362 | "total_tokens": 2 |
| 1363 | } |
| 1364 | }))) |
| 1365 | .expect(5) |
| 1366 | .mount(&server) |
| 1367 | .await; |
| 1368 | |
| 1369 | let client = ollama_cloud_request_boundary_client(server.uri()); |
| 1370 | for requested in ["off", "low", "medium", "high", "max"] { |
| 1371 | client |
| 1372 | .create_message(MessageRequest { |
| 1373 | model: "gpt-oss:120b".to_string(), |
| 1374 | messages: vec![Message { |
| 1375 | role: Role::User, |
| 1376 | content: vec![ContentBlock::Text { |
| 1377 | text: "Ollama Cloud request boundary".to_string(), |
| 1378 | cache_control: None, |
| 1379 | }], |
| 1380 | }], |
| 1381 | max_tokens: 64, |
| 1382 | system: None, |
| 1383 | tools: None, |
| 1384 | tool_choice: None, |
| 1385 | metadata: None, |
| 1386 | thinking: None, |
| 1387 | reasoning_effort: Some(requested.to_string()), |
| 1388 | stream: Some(false), |
| 1389 | temperature: None, |
| 1390 | top_p: None, |
| 1391 | safety_check: None, |
| 1392 | title: None, |
| 1393 | }) |
| 1394 | .await |
| 1395 | .expect("Ollama Cloud request succeeds"); |
| 1396 | } |
| 1397 | |
| 1398 | let requests = server.received_requests().await.expect("recorded request"); |
| 1399 | assert_eq!(requests.len(), 5); |
| 1400 | for (request, expected) in requests |
| 1401 | .iter() |
| 1402 | .zip(["none", "low", "medium", "high", "max"]) |
| 1403 | { |
| 1404 | let body: Value = serde_json::from_slice(&request.body).expect("captured request JSON"); |
| 1405 | assert_eq!(body["model"], "gpt-oss:120b"); |
| 1406 | assert_eq!(body["reasoning_effort"], expected); |
| 1407 | assert!( |
| 1408 | body.get("think").is_none(), |
| 1409 | "native Ollama field leaked: {body}" |
| 1410 | ); |
| 1411 | assert!( |
| 1412 | body.get("thinking").is_none(), |
| 1413 | "foreign field leaked: {body}" |
| 1414 | ); |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | // This synchronous guard deliberately spans every await: the assertions |
| 1419 | // require exclusive access to process-global retry state for the full call. |
| 1420 | #[allow(clippy::await_holding_lock)] |
| 1421 | #[tokio::test(flavor = "current_thread")] |
| 1422 | async fn cache_free_message_call_neither_reads_nor_writes_global_cache() { |
| 1423 | let _retry_guard = codewhale_runtime::retry_status::test_guard(); |
| 1424 | codewhale_runtime::retry_status::clear(); |
| 1425 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 1426 | codewhale_runtime::retry_status::start(7, Duration::from_secs(60), "foreground sentinel"); |
| 1427 | let server = MockServer::start().await; |
| 1428 | Mock::given(method("POST")) |
| 1429 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 1430 | "id": "chatcmpl-cache-free-provider", |
| 1431 | "object": "chat.completion", |
| 1432 | "model": "deepseek-v4-pro", |
| 1433 | "choices": [{ |
| 1434 | "index": 0, |
| 1435 | "message": {"role": "assistant", "content": "provider result"}, |
| 1436 | "finish_reason": "stop" |
| 1437 | }], |
| 1438 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} |
| 1439 | }))) |
| 1440 | .expect(1) |
| 1441 | .mount(&server) |
| 1442 | .await; |
| 1443 | |
| 1444 | let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 1445 | codewhale_runtime::retry_status::note_rate_limit( |
| 1446 | &client.rate_limit_scope(), |
| 1447 | Duration::from_secs(60), |
| 1448 | ); |
| 1449 | let request = MessageRequest { |
| 1450 | model: "deepseek-v4-pro".to_string(), |
| 1451 | messages: vec![Message { |
| 1452 | role: Role::User, |
| 1453 | content: vec![ContentBlock::Text { |
| 1454 | text: "preview-router-cache-isolation-regression".to_string(), |
| 1455 | cache_control: None, |
| 1456 | }], |
| 1457 | }], |
| 1458 | max_tokens: 128, |
| 1459 | system: None, |
| 1460 | tools: None, |
| 1461 | tool_choice: None, |
| 1462 | metadata: None, |
| 1463 | thinking: None, |
| 1464 | reasoning_effort: Some("off".to_string()), |
| 1465 | stream: Some(false), |
| 1466 | temperature: Some(0.0), |
| 1467 | top_p: None, |
| 1468 | safety_check: None, |
| 1469 | title: None, |
| 1470 | }; |
| 1471 | let prepared = client |
| 1472 | .prepare_outbound_request(request.clone(), false) |
| 1473 | .expect("request prepares"); |
| 1474 | let wire_body = serde_json::to_vec(&prepared.body).expect("wire body serializes"); |
| 1475 | let cache_key = codewhale_runtime::llm_response_cache::ResponseCache::make_key( |
| 1476 | client.api_provider.as_str(), |
| 1477 | &client.base_url, |
| 1478 | client.path_suffix.as_deref(), |
| 1479 | &client.api_key, |
| 1480 | &wire_body, |
| 1481 | ); |
| 1482 | codewhale_runtime::llm_response_cache::response_cache().put( |
| 1483 | cache_key, |
| 1484 | MessageResponse { |
| 1485 | tool_projection_warning: None, |
| 1486 | id: "cached-sentinel-must-survive".to_string(), |
| 1487 | r#type: "message".to_string(), |
| 1488 | role: "assistant".to_string(), |
| 1489 | content: Vec::new(), |
| 1490 | model: "deepseek-v4-pro".to_string(), |
| 1491 | stop_reason: Some("end_turn".to_string()), |
| 1492 | stop_sequence: None, |
| 1493 | container: None, |
| 1494 | usage: Default::default(), |
| 1495 | title: None, |
| 1496 | stop_details: None, |
| 1497 | refusal: None, |
| 1498 | }, |
| 1499 | ); |
| 1500 | |
| 1501 | let response = client |
| 1502 | .create_message_without_response_cache( |
| 1503 | request, |
| 1504 | crate::llm_client::RequestRetryObservation::isolated(), |
| 1505 | ) |
| 1506 | .await |
| 1507 | .expect("cache-free provider call succeeds"); |
| 1508 | assert_eq!(response.id, "chatcmpl-cache-free-provider"); |
| 1509 | assert_eq!( |
| 1510 | codewhale_runtime::llm_response_cache::response_cache() |
| 1511 | .get(&cache_key) |
| 1512 | .expect("sentinel remains") |
| 1513 | .id, |
| 1514 | "cached-sentinel-must-survive" |
| 1515 | ); |
| 1516 | match codewhale_runtime::retry_status::snapshot() { |
| 1517 | codewhale_runtime::retry_status::RetryState::Active(banner) => { |
| 1518 | assert_eq!(banner.attempt, 7); |
| 1519 | assert_eq!(banner.reason, "foreground sentinel"); |
| 1520 | } |
| 1521 | state => panic!("isolated success mutated retry state: {state:?}"), |
| 1522 | } |
| 1523 | assert!( |
| 1524 | codewhale_runtime::retry_status::rate_limit_remaining(&client.rate_limit_scope()).is_some(), |
| 1525 | "isolated success must not clear the foreground provider pause" |
| 1526 | ); |
| 1527 | codewhale_runtime::retry_status::clear(); |
| 1528 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 1529 | } |
| 1530 | |
| 1531 | // This synchronous guard deliberately spans every await: the assertions |
| 1532 | // require exclusive access to process-global retry state for the full call. |
| 1533 | #[allow(clippy::await_holding_lock)] |
| 1534 | #[tokio::test(flavor = "current_thread")] |
| 1535 | async fn cache_free_classifier_429_does_not_publish_global_retry_or_rate_limit_state() { |
| 1536 | let _retry_guard = codewhale_runtime::retry_status::test_guard(); |
| 1537 | codewhale_runtime::retry_status::clear(); |
| 1538 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 1539 | codewhale_runtime::retry_status::start(9, Duration::from_secs(60), "foreground sentinel 429"); |
| 1540 | |
| 1541 | let server = MockServer::start().await; |
| 1542 | Mock::given(method("POST")) |
| 1543 | .respond_with( |
| 1544 | ResponseTemplate::new(429) |
| 1545 | .insert_header("retry-after", "120") |
| 1546 | .set_body_string("rate limited"), |
| 1547 | ) |
| 1548 | .expect(1) |
| 1549 | .mount(&server) |
| 1550 | .await; |
| 1551 | let mut client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri()); |
| 1552 | client.retry.enabled = false; |
| 1553 | client.retry.max_retries = 0; |
| 1554 | codewhale_runtime::retry_status::note_rate_limit( |
| 1555 | &client.rate_limit_scope(), |
| 1556 | Duration::from_secs(60), |
| 1557 | ); |
| 1558 | let request = MessageRequest { |
| 1559 | model: "deepseek-v4-pro".to_string(), |
| 1560 | messages: vec![Message { |
| 1561 | role: Role::User, |
| 1562 | content: vec![ContentBlock::Text { |
| 1563 | text: "preview-router-429-isolation-regression".to_string(), |
| 1564 | cache_control: None, |
| 1565 | }], |
| 1566 | }], |
| 1567 | max_tokens: 64, |
| 1568 | system: None, |
| 1569 | tools: None, |
| 1570 | tool_choice: None, |
| 1571 | metadata: None, |
| 1572 | thinking: None, |
| 1573 | reasoning_effort: Some("off".to_string()), |
| 1574 | stream: Some(false), |
| 1575 | temperature: Some(0.0), |
| 1576 | top_p: None, |
| 1577 | safety_check: None, |
| 1578 | title: None, |
| 1579 | }; |
| 1580 | let error = client |
| 1581 | .create_message_without_response_cache( |
| 1582 | request, |
| 1583 | crate::llm_client::RequestRetryObservation::isolated(), |
| 1584 | ) |
| 1585 | .await |
| 1586 | .expect_err("429 must fail when isolated retries are disabled"); |
| 1587 | assert!( |
| 1588 | matches!( |
| 1589 | error.downcast_ref::<LlmError>(), |
| 1590 | Some(LlmError::RateLimited { .. }) |
| 1591 | ), |
| 1592 | "{error:#}" |
| 1593 | ); |
| 1594 | match codewhale_runtime::retry_status::snapshot() { |
| 1595 | codewhale_runtime::retry_status::RetryState::Active(banner) => { |
| 1596 | assert_eq!(banner.attempt, 9); |
| 1597 | assert_eq!(banner.reason, "foreground sentinel 429"); |
| 1598 | } |
| 1599 | state => panic!("isolated 429 mutated retry state: {state:?}"), |
| 1600 | } |
| 1601 | let remaining = |
| 1602 | codewhale_runtime::retry_status::rate_limit_remaining(&client.rate_limit_scope()) |
| 1603 | .expect("foreground provider pause remains"); |
| 1604 | assert!( |
| 1605 | remaining < Duration::from_secs(70), |
| 1606 | "classifier Retry-After must not extend the global pause: {remaining:?}" |
| 1607 | ); |
| 1608 | codewhale_runtime::retry_status::clear(); |
| 1609 | codewhale_runtime::retry_status::clear_rate_limit(); |
| 1610 | } |
| 1611 | |
| 1612 | async fn assert_deepseek_strict_request_route_boundary(streaming: bool) { |
| 1613 | for (route_base_url, strict, expected_path, expected_wire_strict) in [ |
| 1614 | ( |
| 1615 | "https://api.deepseek.com/beta", |
| 1616 | false, |
| 1617 | "/v1/chat/completions", |
| 1618 | None, |
| 1619 | ), |
| 1620 | ( |
| 1621 | "https://api.deepseek.com/beta", |
| 1622 | true, |
| 1623 | "/beta/chat/completions", |
| 1624 | Some(true), |
| 1625 | ), |
| 1626 | ( |
| 1627 | "https://api.deepseek.com/v1", |
| 1628 | true, |
| 1629 | "/v1/chat/completions", |
| 1630 | None, |
| 1631 | ), |
| 1632 | ] { |
| 1633 | let (captured_path, body) = |
| 1634 | capture_deepseek_chat_request(route_base_url, strict, streaming).await; |
| 1635 | assert_eq!(captured_path, expected_path, "{route_base_url} {body}"); |
| 1636 | assert_eq!( |
| 1637 | body.pointer("/tools/0/function/strict") |
| 1638 | .and_then(Value::as_bool), |
| 1639 | expected_wire_strict, |
| 1640 | "{route_base_url} {body}" |
| 1641 | ); |
| 1642 | let parameters = &body["tools"][0]["function"]["parameters"]; |
| 1643 | if expected_wire_strict == Some(true) { |
| 1644 | assert_eq!(parameters["additionalProperties"], false); |
| 1645 | assert_eq!(parameters["required"], json!([])); |
| 1646 | } else { |
| 1647 | assert!(parameters.get("additionalProperties").is_none()); |
| 1648 | assert!(parameters.get("required").is_none()); |
| 1649 | } |
| 1650 | } |
| 1651 | } |
| 1652 | |
| 1653 | fn k3_request_fixture(model: &str, effort: Option<&str>, stream: bool) -> MessageRequest { |
| 1654 | MessageRequest { |
| 1655 | model: model.to_string(), |
| 1656 | messages: vec![Message { |
| 1657 | role: Role::User, |
| 1658 | content: vec![ContentBlock::Text { |
| 1659 | text: "request-boundary fixture".to_string(), |
| 1660 | cache_control: None, |
| 1661 | }], |
| 1662 | }], |
| 1663 | max_tokens: 64, |
| 1664 | system: None, |
| 1665 | tools: None, |
| 1666 | tool_choice: None, |
| 1667 | metadata: None, |
| 1668 | thinking: None, |
| 1669 | reasoning_effort: effort.map(str::to_string), |
| 1670 | stream: Some(stream), |
| 1671 | temperature: Some(0.25), |
| 1672 | top_p: Some(0.75), |
| 1673 | safety_check: None, |
| 1674 | title: None, |
| 1675 | } |
| 1676 | } |
| 1677 | |
| 1678 | async fn capture_moonshot_chat_request( |
| 1679 | route_base_url: &str, |
| 1680 | model: &str, |
| 1681 | effort: Option<&str>, |
| 1682 | streaming: bool, |
| 1683 | ) -> Value { |
| 1684 | let request = k3_request_fixture(model, effort, streaming); |
| 1685 | capture_moonshot_chat_request_body(route_base_url, model, request).await |
| 1686 | } |
| 1687 | |
| 1688 | async fn capture_moonshot_chat_request_body( |
| 1689 | route_base_url: &str, |
| 1690 | model: &str, |
| 1691 | request: MessageRequest, |
| 1692 | ) -> Value { |
| 1693 | let streaming = request.stream == Some(true); |
| 1694 | let server = MockServer::start().await; |
| 1695 | let response = if streaming { |
| 1696 | ResponseTemplate::new(200) |
| 1697 | .insert_header("content-type", "text/event-stream") |
| 1698 | .set_body_string("data: [DONE]\n\n") |
| 1699 | } else { |
| 1700 | ResponseTemplate::new(200).set_body_json(json!({ |
| 1701 | "id": "chatcmpl-k3-request-boundary", |
| 1702 | "object": "chat.completion", |
| 1703 | "model": model, |
| 1704 | "choices": [{ |
| 1705 | "index": 0, |
| 1706 | "message": {"role": "assistant", "content": "ok"}, |
| 1707 | "finish_reason": "stop" |
| 1708 | }], |
| 1709 | "usage": { |
| 1710 | "prompt_tokens": 1, |
| 1711 | "completion_tokens": 1, |
| 1712 | "total_tokens": 2 |
| 1713 | } |
| 1714 | })) |
| 1715 | }; |
| 1716 | Mock::given(method("POST")) |
| 1717 | .and(path("/v1/chat/completions")) |
| 1718 | .respond_with(response) |
| 1719 | .expect(1) |
| 1720 | .mount(&server) |
| 1721 | .await; |
| 1722 | |
| 1723 | let client = moonshot_request_boundary_client(route_base_url, model, server.uri()); |
| 1724 | |
| 1725 | if streaming { |
| 1726 | let mut stream = client |
| 1727 | .create_message_stream(request) |
| 1728 | .await |
| 1729 | .expect("streaming request succeeds"); |
| 1730 | while let Some(event) = stream.next().await { |
| 1731 | event.expect("captured SSE response remains valid"); |
| 1732 | } |
| 1733 | } else { |
| 1734 | client |
| 1735 | .create_message(request) |
| 1736 | .await |
| 1737 | .expect("non-streaming request succeeds"); |
| 1738 | } |
| 1739 | |
| 1740 | let requests = server.received_requests().await.expect("recorded request"); |
| 1741 | assert_eq!(requests.len(), 1); |
| 1742 | serde_json::from_slice(&requests[0].body).expect("captured request JSON") |
| 1743 | } |
| 1744 | |
| 1745 | async fn capture_route_chat_request_body( |
| 1746 | model: &str, |
| 1747 | request: MessageRequest, |
| 1748 | client_for_transport: impl FnOnce(String) -> CodewhaleClient, |
| 1749 | ) -> (String, Value) { |
| 1750 | let streaming = request.stream == Some(true); |
| 1751 | let server = MockServer::start().await; |
| 1752 | let response = if streaming { |
| 1753 | ResponseTemplate::new(200) |
| 1754 | .insert_header("content-type", "text/event-stream") |
| 1755 | .set_body_string("data: [DONE]\n\n") |
| 1756 | } else { |
| 1757 | ResponseTemplate::new(200).set_body_json(json!({ |
| 1758 | "id": "chatcmpl-provider-request-boundary", |
| 1759 | "object": "chat.completion", |
| 1760 | "model": model, |
| 1761 | "choices": [{ |
| 1762 | "index": 0, |
| 1763 | "message": {"role": "assistant", "content": "ok"}, |
| 1764 | "finish_reason": "stop" |
| 1765 | }], |
| 1766 | "usage": { |
| 1767 | "prompt_tokens": 1, |
| 1768 | "completion_tokens": 1, |
| 1769 | "total_tokens": 2 |
| 1770 | } |
| 1771 | })) |
| 1772 | }; |
| 1773 | Mock::given(method("POST")) |
| 1774 | .and(path("/v1/chat/completions")) |
| 1775 | .respond_with(response) |
| 1776 | .expect(1) |
| 1777 | .mount(&server) |
| 1778 | .await; |
| 1779 | |
| 1780 | let client = client_for_transport(server.uri()); |
| 1781 | if streaming { |
| 1782 | let mut stream = client |
| 1783 | .create_message_stream(request) |
| 1784 | .await |
| 1785 | .expect("streaming request succeeds"); |
| 1786 | while let Some(event) = stream.next().await { |
| 1787 | event.expect("captured SSE response remains valid"); |
| 1788 | } |
| 1789 | } else { |
| 1790 | client |
| 1791 | .create_message(request) |
| 1792 | .await |
| 1793 | .expect("non-streaming request succeeds"); |
| 1794 | } |
| 1795 | |
| 1796 | let requests = server.received_requests().await.expect("recorded request"); |
| 1797 | assert_eq!(requests.len(), 1); |
| 1798 | ( |
| 1799 | requests[0].url.path().to_string(), |
| 1800 | serde_json::from_slice(&requests[0].body).expect("captured request JSON"), |
| 1801 | ) |
| 1802 | } |
| 1803 | |
| 1804 | async fn capture_zai_chat_request( |
| 1805 | route_base_url: &str, |
| 1806 | model: &str, |
| 1807 | effort: Option<&str>, |
| 1808 | streaming: bool, |
| 1809 | ) -> (String, Value) { |
| 1810 | capture_route_chat_request_body(model, k3_request_fixture(model, effort, streaming), |uri| { |
| 1811 | zai_request_boundary_client(route_base_url, model, uri) |
| 1812 | }) |
| 1813 | .await |
| 1814 | } |
| 1815 | |
| 1816 | async fn capture_minimax_chat_request( |
| 1817 | route_base_url: &str, |
| 1818 | model: &str, |
| 1819 | effort: Option<&str>, |
| 1820 | streaming: bool, |
| 1821 | ) -> (String, Value) { |
| 1822 | capture_route_chat_request_body(model, k3_request_fixture(model, effort, streaming), |uri| { |
| 1823 | minimax_request_boundary_client(route_base_url, model, uri) |
| 1824 | }) |
| 1825 | .await |
| 1826 | } |
| 1827 | |
| 1828 | fn modelstudio_request_boundary_client( |
| 1829 | route_base_url: &str, |
| 1830 | model: &str, |
| 1831 | transport_base_url: String, |
| 1832 | ) -> CodewhaleClient { |
| 1833 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1834 | let mut client = CodewhaleClient::new(&{ |
| 1835 | let __cw_config_init_5_0 = Some("modelstudio-token-plan".to_string()); |
| 1836 | let __cw_config_init_5_1 = Some(ProvidersConfig { |
| 1837 | modelstudio_token_plan: ProviderConfig { |
| 1838 | api_key: Some("modelstudio-request-boundary-key".to_string()), |
| 1839 | base_url: Some(route_base_url.to_string()), |
| 1840 | model: Some(model.to_string()), |
| 1841 | ..ProviderConfig::default() |
| 1842 | }, |
| 1843 | ..ProvidersConfig::default() |
| 1844 | }); |
| 1845 | let mut __cw_config_init_5_value: Config = Config::default(); |
| 1846 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 1847 | __cw_config_init_5_value.providers = __cw_config_init_5_1; |
| 1848 | __cw_config_init_5_value |
| 1849 | }) |
| 1850 | .expect("Model Studio request-boundary client"); |
| 1851 | assert_eq!(client.base_url, route_base_url); |
| 1852 | client.test_chat_transport_base_url = Some(transport_base_url); |
| 1853 | client |
| 1854 | } |
| 1855 | |
| 1856 | async fn capture_modelstudio_chat_request( |
| 1857 | route_base_url: &str, |
| 1858 | model: &str, |
| 1859 | effort: Option<&str>, |
| 1860 | streaming: bool, |
| 1861 | ) -> (String, Value) { |
| 1862 | capture_route_chat_request_body(model, k3_request_fixture(model, effort, streaming), |uri| { |
| 1863 | modelstudio_request_boundary_client(route_base_url, model, uri) |
| 1864 | }) |
| 1865 | .await |
| 1866 | } |
| 1867 | |
| 1868 | async fn assert_modelstudio_request_truth(streaming: bool) { |
| 1869 | // Token Plan and Coding Plan share DashScope's reasoning controls on |
| 1870 | // their OpenAI-compatible Chat Completions endpoints — but the fields |
| 1871 | // are model-specific, not provider-wide. |
| 1872 | for base_url in [ |
| 1873 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 1874 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL, |
| 1875 | ] { |
| 1876 | // The default model, qwen3.8-max, is thinking-only: the bundled |
| 1877 | // catalog records it as `thinking: always_on`, and |
| 1878 | // qwen3.8-max-preview has effort/budget options with no toggle. |
| 1879 | // Neither accepts an enable/disable switch, so CodeWhale must not |
| 1880 | // send one — not even `false` for an explicit `off`. This assertion |
| 1881 | // used to pin the opposite; PR #5233 caught it. |
| 1882 | for effort in [None, Some("off"), Some("high"), Some("max")] { |
| 1883 | let (path, body) = capture_modelstudio_chat_request( |
| 1884 | base_url, |
| 1885 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_MODEL, |
| 1886 | effort, |
| 1887 | streaming, |
| 1888 | ) |
| 1889 | .await; |
| 1890 | assert_eq!(path, "/v1/chat/completions"); |
| 1891 | assert!( |
| 1892 | body.get("enable_thinking").is_none(), |
| 1893 | "{base_url} {effort:?}: {body}" |
| 1894 | ); |
| 1895 | assert!( |
| 1896 | body.get("thinking").is_none(), |
| 1897 | "{base_url} {effort:?}: {body}" |
| 1898 | ); |
| 1899 | assert!( |
| 1900 | body.get("reasoning_effort").is_none(), |
| 1901 | "{base_url} {effort:?}: {body}" |
| 1902 | ); |
| 1903 | } |
| 1904 | |
| 1905 | // A hybrid model does get the documented switch, plus |
| 1906 | // `preserve_thinking` so the next turn keeps its trace. |
| 1907 | for (effort, enabled) in [(None, true), (Some("high"), true), (Some("off"), false)] { |
| 1908 | let (_, body) = |
| 1909 | capture_modelstudio_chat_request(base_url, "qwen3.7-plus", effort, streaming).await; |
| 1910 | assert_eq!( |
| 1911 | body["enable_thinking"], |
| 1912 | json!(enabled), |
| 1913 | "{base_url} {effort:?}: {body}" |
| 1914 | ); |
| 1915 | assert_eq!( |
| 1916 | body["preserve_thinking"], |
| 1917 | json!(enabled), |
| 1918 | "{base_url} {effort:?}: {body}" |
| 1919 | ); |
| 1920 | // The hybrid Qwen families have no effort ladder on the wire. |
| 1921 | assert!( |
| 1922 | body.get("reasoning_effort").is_none(), |
| 1923 | "{base_url} {effort:?}: {body}" |
| 1924 | ); |
| 1925 | } |
| 1926 | |
| 1927 | // DeepSeek-V4 is one of the two families with a documented effort |
| 1928 | // ladder (`high` / `max`). |
| 1929 | let (_, deepseek) = |
| 1930 | capture_modelstudio_chat_request(base_url, "deepseek-v4-pro", Some("xhigh"), streaming) |
| 1931 | .await; |
| 1932 | assert_eq!( |
| 1933 | deepseek["enable_thinking"], |
| 1934 | json!(true), |
| 1935 | "{base_url}: {deepseek}" |
| 1936 | ); |
| 1937 | assert_eq!( |
| 1938 | deepseek["reasoning_effort"], |
| 1939 | json!("max"), |
| 1940 | "{base_url}: {deepseek}" |
| 1941 | ); |
| 1942 | } |
| 1943 | |
| 1944 | // Fail closed: the same provider identity pointed at a custom gateway |
| 1945 | // must not be handed Alibaba's dialect. |
| 1946 | let (_, proxied) = capture_modelstudio_chat_request( |
| 1947 | "https://proxy.example/v1", |
| 1948 | "qwen3.7-plus", |
| 1949 | Some("high"), |
| 1950 | streaming, |
| 1951 | ) |
| 1952 | .await; |
| 1953 | assert!(proxied.get("enable_thinking").is_none(), "{proxied}"); |
| 1954 | assert!(proxied.get("preserve_thinking").is_none(), "{proxied}"); |
| 1955 | assert!(proxied.get("reasoning_effort").is_none(), "{proxied}"); |
| 1956 | } |
| 1957 |