返回 CodeWhale
stream_entry.rs
根目录 / crates / engine / src / client / stream_entry.rs
1 //! Shared stream entry seam for Chat Completions / Anthropic Messages / Responses.
2 //!
3 //! Scoped consolidation for v0.9.1: wire-protocol adapters stay at the edge
4 //! (`chat.rs`, `anthropic.rs`, `responses.rs`); this module owns the common
5 //! open path, HTTP/1.1 fallback policy, and idle-timeout envelope so providers
6 //! do not re-implement transport differently.
7 //!
8 //! Full piagent-style provider collapse is deferred — see
9 //! `docs/notes/post-0.9.1-thin-tui-and-stream.md`.
10
11 use std::future::Future;
12 use std::time::Duration;
13
14 use anyhow::Result;
15 use reqwest::Client;
16
17 use crate::llm_client::LlmError;
18
19 /// Default wait for the first body byte after the response headers (#6184).
20 /// Well under the 900s default inter-chunk idle budget: a provider that has
21 /// answered the headers and then sends nothing at all — not even an SSE
22 /// keep-alive — for five minutes has stopped, it is not thinking. Applies only
23 /// while the idle budget is the default; an explicitly configured
24 /// `stream_chunk_timeout_secs` is respected for the first byte too, so a user
25 /// who raised it for long silent reasoning keeps that allowance.
26 pub const DEFAULT_STREAM_FIRST_BYTE_TIMEOUT: Duration = Duration::from_secs(300);
27
28 /// Resolve the first-body-byte bound for a stream whose inter-chunk idle
29 /// budget is `idle`. `CODEWHALE_STREAM_FIRST_BYTE_TIMEOUT_SECS` overrides it
30 /// (clamped to 5..=3600).
31 #[must_use]
32 pub fn first_byte_timeout(idle: Duration) -> Duration {
33 first_byte_timeout_from_env(
34 idle,
35 std::env::var("CODEWHALE_STREAM_FIRST_BYTE_TIMEOUT_SECS")
36 .ok()
37 .as_deref(),
38 )
39 }
40
41 pub fn first_byte_timeout_from_env(idle: Duration, value: Option<&str>) -> Duration {
42 if let Some(secs) = value.and_then(|v| v.trim().parse::<u64>().ok()) {
43 return Duration::from_secs(secs.clamp(5, 3600));
44 }
45 let default_idle =
46 Duration::from_secs(codewhale_runtime::config::DEFAULT_STREAM_CHUNK_TIMEOUT_SECS);
47 if idle == default_idle {
48 DEFAULT_STREAM_FIRST_BYTE_TIMEOUT.min(idle)
49 } else {
50 idle
51 }
52 }
53
54 /// Bound for the next body read: the first-byte bound until any byte arrived,
55 /// the inter-chunk idle budget after.
56 #[must_use]
57 pub fn next_chunk_timeout(idle: Duration, first_byte: Duration, bytes_received: usize) -> Duration {
58 if bytes_received == 0 {
59 first_byte
60 } else {
61 idle
62 }
63 }
64
65 /// Message and stall record for a body read that timed out. A first-byte
66 /// timeout is a stall worth a `crashes/` record (#6184); a later idle timeout
67 /// is reported the same way so every silent provider wait leaves a trace.
68 pub fn body_timeout_message(
69 timeout: Duration,
70 bytes_received: usize,
71 stream_age: Duration,
72 since_last_chunk: Duration,
73 provider: &str,
74 ) -> String {
75 let message = if bytes_received == 0 {
76 format!(
77 "SSE stream first-byte timeout after {}s — the provider sent headers but no data \
78 (stream_age_ms={})",
79 timeout.as_secs(),
80 stream_age.as_millis(),
81 )
82 } else {
83 idle_timeout_message(timeout, bytes_received, stream_age, since_last_chunk)
84 };
85 let phase = if bytes_received == 0 {
86 "waiting for the provider's first byte"
87 } else {
88 "waiting for the next stream chunk"
89 };
90 codewhale_runtime::stall_report::report_stall(&codewhale_runtime::stall_report::StallReport {
91 source: "client",
92 phase: format!("while {phase}"),
93 detail: Some(provider.to_string()),
94 turn_id: None,
95 provider_request: None,
96 since_progress: since_last_chunk,
97 bound: Some(timeout),
98 });
99 message
100 }
101
102 /// How the shared stream open path should pin HTTP version.
103 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
104 pub enum StreamHttpPolicy {
105 /// Prefer the dual client (H2 primary, H1 twin for fallback).
106 DualWithH1Fallback,
107 /// Force HTTP/1.1 only (config/env pin or prior H2 stall).
108 Http1Only,
109 }
110
111 /// Inputs shared by every streaming provider adapter at open time.
112 #[derive(Debug, Clone)]
113 pub struct StreamOpenRequest {
114 pub policy: StreamHttpPolicy,
115 pub open_timeout: Duration,
116 pub idle_timeout: Duration,
117 }
118
119 impl StreamOpenRequest {
120 /// `force_http1` is the client's resolved pin (`Config::force_http1`:
121 /// `[stream].force_http1`, legacy `[tui]`, or `CODEWHALE_FORCE_HTTP1`), never re-read here.
122 #[must_use]
123 pub fn new(force_http1: bool, open_timeout: Duration, idle_timeout: Duration) -> Self {
124 Self {
125 policy: if force_http1 {
126 StreamHttpPolicy::Http1Only
127 } else {
128 StreamHttpPolicy::DualWithH1Fallback
129 },
130 open_timeout,
131 idle_timeout,
132 }
133 }
134
135 /// After an H2 stall, retry on the HTTP/1.1 twin.
136 #[must_use]
137 pub fn with_h1_only(mut self) -> Self {
138 self.policy = StreamHttpPolicy::Http1Only;
139 self
140 }
141 }
142
143 impl super::CodewhaleClient {
144 /// The open request every streaming adapter starts from, carrying this
145 /// client's resolved HTTP/1.1 pin and timeouts (#6700).
146 #[must_use]
147 pub(super) fn stream_open_request(&self) -> StreamOpenRequest {
148 StreamOpenRequest::new(
149 self.force_http1,
150 self.stream_open_timeout,
151 self.stream_idle_timeout,
152 )
153 }
154 }
155
156 /// Select the HTTP client for a stream open attempt.
157 #[must_use]
158 pub fn client_for_policy<'a>(
159 primary: &'a Client,
160 http1_fallback: &'a Client,
161 policy: StreamHttpPolicy,
162 ) -> &'a Client {
163 match policy {
164 StreamHttpPolicy::DualWithH1Fallback => primary,
165 StreamHttpPolicy::Http1Only => http1_fallback,
166 }
167 }
168
169 /// Whether a transport error should trigger H1 fallback retry.
170 #[must_use]
171 pub fn should_retry_with_h1(policy: StreamHttpPolicy, err_text: &str) -> bool {
172 if policy != StreamHttpPolicy::DualWithH1Fallback {
173 return false;
174 }
175 let lower = err_text.to_ascii_lowercase();
176 lower.contains("http2")
177 || lower.contains("h2 ")
178 || lower.contains("stream closed")
179 || lower.contains("connection reset")
180 || lower.contains("protocol error")
181 || lower.contains("frame size")
182 }
183
184 #[must_use]
185 fn should_retry_error_with_h1(policy: StreamHttpPolicy, err: &anyhow::Error) -> bool {
186 policy == StreamHttpPolicy::DualWithH1Fallback && is_stream_open_transport_failure(err)
187 }
188
189 #[must_use]
190 pub fn is_stream_open_transport_failure(err: &anyhow::Error) -> bool {
191 err.chain()
192 .find_map(|cause| {
193 if let Some(error) = cause.downcast_ref::<LlmError>() {
194 return Some(matches!(
195 error,
196 LlmError::ConnectError {
197 transient: true,
198 ..
199 }
200 ));
201 }
202 cause.downcast_ref::<reqwest::Error>().map(|error| {
203 matches!(
204 LlmError::from_reqwest(error),
205 LlmError::ConnectError {
206 transient: true,
207 ..
208 }
209 )
210 })
211 })
212 .unwrap_or(false)
213 }
214
215 fn h1_fallback_error(err: anyhow::Error) -> anyhow::Error {
216 if err.downcast_ref::<LlmError>().is_some() {
217 return err;
218 }
219 if let Some(error) = err
220 .chain()
221 .find_map(|cause| cause.downcast_ref::<reqwest::Error>())
222 {
223 let mut classified = LlmError::from_reqwest(error);
224 if let Some(unreachable) = connect_failure_summary(&err)
225 && let LlmError::ConnectError { message, .. } = &mut classified
226 {
227 *message = format!("{unreachable}: {message}");
228 }
229 if has_tls_cause(&err)
230 && let LlmError::ConnectError { message, .. } = &mut classified
231 {
232 message.push_str(" On Windows or proxy networks, try CODEWHALE_FORCE_HTTP1=1 after checking the TLS configuration.");
233 }
234 return anyhow::Error::new(classified);
235 }
236 anyhow::Error::new(LlmError::NetworkError(format!(
237 "SSE stream request failed: {err:#}"
238 )))
239 }
240
241 /// `Cannot reach host:port (<why>)` for a failure to open the connection.
242 /// reqwest also reports TLS handshake and certificate failures as connect
243 /// errors; those return `None` so they keep the HTTP/1.1 and proxy hint.
244 fn connect_failure_summary(err: &anyhow::Error) -> Option<String> {
245 let reqwest_error = err
246 .chain()
247 .find_map(|cause| cause.downcast_ref::<reqwest::Error>())
248 .filter(|error| error.is_connect())?;
249 // Classify on the underlying causes only: reqwest's own message embeds
250 // the request URL, whose host or path could contain "dns" or "tls".
251 let mut causes = String::new();
252 let mut source = std::error::Error::source(reqwest_error);
253 while let Some(cause) = source {
254 causes.push_str(&cause.to_string().to_ascii_lowercase());
255 causes.push('\n');
256 source = cause.source();
257 }
258 if has_tls_cause(err) || is_protocol_or_tls_failure(&causes) {
259 return None;
260 }
261 let target = reqwest_error
262 .url()
263 .and_then(|url| {
264 Some(format!(
265 "{}:{}",
266 url.host_str()?,
267 url.port_or_known_default()?
268 ))
269 })
270 .unwrap_or_else(|| "the provider host".to_string());
271 let why = if causes.contains("refused") {
272 "connection refused"
273 } else if causes.contains("dns") || causes.contains("lookup") {
274 "DNS lookup failed"
275 } else {
276 "connection failed"
277 };
278 // With a proxy configured, the host that refused may be the proxy.
279 let via_proxy = [
280 "HTTPS_PROXY",
281 "https_proxy",
282 "ALL_PROXY",
283 "all_proxy",
284 "HTTP_PROXY",
285 "http_proxy",
286 ]
287 .iter()
288 .any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()));
289 Some(if via_proxy {
290 format!("Cannot reach {target} or the configured proxy ({why})")
291 } else {
292 format!("Cannot reach {target} ({why})")
293 })
294 }
295
296 fn has_tls_cause(err: &anyhow::Error) -> bool {
297 crate::llm_client::has_tls_cause(err.as_ref())
298 }
299
300 fn is_protocol_or_tls_failure(detail: &str) -> bool {
301 let lower = detail.to_ascii_lowercase();
302 should_retry_with_h1(StreamHttpPolicy::DualWithH1Fallback, &lower)
303 || ["tls", "ssl", "certificate", "handshake", "alpn"]
304 .iter()
305 .any(|needle| lower.contains(needle))
306 }
307
308 #[must_use]
309 pub fn stream_open_header_timeout(err: &anyhow::Error) -> Option<Duration> {
310 err.chain()
311 .find_map(|cause| match cause.downcast_ref::<LlmError>() {
312 Some(LlmError::HeaderTimeout { waited, .. }) => Some(*waited),
313 _ => None,
314 })
315 }
316
317 pub async fn open_sse_response<F, Fut>(
318 open_req: &StreamOpenRequest,
319 attempt: F,
320 ) -> Result<reqwest::Response>
321 where
322 F: Fn(StreamHttpPolicy) -> Fut,
323 Fut: Future<Output = Result<reqwest::Response>>,
324 {
325 match crate::llm_client::rate_limit::active_timeout(
326 open_req.open_timeout,
327 attempt(open_req.policy),
328 )
329 .await
330 {
331 Ok(Ok(response)) => return Ok(response),
332 Ok(Err(err)) => {
333 if !should_retry_error_with_h1(open_req.policy, &err) {
334 return Err(h1_fallback_error(err));
335 }
336 }
337 Err(_) => {
338 return Err(anyhow::Error::new(LlmError::HeaderTimeout {
339 waited: open_req.open_timeout,
340 http1: false,
341 retried: 0,
342 }));
343 }
344 }
345 let h1_req = open_req.clone().with_h1_only();
346 crate::llm_client::observe_transport_attempt();
347 match crate::llm_client::rate_limit::active_timeout(h1_req.open_timeout, attempt(h1_req.policy))
348 .await
349 {
350 Ok(Ok(response)) => Ok(response),
351 Ok(Err(err)) => Err(h1_fallback_error(err)),
352 Err(_) => Err(anyhow::Error::new(LlmError::HeaderTimeout {
353 waited: h1_req.open_timeout,
354 http1: true,
355 retried: 0,
356 })),
357 }
358 }
359
360 /// Format a stable idle-timeout message shared across adapters.
361 #[must_use]
362 pub fn idle_timeout_message(
363 idle: Duration,
364 bytes_received: usize,
365 stream_age: Duration,
366 since_last_chunk: Duration,
367 ) -> String {
368 format!(
369 "SSE stream idle timeout after {}s — no data received \
370 (bytes_received={}, stream_age_ms={}, ms_since_last_chunk={})",
371 idle.as_secs(),
372 bytes_received,
373 stream_age.as_millis(),
374 since_last_chunk.as_millis(),
375 )
376 }
377
378 #[cfg(test)]
379 mod tests {
380 use std::sync::Arc;
381 use std::sync::atomic::{AtomicUsize, Ordering};
382
383 use wiremock::matchers::method;
384 use wiremock::{Mock, MockServer, ResponseTemplate};
385
386 use super::*;
387 use codewhale_config::{
388 MAX_STREAM_OPEN_TIMEOUT_SECS, MIN_STREAM_OPEN_TIMEOUT_SECS, resolve_stream_open_timeout,
389 stream_open_timeout_from_env,
390 };
391
392 fn open_req(policy: StreamHttpPolicy, open_timeout: Duration) -> StreamOpenRequest {
393 StreamOpenRequest {
394 policy,
395 open_timeout,
396 idle_timeout: Duration::from_secs(30),
397 }
398 }
399
400 async fn ok_server() -> MockServer {
401 let server = MockServer::start().await;
402 Mock::given(method("POST"))
403 .respond_with(ResponseTemplate::new(200))
404 .mount(&server)
405 .await;
406 server
407 }
408
409 #[test]
410 fn configured_http1_pin_controls_open_attempts_and_survives_clone() {
411 let _env = crate::test_support::lock_test_env();
412 let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_FORCE_HTTP1");
413 let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_FORCE_HTTP1");
414 let runtime = tokio::runtime::Builder::new_current_thread()
415 .enable_all()
416 .build()
417 .unwrap();
418 for pinned in [true, false] {
419 let config: codewhale_runtime::config::Config = toml::from_str(&format!(
420 r#"
421 provider = "zai"
422 [providers.zai]
423 api_key = "stream-open-fixture-key"
424 [tui]
425 force_http1 = {pinned}
426 "#
427 ))
428 .unwrap();
429 let client = super::super::CodewhaleClient::new(&config).unwrap();
430 for client in [client.clone(), client] {
431 let attempts = AtomicUsize::new(0);
432 let result =
433 runtime.block_on(open_sse_response(&client.stream_open_request(), |policy| {
434 let attempt = attempts.fetch_add(1, Ordering::SeqCst);
435 async move {
436 if attempt == 0 {
437 // Only a genuinely dual-protocol request may
438 // retry this failure on its HTTP/1.1 twin.
439 return Err(anyhow::Error::new(LlmError::ConnectError {
440 message: "connection refused before dispatch".into(),
441 transient: true,
442 timed_out: false,
443 }));
444 }
445 assert_eq!(policy, StreamHttpPolicy::Http1Only);
446 Ok(reqwest::Response::from(
447 axum::http::Response::builder().status(200).body("")?,
448 ))
449 }
450 }));
451 if pinned {
452 assert!(result.is_err(), "config pin must forbid a second send");
453 assert_eq!(attempts.load(Ordering::SeqCst), 1);
454 } else {
455 assert_eq!(result.unwrap().status(), 200);
456 assert_eq!(attempts.load(Ordering::SeqCst), 2);
457 }
458 }
459 }
460 }
461
462 #[tokio::test]
463 async fn open_returns_first_attempt_response_on_dual_policy() {
464 let server = ok_server().await;
465 let client = codewhale_release::tls::reqwest_client();
466 let attempts = Arc::new(AtomicUsize::new(0));
467 let response = open_sse_response(
468 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
469 |policy| {
470 assert_eq!(policy, StreamHttpPolicy::DualWithH1Fallback);
471 let attempts = Arc::clone(&attempts);
472 let client = client.clone();
473 let url = server.uri();
474 async move {
475 attempts.fetch_add(1, Ordering::SeqCst);
476 Ok(client.post(url).send().await?)
477 }
478 },
479 )
480 .await
481 .expect("first attempt succeeds");
482 assert_eq!(response.status(), 200);
483 assert_eq!(attempts.load(Ordering::SeqCst), 1);
484 }
485
486 #[tokio::test]
487 async fn header_stall_on_dual_policy_retries_exactly_once_on_h1() {
488 let attempts = Arc::new(AtomicUsize::new(0));
489 let error = open_sse_response(
490 &open_req(
491 StreamHttpPolicy::DualWithH1Fallback,
492 Duration::from_millis(150),
493 ),
494 |policy| {
495 let attempts = Arc::clone(&attempts);
496 async move {
497 let attempt = attempts.fetch_add(1, Ordering::SeqCst);
498 if attempt == 0 {
499 // First attempt stalls before response headers.
500 assert_eq!(policy, StreamHttpPolicy::DualWithH1Fallback);
501 std::future::pending::<()>().await;
502 }
503 assert_eq!(policy, StreamHttpPolicy::Http1Only);
504 // This test exercises retry policy, not loopback scheduling.
505 // A ready response keeps the 150 ms first-attempt timeout
506 // from also imposing a network deadline under suite load.
507 Ok(reqwest::Response::from(
508 axum::http::Response::builder().status(200).body("")?,
509 ))
510 }
511 },
512 )
513 .await
514 .expect_err("header stall must retain an unknown outcome without replay");
515 assert!(error.to_string().contains("outcome unknown"));
516 assert_eq!(
517 attempts.load(Ordering::SeqCst),
518 1,
519 "an unknown header stall must not fall back"
520 );
521 }
522
523 #[tokio::test]
524 async fn transport_error_before_headers_retries_exactly_once_on_h1() {
525 let server = ok_server().await;
526 let client = codewhale_release::tls::reqwest_client();
527 let attempts = Arc::new(AtomicUsize::new(0));
528 let response = open_sse_response(
529 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
530 |policy| {
531 let attempts = Arc::clone(&attempts);
532 let client = client.clone();
533 let url = server.uri();
534 async move {
535 let attempt = attempts.fetch_add(1, Ordering::SeqCst);
536 if attempt == 0 {
537 assert_eq!(policy, StreamHttpPolicy::DualWithH1Fallback);
538 return Err(anyhow::Error::new(LlmError::ConnectError {
539 message: "connection refused before dispatch".into(),
540 transient: true,
541 timed_out: false,
542 })
543 .context("Chat API request failed"));
544 }
545 assert_eq!(policy, StreamHttpPolicy::Http1Only);
546 Ok(client.post(url).send().await?)
547 }
548 },
549 )
550 .await
551 .expect("H1 fallback retry succeeds after a transport error");
552 assert_eq!(response.status(), 200);
553 assert_eq!(
554 attempts.load(Ordering::SeqCst),
555 2,
556 "exactly one fallback retry"
557 );
558 }
559
560 #[tokio::test]
561 async fn header_stall_when_h1_pinned_never_retries_and_reports_timeout_text() {
562 let attempts = Arc::new(AtomicUsize::new(0));
563 let err = open_sse_response(
564 &open_req(StreamHttpPolicy::Http1Only, Duration::from_millis(100)),
565 |_| {
566 let attempts = Arc::clone(&attempts);
567 async move {
568 attempts.fetch_add(1, Ordering::SeqCst);
569 std::future::pending::<()>().await;
570 unreachable!("stalled attempt never resolves")
571 }
572 },
573 )
574 .await
575 .expect_err("H1-pinned stall fails without retry");
576 assert_eq!(attempts.load(Ordering::SeqCst), 1, "no retry when pinned");
577 let text = err.to_string();
578 assert!(text.contains("did not receive response headers"), "{text}");
579 let classified = err
580 .downcast_ref::<crate::llm_client::LlmError>()
581 .expect("header stall must be a typed LlmError");
582 assert!(
583 !classified.is_retryable(),
584 "the HTTP retry loop must not replay a header stall: {classified:?}"
585 );
586 assert_eq!(
587 stream_open_header_timeout(&err.context("adapter context")),
588 Some(Duration::from_millis(100)),
589 "the turn loop recognizes the header timeout by type"
590 );
591 assert!(text.contains("outcome unknown"), "{text}");
592 assert!(
593 text.contains("prefilling a large or high-thinking request or loading a cold model"),
594 "{text}"
595 );
596 assert!(
597 text.contains("codewhale config set stream.open_timeout_secs 300` (up to 600)"),
598 "{text}"
599 );
600 assert!(
601 !text.contains("HTTP/2 and HTTP/1.1"),
602 "single-protocol stall must not claim a dual-protocol attempt: {text}"
603 );
604 }
605
606 #[tokio::test]
607 async fn transport_error_when_h1_pinned_never_retries() {
608 let attempts = Arc::new(AtomicUsize::new(0));
609 let err = open_sse_response(
610 &open_req(StreamHttpPolicy::Http1Only, Duration::from_secs(5)),
611 |_| {
612 let attempts = Arc::clone(&attempts);
613 async move {
614 attempts.fetch_add(1, Ordering::SeqCst);
615 Err(anyhow::Error::new(LlmError::NetworkError(
616 "connection reset before response headers".to_string(),
617 )))
618 }
619 },
620 )
621 .await
622 .expect_err("an H1-pinned transport error must not retry");
623 assert_eq!(attempts.load(Ordering::SeqCst), 1, "no retry when pinned");
624 assert!(err.to_string().contains("connection reset"), "{err}");
625 }
626
627 #[tokio::test]
628 async fn refused_connection_names_the_host_and_skips_the_http1_hint() {
629 let port = {
630 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
631 listener.local_addr().expect("addr").port()
632 };
633 let client = codewhale_release::tls::reqwest_client();
634 let url = format!("http://127.0.0.1:{port}/v1/chat");
635 let err = open_sse_response(
636 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
637 |_| {
638 let request = client.post(&url);
639 async move { Ok::<_, anyhow::Error>(request.send().await?) }
640 },
641 )
642 .await
643 .expect_err("nothing listens on the port");
644 let text = err.to_string();
645 assert!(
646 text.contains(&format!("Cannot reach 127.0.0.1:{port}"))
647 && text.contains("(connection refused)"),
648 "{text}"
649 );
650 assert!(!text.contains("CODEWHALE_FORCE_HTTP1"), "{text}");
651 assert!(
652 err.downcast_ref::<LlmError>()
653 .is_some_and(LlmError::is_retryable),
654 "{err:#}"
655 );
656 }
657
658 #[tokio::test]
659 async fn tls_failure_during_connect_keeps_the_http1_hint() {
660 // A plain-TCP peer on an https URL fails the TLS handshake, which
661 // reqwest reports as a connect error; it must not read as
662 // "Cannot reach" and must keep the FORCE_HTTP1/proxy hint.
663 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
664 .await
665 .expect("bind");
666 let port = listener.local_addr().expect("addr").port();
667 let server = tokio::spawn(async move {
668 use tokio::io::AsyncWriteExt;
669 while let Ok((mut socket, _)) = listener.accept().await {
670 let _ = socket.write_all(b"HTTP/1.1 400 Not TLS\r\n\r\n").await;
671 // Keep reading until the client closes. Dropping a socket with
672 // unread ClientHello bytes can send a TCP reset on Windows,
673 // hiding the TLS protocol error this fixture is meant to test.
674 let _ = tokio::io::copy(&mut socket, &mut tokio::io::sink()).await;
675 }
676 });
677 codewhale_release::tls::ensure_rustls_crypto_provider();
678 let client = codewhale_release::tls::reqwest_client();
679 let url = format!("https://127.0.0.1:{port}/v1/chat");
680 let err = open_sse_response(
681 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
682 |_| {
683 let request = client.post(&url);
684 async move { Ok::<_, anyhow::Error>(request.send().await?) }
685 },
686 )
687 .await
688 .expect_err("the peer does not speak TLS");
689 server.abort();
690 let text = err.to_string();
691 assert!(!text.contains("Cannot reach"), "{text}");
692 assert!(text.contains("CODEWHALE_FORCE_HTTP1=1"), "{text}");
693 }
694
695 #[test]
696 fn h1_fallback_hint_follows_protocol_errors_with_the_full_chain() {
697 let protocol = h1_fallback_error(
698 anyhow::Error::new(LlmError::NetworkError("http2 protocol error".to_string()))
699 .context("sending stream request"),
700 );
701 let text = format!("{protocol:#}");
702 assert!(text.contains("sending stream request: "), "{text}");
703 assert!(text.contains("http2 protocol error"), "{text}");
704 assert!(!protocol.downcast_ref::<LlmError>().unwrap().is_retryable());
705
706 let other = h1_fallback_error(anyhow::Error::new(LlmError::NetworkError(
707 "unexpected end of body".to_string(),
708 )));
709 assert!(
710 !other.to_string().contains("CODEWHALE_FORCE_HTTP1"),
711 "{other}"
712 );
713 }
714
715 #[tokio::test]
716 async fn provider_error_from_h1_fallback_keeps_its_semantic_type() {
717 let attempts = Arc::new(AtomicUsize::new(0));
718 let err = open_sse_response(
719 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
720 |policy| {
721 let attempts = Arc::clone(&attempts);
722 async move {
723 let attempt = attempts.fetch_add(1, Ordering::SeqCst);
724 if attempt == 0 {
725 assert_eq!(policy, StreamHttpPolicy::DualWithH1Fallback);
726 return Err(anyhow::Error::new(LlmError::ConnectError {
727 message: "connection refused before dispatch".into(),
728 transient: true,
729 timed_out: false,
730 }));
731 }
732 assert_eq!(policy, StreamHttpPolicy::Http1Only);
733 Err(anyhow::Error::new(LlmError::InvalidRequest {
734 status: 400,
735 message: "invalid request".to_string(),
736 }))
737 }
738 },
739 )
740 .await
741 .expect_err("the H1 provider error must be returned");
742 assert_eq!(attempts.load(Ordering::SeqCst), 2, "one fallback attempt");
743 assert!(
744 matches!(
745 err.downcast_ref::<LlmError>(),
746 Some(LlmError::InvalidRequest { status: 400, .. })
747 ),
748 "provider error was reclassified: {err:#}"
749 );
750 }
751
752 #[tokio::test]
753 async fn attempt_error_before_headers_is_not_h1_retried() {
754 let attempts = Arc::new(AtomicUsize::new(0));
755 let err = open_sse_response(
756 &open_req(StreamHttpPolicy::DualWithH1Fallback, Duration::from_secs(5)),
757 |_| {
758 let attempts = Arc::clone(&attempts);
759 async move {
760 attempts.fetch_add(1, Ordering::SeqCst);
761 Err(anyhow::anyhow!("HTTP 401: invalid api key"))
762 }
763 },
764 )
765 .await
766 .expect_err("provider error propagates");
767 assert_eq!(
768 attempts.load(Ordering::SeqCst),
769 1,
770 "non-stall errors are never H1-retried"
771 );
772 assert!(err.to_string().contains("HTTP 401"), "{err}");
773 }
774
775 #[tokio::test]
776 async fn double_stall_reports_both_protocols_in_timeout_text() {
777 let attempts = Arc::new(AtomicUsize::new(0));
778 let err = open_sse_response(
779 &open_req(
780 StreamHttpPolicy::DualWithH1Fallback,
781 Duration::from_millis(100),
782 ),
783 |_| {
784 let attempts = Arc::clone(&attempts);
785 async move {
786 attempts.fetch_add(1, Ordering::SeqCst);
787 std::future::pending::<()>().await;
788 unreachable!("stalled attempt never resolves")
789 }
790 },
791 )
792 .await
793 .expect_err("double stall fails");
794 assert_eq!(
795 attempts.load(Ordering::SeqCst),
796 1,
797 "no replay after unknown stall"
798 );
799 let text = err.to_string();
800 assert!(!text.contains("HTTP/2 and HTTP/1.1"), "{text}");
801 assert!(
802 text.contains("prefilling a large or high-thinking request or loading a cold model"),
803 "{text}"
804 );
805 assert!(
806 text.contains("codewhale config set stream.open_timeout_secs 300` (up to 600)"),
807 "{text}"
808 );
809 }
810
811 #[test]
812 fn h1_retry_only_on_dual_policy() {
813 assert!(should_retry_with_h1(
814 StreamHttpPolicy::DualWithH1Fallback,
815 "http2 protocol error"
816 ));
817 assert!(!should_retry_with_h1(
818 StreamHttpPolicy::Http1Only,
819 "http2 protocol error"
820 ));
821 }
822
823 #[test]
824 fn stall_first_byte_timeout_is_well_under_default_idle_budget() {
825 let default_idle =
826 Duration::from_secs(codewhale_runtime::config::DEFAULT_STREAM_CHUNK_TIMEOUT_SECS);
827 let first_byte = first_byte_timeout_from_env(default_idle, None);
828 assert_eq!(first_byte, DEFAULT_STREAM_FIRST_BYTE_TIMEOUT);
829 assert!(
830 first_byte * 3 <= default_idle,
831 "{first_byte:?} vs {default_idle:?}"
832 );
833 // An explicitly configured idle budget is respected for the first byte.
834 let custom = Duration::from_secs(1800);
835 assert_eq!(first_byte_timeout_from_env(custom, None), custom);
836 assert_eq!(
837 first_byte_timeout_from_env(Duration::from_secs(60), None),
838 Duration::from_secs(60)
839 );
840 assert_eq!(
841 first_byte_timeout_from_env(default_idle, Some("90")),
842 Duration::from_secs(90)
843 );
844 assert_eq!(next_chunk_timeout(default_idle, first_byte, 0), first_byte);
845 assert_eq!(
846 next_chunk_timeout(default_idle, first_byte, 1),
847 default_idle
848 );
849 }
850
851 #[test]
852 fn stream_open_timeout_defaults_and_clamps_env_values() {
853 assert_eq!(stream_open_timeout_from_env(None), Duration::from_secs(180));
854 assert_eq!(
855 stream_open_timeout_from_env(Some("not-a-number")),
856 Duration::from_secs(180)
857 );
858 assert_eq!(
859 stream_open_timeout_from_env(Some("1")),
860 Duration::from_secs(5)
861 );
862 assert_eq!(
863 stream_open_timeout_from_env(Some("120")),
864 Duration::from_secs(120)
865 );
866 assert_eq!(
867 stream_open_timeout_from_env(Some("450")),
868 Duration::from_secs(450)
869 );
870 assert_eq!(
871 stream_open_timeout_from_env(Some("999")),
872 Duration::from_secs(600)
873 );
874 }
875
876 #[test]
877 fn configured_stream_open_timeout_wins_and_clamps() {
878 // Positive config values never consult the env, so these are
879 // deterministic regardless of the test process environment.
880 assert_eq!(
881 resolve_stream_open_timeout(Some(90)),
882 Duration::from_secs(90)
883 );
884 assert_eq!(
885 resolve_stream_open_timeout(Some(1)),
886 Duration::from_secs(MIN_STREAM_OPEN_TIMEOUT_SECS)
887 );
888 assert_eq!(
889 resolve_stream_open_timeout(Some(u64::MAX)),
890 Duration::from_secs(MAX_STREAM_OPEN_TIMEOUT_SECS)
891 );
892 }
893
894 #[test]
895 fn idle_message_is_stable() {
896 let msg = idle_timeout_message(
897 Duration::from_secs(30),
898 0,
899 Duration::from_secs(30),
900 Duration::from_secs(30),
901 );
902 assert!(msg.contains("idle timeout"));
903 assert!(msg.contains("bytes_received=0"));
904 }
905 }
906
906 lines RUST