test(e2e): core eval and rpc workflows through the binary
b0e908b7492707f9fc480c0c2862b94ae4b90e57
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 6f5ecb2e2a96
There are many coding harnesses - but this one is fast
b0e908b7492707f9fc480c0c2862b94ae4b90e57
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+389 / −0 text lines
+1 / −0 text lines
+1 / −0 text lines
new file mode 100644+100 / −0 text lines
//! End-to-end `smith eval` workflows through the built binary//! (`SMH-SPEC-SPEC0001`, Interface modes: Eval).use assert_cmd::Command;use smith_core::trace::build_trace;use smith_core::{Session, TraceRecord, load_session};use std::path::{Path, PathBuf};const MOCK_REPLY: &str = "mock provider: no model configured";/// A fresh data home per test; stale runs never leak into assertions.fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("smith-eval-test-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); dir}fn smith(data_home: &Path) -> Command { let mut command = Command::cargo_bin("smith").unwrap(); command .env("XDG_DATA_HOME", data_home) .env_remove("SMITH_PROVIDER") .env_remove("SMITH_MODEL") .env_remove("SMITH_BASE_URL") .env_remove("ANTHROPIC_API_KEY") .env_remove("OPENAI_API_KEY") .env_remove("GEMINI_API_KEY"); command}fn eval_session(data_home: &Path) -> PathBuf { data_home.join("smith/sessions/run/eval.smh")}/// Decode the session file the binary left behind into its trace.fn trace_of(path: &Path) -> Vec<TraceRecord> { let recovery = load_session(path, smith::config::Config::default_valid().max_frame_bytes).unwrap(); assert!(recovery.damage.is_empty(), "{:?}", recovery.damage); assert_eq!(recovery.torn_tail_at, None); build_trace(&Session::from_frames(&recovery.frames).unwrap())}#[test]fn eval_mock_turn_prints_the_reply() { let home = scratch("text"); smith(&home) .args(["eval", "--mock", "hello"]) .assert() .success() .stdout(format!("{MOCK_REPLY}\n")) .stderr("");}#[test]fn eval_json_reports_text_reason_and_cost() { let home = scratch("json"); let output = smith(&home) .args(["eval", "--mock", "--json", "hello"]) .output() .unwrap(); assert!(output.status.success()); let stdout = String::from_utf8(output.stdout).unwrap(); assert_eq!(stdout.lines().count(), 1, "{stdout}"); let report: serde_json::Value = serde_json::from_str(&stdout).unwrap(); assert_eq!( report, serde_json::json!({ "text": MOCK_REPLY, "reason": "EndTurn", "cost": {"input_tokens": 0, "output_tokens": 0}, }) );}#[test]fn second_eval_appends_to_the_same_session_and_keeps_the_first_trace() { let home = scratch("resume"); let session = eval_session(&home); smith(&home) .args(["eval", "--mock", "first"]) .assert() .success(); let first_len = std::fs::metadata(&session).unwrap().len(); let first_trace = trace_of(&session); assert!(first_trace.len() > 1, "{first_trace:?}"); smith(&home) .args(["eval", "--mock", "second"]) .assert() .success() .stdout(format!("{MOCK_REPLY}\n")); let second_len = std::fs::metadata(&session).unwrap().len(); let second_trace = trace_of(&session); assert!(second_len > first_len, "{second_len} <= {first_len}"); assert!(second_trace.len() > first_trace.len()); assert_eq!(second_trace[..first_trace.len()], first_trace[..]);}new file mode 100644+287 / −0 text lines
//! End-to-end `smith rpc` workflows over piped standard input and output//! (`SMH-SPEC-SPEC0001`, Interface modes: JSON-RPC).//!//! Every read waits on a line or end of output with a deadline; nothing//! sleeps or polls.use serde_json::{Value, json};use std::io::{BufRead, BufReader, Read, Write};use std::net::TcpListener;use std::process::{Child, ChildStdin, Command, Stdio};use std::sync::mpsc::{self, Receiver};use std::time::Duration;const DEADLINE: Duration = Duration::from_secs(10);const MOCK_REPLY: &str = "rpc mock provider ready";/// One running `smith rpc` process; killed on drop if a test fails early.struct Rpc { child: Child, stdin: Option<ChildStdin>, /// Parsed stdout lines; `None` marks end of output. lines: Receiver<Option<Value>>,}impl Rpc { fn spawn(name: &str, args: &[&str], envs: &[(&str, &str)]) -> Self { let home = std::env::temp_dir().join(format!("smith-rpc-test-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&home); let mut child = Command::new(assert_cmd::cargo::cargo_bin("smith")) .arg("rpc") .args(args) .env("XDG_DATA_HOME", &home) .env_remove("SMITH_PROVIDER") .env_remove("SMITH_MODEL") .env_remove("SMITH_BASE_URL") .env_remove("ANTHROPIC_API_KEY") .env_remove("OPENAI_API_KEY") .env_remove("GEMINI_API_KEY") .envs(envs.iter().copied()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .unwrap(); let stdout = child.stdout.take().unwrap(); let (sender, lines) = mpsc::channel(); std::thread::spawn(move || { for line in BufReader::new(stdout).lines() { let line = line.unwrap(); let value = serde_json::from_str(&line) .unwrap_or_else(|error| panic!("stdout line is not JSON ({error}): {line}")); if sender.send(Some(value)).is_err() { return; } } let _ = sender.send(None); }); let stdin = child.stdin.take(); Self { child, stdin, lines, } } fn mock(name: &str) -> Self { Self::spawn(name, &[], &[]) } fn send(&mut self, line: &str) { let stdin = self.stdin.as_mut().unwrap(); stdin.write_all(line.as_bytes()).unwrap(); stdin.write_all(b"\n").unwrap(); stdin.flush().unwrap(); } fn next(&self) -> Value { match self.lines.recv_timeout(DEADLINE) { Ok(Some(value)) => value, Ok(None) => panic!("rpc output ended early"), Err(error) => panic!("no rpc line within {DEADLINE:?}: {error}"), } } /// Close stdin, then expect end of output and the exit status. fn close(mut self) -> std::process::ExitStatus { drop(self.stdin.take()); match self.lines.recv_timeout(DEADLINE) { Ok(None) => {} Ok(Some(value)) => panic!("unexpected rpc line after close: {value}"), Err(error) => panic!("rpc did not end output within {DEADLINE:?}: {error}"), } self.child.wait().unwrap() }}impl Drop for Rpc { fn drop(&mut self) { if matches!(self.child.try_wait(), Ok(None)) { let _ = self.child.kill(); let _ = self.child.wait(); } }}#[test]fn rpc_ping_correlates_the_request_id() { let mut rpc = Rpc::mock("ping"); rpc.send(r#"{"id": 7, "method": "ping"}"#); assert_eq!(rpc.next(), json!({"id": 7, "pong": true})); rpc.send(r#"{"id": "seven", "method": "ping"}"#); assert_eq!(rpc.next(), json!({"id": "seven", "pong": true})); assert!(rpc.close().success());}#[test]fn rpc_prompt_streams_start_delta_end_then_wait_and_status_report_settled() { let mut rpc = Rpc::mock("prompt"); rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "hi"}}"#); rpc.send(r#"{"id": 2, "method": "wait"}"#); assert_eq!(rpc.next(), json!({"id": 1, "event": "start"})); assert_eq!( rpc.next(), json!({"id": 1, "event": "delta", "text": MOCK_REPLY}) ); assert_eq!( rpc.next(), json!({ "id": 1, "event": "end", "text": MOCK_REPLY, "reason": "EndTurn", "cost": {"input_tokens": 0, "output_tokens": 0}, }) ); // The worker answers `wait` only after the prompt has settled. assert_eq!(rpc.next(), json!({"id": 2, "settled": true})); // `wait` answers once the aborted turn has settled; `status` then agrees. rpc.send(r#"{"id": 3, "method": "wait"}"#); assert_eq!(rpc.next(), json!({"id": 3, "settled": true})); rpc.send(r#"{"id": 4, "method": "status"}"#); assert_eq!(rpc.next(), json!({"id": 4, "settled": true})); assert!(rpc.close().success());}#[test]fn rpc_malformed_line_reports_parse_error_with_null_id() { let mut rpc = Rpc::mock("malformed"); rpc.send("not json"); let record = rpc.next(); assert_eq!(record["id"], Value::Null); assert_eq!(record["error"]["code"], "PARSE"); // The server keeps serving after a bad line. rpc.send(r#"{"id": 1, "method": "ping"}"#); assert_eq!(rpc.next(), json!({"id": 1, "pong": true})); assert!(rpc.close().success());}#[test]fn rpc_unknown_method_reports_method_unknown() { let mut rpc = Rpc::mock("unknown"); rpc.send(r#"{"id": "x", "method": "explode"}"#); assert_eq!( rpc.next(), json!({ "id": "x", "error": {"code": "METHOD_UNKNOWN", "message": "unknown method explode"}, }) ); assert!(rpc.close().success());}#[test]fn rpc_closing_stdin_after_settle_exits_zero() { let mut rpc = Rpc::mock("shutdown"); rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "hi"}}"#); rpc.send(r#"{"id": 2, "method": "wait"}"#); let mut records = Vec::new(); loop { let record = rpc.next(); let done = record["id"] == 2; records.push(record); if done { break; } } assert!(records.iter().any(|r| r["id"] == 1 && r["event"] == "end")); let status = rpc.close(); assert_eq!(status.code(), Some(0));}/// A loopback provider endpoint that holds its response: it reports each/// received request, then answers only when released.struct StalledProvider { url: String, received: Receiver<()>, release: mpsc::Sender<()>,}impl StalledProvider { fn start() -> Self { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); let (received_tx, received) = mpsc::channel(); let (release, release_rx) = mpsc::channel::<()>(); std::thread::spawn(move || { let Ok((stream, _)) = listener.accept() else { return; }; let mut reader = BufReader::new(stream); let mut length = 0; loop { let mut header = String::new(); if reader.read_line(&mut header).unwrap_or(0) == 0 { return; } let header = header.trim_end(); if header.is_empty() { break; } if let Some((name, value)) = header.split_once(':') && name.eq_ignore_ascii_case("content-length") { length = value.trim().parse().unwrap(); } } let mut body = vec![0; length]; reader.read_exact(&mut body).unwrap(); let _ = received_tx.send(()); if release_rx.recv().is_err() { return; } let chunk = json!({"choices": [{"index": 0, "delta": {"content": "late"}}]}); let response = format!( "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\ndata: {chunk}\n\n" ); let _ = reader.get_mut().write_all(response.as_bytes()); }); Self { url, received, release, } }}#[test]fn rpc_abort_ends_the_running_prompt_with_turn_failed() { let provider = StalledProvider::start(); let mut rpc = Rpc::spawn( "abort", &[ "--provider", "openai", "--model", "e2e-model", "--base-url", &provider.url, ], &[("OPENAI_API_KEY", "sk-e2e-fixture")], ); rpc.send(r#"{"id": 1, "method": "prompt", "params": {"input": "block"}}"#); assert_eq!(rpc.next(), json!({"id": 1, "event": "start"})); provider .received .recv_timeout(DEADLINE) .expect("provider request within the deadline"); rpc.send(r#"{"id": 2, "method": "abort"}"#); assert_eq!(rpc.next(), json!({"id": 2, "aborting": true})); provider.release.send(()).unwrap(); let end = rpc.next(); assert_eq!(end["id"], 1); assert_eq!(end["event"], "end"); assert_eq!(end["error"]["code"], "TURN_FAILED"); assert_eq!(end["error"]["message"], "operation cancelled"); assert!(end.get("text").is_none(), "{end}"); // `wait` answers once the aborted turn has settled; `status` then agrees. rpc.send(r#"{"id": 3, "method": "wait"}"#); assert_eq!(rpc.next(), json!({"id": 3, "settled": true})); rpc.send(r#"{"id": 4, "method": "status"}"#); assert_eq!(rpc.next(), json!({"id": 4, "settled": true})); assert!(rpc.close().success());}