返回 CodeWhale
test_cases_06.rs
根目录 / crates / engine / src / client / test_cases_06.rs
1
2 #[tokio::test]
3 async fn fetch_catalog_delta_rejects_oversized_bodies_and_rosters() {
4 let server = MockServer::start().await;
5 Mock::given(method("GET"))
6 .and(path("/v1/models"))
7 .respond_with(ResponseTemplate::new(200).set_body_raw(
8 "x".repeat(PROVIDER_CATALOG_MAX_RESPONSE_BYTES + 1),
9 "application/json",
10 ))
11 .mount(&server)
12 .await;
13 assert_eq!(
14 openrouter_client_for(&server)
15 .fetch_catalog_delta()
16 .await
17 .expect_err("oversized body"),
18 CatalogRefreshError::InvalidResponse
19 );
20
21 let server = MockServer::start().await;
22 let rows: Vec<_> = (0..=PROVIDER_CATALOG_MAX_ROWS)
23 .map(|index| json!({"id": format!("synthetic-model-{index}")}))
24 .collect();
25 mount_models_json(&server, 200, json!({"data": rows})).await;
26 assert_eq!(
27 openrouter_client_for(&server)
28 .fetch_catalog_delta()
29 .await
30 .expect_err("oversized roster"),
31 CatalogRefreshError::InvalidResponse
32 );
33 }
34
35 #[tokio::test]
36 async fn refresh_catalog_cache_records_success_then_preserves_rows_on_failure() {
37 // First refresh succeeds and caches live rows.
38 let server = MockServer::start().await;
39 mount_models_json(
40 &server,
41 200,
42 json!({"data": [{"id": "synthetic-model-gamma"}]}),
43 )
44 .await;
45 let client = openrouter_client_for(&server);
46 let mut cache = ProviderCatalogCache::new();
47
48 let status = client.refresh_catalog_cache(&mut cache, 3600).await;
49 assert_eq!(status, CatalogStatus::Fresh);
50 let fp = base_url_fingerprint(&server.uri());
51 let cached = cache.get("openrouter", &fp).expect("cached entry");
52 assert_eq!(cached.offerings.len(), 1);
53 assert_eq!(cached.offerings[0].wire_model_id, "synthetic-model-gamma");
54
55 // A later failing refresh on the same base URL flips status to Failed
56 // but PRESERVES the rows.
57 server.reset().await;
58 mount_models_json(&server, 401, json!({"error": "denied"})).await;
59 let status = client.refresh_catalog_cache(&mut cache, 3600).await;
60 assert!(matches!(
61 status,
62 CatalogStatus::Failed {
63 reason: CatalogRefreshError::Unauthorized,
64 ..
65 }
66 ));
67 let cached = cache.get("openrouter", &fp).expect("entry still present");
68 assert_eq!(
69 cached.offerings.len(),
70 1,
71 "rows from the prior success must survive a failed refresh"
72 );
73 assert!(matches!(cached.status, CatalogStatus::Failed { .. }));
74
75 // #4139: failed/stale rows must still publish into ProviderLake so
76 // pickers keep live coverage instead of dropping back to bundled-only.
77 let visible = cache.all_visible_offerings(now_unix());
78 assert_eq!(visible.len(), 1);
79 assert_eq!(visible[0].wire_model_id, "synthetic-model-gamma");
80 assert!(
81 cache.all_fresh_offerings(now_unix()).is_empty(),
82 "Failed entries are not fresh, but they remain visible"
83 );
84 }
85
86 #[tokio::test]
87 async fn invalid_live_prices_fail_refresh_and_preserve_each_provider_last_known_good() {
88 let openrouter_server = MockServer::start().await;
89 mount_models_json(
90 &openrouter_server,
91 200,
92 json!({"data": [{
93 "id": "synthetic/openrouter-priced",
94 "pricing": {"prompt": "0.000001", "completion": "0.000002"}
95 }]}),
96 )
97 .await;
98 let openrouter = openrouter_client_for(&openrouter_server);
99 let mut openrouter_cache = ProviderCatalogCache::new();
100 assert_eq!(
101 openrouter
102 .refresh_catalog_cache(&mut openrouter_cache, 3_600)
103 .await,
104 CatalogStatus::Fresh
105 );
106 let openrouter_fp = base_url_fingerprint(&openrouter_server.uri());
107 let openrouter_lkg = openrouter_cache
108 .get("openrouter", &openrouter_fp)
109 .expect("OpenRouter LKG")
110 .offerings
111 .clone();
112
113 openrouter_server.reset().await;
114 mount_models_json(
115 &openrouter_server,
116 200,
117 json!({"data": [{
118 "id": "synthetic/openrouter-priced",
119 "pricing": {"prompt": "1e308", "completion": "0.000002"}
120 }]}),
121 )
122 .await;
123 assert!(matches!(
124 openrouter
125 .refresh_catalog_cache(&mut openrouter_cache, 3_600)
126 .await,
127 CatalogStatus::Failed {
128 reason: CatalogRefreshError::InvalidResponse
129 }
130 ));
131 assert_eq!(
132 openrouter_cache
133 .get("openrouter", &openrouter_fp)
134 .expect("preserved OpenRouter LKG")
135 .offerings,
136 openrouter_lkg
137 );
138
139 // Same plumbing for an ordinary custom host: the generic branch
140 // ignores unknown pricing fields, so the failure injector here is a
141 // body that is not a model list at all. Absurd-price rejection stays
142 // covered at the Baseten builder's own fixture tests.
143 let custom_server = MockServer::start().await;
144 mount_models_json(
145 &custom_server,
146 200,
147 json!({"data": [{
148 "id": "synthetic/custom-model"
149 }]}),
150 )
151 .await;
152 let custom = custom_mock_client_for_identity(&custom_server, "custom-lkg");
153 let mut custom_cache = ProviderCatalogCache::new();
154 assert_eq!(
155 custom.refresh_catalog_cache(&mut custom_cache, 3_600).await,
156 CatalogStatus::Fresh
157 );
158 let custom_fp = base_url_fingerprint(&format!("{}/v1", custom_server.uri()));
159 let custom_lkg = custom_cache
160 .get("custom-lkg", &custom_fp)
161 .expect("custom LKG")
162 .offerings
163 .clone();
164
165 custom_server.reset().await;
166 mount_models_json(&custom_server, 200, json!("not a model list")).await;
167 assert!(matches!(
168 custom.refresh_catalog_cache(&mut custom_cache, 3_600).await,
169 CatalogStatus::Failed {
170 reason: CatalogRefreshError::InvalidResponse
171 }
172 ));
173 assert_eq!(
174 custom_cache
175 .get("custom-lkg", &custom_fp)
176 .expect("preserved custom LKG")
177 .offerings,
178 custom_lkg
179 );
180 }
181
182 #[tokio::test]
183 async fn live_catalog_is_scoped_by_base_url_fingerprint() {
184 // Same provider, two different base URLs -> two distinct cache scopes.
185 let server_a = MockServer::start().await;
186 mount_models_json(&server_a, 200, json!({"data": [{"id": "synthetic-a"}]})).await;
187 let server_b = MockServer::start().await;
188 mount_models_json(&server_b, 200, json!({"data": [{"id": "synthetic-b"}]})).await;
189
190 let mut cache = ProviderCatalogCache::new();
191 openrouter_client_for(&server_a)
192 .refresh_catalog_cache(&mut cache, 3600)
193 .await;
194 openrouter_client_for(&server_b)
195 .refresh_catalog_cache(&mut cache, 3600)
196 .await;
197
198 let fp_a = base_url_fingerprint(&server_a.uri());
199 let fp_b = base_url_fingerprint(&server_b.uri());
200 assert_ne!(
201 fp_a, fp_b,
202 "different base URLs must fingerprint differently"
203 );
204 assert_eq!(
205 cache.get("openrouter", &fp_a).expect("a").offerings[0].wire_model_id,
206 "synthetic-a"
207 );
208 assert_eq!(
209 cache.get("openrouter", &fp_b).expect("b").offerings[0].wire_model_id,
210 "synthetic-b"
211 );
212 }
213
214 #[tokio::test]
215 async fn static_rows_survive_a_live_refresh_failure() {
216 // Bundled/static rows compile through even when the live layer is empty
217 // (the state after a failed refresh with no prior success).
218 let server = MockServer::start().await;
219 mount_models_json(&server, 503, json!({"error": "down"})).await;
220 let client = openrouter_client_for(&server);
221 let mut cache = ProviderCatalogCache::new();
222 let status = client.refresh_catalog_cache(&mut cache, 3600).await;
223 assert!(matches!(status, CatalogStatus::Failed { .. }));
224
225 let static_row = CatalogOffering {
226 provider: "openrouter".to_string(),
227 wire_model_id: "synthetic-static".to_string(),
228 endpoint_key: "chat".to_string(),
229 ..CatalogOffering::default()
230 };
231 let fp = base_url_fingerprint(&server.uri());
232 let fresh_live: Vec<CatalogOffering> = cache
233 .get("openrouter", &fp)
234 .filter(|entry| entry.is_fresh(now_unix()))
235 .map(|entry| entry.offerings.clone())
236 .unwrap_or_default();
237 let snapshot = codewhale_config::catalog::CatalogCompiler::new()
238 .with_bundled(vec![static_row])
239 .with_live(fresh_live)
240 .compile();
241 assert!(
242 snapshot
243 .offerings
244 .iter()
245 .any(|offering| offering.wire_model_id == "synthetic-static"),
246 "static fallback row must remain available after a failed refresh"
247 );
248 }
249
250 #[test]
251 fn client_route_envelope_freezes_saved_minimax_billing_mode_and_wire_model() {
252 let _ = rustls::crypto::ring::default_provider().install_default();
253 let config = {
254 let __cw_config_init_0_0 = Some("minimax".to_string());
255 let __cw_config_init_0_1 = Some(ProvidersConfig {
256 minimax: ProviderConfig {
257 api_key: Some("test-key".to_string()),
258 mode: Some("pay-as-you-go".to_string()),
259 ..ProviderConfig::default()
260 },
261 ..ProvidersConfig::default()
262 });
263 let mut __cw_config_init_0_value: Config = Config::default();
264 __cw_config_init_0_value.provider = __cw_config_init_0_0;
265 __cw_config_init_0_value.providers = __cw_config_init_0_1;
266 __cw_config_init_0_value
267 };
268 let client = CodewhaleClient::new(&config).expect("MiniMax client");
269 let dispatched_at =
270 chrono::DateTime::<chrono::Utc>::from_timestamp(1_234, 0).expect("timestamp");
271 let route = client.effective_route_envelope("MiniMax-M3", dispatched_at);
272
273 assert_eq!(route.provider, ProviderKind::Minimax);
274 assert_eq!(route.provider_identity, "minimax");
275 assert_eq!(route.model, "MiniMax-M3");
276 assert_eq!(
277 route.billing_surface.as_deref(),
278 Some(crate::pricing::MINIMAX_PAYG_BILLING_SURFACE)
279 );
280 assert_eq!(
281 route.billing_mode,
282 crate::cost_status::RouteBillingMode::Metered
283 );
284 assert_eq!(route.dispatched_at.timestamp(), 1_234);
285 }
286
287 #[test]
288 fn sanitize_thinking_mode_counts_reasoning_replay_across_assistant_turns() {
289 // Multi-turn body that mimics two prior tool-calling rounds: each
290 // assistant message carries its `reasoning_content`. The sanitizer
291 // should keep all of them and the count helper should tally bytes
292 // across every assistant message.
293 let mut body = json!({
294 "model": "deepseek-v4-pro",
295 "messages": [
296 { "role": "system", "content": "you are helpful" },
297 { "role": "user", "content": "step 1" },
298 {
299 "role": "assistant",
300 "content": "",
301 "reasoning_content": "I need to call tool A first.",
302 "tool_calls": [{ "id": "1", "type": "function" }]
303 },
304 { "role": "tool", "tool_call_id": "1", "content": "ok" },
305 {
306 "role": "assistant",
307 "content": "",
308 "reasoning_content": "Now I call tool B.",
309 "tool_calls": [{ "id": "2", "type": "function" }]
310 },
311 { "role": "tool", "tool_call_id": "2", "content": "ok" },
312 { "role": "user", "content": "step 2" }
313 ]
314 });
315
316 let approx_tokens = sanitize_thinking_mode_messages(
317 &mut body,
318 "deepseek-v4-pro",
319 Some("max"),
320 ProviderKind::Deepseek,
321 )
322 .expect("multi-turn thinking-mode conversation should report replay tokens");
323 // ~4 chars/token; 46 bytes of reasoning -> 11 tokens.
324 assert_eq!(approx_tokens, 11);
325
326 let chars = count_reasoning_replay_chars(&body);
327 // "I need to call tool A first." (28) + "Now I call tool B." (18) = 46
328 assert_eq!(chars, 46);
329
330 // No assistant messages should have lost or had their reasoning_content blanked.
331 let messages = body["messages"].as_array().unwrap();
332 let assistant_with_reasoning: usize = messages
333 .iter()
334 .filter(|m| m["role"] == "assistant")
335 .filter(|m| {
336 m["reasoning_content"]
337 .as_str()
338 .is_some_and(|s| !s.is_empty())
339 })
340 .count();
341 assert_eq!(assistant_with_reasoning, 2);
342 }
343
344 /// Issue #30: when no thinking-mode replay applies (non-thinking model or
345 /// empty conversation), the sanitizer returns `None` so the footer chip
346 /// stays hidden.
347 #[test]
348 fn sanitize_thinking_mode_returns_none_for_non_thinking_model() {
349 let mut body = json!({
350 "model": "deepseek-v4-flash",
351 "messages": [
352 { "role": "user", "content": "hi" }
353 ]
354 });
355 let result = sanitize_thinking_mode_messages(
356 &mut body,
357 "deepseek-v4-flash",
358 None,
359 ProviderKind::Deepseek,
360 );
361 // reasoning_effort is None → no thinking injection, result is None
362 assert!(result.is_none());
363 }
364
365 #[test]
366 fn sanitize_thinking_mode_counts_substituted_placeholder() {
367 // An assistant tool-call message is missing reasoning_content; the
368 // sanitizer must inject the placeholder, and the count helper must
369 // include the placeholder in the total (since it's in the wire
370 // payload that ships to DeepSeek).
371 let mut body = json!({
372 "model": "deepseek-v4-pro",
373 "messages": [
374 { "role": "user", "content": "hi" },
375 {
376 "role": "assistant",
377 "content": "",
378 "tool_calls": [{ "id": "1", "type": "function" }]
379 }
380 ]
381 });
382
383 sanitize_thinking_mode_messages(
384 &mut body,
385 "deepseek-v4-pro",
386 Some("max"),
387 ProviderKind::Deepseek,
388 );
389
390 let chars = count_reasoning_replay_chars(&body);
391 // "(reasoning omitted)" is 19 bytes.
392 assert_eq!(chars, 19);
393 }
394
395 #[test]
396 fn sanitize_thinking_mode_skips_generic_openai_provider() {
397 // #1542 intent (narrowed by #1739/#1694): the sanitizer only skips for
398 // a *genuine non-DeepSeek* model on the generic openai provider. A
399 // DeepSeek reasoning model on the openai provider still gets sanitized
400 // (see chat.rs `deepseek_model_on_openai_provider_still_replays_*`).
401 let mut body = json!({
402 "model": "qwen3-coder",
403 "messages": [
404 { "role": "user", "content": "hi" },
405 {
406 "role": "assistant",
407 "content": "",
408 "tool_calls": [{ "id": "1", "type": "function" }]
409 }
410 ]
411 });
412
413 let result = sanitize_thinking_mode_messages(
414 &mut body,
415 "qwen3-coder",
416 Some("max"),
417 ProviderKind::Openai,
418 );
419
420 assert!(result.is_none());
421 let assistant = body["messages"]
422 .as_array()
423 .and_then(|messages| {
424 messages
425 .iter()
426 .find(|message| message["role"] == "assistant")
427 })
428 .expect("assistant message");
429 assert!(
430 assistant.get("reasoning_content").is_none(),
431 "generic OpenAI-compatible provider payload must not get reasoning_content (#1542)"
432 );
433 }
434
435 #[test]
436 fn sanitize_thinking_mode_keeps_tool_call_placeholder_after_new_user_turn() {
437 let mut body = json!({
438 "model": "deepseek-v4-pro",
439 "messages": [
440 { "role": "user", "content": "step 1" },
441 {
442 "role": "assistant",
443 "content": "",
444 "tool_calls": [{ "id": "1", "type": "function" }]
445 },
446 { "role": "tool", "tool_call_id": "1", "content": "ok" },
447 { "role": "user", "content": "step 2" }
448 ]
449 });
450
451 sanitize_thinking_mode_messages(
452 &mut body,
453 "deepseek-v4-pro",
454 Some("max"),
455 ProviderKind::Deepseek,
456 );
457
458 let messages = body["messages"].as_array().unwrap();
459 let assistant = messages
460 .iter()
461 .find(|m| m["role"] == "assistant")
462 .expect("assistant tool-call message");
463 assert_eq!(
464 assistant.get("reasoning_content").and_then(Value::as_str),
465 Some("(reasoning omitted)")
466 );
467 }
468
469 #[test]
470 fn token_bucket_enforces_delay_when_empty() {
471 let now = Instant::now();
472 let mut bucket = TokenBucket {
473 enabled: true,
474 capacity: 1.0,
475 tokens: 1.0,
476 refill_per_sec: 2.0,
477 last_refill: now,
478 };
479
480 assert!(bucket.delay_until_available(1.0).is_none());
481 let delay = bucket
482 .delay_until_available(1.0)
483 .expect("bucket should require refill delay");
484 assert!(
485 delay >= Duration::from_millis(400) && delay <= Duration::from_millis(600),
486 "unexpected refill delay: {delay:?}"
487 );
488 }
489
490 #[test]
491 fn token_bucket_saturates_delay_for_a_tiny_refill_rate() {
492 let mut bucket = TokenBucket {
493 enabled: true,
494 capacity: 1.0,
495 tokens: 0.0,
496 refill_per_sec: 1e-30,
497 last_refill: Instant::now(),
498 };
499
500 assert_eq!(bucket.delay_until_available(1.0), Some(Duration::MAX));
501 }
502
503 /// Every queued waiter must be given a *distinct* wake time. `client.rs`
504 /// releases the bucket lock before sleeping (`wait_for_rate_limit`), and a
505 /// clone of the client shares one `Arc<AsyncMutex<TokenBucket>>` across
506 /// sub-agents, so if the bucket hands two waiters the same delay they both
507 /// wake at the same instant and fire together — a burst the configured
508 /// limit was supposed to prevent.
509 #[test]
510 fn token_bucket_queues_concurrent_waiters_instead_of_stacking_them() {
511 let now = Instant::now();
512 let mut bucket = TokenBucket {
513 enabled: true,
514 capacity: 1.0,
515 tokens: 1.0,
516 refill_per_sec: 1.0,
517 last_refill: now,
518 };
519
520 assert!(bucket.delay_until_available(1.0).is_none());
521 let first = bucket
522 .delay_until_available(1.0)
523 .expect("second caller waits for a refill");
524 let second = bucket
525 .delay_until_available(1.0)
526 .expect("third caller waits for a refill");
527
528 assert!(
529 first >= Duration::from_millis(900) && first <= Duration::from_millis(1100),
530 "unexpected first wait: {first:?}"
531 );
532 assert!(
533 second >= Duration::from_millis(1900) && second <= Duration::from_millis(2100),
534 "third caller must queue behind the second, not wake with it: {second:?}"
535 );
536 }
537
538 #[test]
539 fn stream_buffer_pool_reuses_released_buffers() {
540 let mut first = acquire_stream_buffer();
541 first.extend_from_slice(b"hello");
542 let released_capacity = first.capacity();
543 release_stream_buffer(first);
544
545 let second = acquire_stream_buffer();
546 assert!(second.is_empty());
547 assert!(
548 second.capacity() >= released_capacity,
549 "pooled buffer capacity should be reused"
550 );
551 }
552
553 #[test]
554 fn base_url_scenario() {
555 // Scenario consolidation of: base_url_security_rejects_insecure_non_local_http, base_url_security_errors_redact_sensitive_url_parts, base_url_security_allows_localhost_http, base_url_security_allows_non_local_http_with_explicit_opt_in
556 // from base_url_security_rejects_insecure_non_local_http
557 {
558 let _lock = crate::test_support::lock_test_env();
559 let _guard = AllowInsecureHttpEnvGuard::capture();
560 unsafe { std::env::remove_var(ALLOW_INSECURE_HTTP_ENV) };
561
562 let err = validate_base_url_security("http://api.deepseek.com", false)
563 .expect_err("non-local insecure HTTP should be rejected");
564 assert!(err.to_string().contains("Refusing insecure base URL"));
565 }
566 // from base_url_security_errors_redact_sensitive_url_parts
567 {
568 let _lock = crate::test_support::lock_test_env();
569 let _guard = AllowInsecureHttpEnvGuard::capture();
570 unsafe { std::env::remove_var(ALLOW_INSECURE_HTTP_ENV) };
571
572 let err = validate_base_url_security(
573 "http://user:secret@example.com/v1?api_key=sk-test&ok=1",
574 false,
575 )
576 .expect_err("non-local insecure HTTP should be rejected");
577 let message = err.to_string();
578
579 assert!(message.contains("http://***:***@example.com/v1?api_key=***&ok=1"));
580 assert!(!message.contains("user:secret"));
581 assert!(!message.contains("sk-test"));
582 }
583 // from base_url_security_allows_localhost_http
584 {
585 let _lock = crate::test_support::lock_test_env();
586 let _guard = AllowInsecureHttpEnvGuard::capture();
587 unsafe { std::env::remove_var(ALLOW_INSECURE_HTTP_ENV) };
588
589 for url in [
590 "http://localhost:8080",
591 "http://LOCALHOST:8080",
592 "http://127.0.0.1:8080",
593 "http://127.0.0.2:8080",
594 "http://[::1]:8080",
595 "https://provider.example/v1",
596 ] {
597 assert!(validate_base_url_security(url, false).is_ok(), "{url}");
598 }
599 for url in [
600 "http://localhost.attacker.example/v1",
601 "http://127.0.0.1.attacker.example/v1",
602 "http://localhost@attacker.example/v1",
603 "http://127.0.0.1@attacker.example/v1",
604 "HTTP://localhost.attacker.example/v1",
605 ] {
606 assert!(validate_base_url_security(url, false).is_err(), "{url}");
607 assert!(validate_base_url_security(url, true).is_ok(), "{url}");
608 }
609 for url in ["https://", "http://[::1", "file:///tmp/provider"] {
610 assert!(validate_base_url_security(url, true).is_err(), "{url}");
611 }
612 }
613 // from base_url_security_allows_non_local_http_with_explicit_opt_in
614 {
615 let _lock = crate::test_support::lock_test_env();
616 let _guard = AllowInsecureHttpEnvGuard::capture();
617 unsafe { std::env::set_var(ALLOW_INSECURE_HTTP_ENV, "1") };
618
619 assert!(validate_base_url_security("http://192.168.0.110:8000/v1", false).is_ok());
620 }
621 // #5991: a provider that opts in via its [providers.<name>] table may
622 // use a plain-HTTP base URL without any env var. This is the
623 // 0.9.11-and-earlier behavior the key silently stopped providing.
624 {
625 let _lock = crate::test_support::lock_test_env();
626 let _guard = AllowInsecureHttpEnvGuard::capture();
627 unsafe { std::env::remove_var(ALLOW_INSECURE_HTTP_ENV) };
628
629 assert!(validate_base_url_security("http://192.168.0.110:8000/v1", true).is_ok());
630 // The refusal message now leads with the config key.
631 let err = validate_base_url_security("http://api.deepseek.com", false)
632 .expect_err("still refused without either opt-in");
633 assert!(err.to_string().contains("allow_insecure_http = true"));
634 }
635 }
636
637 struct AllowInsecureHttpEnvGuard {
638 prior: Option<std::ffi::OsString>,
639 prior_legacy: Option<std::ffi::OsString>,
640 }
641 impl AllowInsecureHttpEnvGuard {
642 fn capture() -> Self {
643 let guard = Self {
644 prior: std::env::var_os(ALLOW_INSECURE_HTTP_ENV),
645 prior_legacy: std::env::var_os(LEGACY_ALLOW_INSECURE_HTTP_ENV),
646 };
647 // Clear the legacy alias so ambient shell state cannot satisfy
648 // the CODEWHALE-first fallback chain behind a test's back.
649 unsafe { std::env::remove_var(LEGACY_ALLOW_INSECURE_HTTP_ENV) };
650 guard
651 }
652 }
653 impl Drop for AllowInsecureHttpEnvGuard {
654 fn drop(&mut self) {
655 match &self.prior {
656 Some(v) => unsafe { std::env::set_var(ALLOW_INSECURE_HTTP_ENV, v) },
657 None => unsafe { std::env::remove_var(ALLOW_INSECURE_HTTP_ENV) },
658 }
659 match &self.prior_legacy {
660 Some(v) => unsafe { std::env::set_var(LEGACY_ALLOW_INSECURE_HTTP_ENV, v) },
661 None => unsafe { std::env::remove_var(LEGACY_ALLOW_INSECURE_HTTP_ENV) },
662 }
663 }
664 }
665
666 #[test]
667 fn connection_health_degrades_and_recovers() {
668 let now = Instant::now();
669 let mut health = ConnectionHealth::default();
670 assert_eq!(health.state, ConnectionState::Healthy);
671
672 apply_request_failure(&mut health, now);
673 assert_eq!(health.state, ConnectionState::Healthy);
674
675 apply_request_failure(&mut health, now + Duration::from_millis(1));
676 assert_eq!(health.state, ConnectionState::Degraded);
677 assert_eq!(health.consecutive_failures, 2);
678
679 let recovered = apply_request_success(&mut health, now + Duration::from_secs(1));
680 assert!(recovered);
681 assert_eq!(health.state, ConnectionState::Healthy);
682 assert_eq!(health.consecutive_failures, 0);
683 }
684
685 #[test]
686 fn recovery_probe_respects_cooldown() {
687 let now = Instant::now();
688 let mut health = ConnectionHealth {
689 state: ConnectionState::Degraded,
690 ..ConnectionHealth::default()
691 };
692
693 assert!(mark_recovery_probe_if_due(&mut health, now));
694 assert_eq!(health.state, ConnectionState::Recovering);
695 assert!(!mark_recovery_probe_if_due(
696 &mut health,
697 now + Duration::from_secs(1)
698 ));
699 assert!(mark_recovery_probe_if_due(
700 &mut health,
701 now + RECOVERY_PROBE_COOLDOWN + Duration::from_millis(1)
702 ));
703 }
704
705 // === #103 Phase 2: HTTP/1 escape hatch ===================================
706
707 struct ForceHttp1EnvGuard {
708 prior: Option<std::ffi::OsString>,
709 }
710 impl ForceHttp1EnvGuard {
711 fn capture() -> Self {
712 Self {
713 prior: std::env::var_os("DEEPSEEK_FORCE_HTTP1"),
714 }
715 }
716 }
717 impl Drop for ForceHttp1EnvGuard {
718 fn drop(&mut self) {
719 // Safety: scoped to test process; reverts to the captured value.
720 match &self.prior {
721 Some(v) => unsafe { std::env::set_var("DEEPSEEK_FORCE_HTTP1", v) },
722 None => unsafe { std::env::remove_var("DEEPSEEK_FORCE_HTTP1") },
723 }
724 }
725 }
726
727 #[tokio::test]
728 async fn configured_http2_keepalive_reaches_real_client_transport() {
729 use tokio::io::{AsyncReadExt, AsyncWriteExt};
730 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
731 let url = format!("http://{}", listener.local_addr().unwrap());
732 let config: Config = toml::from_str(
733 "[stream]\nhttp2_keep_alive_interval_secs=1\nhttp2_keep_alive_timeout_secs=1\n",
734 )
735 .unwrap();
736 let client = CodewhaleClient::http_client_builder_with_auth_mode(
737 "",
738 &HashMap::new(),
739 ProviderKind::Deepseek,
740 &url,
741 WireFormat::ChatCompletions,
742 true,
743 false,
744 &config,
745 AuthHeaderSurface::Inference,
746 None,
747 )
748 .unwrap()
749 .no_proxy()
750 .http2_prior_knowledge()
751 .build()
752 .unwrap();
753 let request = tokio::spawn(async move { client.get(url).send().await });
754 // Minimal HTTP/2 peer: handshake, leave the request open, and observe
755 // the actual PING. No additional dependency or external provider.
756 let peer = tokio::time::timeout(Duration::from_secs(5), async {
757 let (mut peer, _) = listener.accept().await.unwrap();
758 let mut preface = [0; 24];
759 peer.read_exact(&mut preface).await.unwrap();
760 assert_eq!(&preface, b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
761 peer.write_all(&[0, 0, 0, 4, 0, 0, 0, 0, 0]).await.unwrap();
762 loop {
763 let mut header = [0; 9];
764 peer.read_exact(&mut header).await.unwrap();
765 let len = (usize::from(header[0]) << 16)
766 | (usize::from(header[1]) << 8)
767 | usize::from(header[2]);
768 assert!(len <= 65536, "bounded test frame");
769 let mut body = vec![0; len];
770 peer.read_exact(&mut body).await.unwrap();
771 if header[3] == 4 && header[4] & 1 == 0 {
772 peer.write_all(&[0, 0, 0, 4, 1, 0, 0, 0, 0]).await.unwrap();
773 }
774 if header[3] == 6 && header[4] & 1 == 0 {
775 assert_eq!(len, 8);
776 return peer; // Deliberately withhold the PING ACK.
777 }
778 }
779 })
780 .await
781 .expect("configured one-second interval must send a PING before the default 15 seconds");
782 let result = tokio::time::timeout(Duration::from_secs(3), request).await
783 .expect("configured one-second acknowledgement timeout must end the request before default 20 seconds")
784 .unwrap();
785 assert!(
786 result.is_err(),
787 "an unacknowledged PING must fail the request"
788 );
789 drop(peer); // Keep the peer open until the client's own timer fires.
790 }
791
792 #[test]
793 fn force_http1_scenario() {
794 // Scenario consolidation of: force_http1_unset_is_false, force_http1_truthy_values, force_http1_falsy_values
795 // from force_http1_unset_is_false
796 {
797 let _lock = crate::test_support::lock_test_env();
798 let _guard = ForceHttp1EnvGuard::capture();
799 unsafe { std::env::remove_var("DEEPSEEK_FORCE_HTTP1") };
800 assert!(!codewhale_config::force_http1_from_env());
801 }
802 // from force_http1_truthy_values
803 {
804 let _lock = crate::test_support::lock_test_env();
805 let _guard = ForceHttp1EnvGuard::capture();
806 for value in ["1", "true", "True", "YES", "on", " 1 "] {
807 // Safety: serialized by lock_test_env; reverted by guard.
808 unsafe { std::env::set_var("DEEPSEEK_FORCE_HTTP1", value) };
809 assert!(
810 codewhale_config::force_http1_from_env(),
811 "{value:?} should be parsed as truthy",
812 );
813 }
814 }
815 // from force_http1_falsy_values
816 {
817 let _lock = crate::test_support::lock_test_env();
818 let _guard = ForceHttp1EnvGuard::capture();
819 for value in ["0", "false", "no", "off", "", "garbage", "2"] {
820 unsafe { std::env::set_var("DEEPSEEK_FORCE_HTTP1", value) };
821 assert!(
822 !codewhale_config::force_http1_from_env(),
823 "{value:?} should NOT be parsed as truthy"
824 );
825 }
826 }
827 }
828
829 #[test]
830 fn redact_url_for_display_masks_userinfo_and_sensitive_query_values() {
831 let redacted = redact_url_for_display(
832 "https://user:secret@example.com/v1?api_key=sk-test&region=us&refresh-token=abc",
833 );
834
835 assert_eq!(
836 redacted,
837 "https://***:***@example.com/v1?api_key=***&region=us&refresh-token=***"
838 );
839 }
840
841 /// Build a DeepSeek config with an inline key/base URL plus the resolved
842 /// runtime route for it. `RouteResolver` (reached through
843 /// `resolve_runtime_route`) is the only producer of `ReadyRouteCandidate`,
844 /// so we mint candidates the same way the engine does at switch time.
845 fn deepseek_route_for_test(
846 base_url: &str,
847 model: &str,
848 ) -> (Config, crate::route_runtime::ResolvedRuntimeRoute) {
849 let config = {
850 let __cw_config_init_1_0 = Some("deepseek".to_string());
851 let __cw_config_init_1_1 = Some(model.to_string());
852 let mut __cw_config_init_1_value: Config = Config::default();
853 __cw_config_init_1_value.provider = __cw_config_init_1_0;
854 __cw_config_init_1_value.default_text_model = __cw_config_init_1_1;
855 __cw_config_init_1_value
856 }
857 .with_legacy_root(Some("ds-test".to_string()), Some(base_url.to_string()));
858 let route =
859 crate::route_runtime::resolve_runtime_route(&config, ProviderKind::Deepseek, Some(model))
860 .expect("deepseek route should resolve");
861 (config, route)
862 }
863
864 #[test]
865 fn from_candidate_scenario() {
866 // Scenario consolidation of: from_candidate_uses_candidate_base_url_and_wire_model, from_candidate_matches_new_when_config_agrees
867 // from from_candidate_uses_candidate_base_url_and_wire_model
868 {
869 let (_config, route) =
870 deepseek_route_for_test("https://route.example.com/v1", "deepseek-v4-pro");
871
872 let client = CodewhaleClient::from_candidate(&route.config, &route.candidate)
873 .expect("client should construct from candidate");
874
875 // The transport is bound to the candidate, not re-derived from Config.
876 assert_eq!(client.base_url, route.candidate.endpoint().base_url);
877 assert_eq!(
878 client.default_model,
879 route.candidate.wire_model_id().as_str()
880 );
881 }
882 // from from_candidate_matches_new_when_config_agrees
883 {
884 // For a normal route, the resolver writes the candidate's wire model and
885 // endpoint back into `route.config`, so constructing from the candidate
886 // must be byte-identical to constructing from that config. This pins the
887 // "no behavior change today" guarantee for Slice A.
888 let (_config, route) =
889 deepseek_route_for_test("https://api.deepseek.com/v1", "deepseek-v4-pro");
890
891 let from_new = CodewhaleClient::new(&route.config).expect("new client");
892 let from_candidate = CodewhaleClient::from_candidate(&route.config, &route.candidate)
893 .expect("candidate client");
894
895 assert_eq!(from_candidate.base_url, from_new.base_url);
896 assert_eq!(from_candidate.default_model, from_new.default_model);
897 assert_eq!(from_candidate.api_provider, from_new.api_provider);
898 }
899 }
900
901 fn route_cap_test_client(wire_format: WireFormat, limits: RouteLimits) -> CodewhaleClient {
902 let config = {
903 let __cw_config_init_2_0 = Some("custom".to_string());
904 let __cw_config_init_2_1 = Some("DeepSeek-V4-Flash".to_string());
905 let mut __cw_config_init_2_value: Config = Config::default();
906 __cw_config_init_2_value.provider = __cw_config_init_2_0;
907 __cw_config_init_2_value.default_text_model = __cw_config_init_2_1;
908 __cw_config_init_2_value
909 }
910 .with_legacy_root(
911 Some("route-cap-test".to_string()),
912 Some("https://route-cap.example/v1".to_string()),
913 );
914 let profile = (wire_format == WireFormat::Responses).then(crate::client::standard_responses_profile);
915 CodewhaleClient::from_parts(
916 "https://route-cap.example/v1".to_string(),
917 "DeepSeek-V4-Flash".to_string(),
918 wire_format,
919 Some(limits),
920 profile,
921 false,
922 &config,
923 )
924 .expect("route cap test client")
925 }
926
927 #[test]
928 fn tool_pairing_admission_uses_the_frozen_wire_protocol() {
929 for wire in [
930 WireFormat::ChatCompletions,
931 WireFormat::AnthropicMessages,
932 WireFormat::Responses,
933 ] {
934 let client = route_cap_test_client(wire, RouteLimits::default());
935 assert!(
936 client
937 .validate_tool_call_ids(["unique-a", "unique-b"])
938 .is_ok()
939 );
940 for ids in [["", "valid"], [" ", "valid"], ["same", "same"]] {
941 assert!(
942 client.validate_tool_call_ids(ids).is_err(),
943 "{wire:?}: {ids:?}"
944 );
945 }
946 let result = client.validate_tool_call_ids(["call|item-a", "call|item-b"]);
947 assert_eq!(result.is_err(), wire == WireFormat::Responses);
948 assert_eq!(
949 client.validate_tool_call_ids(["|item"]).is_err(),
950 wire == WireFormat::Responses
951 );
952 // Each response is independent: provider reuse on another round is valid.
953 assert!(client.validate_tool_call_ids(["reused"]).is_ok());
954 assert!(client.validate_tool_call_ids(["reused"]).is_ok());
955 }
956 }
957
958 #[test]
959 fn outbound_seam_excludes_host_execution_identity_for_every_dialect() {
960 let _lock = crate::test_support::lock_test_env();
961 const IMAGE: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
962 for (wire, google_route) in [
963 (WireFormat::ChatCompletions, false),
964 (WireFormat::ChatCompletions, true),
965 (WireFormat::Responses, false),
966 (WireFormat::AnthropicMessages, false),
967 ] {
968 let model = if google_route {
969 "gemini-2.5-flash"
970 } else {
971 "DeepSeek-V4-Flash"
972 };
973 let client = if google_route {
974 let base_url = "https://generativelanguage.googleapis.com/v1beta/openai";
975 let config = {
976 let __cw_config_init_3_0 = Some("custom".to_string());
977 let __cw_config_init_3_1 = Some(model.to_string());
978 let mut __cw_config_init_3_value: Config = Config::default();
979 __cw_config_init_3_value.provider = __cw_config_init_3_0;
980 __cw_config_init_3_value.default_text_model = __cw_config_init_3_1;
981 __cw_config_init_3_value
982 }
983 .with_legacy_root(Some("fixture".to_string()), Some(base_url.to_string()));
984 CodewhaleClient::from_parts(
985 base_url.to_string(),
986 model.to_string(),
987 wire,
988 Some(RouteLimits::default()),
989 None,
990 false,
991 &config,
992 )
993 .unwrap()
994 } else {
995 route_cap_test_client(wire, RouteLimits::default())
996 };
997 let provider_id = if wire == WireFormat::Responses {
998 "wire-call|provider-item"
999 } else {
1000 "wire-call"
1001 };
1002 let mut request =
1003 translation_message_request("inspect", model.to_string(), "English", 1024);
1004 request.messages.extend([
1005 Message {
1006 role: Role::Assistant,
1007 content: vec![ContentBlock::ToolUse {
1008 id: provider_id.to_string(),
1009 execution_id: Some("local-execution-sentinel".to_string()),
1010 name: "read".to_string(),
1011 input: json!({"path": "shot.png"}),
1012 caller: Some(codewhale_models::ToolCaller {
1013 caller_type: "code_execution".to_string(),
1014 tool_id: Some("parent-wire".to_string()),
1015 }),
1016 thought_signature: Some("provider-signature".to_string()),
1017 }],
1018 },
1019 Message {
1020 role: Role::User,
1021 content: vec![ContentBlock::ToolResult {
1022 tool_use_id: provider_id.to_string(),
1023 execution_id: Some("local-execution-sentinel".to_string()),
1024 content: "captured image".to_string(),
1025 is_error: Some(false),
1026 content_blocks: Some(vec![
1027 json!({"type": "image", "mime_type": "image/png", "data": IMAGE}),
1028 ]),
1029 }],
1030 },
1031 ]);
1032 let mut legacy = request.clone();
1033 for block in legacy
1034 .messages
1035 .iter_mut()
1036 .flat_map(|message| &mut message.content)
1037 {
1038 match block {
1039 ContentBlock::ToolUse { execution_id, .. }
1040 | ContentBlock::ToolResult { execution_id, .. } => *execution_id = None,
1041 _ => {}
1042 }
1043 }
1044 for streaming in [false, true] {
1045 let prepared = client
1046 .prepare_outbound_request(request.clone(), streaming)
1047 .unwrap();
1048 let without_local = client
1049 .prepare_outbound_request(legacy.clone(), streaming)
1050 .unwrap();
1051 assert_eq!(
1052 prepared.body, without_local.body,
1053 "{wire:?}, stream={streaming}"
1054 );
1055 let bytes = prepared.body.to_string();
1056 assert!(!bytes.contains("execution_id") && !bytes.contains("local-execution-sentinel"));
1057 assert!(bytes.contains("wire-call") && bytes.contains(IMAGE));
1058 if wire == WireFormat::ChatCompletions {
1059 assert!(bytes.contains("parent-wire"));
1060 assert_eq!(
1061 bytes.contains("provider-signature"),
1062 google_route,
1063 "Google signatures remain restricted to Google's route"
1064 );
1065 }
1066 if wire == WireFormat::Responses {
1067 let input = prepared.body["input"].as_array().unwrap();
1068 assert!(
1069 input
1070 .iter()
1071 .any(|item| item["type"] == "function_call"
1072 && item["call_id"] == "wire-call")
1073 );
1074 assert!(
1075 input
1076 .iter()
1077 .any(|item| item["type"] == "function_call_output"
1078 && item["call_id"] == "wire-call")
1079 );
1080 }
1081 }
1082 assert_eq!(
1083 request.messages[1].content[0].tool_call_key(),
1084 Some(codewhale_models::ToolCallKey::Execution(
1085 "local-execution-sentinel"
1086 ))
1087 );
1088 }
1089 }
1090
1091 #[test]
1092 fn unresolved_ollama_client_waits_for_catalog_but_probe_can_bootstrap() {
1093 use codewhale_config::catalog::CatalogOffering;
1094 let _env = crate::test_support::lock_test_env();
1095 let _live = crate::provider_lake::lock_live_snapshot();
1096 let home = tempfile::tempdir().unwrap();
1097 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
1098 crate::provider_catalog_live::reset_cache_for_test();
1099 crate::provider_lake::clear_live_snapshot();
1100 let endpoint = "http://127.0.0.1:11452/v1";
1101 let mut config = {
1102 let __cw_config_init_4_0 = Some("ollama".into());
1103 let mut __cw_config_init_4_value: Config = Default::default();
1104 __cw_config_init_4_value.provider = __cw_config_init_4_0;
1105 __cw_config_init_4_value
1106 };
1107 config
1108 .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Ollama))
1109 .unwrap()
1110 .base_url = Some(endpoint.into());
1111 assert!(
1112 CodewhaleClient::new(&config).is_err(),
1113 "unknown must not become a dispatch model"
1114 );
1115 let probe = CodewhaleClient::for_catalog_refresh(&config).expect("catalog bootstrap client");
1116 assert_eq!(probe.base_url, endpoint);
1117 let ticket = crate::provider_catalog_live::begin_refresh_for_identity(
1118 ProviderKind::Ollama,
1119 "ollama",
1120 endpoint,
1121 );
1122 let fingerprint = base_url_fingerprint(endpoint);
1123 let fetched_at = now_unix();
1124 crate::provider_catalog_live::record_success_if_current(
1125 &ticket,
1126 ProviderCatalogDelta {
1127 provider: "ollama".into(),
1128 base_url_fingerprint: fingerprint.clone(),
1129 fetched_at,
1130 offerings: ["zeta:tag", "alpha:tag"]
1131 .into_iter()
1132 .map(|id| CatalogOffering {
1133 provider: "ollama".into(),
1134 wire_model_id: id.into(),
1135 endpoint_key: "chat".into(),
1136 default_for_provider: id == "alpha:tag",
1137 source: CatalogSource::Live {
1138 base_url_fingerprint: fingerprint.clone(),
1139 fetched_at,
1140 },
1141 ..Default::default()
1142 })
1143 .collect(),
1144 },
1145 );
1146 let client = CodewhaleClient::new(&config).expect("fresh local model client");
1147 assert_eq!(client.default_model, "alpha:tag");
1148 let route =
1149 crate::route_runtime::resolve_runtime_route(&config, ProviderKind::Ollama, None).unwrap();
1150 assert_eq!(
1151 client.default_model,
1152 route.candidate.wire_model_id().as_str()
1153 );
1154 config
1155 .set_provider_model_override(
1156 &config.test_identity_for_kind(ProviderKind::Ollama),
1157 Some("saved:tag".into()),
1158 )
1159 .unwrap();
1160 assert_eq!(
1161 CodewhaleClient::new(&config).unwrap().default_model,
1162 "saved:tag"
1163 );
1164 crate::provider_catalog_live::reset_cache_for_test();
1165 crate::provider_lake::clear_live_snapshot();
1166 }
1167
1168 #[test]
1169 fn provider_regression_5820_ollama_config_reaches_the_wire_with_safe_output() {
1170 let _lock = crate::test_support::lock_test_env();
1171 let _canonical = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS");
1172 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS");
1173 let config = {
1174 let __cw_config_init_5_0 = Some("ollama".to_string());
1175 let __cw_config_init_5_1 = Some(ProvidersConfig {
1176 ollama: ProviderConfig {
1177 model: Some("qwen2.5:7b".to_string()),
1178 context_window: Some(32_768),
1179 base_url: Some("http://127.0.0.1:11434".to_string()),
1180 ..Default::default()
1181 },
1182 ..Default::default()
1183 });
1184 let mut __cw_config_init_5_value: Config = Default::default();
1185 __cw_config_init_5_value.provider = __cw_config_init_5_0;
1186 __cw_config_init_5_value.providers = __cw_config_init_5_1;
1187 __cw_config_init_5_value
1188 };
1189 let client = CodewhaleClient::new(&config).unwrap();
1190 assert_eq!(
1191 client
1192 .route_limits()
1193 .and_then(|limits| limits.context_tokens),
1194 Some(32_768)
1195 );
1196 assert_eq!(client.effective_max_output_tokens("qwen2.5:7b"), 8_192);
1197 let prepared = client
1198 .prepare_outbound_request(
1199 MessageRequest {
1200 model: "qwen2.5:7b".to_string(),
1201 messages: vec![Message {
1202 role: Role::User,
1203 content: vec![ContentBlock::Text {
1204 text: "hello".to_string(),
1205 cache_control: None,
1206 }],
1207 }],
1208 max_tokens: 64_000,
1209 system: None,
1210 tools: None,
1211 tool_choice: None,
1212 metadata: None,
1213 thinking: None,
1214 reasoning_effort: None,
1215 stream: Some(false),
1216 temperature: None,
1217 top_p: None,
1218 safety_check: None,
1219 title: None,
1220 },
1221 false,
1222 )
1223 .unwrap();
1224 assert_eq!(prepared.body["max_tokens"], 8_192);
1225 }
1226
1227 #[test]
1228 fn outbound_seam_clamps_every_dialect_to_the_exact_route_envelope() {
1229 let _lock = crate::test_support::lock_test_env();
1230 let _canonical = crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000");
1231 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS");
1232
1233 for (limits, expected) in [
1234 (
1235 RouteLimits {
1236 context_tokens: Some(327_680),
1237 ..RouteLimits::default()
1238 },
1239 325_632_u64,
1240 ),
1241 (
1242 RouteLimits {
1243 context_tokens: Some(327_680),
1244 output_tokens: Some(100_000),
1245 ..RouteLimits::default()
1246 },
1247 100_000,
1248 ),
1249 (
1250 RouteLimits {
1251 context_tokens: Some(327_680),
1252 output_tokens: Some(128),
1253 ..RouteLimits::default()
1254 },
1255 128,
1256 ),
1257 ] {
1258 for (wire_format, body_field) in [
1259 (WireFormat::ChatCompletions, "max_tokens"),
1260 (WireFormat::Responses, "max_output_tokens"),
1261 (WireFormat::AnthropicMessages, "max_tokens"),
1262 ] {
1263 let client = route_cap_test_client(wire_format, limits);
1264 let prepared = client
1265 .prepare_outbound_request(
1266 MessageRequest {
1267 model: "DeepSeek-V4-Flash".to_string(),
1268 messages: vec![Message {
1269 role: Role::User,
1270 content: vec![ContentBlock::Text {
1271 text: "route cap".to_string(),
1272 cache_control: None,
1273 }],
1274 }],
1275 max_tokens: 384_000,
1276 system: None,
1277 tools: None,
1278 tool_choice: None,
1279 metadata: None,
1280 thinking: None,
1281 reasoning_effort: Some("max".to_string()),
1282 stream: Some(false),
1283 temperature: None,
1284 top_p: None,
1285 safety_check: None,
1286 title: None,
1287 },
1288 false,
1289 )
1290 .expect("request prepares through preview/wire seam");
1291 assert_eq!(
1292 prepared.body[body_field].as_u64(),
1293 Some(expected),
1294 "wire={wire_format:?} limits={limits:?}"
1295 );
1296 }
1297 }
1298 }
1299
1300 #[test]
1301 fn same_protocol_model_switch_rebinds_exact_candidate_identity_and_limits() {
1302 let _lock = crate::test_support::lock_test_env();
1303 let _canonical = crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000");
1304 let config = {
1305 let __cw_config_init_6_0 = Some("openrouter".to_string());
1306 let __cw_config_init_6_1 = Some(ProvidersConfig {
1307 openrouter: ProviderConfig {
1308 api_key: Some("openrouter-route-cap-test".to_string()),
1309 base_url: Some("https://openrouter.ai/api/v1".to_string()),
1310 model: Some("deepseek/deepseek-v4-pro".to_string()),
1311 ..ProviderConfig::default()
1312 },
1313 ..ProvidersConfig::default()
1314 });
1315 let mut __cw_config_init_6_value: Config = Config::default();
1316 __cw_config_init_6_value.provider = __cw_config_init_6_0;
1317 __cw_config_init_6_value.providers = __cw_config_init_6_1;
1318 __cw_config_init_6_value
1319 };
1320 let client = CodewhaleClient::new(&config).expect("OpenRouter client resolves");
1321 assert_eq!(client.wire_format, WireFormat::ChatCompletions);
1322 assert!(client.route_limits.is_some());
1323
1324 let rebound = client
1325 .rebound_for_model_protocol(Some(&config), OPENROUTER_QWEN_3_6_FLASH_MODEL)
1326 .expect("same-protocol alternate route resolves")
1327 .expect("model/limit identity change requires a rebound");
1328 assert_eq!(rebound.wire_format, WireFormat::ChatCompletions);
1329 assert_eq!(rebound.default_model, OPENROUTER_QWEN_3_6_FLASH_MODEL);
1330 assert_ne!(rebound.route_limits, client.route_limits);
1331
1332 let pro_cap = client.effective_max_output_tokens("deepseek/deepseek-v4-pro");
1333 let alternate_cap = client.effective_max_output_tokens(OPENROUTER_QWEN_3_6_FLASH_MODEL);
1334 assert!(
1335 alternate_cap < pro_cap,
1336 "fixture must prove a smaller same-protocol alternate route: pro={pro_cap}, alternate={alternate_cap}"
1337 );
1338 assert_eq!(
1339 alternate_cap,
1340 rebound.effective_max_output_tokens(OPENROUTER_QWEN_3_6_FLASH_MODEL),
1341 "the original bound client and rebound client must resolve the same alternate envelope"
1342 );
1343 let prepared = client
1344 .prepare_outbound_request(
1345 MessageRequest {
1346 model: OPENROUTER_QWEN_3_6_FLASH_MODEL.to_string(),
1347 messages: vec![Message {
1348 role: Role::User,
1349 content: vec![ContentBlock::Text {
1350 text: "alternate route cap".to_string(),
1351 cache_control: None,
1352 }],
1353 }],
1354 max_tokens: 384_000,
1355 system: None,
1356 tools: None,
1357 tool_choice: None,
1358 metadata: None,
1359 thinking: None,
1360 reasoning_effort: Some("max".to_string()),
1361 stream: Some(false),
1362 temperature: None,
1363 top_p: None,
1364 safety_check: None,
1365 title: None,
1366 },
1367 false,
1368 )
1369 .expect("same-protocol alternate prepares");
1370 assert_eq!(prepared.body["max_tokens"], json!(alternate_cap));
1371 }
1372
1373 #[allow(clippy::await_holding_lock)]
1374 #[tokio::test(flavor = "current_thread")]
1375 async fn fim_non_message_request_is_clamped_to_bound_route() {
1376 let _lock = crate::test_support::lock_test_env();
1377 let _canonical = crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000");
1378 let server = MockServer::start().await;
1379 Mock::given(method("POST"))
1380 .and(path("/beta/completions"))
1381 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1382 "choices": [{"text": "middle"}]
1383 })))
1384 .expect(1)
1385 .mount(&server)
1386 .await;
1387 let base_url = format!("{}/v1", server.uri());
1388 let config = {
1389 let __cw_config_init_7_0 = Some("custom".to_string());
1390 let __cw_config_init_7_1 = Some("local-fim".to_string());
1391 let mut __cw_config_init_7_value: Config = Config::default();
1392 __cw_config_init_7_value.provider = __cw_config_init_7_0;
1393 __cw_config_init_7_value.default_text_model = __cw_config_init_7_1;
1394 __cw_config_init_7_value
1395 }
1396 .with_legacy_root(Some("fim-cap-test".to_string()), Some(base_url.clone()));
1397 let client = CodewhaleClient::from_parts(
1398 base_url,
1399 "local-fim".to_string(),
1400 WireFormat::ChatCompletions,
1401 Some(RouteLimits {
1402 context_tokens: Some(327_680),
1403 output_tokens: Some(128),
1404 ..RouteLimits::default()
1405 }),
1406 None,
1407 false,
1408 &config,
1409 )
1410 .expect("FIM route client");
1411
1412 assert_eq!(
1413 client
1414 .fim_completion("local-fim", "prefix", "suffix", 4_096)
1415 .await
1416 .expect("FIM response"),
1417 "middle"
1418 );
1419 let requests = server
1420 .received_requests()
1421 .await
1422 .expect("recorded FIM request");
1423 let body: Value = serde_json::from_slice(&requests[0].body).expect("FIM JSON");
1424 assert_eq!(body["max_tokens"], json!(128));
1425 }
1426
1427 #[test]
1428 fn official_deepseek_flash_binds_responses_request_and_endpoint() {
1429 let (_config, route) =
1430 deepseek_route_for_test("https://api.deepseek.com/beta", "deepseek-v4-flash");
1431 assert_eq!(route.candidate.protocol(), WireFormat::Responses);
1432
1433 let client = CodewhaleClient::new(&route.config).expect("Flash client resolves");
1434 assert_eq!(client.wire_format, WireFormat::Responses);
1435
1436 let prepared = client
1437 .prepare_outbound_request(
1438 MessageRequest {
1439 model: "deepseek-v4-flash".to_string(),
1440 messages: vec![Message {
1441 role: Role::User,
1442 content: vec![ContentBlock::Text {
1443 text: "hello".to_string(),
1444 cache_control: None,
1445 }],
1446 }],
1447 max_tokens: 64,
1448 system: None,
1449 tools: None,
1450 tool_choice: None,
1451 metadata: None,
1452 thinking: None,
1453 reasoning_effort: Some("max".to_string()),
1454 stream: Some(true),
1455 temperature: None,
1456 top_p: None,
1457 safety_check: None,
1458 title: None,
1459 },
1460 true,
1461 )
1462 .expect("Flash Responses request prepares");
1463
1464 assert_eq!(prepared.dialect, WireDialect::OpenAiResponses);
1465 assert_eq!(prepared.endpoint.url, "https://api.deepseek.com/responses");
1466 assert_eq!(prepared.body["model"], "deepseek-v4-flash");
1467 assert_eq!(prepared.body["reasoning"]["effort"], "max");
1468 }
1469
1470 #[test]
1471 fn uncatalogued_deepseek_preview_binds_chat_request_without_model_fallback() {
1472 let model = "deepseek-v4.1-flash-expires-on-0910";
1473 let (_config, route) = deepseek_route_for_test("https://api.deepseek.com", model);
1474 assert_eq!(route.candidate.protocol(), WireFormat::ChatCompletions);
1475 assert_eq!(route.candidate.wire_model_id().as_str(), model);
1476 assert!(route.candidate.canonical_model().is_none());
1477
1478 for client in [
1479 CodewhaleClient::new(&route.config).expect("preview client resolves"),
1480 CodewhaleClient::from_candidate(&route.config, &route.candidate)
1481 .expect("preview client binds the admitted candidate"),
1482 ] {
1483 assert_eq!(client.wire_format, WireFormat::ChatCompletions);
1484 assert_eq!(client.default_model, model);
1485 let prepared = client
1486 .prepare_outbound_request(
1487 MessageRequest {
1488 model: model.to_string(),
1489 messages: vec![Message {
1490 role: Role::User,
1491 content: vec![ContentBlock::Text {
1492 text: "hello".to_string(),
1493 cache_control: None,
1494 }],
1495 }],
1496 max_tokens: 64,
1497 system: None,
1498 tools: None,
1499 tool_choice: None,
1500 metadata: None,
1501 thinking: None,
1502 reasoning_effort: None,
1503 stream: Some(true),
1504 temperature: None,
1505 top_p: None,
1506 safety_check: None,
1507 title: None,
1508 },
1509 true,
1510 )
1511 .expect("preview Chat request prepares");
1512 assert_eq!(prepared.dialect, WireDialect::ChatCompletions);
1513 assert_eq!(
1514 prepared.endpoint.url,
1515 "https://api.deepseek.com/v1/chat/completions"
1516 );
1517 assert_eq!(prepared.body["model"], model);
1518 assert_eq!(prepared.body["messages"][0]["content"], "hello");
1519 }
1520 }
1521
1522 #[test]
1523 fn exact_catalog_deepseek_preview_binding_survives_prepare_and_same_model_rebind() {
1524 use codewhale_config::route::{
1525 PricingSku, ProviderId, RouteCapabilities, WireModelId, offering::ProviderModelOffering,
1526 };
1527
1528 let model = "deepseek-v4.1-flash-expires-on-0910";
1529 // Synthetic catalog evidence: the offline catalog has no such row.
1530 // This fixture does not assert that the real preview supports Responses.
1531 let resolver = RouteResolver::from_offerings(vec![ProviderModelOffering {
1532 provider: ProviderId::from("deepseek"),
1533 canonical_model: None,
1534 wire_model_id: WireModelId::from(model),
1535 endpoint_key: "responses".to_string(),
1536 default_for_provider: false,
1537 limits: RouteLimits {
1538 output_tokens: Some(777),
1539 ..Default::default()
1540 },
1541 capabilities: RouteCapabilities::default(),
1542 pricing: PricingSku::UnknownOrStale,
1543 }]);
1544 let candidate = resolver
1545 .resolve(&RouteRequest {
1546 explicit_provider: Some(codewhale_config::ProviderKind::Deepseek),
1547 model_selector: Some(LogicalModelRef::from(model)),
1548 base_url_override: Some("https://api.deepseek.com".to_string()),
1549 ..Default::default()
1550 })
1551 .expect("exact synthetic catalog offering resolves");
1552 assert_eq!(candidate.protocol(), WireFormat::Responses);
1553 assert_eq!(candidate.wire_model_id().as_str(), model);
1554
1555 let config = {
1556 let __cw_config_init_8_0 = Some("deepseek".to_string());
1557 let __cw_config_init_8_1 = Some(model.to_string());
1558 let mut __cw_config_init_8_value: Config = Default::default();
1559 __cw_config_init_8_value.provider = __cw_config_init_8_0;
1560 __cw_config_init_8_value.default_text_model = __cw_config_init_8_1;
1561 __cw_config_init_8_value
1562 }
1563 .with_legacy_root(
1564 Some("ds-test".to_string()),
1565 Some("https://api.deepseek.com".to_string()),
1566 );
1567 let client = CodewhaleClient::from_candidate(&config, &candidate)
1568 .expect("client binds exact synthetic catalog offering");
1569 assert!(
1570 client
1571 .rebound_for_model_protocol(None, model)
1572 .expect("the same admitted model needs no offline lookup")
1573 .is_none()
1574 );
1575 let prepared = client
1576 .prepare_outbound_request(
1577 translation_message_request("hello", model.to_string(), "English", 4_096),
1578 true,
1579 )
1580 .expect("same-model request preserves the exact catalog binding");
1581 assert_eq!(prepared.dialect, WireDialect::OpenAiResponses);
1582 assert_eq!(prepared.endpoint.url, "https://api.deepseek.com/responses");
1583 assert_eq!(prepared.body["model"], model);
1584 assert_eq!(prepared.body["max_output_tokens"], 777);
1585
1586 let other_model = "deepseek-v4-pro";
1587 assert!(
1588 client
1589 .prepare_outbound_request(
1590 translation_message_request("hello", other_model.to_string(), "English", 4_096,),
1591 true,
1592 )
1593 .is_err(),
1594 "a different model must still obey the protocol switch guard"
1595 );
1596 let rebound = client
1597 .rebound_for_model_protocol(Some(&config), other_model)
1598 .expect("different model resolves independently")
1599 .expect("Pro requires a Chat client");
1600 let prepared = rebound
1601 .prepare_outbound_request(
1602 translation_message_request("hello", other_model.to_string(), "English", 4_096),
1603 true,
1604 )
1605 .expect("rebound Pro prepares Chat");
1606 assert_eq!(prepared.dialect, WireDialect::ChatCompletions);
1607 assert_eq!(
1608 prepared.endpoint.url,
1609 "https://api.deepseek.com/v1/chat/completions"
1610 );
1611 assert_eq!(prepared.body["model"], other_model);
1612 }
1613
1614 #[test]
1615 fn rebinding_a_chat_bound_client_for_flash_switches_to_responses() {
1616 // #5042: fleet dispatch binds the child client before the profile
1617 // model is resolved; a chat-bound DeepSeek client asked to run flash
1618 // must be rebuilt on the Responses protocol by the central resolver
1619 // instead of failing deterministically at first send.
1620 let (_config, route) =
1621 deepseek_route_for_test("https://api.deepseek.com/beta", "deepseek-v4-pro");
1622 let client = CodewhaleClient::new(&route.config).expect("pro client resolves");
1623 assert_eq!(client.wire_format, WireFormat::ChatCompletions);
1624
1625 let rebound = client
1626 .rebound_for_model_protocol(Some(&route.config), "deepseek-v4-flash")
1627 .expect("flash rebind resolves")
1628 .expect("flash requires a different protocol");
1629 assert_eq!(rebound.wire_format, WireFormat::Responses);
1630 assert_eq!(rebound.default_model, "deepseek-v4-flash");
1631
1632 assert!(
1633 client
1634 .rebound_for_model_protocol(Some(&route.config), "deepseek-v4-pro")
1635 .expect("pro rebind resolves")
1636 .is_none(),
1637 "a matching protocol must not rebuild the client"
1638 );
1639 }
1640
1640 lines RUST