repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

test(e2e): core eval and rpc workflows through the binary

b0e908b7492707f9fc480c0c2862b94ae4b90e57

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (4)

+389 / −0 text lines

Diff layout

Cargo.lock

Modified

+1 / −0 text lines

17701770 "serde_json",
17711771 "smith",
17721772 "smith-alloc",
1773 "smith-core",
17731774 "smith-harness",
17741775 "smith-rpc",

smith-cli/Cargo.toml

Modified

+1 / −0 text lines

2121archunit = { workspace = true }
2222assert_cmd = { workspace = true }
2323predicates = { workspace = true }
24smith-core = { path = "../smith-core", version = "0.1.0" }

smith-cli/tests/e2e_eval.rs

Added
new file mode 100644

+100 / −0 text lines

1//! End-to-end `smith eval` workflows through the built binary
2//! (`SMH-SPEC-SPEC0001`, Interface modes: Eval).
3
4use assert_cmd::Command;
5use smith_core::trace::build_trace;
6use smith_core::{Session, TraceRecord, load_session};
7use std::path::{Path, PathBuf};
8
9const MOCK_REPLY: &str = "mock provider: no model configured";
11/// A fresh data home per test; stale runs never leak into assertions.
12fn scratch(name: &str) -> PathBuf {
13 let dir = std::env::temp_dir().join(format!("smith-eval-test-{name}-{}", std::process::id()));
14 let _ = std::fs::remove_dir_all(&dir);
15 dir
16}
18fn smith(data_home: &Path) -> Command {
19 let mut command = Command::cargo_bin("smith").unwrap();
20 command
21 .env("XDG_DATA_HOME", data_home)
22 .env_remove("SMITH_PROVIDER")
23 .env_remove("SMITH_MODEL")
24 .env_remove("SMITH_BASE_URL")
25 .env_remove("ANTHROPIC_API_KEY")
26 .env_remove("OPENAI_API_KEY")
27 .env_remove("GEMINI_API_KEY");
28 command
29}
31fn eval_session(data_home: &Path) -> PathBuf {
32 data_home.join("smith/sessions/run/eval.smh")
33}
35/// Decode the session file the binary left behind into its trace.
36fn trace_of(path: &Path) -> Vec<TraceRecord> {
37 let recovery =
38 load_session(path, smith::config::Config::default_valid().max_frame_bytes).unwrap();
39 assert!(recovery.damage.is_empty(), "{:?}", recovery.damage);
40 assert_eq!(recovery.torn_tail_at, None);
41 build_trace(&Session::from_frames(&recovery.frames).unwrap())
42}
44#[test]
45fn eval_mock_turn_prints_the_reply() {
46 let home = scratch("text");
47 smith(&home)
48 .args(["eval", "--mock", "hello"])
49 .assert()
50 .success()
51 .stdout(format!("{MOCK_REPLY}\n"))
52 .stderr("");
53}
55#[test]
56fn eval_json_reports_text_reason_and_cost() {
57 let home = scratch("json");
58 let output = smith(&home)
59 .args(["eval", "--mock", "--json", "hello"])
60 .output()
61 .unwrap();
62 assert!(output.status.success());
63 let stdout = String::from_utf8(output.stdout).unwrap();
64 assert_eq!(stdout.lines().count(), 1, "{stdout}");
65 let report: serde_json::Value = serde_json::from_str(&stdout).unwrap();
66 assert_eq!(
67 report,
68 serde_json::json!({
69 "text": MOCK_REPLY,
70 "reason": "EndTurn",
71 "cost": {"input_tokens": 0, "output_tokens": 0},
72 })
73 );
74}
76#[test]
77fn second_eval_appends_to_the_same_session_and_keeps_the_first_trace() {
78 let home = scratch("resume");
79 let session = eval_session(&home);
81 smith(&home)
82 .args(["eval", "--mock", "first"])
83 .assert()
84 .success();
85 let first_len = std::fs::metadata(&session).unwrap().len();
86 let first_trace = trace_of(&session);
87 assert!(first_trace.len() > 1, "{first_trace:?}");
89 smith(&home)
90 .args(["eval", "--mock", "second"])
91 .assert()
92 .success()
93 .stdout(format!("{MOCK_REPLY}\n"));
94 let second_len = std::fs::metadata(&session).unwrap().len();
95 let second_trace = trace_of(&session);
97 assert!(second_len > first_len, "{second_len} <= {first_len}");
98 assert!(second_trace.len() > first_trace.len());
99 assert_eq!(second_trace[..first_trace.len()], first_trace[..]);
100}

smith-cli/tests/e2e_rpc.rs

Added
new file mode 100644

+287 / −0 text lines

1//! End-to-end `smith rpc` workflows over piped standard input and output
2//! (`SMH-SPEC-SPEC0001`, Interface modes: JSON-RPC).
3//!
4//! Every read waits on a line or end of output with a deadline; nothing
5//! sleeps or polls.
6
7use serde_json::{Value, json};
8use std::io::{BufRead, BufReader, Read, Write};
9use std::net::TcpListener;
10use std::process::{Child, ChildStdin, Command, Stdio};
11use std::sync::mpsc::{self, Receiver};
12use std::time::Duration;
14const DEADLINE: Duration = Duration::from_secs(10);
15const MOCK_REPLY: &str = "rpc mock provider ready";
17/// One running `smith rpc` process; killed on drop if a test fails early.
18struct Rpc {
19 child: Child,
20 stdin: Option<ChildStdin>,
21 /// Parsed stdout lines; `None` marks end of output.
22 lines: Receiver<Option<Value>>,
23}
25impl Rpc {
26 fn spawn(name: &str, args: &[&str], envs: &[(&str, &str)]) -> Self {
27 let home =
28 std::env::temp_dir().join(format!("smith-rpc-test-{name}-{}", std::process::id()));
29 let _ = std::fs::remove_dir_all(&home);
30 let mut child = Command::new(assert_cmd::cargo::cargo_bin("smith"))
31 .arg("rpc")
32 .args(args)
33 .env("XDG_DATA_HOME", &home)
34 .env_remove("SMITH_PROVIDER")
35 .env_remove("SMITH_MODEL")
36 .env_remove("SMITH_BASE_URL")
37 .env_remove("ANTHROPIC_API_KEY")
38 .env_remove("OPENAI_API_KEY")
39 .env_remove("GEMINI_API_KEY")
40 .envs(envs.iter().copied())
41 .stdin(Stdio::piped())
42 .stdout(Stdio::piped())
43 .stderr(Stdio::null())
44 .spawn()
45 .unwrap();
46 let stdout = child.stdout.take().unwrap();
47 let (sender, lines) = mpsc::channel();
48 std::thread::spawn(move || {
49 for line in BufReader::new(stdout).lines() {
50 let line = line.unwrap();
51 let value = serde_json::from_str(&line)
52 .unwrap_or_else(|error| panic!("stdout line is not JSON ({error}): {line}"));
53 if sender.send(Some(value)).is_err() {
54 return;
55 }
56 }
57 let _ = sender.send(None);
58 });
59 let stdin = child.stdin.take();
60 Self {
61 child,
62 stdin,
63 lines,
64 }
65 }
67 fn mock(name: &str) -> Self {
68 Self::spawn(name, &[], &[])
69 }
71 fn send(&mut self, line: &str) {
72 let stdin = self.stdin.as_mut().unwrap();
73 stdin.write_all(line.as_bytes()).unwrap();
74 stdin.write_all(b"\n").unwrap();
75 stdin.flush().unwrap();
76 }
78 fn next(&self) -> Value {
79 match self.lines.recv_timeout(DEADLINE) {
80 Ok(Some(value)) => value,
81 Ok(None) => panic!("rpc output ended early"),
82 Err(error) => panic!("no rpc line within {DEADLINE:?}: {error}"),
83 }
84 }
86 /// Close stdin, then expect end of output and the exit status.
87 fn close(mut self) -> std::process::ExitStatus {
88 drop(self.stdin.take());
89 match self.lines.recv_timeout(DEADLINE) {
90 Ok(None) => {}
91 Ok(Some(value)) => panic!("unexpected rpc line after close: {value}"),
92 Err(error) => panic!("rpc did not end output within {DEADLINE:?}: {error}"),
93 }
94 self.child.wait().unwrap()
95 }
96}
98impl Drop for Rpc {
99 fn drop(&mut self) {
100 if matches!(self.child.try_wait(), Ok(None)) {
101 let _ = self.child.kill();
102 let _ = self.child.wait();
103 }
104 }
105}
107#[test]
108fn rpc_ping_correlates_the_request_id() {
109 let mut rpc = Rpc::mock("ping");
110 rpc.send(r#"{"id": 7, "method": "ping"}"#);
111 assert_eq!(rpc.next(), json!({"id": 7, "pong": true}));
112 rpc.send(r#"{"id": "seven", "method": "ping"}"#);
113 assert_eq!(rpc.next(), json!({"id": "seven", "pong": true}));
114 assert!(rpc.close().success());
115}
117#[test]
118fn rpc_prompt_streams_start_delta_end_then_wait_and_status_report_settled() {
119 let mut rpc = Rpc::mock("prompt");
120 rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "hi"}}"#);
121 rpc.send(r#"{"id": 2, "method": "wait"}"#);
122 assert_eq!(rpc.next(), json!({"id": 1, "event": "start"}));
123 assert_eq!(
124 rpc.next(),
125 json!({"id": 1, "event": "delta", "text": MOCK_REPLY})
126 );
127 assert_eq!(
128 rpc.next(),
129 json!({
130 "id": 1,
131 "event": "end",
132 "text": MOCK_REPLY,
133 "reason": "EndTurn",
134 "cost": {"input_tokens": 0, "output_tokens": 0},
135 })
136 );
137 // The worker answers `wait` only after the prompt has settled.
138 assert_eq!(rpc.next(), json!({"id": 2, "settled": true}));
139 // `wait` answers once the aborted turn has settled; `status` then agrees.
140 rpc.send(r#"{"id": 3, "method": "wait"}"#);
141 assert_eq!(rpc.next(), json!({"id": 3, "settled": true}));
142 rpc.send(r#"{"id": 4, "method": "status"}"#);
143 assert_eq!(rpc.next(), json!({"id": 4, "settled": true}));
144 assert!(rpc.close().success());
145}
147#[test]
148fn rpc_malformed_line_reports_parse_error_with_null_id() {
149 let mut rpc = Rpc::mock("malformed");
150 rpc.send("not json");
151 let record = rpc.next();
152 assert_eq!(record["id"], Value::Null);
153 assert_eq!(record["error"]["code"], "PARSE");
154 // The server keeps serving after a bad line.
155 rpc.send(r#"{"id": 1, "method": "ping"}"#);
156 assert_eq!(rpc.next(), json!({"id": 1, "pong": true}));
157 assert!(rpc.close().success());
158}
160#[test]
161fn rpc_unknown_method_reports_method_unknown() {
162 let mut rpc = Rpc::mock("unknown");
163 rpc.send(r#"{"id": "x", "method": "explode"}"#);
164 assert_eq!(
165 rpc.next(),
166 json!({
167 "id": "x",
168 "error": {"code": "METHOD_UNKNOWN", "message": "unknown method explode"},
169 })
170 );
171 assert!(rpc.close().success());
172}
174#[test]
175fn rpc_closing_stdin_after_settle_exits_zero() {
176 let mut rpc = Rpc::mock("shutdown");
177 rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "hi"}}"#);
178 rpc.send(r#"{"id": 2, "method": "wait"}"#);
179 let mut records = Vec::new();
180 loop {
181 let record = rpc.next();
182 let done = record["id"] == 2;
183 records.push(record);
184 if done {
185 break;
186 }
187 }
188 assert!(records.iter().any(|r| r["id"] == 1 && r["event"] == "end"));
189 let status = rpc.close();
190 assert_eq!(status.code(), Some(0));
191}
193/// A loopback provider endpoint that holds its response: it reports each
194/// received request, then answers only when released.
195struct StalledProvider {
196 url: String,
197 received: Receiver<()>,
198 release: mpsc::Sender<()>,
199}
201impl StalledProvider {
202 fn start() -> Self {
203 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
204 let url = format!("http://{}", listener.local_addr().unwrap());
205 let (received_tx, received) = mpsc::channel();
206 let (release, release_rx) = mpsc::channel::<()>();
207 std::thread::spawn(move || {
208 let Ok((stream, _)) = listener.accept() else {
209 return;
210 };
211 let mut reader = BufReader::new(stream);
212 let mut length = 0;
213 loop {
214 let mut header = String::new();
215 if reader.read_line(&mut header).unwrap_or(0) == 0 {
216 return;
217 }
218 let header = header.trim_end();
219 if header.is_empty() {
220 break;
221 }
222 if let Some((name, value)) = header.split_once(':')
223 && name.eq_ignore_ascii_case("content-length")
224 {
225 length = value.trim().parse().unwrap();
226 }
227 }
228 let mut body = vec![0; length];
229 reader.read_exact(&mut body).unwrap();
230 let _ = received_tx.send(());
231 if release_rx.recv().is_err() {
232 return;
233 }
234 let chunk = json!({"choices": [{"index": 0, "delta": {"content": "late"}}]});
235 let response = format!(
236 "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\ndata: {chunk}\n\n"
237 );
238 let _ = reader.get_mut().write_all(response.as_bytes());
239 });
240 Self {
241 url,
242 received,
243 release,
244 }
245 }
246}
248#[test]
249fn rpc_abort_ends_the_running_prompt_with_turn_failed() {
250 let provider = StalledProvider::start();
251 let mut rpc = Rpc::spawn(
252 "abort",
253 &[
254 "--provider",
255 "openai",
256 "--model",
257 "e2e-model",
258 "--base-url",
259 &provider.url,
260 ],
261 &[("OPENAI_API_KEY", "sk-e2e-fixture")],
262 );
263 rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "block"}}"#);
264 assert_eq!(rpc.next(), json!({"id": 1, "event": "start"}));
265 provider
266 .received
267 .recv_timeout(DEADLINE)
268 .expect("provider request within the deadline");
270 rpc.send(r#"{"id": 2, "method": "abort"}"#);
271 assert_eq!(rpc.next(), json!({"id": 2, "aborting": true}));
272 provider.release.send(()).unwrap();
274 let end = rpc.next();
275 assert_eq!(end["id"], 1);
276 assert_eq!(end["event"], "end");
277 assert_eq!(end["error"]["code"], "TURN_FAILED");
278 assert_eq!(end["error"]["message"], "operation cancelled");
279 assert!(end.get("text").is_none(), "{end}");
281 // `wait` answers once the aborted turn has settled; `status` then agrees.
282 rpc.send(r#"{"id": 3, "method": "wait"}"#);
283 assert_eq!(rpc.next(), json!({"id": 3, "settled": true}));
284 rpc.send(r#"{"id": 4, "method": "status"}"#);
285 assert_eq!(rpc.next(), json!({"id": 4, "settled": true}));
286 assert!(rpc.close().success());
287}