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 / prime-drag-race / src / validate.rs

426 lines · 16461 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//! Strict validation of one implementation run against the canonical result.
17use super::exec::Executed;
18use super::reference::{self, Diff};
19use super::REPORT_SCHEMA;
20use serde_json::Value;
21
22#[derive(Debug, Clone, PartialEq)]
23pub struct Line {
24 pub label: String,
25 pub passes: u64,
26 pub elapsed_text: String,
27 pub elapsed: f64,
28 pub threads: u64,
29 pub algorithm: String,
30 pub faithful: String,
31 pub bits: u64,
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct Tags {
36 pub algorithm: String,
37 pub faithful: String,
38 pub bits: u64,
39 pub threads: Option<u64>,
40}
41
42impl Tags {
43 /// "algorithm=base,faithful=yes,bits=1[,threads=1]"
44 pub fn parse(text: &str) -> Result<Tags, String> {
45 let (mut a, mut f, mut b, mut t) = (None, None, None, None);
46 for kv in text.split(',') {
47 let (k, v) = kv.split_once('=').ok_or_else(|| format!("bad tag {kv}"))?;
48 match k {
49 "algorithm" => a = Some(v.to_string()),
50 "faithful" => f = Some(v.to_string()),
51 "bits" => b = Some(v.parse::<u64>().map_err(|_| format!("bad bits {v}"))?),
52 "threads" => t = Some(v.parse::<u64>().map_err(|_| format!("bad threads {v}"))?),
53 _ => return Err(format!("unknown tag {k}")),
54 }
55 }
56 Ok(Tags {
57 algorithm: a.ok_or("missing algorithm")?,
58 faithful: f.ok_or("missing faithful")?,
59 bits: b.ok_or("missing bits")?,
60 threads: t,
61 })
62 }
63}
64
65#[derive(Debug, Clone)]
66pub struct Expect {
67 /// Implementation name N: the stdout label must be `aien-N`, report impl must be N.
68 pub name: String,
69 pub limit: u64,
70 pub min_seconds: f64,
71 pub audit: Option<u32>,
72 pub tags: Tags,
73}
74
75impl Expect {
76 pub fn line_label(&self) -> String {
77 format!("aien-{}", self.name)
78 }
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub enum Reject {
83 Spawn(String),
84 ExitCode(Option<i32>),
85 NoStdoutLine,
86 AuditStdoutLine,
87 MultipleStdoutLines(usize),
88 MalformedLine(String),
89 ReportMissing,
90 BadReport(String),
91 StatusNotComplete(String),
92 LabelMismatch(String),
93 LineReportMismatch(String),
94 PassesZero,
95 ElapsedBelowMin { elapsed: f64, min: f64 },
96 /// The runner's own monotonic wall clock contradicts the implementation's report.
97 WallClockShort { wall: f64, elapsed: f64, min: f64 },
98 AuditPassCount { got: u64, want: u32 },
99 BitmapMissing,
100 BitmapLength { got: usize, want: usize },
101 BitmapDiff(Diff),
102 AuditPassDiff { pass: usize, diff: Diff },
103}
104
105impl Reject {
106 pub fn kind(&self) -> &'static str {
107 match self {
108 Reject::Spawn(_) => "spawn_error",
109 Reject::ExitCode(_) => "exit_code",
110 Reject::NoStdoutLine => "no_stdout_line",
111 Reject::AuditStdoutLine => "audit_stdout_line",
112 Reject::MultipleStdoutLines(_) => "multiple_stdout_lines",
113 Reject::MalformedLine(_) => "malformed_line",
114 Reject::ReportMissing => "report_missing",
115 Reject::BadReport(_) => "bad_report",
116 Reject::StatusNotComplete(_) => "status_not_complete",
117 Reject::LabelMismatch(_) => "label_mismatch",
118 Reject::LineReportMismatch(_) => "line_report_mismatch",
119 Reject::PassesZero => "passes_zero",
120 Reject::ElapsedBelowMin { .. } => "elapsed_below_min",
121 Reject::WallClockShort { .. } => "wall_clock_short",
122 Reject::AuditPassCount { .. } => "audit_pass_count",
123 Reject::BitmapMissing => "bitmap_missing",
124 Reject::BitmapLength { .. } => "bitmap_length",
125 Reject::BitmapDiff(_) => "bitmap_diff",
126 Reject::AuditPassDiff { .. } => "audit_pass_diff",
127 }
128 }
129}
130
131impl std::fmt::Display for Reject {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 write!(f, "{}: ", self.kind())?;
134 match self {
135 Reject::Spawn(e) | Reject::MalformedLine(e) | Reject::BadReport(e) | Reject::LabelMismatch(e)
136 | Reject::LineReportMismatch(e) | Reject::StatusNotComplete(e) => write!(f, "{e}"),
137 Reject::ExitCode(c) => write!(f, "exit code {c:?}, expected 0"),
138 Reject::NoStdoutLine => write!(f, "no result line on stdout"),
139 Reject::AuditStdoutLine => write!(f, "audit mode printed a stdout line; audit runs make no timing claim"),
140 Reject::MultipleStdoutLines(n) => write!(f, "{n} lines on stdout, expected exactly one"),
141 Reject::ReportMissing => write!(f, "report file not written"),
142 Reject::PassesZero => write!(f, "passes is 0"),
143 Reject::ElapsedBelowMin { elapsed, min } => write!(f, "elapsed {elapsed} is below min_seconds {min}"),
144 Reject::WallClockShort { wall, elapsed, min } => {
145 write!(f, "runner wall time {wall} is below reported elapsed {elapsed} or min_seconds {min}")
146 }
147 Reject::AuditPassCount { got, want } => write!(f, "audit passes {got}, wanted {want}"),
148 Reject::BitmapMissing => write!(f, "bitmap file not written"),
149 Reject::BitmapLength { got, want } => write!(f, "bitmap is {got} bytes, expected {want}"),
150 Reject::BitmapDiff(d) => write!(f, "{d}"),
151 Reject::AuditPassDiff { pass, diff } => write!(f, "audit pass {pass}: {diff}"),
152 }
153 }
154}
155
156#[derive(Debug, Clone)]
157pub struct Validated {
158 pub passes: u64,
159 pub elapsed: f64,
160 /// The upstream line; `None` in audit mode, which prints no line.
161 pub line: Option<Line>,
162 pub report: Value,
163}
164
165/// Strict parse of `<label>;<passes>;<elapsed %.6f>;<threads>;algorithm=..,faithful=..,bits=..`.
166pub fn parse_line(s: &str) -> Result<Line, String> {
167 let parts: Vec<&str> = s.split(';').collect();
168 if parts.len() != 5 {
169 return Err(format!("expected 5 ';' fields, found {}", parts.len()));
170 }
171 let label = parts[0];
172 if label.is_empty() || label.chars().any(|c| c.is_whitespace() || c == ',' || c == '=') {
173 return Err("bad label".into());
174 }
175 let uint = |t: &str, what: &str| -> Result<u64, String> {
176 if t.is_empty() || !t.bytes().all(|b| b.is_ascii_digit()) || (t.len() > 1 && t.starts_with('0')) {
177 return Err(format!("bad {what} '{t}'"));
178 }
179 t.parse::<u64>().map_err(|_| format!("bad {what} '{t}'"))
180 };
181 let passes = uint(parts[1], "passes")?;
182 let el = parts[2];
183 let ok = match el.split_once('.') {
184 Some((i, d)) => {
185 !i.is_empty() && i.bytes().all(|b| b.is_ascii_digit()) && d.len() == 6 && d.bytes().all(|b| b.is_ascii_digit())
186 }
187 None => false,
188 };
189 if !ok {
190 return Err(format!("elapsed '{el}' is not %.6f"));
191 }
192 let elapsed: f64 = el.parse().map_err(|_| "bad elapsed".to_string())?;
193 let threads = uint(parts[3], "threads")?;
194 let tags: Vec<&str> = parts[4].split(',').collect();
195 if tags.len() != 3 {
196 return Err("tags must be algorithm,faithful,bits".into());
197 }
198 let tag = |t: &str, key: &str| -> Result<String, String> {
199 t.strip_prefix(&format!("{key}="))
200 .filter(|v| !v.is_empty() && !v.contains('='))
201 .map(String::from)
202 .ok_or_else(|| format!("expected tag {key}=.. got '{t}'"))
203 };
204 let algorithm = tag(tags[0], "algorithm")?;
205 let faithful = tag(tags[1], "faithful")?;
206 if faithful != "yes" && faithful != "no" {
207 return Err(format!("faithful must be yes or no, got '{faithful}'"));
208 }
209 let bits = uint(&tag(tags[2], "bits")?, "bits")?;
210 Ok(Line {
211 label: label.to_string(),
212 passes,
213 elapsed_text: el.to_string(),
214 elapsed,
215 threads,
216 algorithm,
217 faithful,
218 bits,
219 })
220}
221
222fn rs(v: &Value, k: &str) -> Result<String, Reject> {
223 v.get(k)
224 .and_then(Value::as_str)
225 .map(String::from)
226 .ok_or_else(|| Reject::BadReport(format!("field {k} missing or not a string")))
227}
228fn ru(v: &Value, k: &str) -> Result<u64, Reject> {
229 v.get(k)
230 .and_then(Value::as_u64)
231 .ok_or_else(|| Reject::BadReport(format!("field {k} missing or not an unsigned integer")))
232}
233fn rf(v: &Value, k: &str) -> Result<f64, Reject> {
234 v.get(k)
235 .and_then(Value::as_f64)
236 .ok_or_else(|| Reject::BadReport(format!("field {k} missing or not a number")))
237}
238fn rfaithful(v: &Value) -> Result<String, Reject> {
239 match v.get("faithful") {
240 Some(Value::Bool(b)) => Ok(if *b { "yes" } else { "no" }.into()),
241 Some(Value::String(s)) => Ok(s.clone()),
242 _ => Err(Reject::BadReport("field faithful missing".into())),
243 }
244}
245
246fn mismatch<T: std::fmt::Debug + PartialEq>(what: &str, a: T, b: T) -> Result<(), Reject> {
247 if a == b {
248 Ok(())
249 } else {
250 Err(Reject::LineReportMismatch(format!("{what}: line {a:?}, report {b:?}")))
251 }
252}
253
254pub fn validate_run(exp: &Expect, ex: &Executed) -> Result<Validated, Reject> {
255 if ex.exit_code != Some(0) {
256 return Err(Reject::ExitCode(ex.exit_code));
257 }
258 let text = std::str::from_utf8(&ex.stdout).map_err(|_| Reject::MalformedLine("stdout is not UTF-8".into()))?;
259 // Timed mode prints exactly one upstream line. Audit mode makes no timing claim and must
260 // print nothing on stdout; its labels are checked from the report alone.
261 let line = match exp.audit {
262 Some(_) => {
263 if !text.is_empty() {
264 return Err(Reject::AuditStdoutLine);
265 }
266 None
267 }
268 None => {
269 if text.is_empty() {
270 return Err(Reject::NoStdoutLine);
271 }
272 let body = text.strip_suffix('\n').unwrap_or(text);
273 let n = body.split('\n').count();
274 if n != 1 {
275 return Err(Reject::MultipleStdoutLines(n));
276 }
277 Some(parse_line(body).map_err(Reject::MalformedLine)?)
278 }
279 };
280
281 let raw = ex.report.as_ref().ok_or(Reject::ReportMissing)?;
282 let rep: Value = serde_json::from_slice(raw).map_err(|e| Reject::BadReport(format!("not JSON: {e}")))?;
283 if rs(&rep, "schema")? != REPORT_SCHEMA {
284 return Err(Reject::BadReport("wrong schema".into()));
285 }
286 let status = rs(&rep, "status")?;
287 if status != "COMPLETE" {
288 return Err(Reject::StatusNotComplete(format!("status {status}")));
289 }
290 let r_impl = rs(&rep, "impl")?;
291 let r_label = rs(&rep, "label")?;
292 let r_alg = rs(&rep, "algorithm")?;
293 let r_faith = rfaithful(&rep)?;
294 let r_bits = ru(&rep, "bits")?;
295 let r_threads = ru(&rep, "threads")?;
296 let r_limit = ru(&rep, "limit")?;
297 let r_mode = rs(&rep, "mode")?;
298 let r_passes = ru(&rep, "passes")?;
299 let r_elapsed = rf(&rep, "elapsed_s")?;
300 rs(&rep, "environment")?;
301
302 // Declared expectations, checked against the report.
303 if r_impl != exp.name {
304 return Err(Reject::LabelMismatch(format!("report impl '{r_impl}', expected '{}'", exp.name)));
305 }
306 if r_label != exp.line_label() {
307 return Err(Reject::LabelMismatch(format!("report label '{r_label}', expected '{}'", exp.line_label())));
308 }
309 let t = &exp.tags;
310 if r_alg != t.algorithm || r_faith != t.faithful || r_bits != t.bits {
311 return Err(Reject::LabelMismatch(format!(
312 "tags algorithm={r_alg},faithful={r_faith},bits={r_bits} differ from declared algorithm={},faithful={},bits={}",
313 t.algorithm, t.faithful, t.bits
314 )));
315 }
316 if let Some(th) = t.threads {
317 if r_threads != th {
318 return Err(Reject::LabelMismatch(format!("threads {r_threads} differ from declared {th}")));
319 }
320 }
321 let want_mode = if exp.audit.is_some() { "audit" } else { "timed" };
322 if r_mode != want_mode {
323 return Err(Reject::BadReport(format!("mode '{r_mode}', expected '{want_mode}'")));
324 }
325 if r_limit != exp.limit {
326 return Err(Reject::BadReport(format!("limit {r_limit}, expected {}", exp.limit)));
327 }
328
329 // The upstream line must equal the report field for field.
330 if let Some(line) = &line {
331 if line.label != r_label {
332 return Err(Reject::LabelMismatch(format!("line label '{}' differs from report label '{r_label}'", line.label)));
333 }
334 if line.algorithm != t.algorithm || line.faithful != t.faithful || line.bits != t.bits {
335 return Err(Reject::LabelMismatch(format!(
336 "line tags algorithm={},faithful={},bits={} differ from declared",
337 line.algorithm, line.faithful, line.bits
338 )));
339 }
340 mismatch("passes", line.passes, r_passes)?;
341 mismatch("threads", line.threads, r_threads)?;
342 mismatch("algorithm", line.algorithm.as_str(), r_alg.as_str())?;
343 mismatch("faithful", line.faithful.as_str(), r_faith.as_str())?;
344 mismatch("bits", line.bits, r_bits)?;
345 if (line.elapsed - r_elapsed).abs() > 5.1e-7 {
346 return Err(Reject::LineReportMismatch(format!("elapsed: line {}, report {r_elapsed}", line.elapsed_text)));
347 }
348 }
349
350 if r_passes == 0 {
351 return Err(Reject::PassesZero);
352 }
353 match exp.audit {
354 None => {
355 if !(r_elapsed >= exp.min_seconds) {
356 return Err(Reject::ElapsedBelowMin { elapsed: r_elapsed, min: exp.min_seconds });
357 }
358 let ms = rf(&rep, "min_seconds")?;
359 if (ms - exp.min_seconds).abs() > 1e-9 {
360 return Err(Reject::BadReport(format!("report min_seconds {ms}, expected {}", exp.min_seconds)));
361 }
362 }
363 Some(k) => {
364 if r_passes != k as u64 {
365 return Err(Reject::AuditPassCount { got: r_passes, want: k });
366 }
367 }
368 }
369
370 let bm = ex.bitmap.as_ref().ok_or(Reject::BitmapMissing)?;
371 let want = reference::canonical_bytes(exp.limit);
372 check_bitmap(&want, bm, exp)?;
373 Ok(Validated { passes: r_passes, elapsed: r_elapsed, line, report: rep })
374}
375
376fn check_bitmap(want: &[u8], got: &[u8], exp: &Expect) -> Result<(), Reject> {
377 let k = exp.audit.unwrap_or(1) as usize;
378 if got.len() != want.len() * k {
379 return Err(Reject::BitmapLength { got: got.len(), want: want.len() * k });
380 }
381 if want.is_empty() {
382 return Ok(());
383 }
384 for (i, chunk) in got.chunks(want.len()).enumerate() {
385 if let Some(d) = reference::first_difference(want, chunk, exp.limit) {
386 return Err(if exp.audit.is_some() { Reject::AuditPassDiff { pass: i, diff: d } } else { Reject::BitmapDiff(d) });
387 }
388 }
389 Ok(())
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 #[test]
397 fn line_ok() {
398 let l = parse_line("aien-cpu-c-base;123;5.000123;1;algorithm=base,faithful=yes,bits=1").unwrap();
399 assert_eq!((l.passes, l.threads, l.bits), (123, 1, 1));
400 }
401
402 #[test]
403 fn line_strict() {
404 for bad in [
405 "",
406 "a;1;5.000000;1",
407 "a;1;5;1;algorithm=base,faithful=yes,bits=1",
408 "a;1;5.0;1;algorithm=base,faithful=yes,bits=1",
409 "a;-1;5.000000;1;algorithm=base,faithful=yes,bits=1",
410 "a;1;5.000000;1;algorithm=base,faithful=maybe,bits=1",
411 "a;1;5.000000;1;faithful=yes,algorithm=base,bits=1",
412 "a;1;5.000000;1;algorithm=base,faithful=yes",
413 "a;1;5.000000;1;algorithm=base,faithful=yes,bits=1;x",
414 " a;1;5.000000;1;algorithm=base,faithful=yes,bits=1",
415 ] {
416 assert!(parse_line(bad).is_err(), "accepted {bad:?}");
417 }
418 }
419
420 #[test]
421 fn tags_parse() {
422 let t = Tags::parse("algorithm=base,faithful=yes,bits=1,threads=1").unwrap();
423 assert_eq!(t.threads, Some(1));
424 assert!(Tags::parse("algorithm=base").is_err());
425 }
426}