repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

test(deflake): waits become signals with deadlines; no sleeps or polls in tests

b7c906b5935d6f87aa17ba7e842ce817f746a31f

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (8)

+309 / −157 text lines

Diff layout

smith-ai/src/auth.rs

Modified

+13 / −2 text lines

6363 self
6464 }
66 /// Attach an absolute expiry; the injectable form of [`Self::expires_in`].
67 #[must_use]
68 pub const fn expires_at(mut self, at: SystemTime) -> Self {
69 self.expires_at = Some(at);
70 self
71 }
6673 /// Attach a renewal closure that returns a fresh value.
6774 #[must_use]
6875 pub fn renew_with(mut self, renew: Arc<dyn Fn() -> Option<String> + Send + Sync>) -> Self {
317324 #[test]
318325 fn expired_credential_renews_or_fails_explicitly() {
326 // inject: expiry is a fixed past instant, never a race against the clock.
327 let past = SystemTime::UNIX_EPOCH;
319328 let credential = Credential::explicit("old")
320 .expires_in(Duration::from_millis(0))
329 .expires_at(past)
321330 .renew_with(Arc::new(|| Some("fresh".to_string())));
322331 assert_eq!(credential.secret().unwrap_or_default(), "fresh");
323 let dead = Credential::explicit("old").expires_in(Duration::from_millis(0));
332 let live = Credential::explicit("old").expires_in(Duration::from_secs(3_600));
333 assert_eq!(live.secret().unwrap_or_default(), "old");
334 let dead = Credential::explicit("old").expires_at(past);
324335 assert_eq!(
325336 dead.secret().err().map(|e| e.code().to_string()),
326337 Some("PROVIDER_AUTH".to_string())

smith-core/src/agent.rs

Modified

+6 / −3 text lines

10001000 #[test]
10011001 fn cancelled_tool_is_paired_before_the_next_turn() {
10021002 let call_id = smith::id::ToolCallId::new();
1003 let signal = crate::process_signal::ProcessSignal::new();
10031004 let running_tool = vec![
10041005 StreamEvent::tool_use(
10051006 smith::id::MessageId::new(),
10061007 "bash",
1007 serde_json::json!({"command": "sleep 10", "timeout_ms": 10_000}),
1008 serde_json::json!({"command": format!("{}; sleep 30", signal.raise()), "timeout_ms": 30_000}),
10081009 call_id,
10091010 ),
10101011 StreamEvent::stop(StopReason::ToolUse, None),
10131014 let tools = temp_tools("cancelled_pair");
10141015 let mut agent = Agent::new(stream, tools, "mock-smith");
10151016 let cancel = agent.cancel_handle();
1017 // synchronize: cancel once the tool's command reports it runs, never after a guessed delay.
10161018 let canceller = std::thread::spawn(move || {
1017 std::thread::sleep(std::time::Duration::from_millis(100));
1019 let mut socket = signal.wait();
10181020 cancel.cancel();
1021 crate::process_signal::closed(&mut socket)
10191022 });
10211024 let error = agent.run_turn("start the command").unwrap_err();
1022 canceller.join().unwrap();
1025 assert!(canceller.join().unwrap(), "tool command kept running");
10231026 assert_eq!(error.code(), "CANCELLED");
10241027 agent.renew_cancel_handle();
10251028 agent.run_turn("continue").unwrap();

smith-core/src/bash.rs

Modified

+32 / −27 text lines

246246)]
247247mod tests {
248248 use super::*;
249 use crate::process_signal::{ProcessSignal, closed};
249250 use std::thread;
250 use std::time::Duration;
252252 fn run(cmd: &str, timeout_ms: u64, cap: usize) -> BashResult {
253253 execute(cmd, None, timeout_ms, cap, &CancelHandle::new()).unwrap()
266266 let res = run("sleep 30", 400, 1024);
267267 assert!(res.timed_out);
268268 assert_eq!(res.exit_code, None);
269 // keep-with-deadline: time is the contract; wide margin over the 400ms timeout.
269270 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
270271 }
273274 fn stderr_heavy_child_cannot_deadlock_the_deadline() {
274275 let res = run("while true; do echo noise >&2; done", 400, 4096);
275276 assert!(res.timed_out);
277 // keep-with-deadline: time is the contract; wide margin over the 400ms timeout.
276278 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
277279 }
279281 #[test]
280282 fn cancellation_stops_execution() {
281283 let cancel = CancelHandle::new();
282 let handle = {
284 let signal = ProcessSignal::new();
285 let script = format!("{}; sleep 30", signal.raise());
286 let running = {
283287 let cancel = cancel.clone();
284 thread::spawn(move || {
285 thread::sleep(Duration::from_millis(120));
286 cancel.cancel();
287 })
288 thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap())
288289 };
289 let res = execute("sleep 30", None, 10_000, 1024, &cancel).unwrap();
290 handle.join().unwrap();
291 assert!(res.cancelled);
292 assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
290 // synchronize: cancel once the command reports it runs, never after a guessed delay.
291 let mut socket = signal.wait();
292 cancel.cancel();
293 let res = running.join().unwrap();
294 assert!(res.cancelled && !res.timed_out);
295 assert!(closed(&mut socket), "cancelled command kept running");
293296 }
295298 #[test]
301304 #[test]
302305 fn high_volume_output_is_not_throttled() {
303 let started = Instant::now();
304 let res = run("head -c 300000 /dev/zero | tr '\\0' 'x'", 10_000, 1 << 20);
305 assert_eq!(res.stdout.len(), 300_000);
306 // keep-with-deadline: the command's own timeout is the throughput bound.
307 let res = run("head -c 300000 /dev/zero | tr '\\0' 'x'", 3_000, 1 << 20);
306308 assert!(
307 started.elapsed() < Duration::from_secs(3),
308 "throughput regression: {} bytes in {:?}",
309 res.stdout.len(),
310 started.elapsed()
309 !res.timed_out,
310 "throughput regression: {}ms",
311 res.duration_ms
311312 );
313 assert_eq!(res.stdout.len(), 300_000);
312314 }
314316 #[test]
315317 fn descendant_processes_are_killed_with_the_tree() {
316 let dir = std::env::temp_dir().join(format!("smith_bash_tree_{}", std::process::id()));
317 let _ = std::fs::remove_dir_all(&dir);
318 std::fs::create_dir_all(&dir).unwrap();
319 let marker = dir.join("descendant_survived");
320 let script = format!("(sleep 30; touch {}) & sleep 30", marker.display());
321 let res = run(&script, 300, 1024);
322 assert!(res.timed_out);
323 thread::sleep(Duration::from_millis(1200));
324 assert!(!marker.exists(), "descendant survived the timeout kill");
325 let _ = std::fs::remove_dir_all(&dir);
318 let cancel = CancelHandle::new();
319 let signal = ProcessSignal::new();
320 // Only the background descendant holds the connection.
321 let script = format!("({}; sleep 30) & sleep 30", signal.raise());
322 let running = {
323 let cancel = cancel.clone();
324 thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap())
325 };
326 // synchronize: kill the tree once the descendant reports it runs.
327 let mut socket = signal.wait();
328 cancel.cancel();
329 assert!(running.join().unwrap().cancelled);
330 assert!(closed(&mut socket), "descendant survived the tree kill");
326331 }

smith-core/src/lib.rs

Modified

+57 / −0 text lines

3636pub use tools::{ToolOutcome, ToolRegistry, ToolSession};
3737pub use trace::{TraceKind, TraceRecord, replay};
39/// Readiness signals raised by real child processes, for tests that must
40/// act while a command runs.
41#[cfg(test)]
42#[expect(
43 clippy::unwrap_used,
44 reason = "tests may panic on invariant violations"
45)]
46mod process_signal {
47 use std::net::{TcpListener, TcpStream};
48 use std::sync::mpsc::{self, Receiver};
49 use std::time::Duration;
51 /// Upper bound on any single wait for a child; generous for loaded CI.
52 const DEADLINE: Duration = Duration::from_secs(10);
54 /// A loopback listener a shell command connects to once it runs.
55 pub struct ProcessSignal {
56 port: u16,
57 connected: Receiver<TcpStream>,
58 }
60 impl ProcessSignal {
61 pub fn new() -> Self {
62 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
63 let port = listener.local_addr().unwrap().port();
64 let (tx, connected) = mpsc::sync_channel(1);
65 std::thread::spawn(move || {
66 if let Ok((socket, _)) = listener.accept() {
67 let _ = tx.send(socket);
68 }
69 });
70 Self { port, connected }
71 }
73 /// Bash that raises the signal and keeps the connection open for
74 /// as long as the raising process lives.
75 pub fn raise(&self) -> String {
76 format!("exec 3<>/dev/tcp/127.0.0.1/{}", self.port)
77 }
79 /// The raising process's connection, once it has connected.
80 pub fn wait(&self) -> TcpStream {
81 let socket = self.connected.recv_timeout(DEADLINE);
82 assert!(socket.is_ok(), "no process connected within {DEADLINE:?}");
83 socket.unwrap()
84 }
85 }
87 /// Whether every process holding `socket` has exited, as seen by end of
88 /// stream before `DEADLINE`.
89 pub fn closed(socket: &mut TcpStream) -> bool {
90 use std::io::Read;
91 socket.set_read_timeout(Some(DEADLINE)).unwrap();
92 matches!(socket.read(&mut [0u8; 1]), Ok(0))
93 }
94}
3996#[cfg(test)]
4097mod tests {
4198 use super::*;

smith-core/src/store.rs

Modified

+11 / −4 text lines

583583 let repair_path = path.clone();
584584 let limit = cfg.max_frame_bytes;
585 let repair = std::thread::spawn(move || repair_session(&repair_path, limit).unwrap());
585 let (entered, repair_started) = std::sync::mpsc::sync_channel(1);
586 let repair = std::thread::spawn(move || {
587 entered.send(()).unwrap();
588 repair_session(&repair_path, limit).unwrap()
589 });
587 // The repair thread must block here; an append after it started is
588 // still committed to the file the repair will republish.
589 std::thread::sleep(std::time::Duration::from_millis(150));
591 // synchronize: the repair has started; the writer's lock holds it
592 // until the drop, so an append now is still committed to the file
593 // the repair will republish.
594 repair_started
595 .recv_timeout(std::time::Duration::from_secs(10))
596 .unwrap();
590597 writer.append_frame(&frame("two")).unwrap();
591598 drop(writer);

smith-core/src/tools.rs

Modified

+29 / −23 text lines

10041004 fn edit_rejects_input_that_describes_an_older_version_of_the_file() {
10051005 let dir = workdir("stale_edit");
10061006 let target = dir.join("doc.txt");
1007 std::fs::write(&target, "alpha\n").unwrap();
1007 std::fs::write(&target, "alpha one\n").unwrap();
10081008 let mut ts = ToolSession::new(&dir);
10091009 ts.invoke("read", &serde_json::json!({"path": "doc.txt"}))
10101010 .unwrap();
1012 // Somebody else rewrites the file after the read.
1013 std::thread::sleep(std::time::Duration::from_millis(20));
1014 std::fs::write(&target, "alpha edited elsewhere\n").unwrap();
1012 // Somebody else rewrites the file after the read; same length, so only the mtime tells.
1013 std::fs::write(&target, "alpha two\n").unwrap();
1014 // inject: pin the rewrite's mtime past the read instead of sleeping for a clock tick.
1015 let later = std::fs::metadata(&target).unwrap().modified().unwrap()
1016 + std::time::Duration::from_secs(60);
1017 std::fs::File::options()
1018 .write(true)
1019 .open(&target)
1020 .unwrap()
1021 .set_modified(later)
1022 .unwrap();
10161024 let err = ts
10171025 .invoke(
10211029 .unwrap_err();
10221030 assert_eq!(err.code(), "STALE_INPUT");
1023 assert_eq!(
1024 std::fs::read_to_string(&target).unwrap(),
1025 "alpha edited elsewhere\n"
1026 );
1031 assert_eq!(std::fs::read_to_string(&target).unwrap(), "alpha two\n");
10281033 // Re-reading refreshes the observed version and unblocks the edit.
10291034 ts.invoke("read", &serde_json::json!({"path": "doc.txt"}))
10331038 &serde_json::json!({"path": "doc.txt", "old_string": "alpha", "new_string": "beta"}),
10351040 .unwrap();
1036 assert_eq!(
1037 std::fs::read_to_string(&target).unwrap(),
1038 "beta edited elsewhere\n"
1039 );
1041 assert_eq!(std::fs::read_to_string(&target).unwrap(), "beta two\n");
10421044 #[test]
11161118 let dir = workdir("cancel_running");
11171119 let mut ts = ToolSession::new(&dir);
11181120 let cancel = ts.cancel_handle();
1119 let waker = std::thread::spawn(move || {
1120 std::thread::sleep(std::time::Duration::from_millis(150));
1121 cancel.cancel();
1122 });
1123 let started = std::time::Instant::now();
1124 let err = ts
1125 .invoke(
1121 let signal = crate::process_signal::ProcessSignal::new();
1122 let command = format!("{}; sleep 30", signal.raise());
1123 let running = std::thread::spawn(move || {
1124 ts.invoke(
11261125 "bash",
1127 &serde_json::json!({"command": "sleep 10", "timeout_ms": 10_000}),
1126 &serde_json::json!({"command": command, "timeout_ms": 30_000}),
1129 .unwrap_err();
1130 waker.join().unwrap();
1128 });
1129 // synchronize: cancel once the command reports it runs, never after a guessed delay.
1130 let mut socket = signal.wait();
1131 cancel.cancel();
1132 // Before the join: a survivor would hold the pipes and stall it.
1133 assert!(
1134 crate::process_signal::closed(&mut socket),
1135 "command kept running"
1136 );
1137 let err = running.join().unwrap().unwrap_err();
11311138 assert_eq!(err.code(), "CANCELLED");
1132 assert!(started.elapsed() < std::time::Duration::from_secs(5));
11351141 #[test]

smith-harness/tests/http_stream.rs

Modified

+91 / −61 text lines

88use smith_harness::http::{MAX_BODY_BYTES, UreqHttpExecutor};
99use std::io::{Read, Write};
1010use std::net::{TcpListener, TcpStream};
11use std::sync::mpsc::RecvTimeoutError;
11use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender};
1212use std::time::{Duration, Instant};
1414const EVENTS: [&str; 3] = ["data: one\n\n", "data: two\n\n", "data: three\n\n"];
15const EVENT_GAP: Duration = Duration::from_millis(200);
16/// Upper bound on any single wait for the fixture or the engine.
17const DEADLINE: Duration = Duration::from_secs(10);
1719/// Accept one connection, read the request head, hand the socket to
1820/// `serve`, then drain until the client closes so unread request bytes
3133 port
34/// Chunked SSE: head plus first event at once, later events after `EVENT_GAP`.
35fn serve_events(socket: &mut TcpStream) {
36 let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
37 Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
38 let _ = socket.write_all(head.as_bytes());
39 for (index, event) in EVENTS.iter().enumerate() {
40 if index > 0 {
41 std::thread::sleep(EVENT_GAP);
36/// Chunked SSE: head plus first event at once; each later event only once
37/// the test sends on the returned gate, so the client must stream what it has.
38fn serve_events() -> (SyncSender<()>, impl FnOnce(&mut TcpStream) + Send + 'static) {
39 let (gate, next) = mpsc::sync_channel::<()>(EVENTS.len());
40 let serve = move |socket: &mut TcpStream| {
41 let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
42 Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
43 let _ = socket.write_all(head.as_bytes());
44 for (index, event) in EVENTS.iter().enumerate() {
45 // synchronize: the test releases each later event.
46 if index > 0 && next.recv_timeout(DEADLINE).is_err() {
47 return;
48 }
49 let _ = write!(socket, "{:x}\r\n{event}\r\n", event.len());
50 let _ = socket.flush();
4251 }
43 let _ = write!(socket, "{:x}\r\n{event}\r\n", event.len());
44 let _ = socket.flush();
45 }
46 let _ = socket.write_all(b"0\r\n\r\n");
52 let _ = socket.write_all(b"0\r\n\r\n");
53 };
54 (gate, serve)
49/// Every chunk with its arrival time, then how the body ended.
50fn drain(
51 response: HttpResponse,
52 start: Instant,
53) -> (Vec<(Duration, Vec<u8>)>, Option<HttpBodyEnd>) {
57/// Hold a fixture until the test is done with it, bounded by `DEADLINE`.
58fn stall(release: &Receiver<()>) {
59 // synchronize: the stall lasts until the test releases it.
60 let _ = release.recv_timeout(DEADLINE);
61}
63/// The next body item, or a failure once `DEADLINE` passes.
64fn next_item(response: &HttpResponse) -> HttpBodyItem {
65 let item = response.body.recv_timeout(DEADLINE);
66 assert!(item.is_ok(), "body stalled: {item:?}");
67 item.unwrap()
68}
70fn chunk(event: &str) -> HttpBodyItem {
71 HttpBodyItem::Chunk(smith::http::HttpChunk {
72 bytes: event.as_bytes().to_vec(),
73 })
74}
76/// Every chunk, then how the body ended.
77fn drain(response: HttpResponse) -> (Vec<Vec<u8>>, Option<HttpBodyEnd>) {
5478 let mut chunks = Vec::new();
5579 for item in response.body {
5680 match item {
57 HttpBodyItem::Chunk(chunk) => chunks.push((start.elapsed(), chunk.bytes)),
81 HttpBodyItem::Chunk(chunk) => chunks.push(chunk.bytes),
5882 HttpBodyItem::End(end) => return (chunks, Some(end)),
5983 }
6084 }
7498#[test]
7599fn chunks_arrive_incrementally() {
76100 let executor = UreqHttpExecutor::new();
77 let port = spawn_server(serve_events);
78 let start = Instant::now();
101 let (gate, serve) = serve_events();
102 let port = spawn_server(serve);
79103 let response = post(&executor, port, CancelHandle::new());
80104 assert_eq!(response.head.status, 200);
81 let (arrivals, end) = drain(response, start);
82 assert_eq!(end, Some(HttpBodyEnd::Complete));
83 let body: Vec<u8> = arrivals.iter().flat_map(|(_, b)| b.clone()).collect();
84 assert_eq!(body, EVENTS.concat().as_bytes());
85 let first = arrivals.first().unwrap().0;
86 let last = arrivals.last().unwrap().0;
87 assert!(first < EVENT_GAP, "first chunk at {first:?}");
88 assert!(
89 last - first >= EVENT_GAP * 3 / 2,
90 "chunks bunched ({first:?}..{last:?})"
105 // Each event arrives before the server may send the next: a buffering
106 // client would stall here instead.
107 for (index, event) in EVENTS.iter().enumerate() {
108 if index > 0 {
109 gate.send(()).unwrap();
110 }
111 assert_eq!(next_item(&response), chunk(event));
112 }
113 assert_eq!(
114 next_item(&response),
115 HttpBodyItem::End(HttpBodyEnd::Complete)
91116 );
94119#[test]
95120fn cancel_after_first_chunk_stops_the_reader() {
96121 let executor = UreqHttpExecutor::new();
97 let port = spawn_server(serve_events);
122 let (gate, serve) = serve_events();
123 let port = spawn_server(serve);
98124 let cancel = CancelHandle::new();
99125 let response = post(&executor, port, cancel.clone());
100 let first = response.body.recv().unwrap();
101 assert_eq!(
102 first,
103 HttpBodyItem::Chunk(smith::http::HttpChunk {
104 bytes: EVENTS[0].as_bytes().to_vec()
105 })
106 );
126 assert_eq!(next_item(&response), chunk(EVENTS[0]));
107127 cancel.cancel();
108 let cancelled_at = Instant::now();
109128 // The reader delivers nothing read after cancellation and ends the body
110 // once its in-flight read returns: within one event gap.
111 let next = response.body.recv_timeout(EVENT_GAP * 2);
112 let stopped = cancelled_at.elapsed();
113 assert_eq!(next, Ok(HttpBodyItem::End(HttpBodyEnd::Cancelled)));
129 // once its in-flight read returns, which the next event forces.
130 gate.send(()).unwrap();
114131 assert_eq!(
115 response.body.recv_timeout(EVENT_GAP),
132 next_item(&response),
133 HttpBodyItem::End(HttpBodyEnd::Cancelled)
134 );
135 assert_eq!(
136 response.body.recv_timeout(DEADLINE),
116137 Err(RecvTimeoutError::Disconnected)
117138 );
118 assert!(stopped < EVENT_GAP * 3 / 2, "stopped after {stopped:?}");
121141#[test]
132152 }
133153 });
134154 let response = post(&executor, port, CancelHandle::new());
135 let (chunks, end) = drain(response, Instant::now());
136 let received: u64 = chunks.iter().map(|(_, b)| b.len() as u64).sum();
155 let (chunks, end) = drain(response);
156 let received: u64 = chunks.iter().map(|b| b.len() as u64).sum();
137157 assert_eq!(
138158 end,
139159 Some(HttpBodyEnd::Truncated {
147167#[test]
148168fn ureq_gap_timeout_ends_a_stalled_body() {
149169 let gap = Duration::from_millis(300);
150 let executor = UreqHttpExecutor::with_timeouts(Duration::from_secs(5), gap);
151 let port = spawn_server(|socket| {
170 let executor = UreqHttpExecutor::with_timeouts(DEADLINE, gap);
171 let (release, stalled) = mpsc::sync_channel::<()>(1);
172 let port = spawn_server(move |socket| {
152173 let head = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n";
153174 let _ = socket.write_all(head.as_bytes());
154 // Keep streaming for longer than `gap` in total, but stall once.
155 for pause in [100, 100, 100, 1_000] {
175 // Keep streaming for longer than `gap` in total, then stall once.
176 for _ in 0..3 {
156177 let _ = socket.write_all(b"2\r\nok\r\n");
157 std::thread::sleep(Duration::from_millis(pause));
178 // keep-with-deadline: fixture pacing below `gap`; sleeps last at least this long.
179 std::thread::sleep(gap / 3);
158180 }
181 let _ = socket.write_all(b"2\r\nok\r\n");
182 stall(&stalled);
159183 let _ = socket.write_all(b"5\r\nlate!\r\n0\r\n\r\n");
160184 });
161185 let start = Instant::now();
162186 let response = post(&executor, port, CancelHandle::new());
163 let (chunks, end) = drain(response, start);
164 let body: Vec<u8> = chunks.into_iter().flat_map(|(_, b)| b).collect();
187 let (chunks, end) = drain(response);
165188 let ended = start.elapsed();
189 let _ = release.send(());
190 let body: Vec<u8> = chunks.into_iter().flatten().collect();
166191 assert_eq!(body, b"okokokok");
167192 assert!(
168193 matches!(end, Some(HttpBodyEnd::Failed { .. })),
169194 "stalled body ended with {end:?}"
170195 );
171 assert!(ended >= Duration::from_millis(600), "ended at {ended:?}");
172 assert!(ended < Duration::from_millis(1_000), "ended at {ended:?}");
196 // keep-with-deadline: time is the contract; the stream outlived `gap`
197 // in total, and the stall failed long before its release.
198 assert!(ended >= gap * 2, "ended at {ended:?}");
199 assert!(ended < DEADLINE / 2, "ended at {ended:?}");
175202#[test]
176203fn ureq_head_timeout_fails_the_exchange() {
177204 let head = Duration::from_millis(300);
178 let executor = UreqHttpExecutor::with_timeouts(head, Duration::from_secs(5));
179 let port = spawn_server(|_| std::thread::sleep(Duration::from_secs(2)));
205 let executor = UreqHttpExecutor::with_timeouts(head, DEADLINE);
206 let (release, stalled) = mpsc::sync_channel::<()>(1);
207 let port = spawn_server(move |_| stall(&stalled));
180208 let exchange = HttpExchange {
181209 method: HttpMethod::Post,
182210 url: format!("http://127.0.0.1:{port}/"),
186214 let start = Instant::now();
187215 let result = executor.execute(exchange, CancelHandle::new());
188216 let failed = start.elapsed();
217 let _ = release.send(());
189218 assert!(result.is_err());
190 assert!(failed < Duration::from_secs(1), "failed at {failed:?}");
219 // keep-with-deadline: time is the contract; failed at `head`, long before the stall's release.
220 assert!(failed < DEADLINE / 2, "failed at {failed:?}");

smith-rpc/src/lib.rs

Modified

+70 / −37 text lines

7272 .collect()
7373 }
75 /// Block up to `timeout` for the next response line.
76 ///
77 /// The deterministic settle signal for callers that must wait: pair a
78 /// `wait` request with this receive instead of polling [`Self::is_settled`].
79 #[must_use]
80 pub fn recv_line(&self, timeout: std::time::Duration) -> Option<String> {
81 let response = self.responses.recv_timeout(timeout).ok()?;
82 response.to_line().ok()
83 }
7585 /// Whether no prompt is currently running.
7686 #[must_use]
7787 pub fn is_settled(&self) -> bool {
348358 use smith_harness::mock_text_reply;
349359 use smith_harness::runtime::{RuntimeConfig, build_agent};
350360 use std::sync::atomic::Ordering;
351 use std::time::{Duration, Instant};
361 use std::time::Duration;
363 /// Upper bound on any single wait for the worker; generous for loaded CI.
364 const DEADLINE: Duration = Duration::from_secs(10);
353366 fn state() -> RpcState {
354367 static NEXT_DIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
368381 .collect()
369382 }
371 fn complete(state: &mut RpcState, input: &str) -> Vec<serde_json::Value> {
372 let mut output = handle_line(state, input);
373 let deadline = Instant::now() + Duration::from_secs(2);
374 while !state.is_settled() && Instant::now() < deadline {
375 output.extend(state.drain_lines());
376 std::thread::sleep(Duration::from_millis(1));
384 /// The next response record, or a failure once `DEADLINE` passes.
385 fn next(state: &RpcState) -> serde_json::Value {
386 let line = state.recv_line(DEADLINE);
387 assert!(
388 line.is_some(),
389 "worker answered nothing within {DEADLINE:?}"
390 );
391 serde_json::from_str(line.unwrap_or_default().trim()).unwrap()
392 }
394 /// Every record before the answer to the `wait` with `id`.
395 fn until_waited(state: &RpcState, id: &serde_json::Value) -> Vec<serde_json::Value> {
396 let mut records = Vec::new();
397 loop {
398 let record = next(state);
399 if record["id"] == *id {
400 assert_eq!(record["settled"], true);
401 return records;
402 }
403 records.push(record);
377404 }
378 output.extend(state.drain_lines());
379 values(&output)
405 }
407 fn complete(state: &mut RpcState, input: &str) -> Vec<serde_json::Value> {
408 let mut records = values(&handle_line(state, input));
409 // synchronize: a `wait` queued behind the prompt answers only after the turn settled.
410 assert!(handle_line(state, r#"{"id": "settle", "method": "wait"}"#).is_empty());
411 records.extend(until_waited(state, &serde_json::json!("settle")));
412 assert!(state.is_settled());
413 records
380414 }
382416 #[test]
420454 #[test]
421455 fn active_prompt_reports_busy_aborts_waits_and_can_restart() {
422 let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
423 let stream_calls = Arc::clone(&calls);
456 let stream_calls = std::sync::atomic::AtomicUsize::new(0);
457 let (started_tx, started) = mpsc::sync_channel::<()>(1);
458 let (release, release_rx) = mpsc::sync_channel::<()>(1);
459 let release_rx = Arc::new(std::sync::Mutex::new(release_rx));
424460 let stream: StreamFn = Arc::new(move |_request, cancel| {
425 if stream_calls.fetch_add(1, Ordering::Relaxed) == 0 {
426 let item = std::iter::once_with(move || {
427 while !cancel.is_cancelled() {
428 std::thread::sleep(Duration::from_millis(1));
429 }
430 Err(smith::error::SmithError::Cancelled)
431 });
432 futures::stream::iter(item).boxed()
433 } else {
434 futures::stream::iter(mock_text_reply("restarted").into_iter().map(Ok)).boxed()
461 if stream_calls.fetch_add(1, Ordering::Relaxed) > 0 {
462 return futures::stream::iter(mock_text_reply("restarted").into_iter().map(Ok))
463 .boxed();
435464 }
465 let _ = started_tx.send(());
466 let release_rx = Arc::clone(&release_rx);
467 let items = std::iter::once_with(move || {
468 // synchronize: the turn holds until the test has aborted it.
469 let released = release_rx
470 .lock()
471 .is_ok_and(|rx| rx.recv_timeout(DEADLINE).is_ok());
472 if released && cancel.is_cancelled() {
473 vec![Err(smith::error::SmithError::Cancelled)]
474 } else {
475 mock_text_reply("not aborted").into_iter().map(Ok).collect()
476 }
477 })
478 .flatten();
479 futures::stream::iter(items).boxed()
436480 });
437481 let tools = ToolSession::new(std::env::temp_dir());
438482 let mut state = RpcState::new(Agent::new(stream, tools, "mock-smith"));
442486 r#"{"id": 1, "method": "prompt", "params": {"input": "block"}}"#,
443487 ));
444488 assert_eq!(start[0]["event"], "start");
445 let started_deadline = Instant::now() + Duration::from_secs(2);
446 while calls.load(Ordering::Acquire) == 0 && Instant::now() < started_deadline {
447 std::thread::sleep(Duration::from_millis(1));
448 }
449 assert_eq!(calls.load(Ordering::Acquire), 1);
489 // synchronize: the provider call is the signal that the turn runs.
490 assert_eq!(started.recv_timeout(DEADLINE), Ok(()));
450491 let status = values(&handle_line(&mut state, r#"{"id": 2, "method": "status"}"#));
451492 assert_eq!(status[0]["settled"], false);
452493 let busy = values(&handle_line(
457498 assert!(handle_line(&mut state, r#"{"id": 4, "method": "wait"}"#).is_empty());
458499 let abort = values(&handle_line(&mut state, r#"{"id": 5, "method": "abort"}"#));
459500 assert_eq!(abort[0]["aborting"], true);
501 release.send(()).unwrap();
461 let deadline = Instant::now() + Duration::from_secs(2);
462 let mut deferred = Vec::new();
463 while (!state.is_settled() || deferred.len() < 2) && Instant::now() < deadline {
464 deferred.extend(values(&state.drain_lines()));
465 std::thread::sleep(Duration::from_millis(1));
466 }
503 let deferred = until_waited(&state, &serde_json::json!(4));
467504 assert!(deferred.iter().any(|record| {
468505 record["id"] == 1
469506 && record["event"] == "end"
470507 && record["error"]["code"] == "TURN_FAILED"
471508 }));
472 assert!(
473 deferred
474 .iter()
475 .any(|record| record["id"] == 4 && record["settled"] == true)
476 );
509 assert!(state.is_settled());
478511 let restarted = complete(
479512 &mut state,