test(deflake): waits become signals with deadlines; no sleeps or polls in tests
b7c906b5935d6f87aa17ba7e842ce817f746a31f
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: fbc47ab4710a
There are many coding harnesses - but this one is fast
b7c906b5935d6f87aa17ba7e842ce817f746a31f
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+309 / −157 text lines
+13 / −2 text lines
+6 / −3 text lines
let signal = crate::process_signal::ProcessSignal::new(); serde_json::json!({"command": "sleep 10", "timeout_ms": 10_000}), serde_json::json!({"command": format!("{}; sleep 30", signal.raise()), "timeout_ms": 30_000}), // synchronize: cancel once the tool's command reports it runs, never after a guessed delay. crate::process_signal::closed(&mut socket)+32 / −27 text lines
use crate::process_signal::{ProcessSignal, closed}; use std::time::Duration; // keep-with-deadline: time is the contract; wide margin over the 400ms timeout. // keep-with-deadline: time is the contract; wide margin over the 400ms timeout. let handle = { thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap()) assert_eq!(res.stdout.len(), 300_000); let dir = std::env::temp_dir().join(format!("smith_bash_tree_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let marker = dir.join("descendant_survived"); let script = format!("(sleep 30; touch {}) & sleep 30", marker.display()); let res = run(&script, 300, 1024); assert!(res.timed_out); thread::sleep(Duration::from_millis(1200)); assert!(!marker.exists(), "descendant survived the timeout kill"); let _ = std::fs::remove_dir_all(&dir); let cancel = CancelHandle::new(); let signal = ProcessSignal::new(); // Only the background descendant holds the connection. let script = format!("({}; sleep 30) & sleep 30", signal.raise()); let running = { let cancel = cancel.clone(); thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap()) }; // synchronize: kill the tree once the descendant reports it runs. let mut socket = signal.wait(); cancel.cancel(); assert!(running.join().unwrap().cancelled); assert!(closed(&mut socket), "descendant survived the tree kill");+57 / −0 text lines
/// Readiness signals raised by real child processes, for tests that must/// act while a command runs.#[cfg(test)]#[expect( clippy::unwrap_used, reason = "tests may panic on invariant violations")]mod process_signal { use std::net::{TcpListener, TcpStream}; use std::sync::mpsc::{self, Receiver}; use std::time::Duration; /// Upper bound on any single wait for a child; generous for loaded CI. const DEADLINE: Duration = Duration::from_secs(10); /// A loopback listener a shell command connects to once it runs. pub struct ProcessSignal { port: u16, connected: Receiver<TcpStream>, } impl ProcessSignal { pub fn new() -> Self { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let (tx, connected) = mpsc::sync_channel(1); std::thread::spawn(move || { if let Ok((socket, _)) = listener.accept() { let _ = tx.send(socket); } }); Self { port, connected } } /// Bash that raises the signal and keeps the connection open for /// as long as the raising process lives. pub fn raise(&self) -> String { format!("exec 3<>/dev/tcp/127.0.0.1/{}", self.port) } /// The raising process's connection, once it has connected. pub fn wait(&self) -> TcpStream { let socket = self.connected.recv_timeout(DEADLINE); assert!(socket.is_ok(), "no process connected within {DEADLINE:?}"); socket.unwrap() } } /// Whether every process holding `socket` has exited, as seen by end of /// stream before `DEADLINE`. pub fn closed(socket: &mut TcpStream) -> bool { use std::io::Read; socket.set_read_timeout(Some(DEADLINE)).unwrap(); matches!(socket.read(&mut [0u8; 1]), Ok(0)) }}+11 / −4 text lines
+29 / −23 text lines
std::fs::write(&target, "alpha\n").unwrap(); std::fs::write(&target, "alpha one\n").unwrap(); // Somebody else rewrites the file after the read. std::thread::sleep(std::time::Duration::from_millis(20)); std::fs::write(&target, "alpha edited elsewhere\n").unwrap(); // Somebody else rewrites the file after the read; same length, so only the mtime tells. std::fs::write(&target, "alpha two\n").unwrap(); // inject: pin the rewrite's mtime past the read instead of sleeping for a clock tick. let later = std::fs::metadata(&target).unwrap().modified().unwrap() + std::time::Duration::from_secs(60); std::fs::File::options() .write(true) .open(&target) .unwrap() .set_modified(later) .unwrap(); assert_eq!( std::fs::read_to_string(&target).unwrap(), "alpha edited elsewhere\n" ); assert_eq!(std::fs::read_to_string(&target).unwrap(), "alpha two\n"); assert_eq!( std::fs::read_to_string(&target).unwrap(), "beta edited elsewhere\n" ); assert_eq!(std::fs::read_to_string(&target).unwrap(), "beta two\n"); &serde_json::json!({"command": "sleep 10", "timeout_ms": 10_000}), &serde_json::json!({"command": command, "timeout_ms": 30_000}), }); // synchronize: cancel once the command reports it runs, never after a guessed delay. let mut socket = signal.wait(); cancel.cancel(); // Before the join: a survivor would hold the pipes and stall it. assert!( crate::process_signal::closed(&mut socket), "command kept running" ); let err = running.join().unwrap().unwrap_err(); assert!(started.elapsed() < std::time::Duration::from_secs(5));+91 / −61 text lines
use std::sync::mpsc::RecvTimeoutError;use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};const EVENT_GAP: Duration = Duration::from_millis(200);/// Chunked SSE: head plus first event at once, later events after `EVENT_GAP`.fn serve_events(socket: &mut TcpStream) { let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\ Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n"; let _ = socket.write_all(head.as_bytes()); for (index, event) in EVENTS.iter().enumerate() { if index > 0 { std::thread::sleep(EVENT_GAP);/// Chunked SSE: head plus first event at once; each later event only once/// the test sends on the returned gate, so the client must stream what it has.fn serve_events() -> (SyncSender<()>, impl FnOnce(&mut TcpStream) + Send + 'static) { let (gate, next) = mpsc::sync_channel::<()>(EVENTS.len()); let serve = move |socket: &mut TcpStream| { let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\ Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n"; let _ = socket.write_all(head.as_bytes()); for (index, event) in EVENTS.iter().enumerate() { // synchronize: the test releases each later event. if index > 0 && next.recv_timeout(DEADLINE).is_err() { return; } let _ = write!(socket, "{:x}\r\n{event}\r\n", event.len()); let _ = socket.flush();/// Every chunk with its arrival time, then how the body ended.fn drain( response: HttpResponse, start: Instant,) -> (Vec<(Duration, Vec<u8>)>, Option<HttpBodyEnd>) {/// Hold a fixture until the test is done with it, bounded by `DEADLINE`.fn stall(release: &Receiver<()>) { // synchronize: the stall lasts until the test releases it. let _ = release.recv_timeout(DEADLINE);}/// The next body item, or a failure once `DEADLINE` passes.fn next_item(response: &HttpResponse) -> HttpBodyItem { let item = response.body.recv_timeout(DEADLINE); assert!(item.is_ok(), "body stalled: {item:?}"); item.unwrap()}fn chunk(event: &str) -> HttpBodyItem { HttpBodyItem::Chunk(smith::http::HttpChunk { bytes: event.as_bytes().to_vec(), })}/// Every chunk, then how the body ended.fn drain(response: HttpResponse) -> (Vec<Vec<u8>>, Option<HttpBodyEnd>) { HttpBodyItem::Chunk(chunk) => chunks.push((start.elapsed(), chunk.bytes)), HttpBodyItem::Chunk(chunk) => chunks.push(chunk.bytes), let (arrivals, end) = drain(response, start); assert_eq!(end, Some(HttpBodyEnd::Complete)); let body: Vec<u8> = arrivals.iter().flat_map(|(_, b)| b.clone()).collect(); assert_eq!(body, EVENTS.concat().as_bytes()); let first = arrivals.first().unwrap().0; let last = arrivals.last().unwrap().0; assert!(first < EVENT_GAP, "first chunk at {first:?}"); assert!( last - first >= EVENT_GAP * 3 / 2, "chunks bunched ({first:?}..{last:?})" // Each event arrives before the server may send the next: a buffering // client would stall here instead. for (index, event) in EVENTS.iter().enumerate() { if index > 0 { gate.send(()).unwrap(); } assert_eq!(next_item(&response), chunk(event)); } assert_eq!( next_item(&response), HttpBodyItem::End(HttpBodyEnd::Complete) let port = spawn_server(serve_events); let first = response.body.recv().unwrap(); assert_eq!( first, HttpBodyItem::Chunk(smith::http::HttpChunk { bytes: EVENTS[0].as_bytes().to_vec() }) ); assert_eq!(next_item(&response), chunk(EVENTS[0])); let cancelled_at = Instant::now(); response.body.recv_timeout(EVENT_GAP), assert!(stopped < EVENT_GAP * 3 / 2, "stopped after {stopped:?}"); std::thread::sleep(Duration::from_millis(pause)); let (chunks, end) = drain(response, start); let body: Vec<u8> = chunks.into_iter().flat_map(|(_, b)| b).collect(); let (chunks, end) = drain(response); let _ = release.send(()); assert!(failed < Duration::from_secs(1), "failed at {failed:?}");+70 / −37 text lines
/// Block up to `timeout` for the next response line. /// /// The deterministic settle signal for callers that must wait: pair a /// `wait` request with this receive instead of polling [`Self::is_settled`]. #[must_use] pub fn recv_line(&self, timeout: std::time::Duration) -> Option<String> { let response = self.responses.recv_timeout(timeout).ok()?; response.to_line().ok() } use std::time::{Duration, Instant}; fn complete(state: &mut RpcState, input: &str) -> Vec<serde_json::Value> { let mut output = handle_line(state, input); let deadline = Instant::now() + Duration::from_secs(2); while !state.is_settled() && Instant::now() < deadline { output.extend(state.drain_lines()); std::thread::sleep(Duration::from_millis(1)); /// The next response record, or a failure once `DEADLINE` passes. fn next(state: &RpcState) -> serde_json::Value { let line = state.recv_line(DEADLINE); assert!( line.is_some(), "worker answered nothing within {DEADLINE:?}" ); serde_json::from_str(line.unwrap_or_default().trim()).unwrap() } /// Every record before the answer to the `wait` with `id`. fn until_waited(state: &RpcState, id: &serde_json::Value) -> Vec<serde_json::Value> { let mut records = Vec::new(); loop { let record = next(state); if record["id"] == *id { assert_eq!(record["settled"], true); return records; } records.push(record); } fn complete(state: &mut RpcState, input: &str) -> Vec<serde_json::Value> { let mut records = values(&handle_line(state, input)); // synchronize: a `wait` queued behind the prompt answers only after the turn settled. assert!(handle_line(state, r#"{"id": "settle", "method": "wait"}"#).is_empty()); records.extend(until_waited(state, &serde_json::json!("settle"))); assert!(state.is_settled()); records if stream_calls.fetch_add(1, Ordering::Relaxed) == 0 { let item = std::iter::once_with(move || { while !cancel.is_cancelled() { std::thread::sleep(Duration::from_millis(1)); } Err(smith::error::SmithError::Cancelled) }); futures::stream::iter(item).boxed() } else { futures::stream::iter(mock_text_reply("restarted").into_iter().map(Ok)).boxed() let _ = started_tx.send(()); let release_rx = Arc::clone(&release_rx); let items = std::iter::once_with(move || { // synchronize: the turn holds until the test has aborted it. let released = release_rx .lock() .is_ok_and(|rx| rx.recv_timeout(DEADLINE).is_ok()); if released && cancel.is_cancelled() { vec![Err(smith::error::SmithError::Cancelled)] } else { mock_text_reply("not aborted").into_iter().map(Ok).collect() } }) .flatten(); futures::stream::iter(items).boxed() release.send(()).unwrap(); let deadline = Instant::now() + Duration::from_secs(2); let mut deferred = Vec::new(); while (!state.is_settled() || deferred.len() < 2) && Instant::now() < deadline { deferred.extend(values(&state.drain_lines())); std::thread::sleep(Duration::from_millis(1)); } let deferred = until_waited(&state, &serde_json::json!(4));