返回 CodeWhale
exec_stream_drop_acceptance.rs
根目录 / crates / tui / tests / integration / exec_stream_drop_acceptance.rs
1 //! Process-level acceptance for mid-stream provider drops.
2 //!
3 //! An opened stream that drops after partial content has an unknown provider
4 //! outcome, so the engine must not replay it: `codewhale exec` surfaces the
5 //! failure once and exits 1, and an interactive session accepts the next
6 //! manual turn.
7 //!
8 //! These tests drive the real binary against a raw TCP server that sends a
9 //! partial SSE body and then closes mid-`content-length`, reproducing the
10 //! exact reqwest decode failure from the bench artifacts.
11
12 use std::io::Read;
13 use std::path::Path;
14 use std::process::{Command, Stdio};
15 use std::sync::atomic::{AtomicUsize, Ordering};
16 use std::sync::{Arc, Mutex};
17 use std::time::Duration;
18
19 use serde_json::{Value, json};
20 use tempfile::TempDir;
21 use wait_timeout::ChildExt;
22
23 #[cfg(all(unix, feature = "long-running-tests"))]
24 use super::qa_harness;
25
26 const MODEL: &str = "stream-drop-test";
27 /// The server claims a body far larger than it delivers on a "drop" response,
28 /// so hyper raises `error decoding response body` after the first SSE chunk —
29 /// the exact failure string in the Terminal-Bench crash artifacts.
30 const CLAIMED_DROP_BODY_LEN: usize = 1_048_576;
31
32 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
33 async fn headless_exec_does_not_replay_a_mid_stream_drop() {
34 let workspace = TempDir::new().expect("workspace");
35 let home = TempDir::new().expect("home");
36 let (base_url, chat_posts, _requests, _server) =
37 start_flaky_server(usize::MAX, Duration::ZERO).await;
38
39 let output = run_exec(workspace.path(), home.path(), &base_url);
40
41 assert_eq!(
42 output.status.code(),
43 Some(1),
44 "an opened stream that drops has an unknown outcome and fails the exec turn\nstdout:\n{}\nstderr:\n{}",
45 String::from_utf8_lossy(&output.stdout),
46 String::from_utf8_lossy(&output.stderr)
47 );
48 assert_eq!(
49 chat_posts.load(Ordering::SeqCst),
50 1,
51 "an opened stream must never be replayed"
52 );
53 let stdout = String::from_utf8_lossy(&output.stdout);
54 let error_events = stdout
55 .lines()
56 .filter(|line| line.contains(r#""type":"error""#))
57 .count();
58 assert_eq!(error_events, 1, "{stdout}");
59 let error_line = stdout
60 .lines()
61 .find(|line| line.contains(r#""type":"error""#))
62 .expect("terminal error event");
63 assert!(
64 error_line.contains("Provider stream connection dropped"),
65 "the error channel must carry the real failure: {error_line}"
66 );
67 let meta = terminal_metadata(&stdout);
68 assert_eq!(meta["meta"]["status"].as_str(), Some("failed"), "{meta}");
69 assert_eq!(
70 meta["meta"]["error_category"].as_str(),
71 Some("network"),
72 "the terminal receipt must classify the failure as network: {meta}"
73 );
74 }
75
76 /// #5769's later report: the NEXT manually submitted turn, with no approval,
77 /// must reach the real dispatcher and survive its UI watchdog after a loss.
78 #[cfg(all(unix, feature = "long-running-tests"))]
79 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
80 async fn tui_next_manual_turn_completes_after_exhausted_partial_sse_drop() {
81 use qa_harness::harness::{Harness, make_sealed_workspace};
82
83 const FIRST: &str = "R4_FIRST_MANUAL";
84 const SECOND: &str = "R4_NEXT_MANUAL";
85 // Deliberately cross the current 30-second dispatch watchdog using wall
86 // time. The request is admitted, but its HTTP response is still pending.
87 const HEALTHY_RESPONSE_DELAY: Duration = Duration::from_secs(35);
88 const WAIT: Duration = Duration::from_secs(60);
89 let workspace = make_sealed_workspace().expect("sealed workspace");
90 let (base_url, chat_posts, requests, server) =
91 start_flaky_server(1, HEALTHY_RESPONSE_DELAY).await;
92 let outbox = workspace.home().join("turn-receipts.jsonl");
93 std::fs::write(workspace.home().join(".codewhale/.onboarded"), "").expect("onboarding receipt");
94 let config = format!(
95 r#"provider = "loopback"
96 prompt_suggestion = false
97 allow_shell = false
98 [providers.loopback]
99 kind = "openai-compatible"
100 base_url = {base_url}
101 api_key = "synthetic-loopback-key"
102 model = "{MODEL}"
103 [retry]
104 enabled = false
105 [notifications]
106 method = "off"
107 completion_sound = "off"
108 [lifecycle_outbox]
109 path = {outbox}
110 "#,
111 base_url = json!(base_url),
112 outbox = json!(outbox),
113 );
114 std::fs::write(workspace.home().join(".codewhale/config.toml"), config)
115 .expect("loopback TUI configuration");
116 workspace.trust_workspace().expect("workspace trust");
117 let mut tui = Harness::builder(Harness::codewhale_binary())
118 .cwd(workspace.workspace())
119 .clear_env()
120 .seal_home(workspace.home())
121 .env("CODEWHALE_DISABLE_MODELS_DEV_FETCH", "1")
122 .env("CODEWHALE_NO_UPDATE_CHECK", "1")
123 .env("CODEWHALE_TELEMETRY", "0")
124 .env("NO_ANIMATIONS", "1")
125 .args([
126 "--workspace",
127 workspace.workspace().to_str().expect("workspace UTF-8"),
128 "--no-project-config",
129 "--fresh",
130 ])
131 .size(40, 120)
132 .spawn()
133 .expect("start the real TUI");
134 let pid = tui.pid().expect("TUI PID");
135 tui.wait_for_text("Describe a task", WAIT)
136 .expect("ready composer");
137 tui.type_line(FIRST).expect("first manual submission");
138 wait_for_tui_turn_ends(&mut tui, &outbox, 1, WAIT);
139 let first_events = read_tui_outbox(&outbox);
140 let first = first_events
141 .iter()
142 .find(|event| event["event"] == "turn_end")
143 .expect("first terminal UI receipt");
144 assert_eq!(first["kind"], "turn.failed", "{first:#}");
145 assert!(
146 first["payload"]["error"]
147 .as_str()
148 .is_some_and(|error| error.starts_with("Provider stream connection dropped")),
149 "the first UI turn must fail on an actual partial SSE loss: {first:#}"
150 );
151 // The lifecycle outbox contains a bounded user-facing error, not the
152 // underlying reqwest chain. The server's partial SSE body and the exact
153 // request count prove the real transport loss and that it was not replayed.
154 assert_eq!(chat_posts.load(Ordering::SeqCst), 1);
155
156 // No restart, continuation, event injection, approval answer, or queue
157 // admission: type into the same running composer after its failed receipt.
158 let submitted = std::time::Instant::now();
159 tui.type_line(SECOND).expect("next manual submission");
160 wait_for_tui_turn_ends(&mut tui, &outbox, 2, WAIT);
161 assert!(submitted.elapsed() >= HEALTHY_RESPONSE_DELAY);
162 tui.wait_for_text("recovered after retry", WAIT)
163 .expect("second answer reaches the actual UI");
164 // Completion is proved by the lifecycle receipt below. The composer
165 // intentionally omits the old transient "turn completed" chrome; prove
166 // that the actual UI is ready and still accepts an unsent edit instead.
167 tui.wait_for(
168 |frame| frame.contains("recovered after retry") && frame.contains("Describe a task"),
169 WAIT,
170 )
171 .expect("completed answer and ready composer reach the actual UI");
172 const UNSENT: &str = "R4_UNSENT_RECOVERY_CHECK";
173 tui.paste(UNSENT).expect("edit the recovered composer");
174 tui.wait_for(|frame| frame.row(frame.cursor().0).contains(UNSENT), WAIT)
175 .expect("the same composer remains editable after completion");
176 assert_eq!(tui.pid(), Some(pid));
177 let events = read_tui_outbox(&outbox);
178 let starts = events
179 .iter()
180 .filter(|event| event["event"] == "turn_start")
181 .collect::<Vec<_>>();
182 let ends = events
183 .iter()
184 .filter(|event| event["event"] == "turn_end")
185 .collect::<Vec<_>>();
186 assert_eq!(starts.len(), 2, "two real TUI dispatches: {events:#?}");
187 assert_eq!(ends.len(), 2, "two real TUI completions: {events:#?}");
188 assert_eq!(ends[1]["kind"], "turn.completed");
189 assert!(ends[1]["payload"]["error"].is_null());
190 let session = ends[0]["thread_id"].as_str().expect("TUI session identity");
191 assert!(!session.is_empty());
192 assert!(
193 starts
194 .iter()
195 .chain(&ends)
196 .all(|event| event["thread_id"] == session)
197 );
198 assert!(ends.iter().all(|event| event["turn_id"].is_string()));
199 assert_ne!(ends[0]["turn_id"], ends[1]["turn_id"]);
200 assert!(events.iter().all(|event| {
201 !event["event"].as_str().unwrap().contains("approval")
202 && !event["event"].as_str().unwrap().contains("user_input")
203 }));
204 let requests = requests.lock().unwrap();
205 assert_eq!(requests.len(), 2, "one failed attempt then one new turn");
206 let final_messages = requests.last().unwrap()["messages"].as_array().unwrap();
207 let users = final_messages
208 .iter()
209 .filter(|message| {
210 message["role"] == "user" && !message.to_string().contains("codewhale:runtime_event")
211 })
212 .collect::<Vec<_>>();
213 assert_eq!(
214 users.len(),
215 2,
216 "no synthetic continuation user turns: {final_messages:#?}"
217 );
218 assert!(users[0]["content"].to_string().contains(FIRST));
219 assert!(users[1]["content"].to_string().contains(SECOND));
220 assert!(
221 final_messages
222 .iter()
223 .all(|message| message["role"] != "tool")
224 );
225 assert!(requests.iter().all(|request| request["stream"] == true));
226 drop(requests);
227 tui.shutdown();
228 server.abort();
229 }
230
231 #[cfg(all(unix, feature = "long-running-tests"))]
232 fn read_tui_outbox(path: &Path) -> Vec<Value> {
233 let text = match std::fs::read_to_string(path) {
234 Ok(text) => text,
235 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
236 Err(error) => panic!("read TUI lifecycle receipt: {error}"),
237 };
238 // A concurrent append can expose an unfinished last line. Only complete
239 // records count as receipts; a malformed complete record is a failure.
240 text.split_inclusive('\n')
241 .filter(|line| line.ends_with('\n'))
242 .map(|line| serde_json::from_str(line).expect("complete TUI outbox record"))
243 .collect()
244 }
245
246 #[cfg(all(unix, feature = "long-running-tests"))]
247 fn wait_for_tui_turn_ends(
248 tui: &mut qa_harness::harness::Harness,
249 outbox: &Path,
250 count: usize,
251 timeout: Duration,
252 ) {
253 tui.wait_for(
254 |frame| {
255 for unexpected in [
256 "Turn dispatch timed out",
257 "engine may have stopped",
258 "Approval required",
259 "engine session id diverged",
260 ] {
261 assert!(
262 !frame.contains(unexpected),
263 "{unexpected}: {}",
264 frame.text()
265 );
266 }
267 read_tui_outbox(outbox)
268 .iter()
269 .filter(|event| event["event"] == "turn_end")
270 .count()
271 >= count
272 },
273 timeout,
274 )
275 .unwrap_or_else(|error| {
276 panic!(
277 "UI did not finish turn {count}: {error}\n{}",
278 tui.diagnostics()
279 )
280 });
281 }
282
283 /// Extract the terminal `metadata` event from the stream-json stdout.
284 fn terminal_metadata(stdout: &str) -> Value {
285 let line = stdout
286 .lines()
287 .rev()
288 .find(|line| line.contains(r#""type":"metadata""#))
289 .unwrap_or_else(|| panic!("stream-json metadata event missing: {stdout}"));
290 serde_json::from_str(line).expect("metadata event is valid JSON")
291 }
292
293 /// Spawn a raw HTTP server that answers `GET /v1/models` and, for every POST
294 /// to the chat endpoint, either truncates the SSE body mid-stream (the first
295 /// `drops` requests) or completes a normal text turn. Returns the base URL
296 /// and a counter of chat-completion POSTs.
297 async fn start_flaky_server(
298 drops: usize,
299 healthy_response_delay: Duration,
300 ) -> (
301 String,
302 Arc<AtomicUsize>,
303 Arc<Mutex<Vec<Value>>>,
304 tokio::task::JoinHandle<()>,
305 ) {
306 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
307 .await
308 .expect("bind flaky server");
309 let addr = listener.local_addr().expect("flaky server addr");
310 let chat_posts = Arc::new(AtomicUsize::new(0));
311 let server_posts = Arc::clone(&chat_posts);
312 let requests = Arc::new(Mutex::new(Vec::new()));
313 let captured = Arc::clone(&requests);
314 let task = tokio::spawn(async move {
315 loop {
316 let (mut socket, _) = match listener.accept().await {
317 Ok(pair) => pair,
318 Err(_) => break,
319 };
320 let request = match read_http_request(&mut socket).await {
321 Some(request) => request,
322 None => continue,
323 };
324 if request.starts_with("GET ") {
325 write_all(
326 &mut socket,
327 &http_response(
328 "application/json",
329 &json!({"object":"list","data":[{"id":MODEL,"object":"model"}]})
330 .to_string(),
331 ),
332 )
333 .await;
334 continue;
335 }
336 let body = request.split_once("\r\n\r\n").expect("request body").1;
337 captured
338 .lock()
339 .unwrap()
340 .push(serde_json::from_str(body).expect("chat request JSON"));
341 let call = server_posts.fetch_add(1, Ordering::SeqCst) + 1;
342 if call <= drops {
343 // Partial SSE (one real content chunk), then the socket
344 // closes with the declared content-length unmet — the
345 // production "Provider stream connection dropped" failure.
346 let partial = sse_chunk(
347 json!({"id":"drop","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{"content":"partial answer that must be discarded"},"finish_reason":null}]}),
348 );
349 let head = format!(
350 "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {CLAIMED_DROP_BODY_LEN}\r\nconnection: close\r\n\r\n"
351 );
352 write_all(&mut socket, &format!("{head}{partial}")).await;
353 } else {
354 tokio::time::sleep(healthy_response_delay).await;
355 let body = [
356 sse_chunk(json!({"id":"final","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{"content":"recovered after retry"},"finish_reason":null}]})),
357 sse_chunk(json!({"id":"final","object":"chat.completion.chunk","model":MODEL,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}})),
358 "data: [DONE]\n\n".to_string(),
359 ]
360 .join("");
361 write_all(&mut socket, &http_response("text/event-stream", &body)).await;
362 }
363 }
364 });
365 (format!("http://{addr}/v1"), chat_posts, requests, task)
366 }
367
368 /// Read one HTTP request (headers plus the content-length body, when any).
369 async fn read_http_request(socket: &mut tokio::net::TcpStream) -> Option<String> {
370 use tokio::io::AsyncReadExt;
371 let mut buffer = Vec::new();
372 let mut chunk = [0u8; 4096];
373 let header_end = loop {
374 if let Some(pos) = find_subslice(&buffer, b"\r\n\r\n") {
375 break pos + 4;
376 }
377 let read = socket.read(&mut chunk).await.ok()?;
378 if read == 0 {
379 return None;
380 }
381 buffer.extend_from_slice(&chunk[..read]);
382 if buffer.len() > 1 << 20 {
383 return None;
384 }
385 };
386 let headers = String::from_utf8_lossy(&buffer[..header_end]).to_string();
387 let content_length = headers
388 .lines()
389 .find_map(|line| {
390 line.to_ascii_lowercase()
391 .strip_prefix("content-length:")
392 .and_then(|value| value.trim().parse::<usize>().ok())
393 })
394 .unwrap_or(0);
395 let request_len = header_end.checked_add(content_length)?;
396 if request_len > 1 << 20 {
397 return None;
398 }
399 while buffer.len() < request_len {
400 let read = socket.read(&mut chunk).await.ok()?;
401 if read == 0 {
402 return None;
403 }
404 buffer.extend_from_slice(&chunk[..read]);
405 }
406 buffer.truncate(request_len);
407 String::from_utf8(buffer).ok()
408 }
409
410 fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
411 haystack
412 .windows(needle.len())
413 .position(|window| window == needle)
414 }
415
416 async fn write_all(socket: &mut tokio::net::TcpStream, bytes: &str) {
417 use tokio::io::AsyncWriteExt;
418 let _ = socket.write_all(bytes.as_bytes()).await;
419 let _ = socket.shutdown().await;
420 }
421
422 fn http_response(content_type: &str, body: &str) -> String {
423 format!(
424 "HTTP/1.1 200 OK\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
425 body.len()
426 )
427 }
428
429 fn sse_chunk(value: Value) -> String {
430 format!(
431 "data: {}\n\n",
432 serde_json::to_string(&value).expect("SSE JSON")
433 )
434 }
435
436 fn run_exec(workspace: &Path, home: &Path, base_url: &str) -> std::process::Output {
437 std::fs::create_dir_all(home.join(".codewhale")).expect("config directory");
438 std::fs::create_dir_all(home.join(".deepseek")).expect("legacy config directory");
439 std::fs::write(
440 home.join(".codewhale/config.toml"),
441 "allow_shell = true\n\n[retry]\nenabled = false\n",
442 )
443 .expect("headless test config");
444 let mut command = Command::new(crate::binary::codewhale());
445 preserve_host_env(&mut command);
446 command
447 .current_dir(workspace)
448 .args(["--workspace", workspace.to_str().expect("workspace utf8")])
449 .arg("--no-project-config")
450 .args([
451 "exec",
452 "--auto",
453 "--model",
454 MODEL,
455 "--output-format",
456 "stream-json",
457 ])
458 .arg("answer briefly")
459 .env("HOME", home)
460 .env("USERPROFILE", home)
461 .env("XDG_CONFIG_HOME", home.join(".config"))
462 .env("XDG_DATA_HOME", home.join(".local/share"))
463 .env("XDG_CACHE_HOME", home.join(".cache"))
464 .env("CODEWHALE_CONFIG_PATH", home.join(".codewhale/config.toml"))
465 .env("DEEPSEEK_CONFIG_PATH", home.join(".deepseek/config.toml"))
466 .env("DEEPSEEK_API_KEY", "ci-test-key-not-real")
467 .env("DEEPSEEK_BASE_URL", base_url)
468 .env("CODEWHALE_BASE_URL", base_url)
469 .env("DEEPSEEK_MODEL", MODEL)
470 .env("CODEWHALE_MODEL", MODEL)
471 .env("RUST_LOG", "warn")
472 .stdout(Stdio::piped())
473 .stderr(Stdio::piped());
474 run_with_timeout(command, Duration::from_secs(45))
475 }
476
477 fn preserve_host_env(command: &mut Command) {
478 command.env_clear();
479 for key in [
480 "PATH",
481 "PATHEXT",
482 "SystemRoot",
483 "SystemDrive",
484 "WINDIR",
485 "COMSPEC",
486 "TEMP",
487 "TMP",
488 "TERM",
489 "LANG",
490 "LC_ALL",
491 ] {
492 if let Some(value) = std::env::var_os(key) {
493 command.env(key, value);
494 }
495 }
496 }
497
498 fn run_with_timeout(mut command: Command, timeout: Duration) -> std::process::Output {
499 let mut child = command.spawn().expect("spawn codewhale exec");
500 let stdout = read_in_background(child.stdout.take().expect("stdout"));
501 let stderr = read_in_background(child.stderr.take().expect("stderr"));
502 let status = child
503 .wait_timeout(timeout)
504 .expect("wait")
505 .unwrap_or_else(|| {
506 let _ = child.kill();
507 let _ = child.wait();
508 panic!("codewhale exec timed out")
509 });
510 std::process::Output {
511 status,
512 stdout: stdout.join().expect("stdout thread").expect("read stdout"),
513 stderr: stderr.join().expect("stderr thread").expect("read stderr"),
514 }
515 }
516
517 fn read_in_background<R: Read + Send + 'static>(
518 mut reader: R,
519 ) -> std::thread::JoinHandle<std::io::Result<Vec<u8>>> {
520 std::thread::spawn(move || {
521 let mut bytes = Vec::new();
522 reader.read_to_end(&mut bytes).map(|_| bytes)
523 })
524 }
525
525 lines RUST