interplane.Get Omega
Read in your language

benchmarks-mv

Measurement harnesses and evidence bundles for AIEN on the NVIDIA DGX Spark GB10. Speed is reported against the machine's physical limit and my own previous run. Attachment of AienOS.

Brought by drakestapleton

branch main Branches Tags History

benchmarks-mv / tests / llm_stream_cli.rs

216 lines · 8689 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! DRA-166: `llm-stream` refuses to present an unbound record as a claim. It runs the CLI
17//! against a loopback fake server (no model, no GPU): without `--llm-binary` and
18//! `--llm-model-file` it writes the record, renames it and its samples to `*.rejected` and exits
19//! 3 naming the missing digests; with both it exits 0 and the record carries their sha256; an
20//! unreadable `--llm-binary` refuses before measuring (exit 2, no request sent). Each written run
21//! is then checked by `verify_paths` from the same root, as `bench_verify_records records` would:
22//! the bound run has no defect, the rejected files are not walked, and the unbound record under
23//! its original name has exactly the two defects the CLI named.
24
25use aien_benchmarks::evidence::verify_paths;
26use std::io::{BufRead, BufReader, Read, Write};
27use std::net::TcpListener;
28use std::path::{Path, PathBuf};
29use std::process::Command;
30use std::sync::atomic::{AtomicUsize, Ordering};
31use std::sync::Arc;
32
33const ROOT: &str = env!("CARGO_MANIFEST_DIR");
34const PARITY: &str = "tests/fixtures/records/good/evidence/parity_tokens.txt";
35const PARITY_SHA: &str = "94a2668d9e83872b4918ba6f6c4222a110991eb0db58c5c9a0cdc68ad2dcbed8";
36
37/// Serve canned SSE replies to every connection; returns the port and a request counter.
38fn fake_server() -> (u16, Arc<AtomicUsize>) {
39 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
40 let port = listener.local_addr().unwrap().port();
41 let seen = Arc::new(AtomicUsize::new(0));
42 let count = seen.clone();
43 std::thread::spawn(move || {
44 for sock in listener.incoming() {
45 let Ok(mut sock) = sock else { break };
46 count.fetch_add(1, Ordering::SeqCst);
47 let mut reader = BufReader::new(sock.try_clone().unwrap());
48 let mut len = 0usize;
49 loop {
50 let mut line = String::new();
51 if reader.read_line(&mut line).unwrap_or(0) == 0 {
52 break;
53 }
54 if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
55 len = v.trim().parse().unwrap_or(0);
56 }
57 if line == "\r\n" {
58 break;
59 }
60 }
61 let mut body = vec![0u8; len];
62 let _ = reader.read_exact(&mut body);
63 let ev = |t: &str| {
64 format!(
65 "data: {{\"choices\":[{{\"index\":0,\"delta\":{{\"content\":\"{t}\"}}}}]}}\n\n"
66 )
67 };
68 let reply = format!(
69 "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\n{}{}data: {{\"choices\":[],\"usage\":{{\"completion_tokens\":2}}}}\n\ndata: [DONE]\n\n",
70 ev("a"),
71 ev("b")
72 );
73 let _ = sock.write_all(reply.as_bytes());
74 }
75 });
76 (port, seen)
77}
78
79/// Run llm-stream from `root` (as from a repository root) with `--out-dir records`.
80fn run(port: u16, root: &Path, extra: &[&str]) -> (i32, String) {
81 std::fs::create_dir_all(root).unwrap();
82 let o = Command::new(env!("CARGO_BIN_EXE_aien-benchmarks"))
83 .current_dir(root)
84 .args([
85 "llm-stream",
86 "--llm-port",
87 &port.to_string(),
88 "--llm-requests",
89 "2",
90 "--llm-warmup",
91 "0",
92 "--llm-model",
93 "fake-model",
94 "--llm-engine",
95 "fake-engine",
96 "--out-dir",
97 "records",
98 ])
99 .args(extra)
100 .output()
101 .expect("run aien-benchmarks llm-stream");
102 (
103 o.status.code().expect("exit code"),
104 String::from_utf8_lossy(&o.stderr).into_owned(),
105 )
106}
107
108fn only_record(dir: &Path) -> serde_json::Value {
109 let recs: Vec<PathBuf> = std::fs::read_dir(dir)
110 .unwrap()
111 .map(|e| e.unwrap().path())
112 .filter(|p| {
113 p.extension().is_some_and(|e| e == "json")
114 && !p.to_string_lossy().ends_with(".samples.json")
115 })
116 .collect();
117 assert_eq!(recs.len(), 1, "one record in {}", dir.display());
118 serde_json::from_str(&std::fs::read_to_string(&recs[0]).unwrap()).unwrap()
119}
120
121#[test]
122fn llm_stream_binds_or_refuses() {
123 let (port, seen) = fake_server();
124 let base = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("llm_stream_binding");
125 let _ = std::fs::remove_dir_all(&base);
126
127 // unbound: record written, exit 3, both missing digests named, record and samples renamed
128 // to *.rejected so the records verifier no longer walks them
129 let unbound = base.join("unbound");
130 let (code, err) = run(port, &unbound, &[]);
131 assert_eq!(code, 3, "stderr: {err}");
132 assert!(
133 err.contains("backend.binary_sha256: missing"),
134 "stderr: {err}"
135 );
136 assert!(
137 err.contains("backend.model_sha256: missing"),
138 "stderr: {err}"
139 );
140 let report = verify_paths(&unbound, &["records".to_string()]);
141 assert_eq!(report.records, 0);
142 assert!(report.defects.is_empty(), "{:?}", report.defects);
143 let mut rejected: Vec<PathBuf> = std::fs::read_dir(unbound.join("records"))
144 .unwrap()
145 .map(|e| e.unwrap().path())
146 .collect();
147 rejected.sort();
148 assert_eq!(rejected.len(), 2, "{rejected:?}");
149 assert!(
150 rejected
151 .iter()
152 .all(|p| p.to_string_lossy().ends_with(".json.rejected")),
153 "{rejected:?}"
154 );
155 // the offline verifier, given the same files under their original names and the same
156 // root layout, refuses the record for the same reasons
157 let check = base.join("unbound-check");
158 std::fs::create_dir_all(check.join("records")).unwrap();
159 for p in &rejected {
160 let name = p.file_name().unwrap().to_string_lossy();
161 let name = name.strip_suffix(".rejected").unwrap();
162 std::fs::copy(p, check.join("records").join(name)).unwrap();
163 }
164 let rec = only_record(&check.join("records"));
165 assert_eq!(rec["status"], "EXPERIMENTAL");
166 assert!(rec["backend"].get("binary_sha256").is_none());
167 assert_eq!(rec["parity"]["verdict"], "NOT_RUN");
168 assert_eq!(rec["methodology"]["warmup"], 0);
169 let report = verify_paths(&check, &["records".to_string()]);
170 let lines: Vec<String> = report.defects.iter().map(|d| d.to_string()).collect();
171 assert_eq!(report.records, 1, "{lines:?}");
172 assert_eq!(lines.len(), 2, "{lines:?}");
173 assert!(
174 lines[0].contains("backend.binary_sha256: missing"),
175 "{lines:?}"
176 );
177 assert!(
178 lines[1].contains("backend.model_sha256: missing"),
179 "{lines:?}"
180 );
181
182 // bound: both digests from the named files, exit 0
183 let parity = format!("{ROOT}/{PARITY}");
184 let bound = base.join("bound");
185 let (code, err) = run(
186 port,
187 &bound,
188 &["--llm-binary", &parity, "--llm-model-file", &parity],
189 );
190 assert_eq!(code, 0, "stderr: {err}");
191 let rec = only_record(&bound.join("records"));
192 assert_eq!(rec["backend"]["binary_sha256"], PARITY_SHA);
193 assert_eq!(rec["backend"]["model_sha256"], PARITY_SHA);
194 assert!(rec["metrics"]["ttft_ms_p50"].is_number());
195 assert_eq!(rec["metrics"]["requests_ok"], 2);
196 // what llm-stream accepts, the offline verifier accepts: record and samples, no defect
197 let report = verify_paths(&bound, &["records".to_string()]);
198 let lines: Vec<String> = report.defects.iter().map(|d| d.to_string()).collect();
199 assert!(lines.is_empty(), "{lines:?}");
200 assert_eq!(report.records, 1);
201 // unreadable binary: refused before any request
202 let before = seen.load(Ordering::SeqCst);
203 let (code, err) = run(
204 port,
205 &base.join("refused"),
206 &["--llm-binary", "/nonexistent/aien-serve"],
207 );
208 assert_eq!(code, 2, "stderr: {err}");
209 assert!(err.contains("--llm-binary"), "stderr: {err}");
210 assert_eq!(
211 seen.load(Ordering::SeqCst),
212 before,
213 "no request after a refusal"
214 );
215 let _ = std::fs::remove_dir_all(&base);
216}