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 / tests / negative.rs

451 lines · 16159 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//! Negative and positive tests: fake implementations written as shell scripts.
17use prime_race::exec::execute;
18use prime_race::reference::canonical_bytes;
19use prime_race::runner::{run, verify, ImplSpec, RunArgs};
20use prime_race::validate::{validate_run, Expect, Reject, Tags};
21use serde_json::json;
22use std::collections::BTreeMap;
23use std::fs;
24use std::os::unix::fs::PermissionsExt;
25use std::path::PathBuf;
26use std::sync::atomic::{AtomicU64, Ordering};
27
28const LIMIT: u64 = 1000;
29const MIN: f64 = 1.0;
30static N: AtomicU64 = AtomicU64::new(0);
31
32fn tags() -> Tags {
33 Tags { algorithm: "base".into(), faithful: "yes".into(), bits: 1, threads: Some(1) }
34}
35
36#[derive(Clone)]
37struct Fake {
38 line: Option<String>,
39 report: Option<String>,
40 bitmap: Option<Vec<u8>>,
41 code: i32,
42}
43
44fn line(label: &str, passes: u64, elapsed: f64) -> String {
45 format!("{label};{passes};{elapsed:.6};1;algorithm=base,faithful=yes,bits=1\n")
46}
47
48fn report(label: &str, passes: u64, elapsed: f64, mode: &str) -> String {
49 json!({
50 "schema": "aien-prime-race/impl-report/v1", "impl": "fake", "label": label,
51 "algorithm": "base", "faithful": "yes", "bits": 1, "threads": 1,
52 "environment": "linux-host-cpu", "limit": LIMIT, "min_seconds": MIN, "mode": mode,
53 "passes": passes, "elapsed_s": elapsed, "status": "COMPLETE", "error": null,
54 "build": {}, "detail": {}
55 })
56 .to_string()
57}
58
59fn good() -> Fake {
60 Fake {
61 line: Some(line("aien-fake", 10, 1.5)),
62 report: Some(report("aien-fake", 10, 1.5, "timed")),
63 bitmap: Some(canonical_bytes(LIMIT)),
64 code: 0,
65 }
66}
67
68fn dir() -> PathBuf {
69 let d = std::env::temp_dir().join(format!("pr-neg-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst)));
70 fs::create_dir_all(&d).unwrap();
71 d
72}
73
74fn script(f: &Fake) -> PathBuf {
75 let d = dir();
76 let mut body = String::from(
77 "#!/bin/sh\nB=; R=\nwhile [ $# -gt 0 ]; do case \"$1\" in --bitmap-out) B=\"$2\"; shift;; --report-out) R=\"$2\"; shift;; esac; shift; done\n",
78 );
79 if let Some(b) = &f.bitmap {
80 fs::write(d.join("bm"), b).unwrap();
81 body.push_str(&format!("cp '{}' \"$B\"\n", d.join("bm").display()));
82 }
83 if let Some(r) = &f.report {
84 fs::write(d.join("rp"), r).unwrap();
85 body.push_str(&format!("cp '{}' \"$R\"\n", d.join("rp").display()));
86 }
87 if let Some(l) = &f.line {
88 fs::write(d.join("ln"), l).unwrap();
89 body.push_str(&format!("cat '{}'\n", d.join("ln").display()));
90 }
91 body.push_str(&format!("exit {}\n", f.code));
92 let p = d.join("impl.sh");
93 fs::write(&p, body).unwrap();
94 fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
95 p
96}
97// A fixture for the frozen receipt path. Timed runs report 5.5 s; `sleep_s` decides whether the
98// runner's own clock agrees (6) or contradicts the report (0). `on_timed` is extra shell run in
99// timed mode, used to disturb the quiet marker mid-run.
100fn protocol_script(sleep_s: u32, on_timed: &str) -> PathBuf {
101 let d = dir();
102 let mut timed: serde_json::Value = serde_json::from_str(&report("aien-fake", 10, 5.5, "timed")).unwrap();
103 timed["min_seconds"] = json!(5.0);
104 fs::write(d.join("timed-report"), timed.to_string()).unwrap();
105 fs::write(d.join("timed-line"), line("aien-fake", 10, 5.5)).unwrap();
106 let audit = report("aien-fake", 5, 0.2, "audit");
107 fs::write(d.join("audit-report"), audit).unwrap();
108 fs::write(d.join("audit-bitmap"), canonical_bytes(LIMIT).repeat(5)).unwrap();
109 fs::write(d.join("timed-bitmap"), canonical_bytes(LIMIT)).unwrap();
110 let body = format!(
111 "#!/bin/sh\nB= R= K=\nwhile [ $# -gt 0 ]; do case \"$1\" in --bitmap-out) B=\"$2\"; shift;; --report-out) R=\"$2\"; shift;; --audit-passes) K=\"$2\"; shift;; esac; shift; done\nif [ -n \"$K\" ]; then cp '{d}/audit-bitmap' \"$B\"; cp '{d}/audit-report' \"$R\"; else sleep {sleep_s}; {on_timed}\ncp '{d}/timed-bitmap' \"$B\"; cp '{d}/timed-report' \"$R\"; cat '{d}/timed-line'; fi\n",
112 d = d.display()
113 );
114 let p = d.join("impl.sh");
115 fs::write(&p, body).unwrap();
116 fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
117 p
118}
119
120fn frozen_args(path: PathBuf, ev: &PathBuf, quiet: &PathBuf) -> RunArgs {
121 RunArgs {
122 impls: vec![ImplSpec { name: "fake".into(), path, tags: tags() }],
123 trials: 10,
124 warmup: 1,
125 limit: LIMIT,
126 min_seconds: 5.0,
127 audit_passes: 5,
128 evidence_dir: ev.clone(),
129 sources: BTreeMap::new(),
130 builds: BTreeMap::new(),
131 runner_commit: Some("test".into()),
132 quiet_file: quiet.clone(),
133 argv: vec!["prime_race".into()],
134 }
135}
136
137fn scratch() -> (PathBuf, PathBuf) {
138 let ev = std::env::temp_dir().join(format!("pr-ev-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst)));
139 let quiet = ev.with_extension("quiet");
140 (ev, quiet)
141}
142
143fn check(f: &Fake, audit: Option<u32>) -> Result<(), Reject> {
144 let p = script(f);
145 let ex = execute(&p, LIMIT, MIN, audit).unwrap();
146 let exp = Expect { name: "fake".into(), limit: LIMIT, min_seconds: MIN, audit, tags: tags() };
147 validate_run(&exp, &ex).map(|_| ())
148}
149
150fn with_bitmap(mut f: Fake, edit: impl FnOnce(&mut Vec<u8>)) -> Fake {
151 edit(f.bitmap.as_mut().unwrap());
152 f
153}
154
155fn kind(r: Result<(), Reject>) -> String {
156 r.expect_err("must be rejected").kind().to_string()
157}
158
159fn bit(b: &mut [u8], k: usize) {
160 b[k / 8] ^= 1 << (k % 8);
161}
162
163#[test]
164fn correct_fake_passes() {
165 check(&good(), None).unwrap();
166}
167
168#[test]
169fn wrong_bit() {
170 let f = with_bitmap(good(), |b| bit(b, 10)); // 21
171 match check(&f, None).unwrap_err() {
172 Reject::BitmapDiff(d) => assert_eq!((d.odd, d.tail, d.expected_prime), (21, false, false)),
173 e => panic!("{e}"),
174 }
175}
176
177#[test]
178fn missing_prime() {
179 let f = with_bitmap(good(), |b| bit(b, 498)); // 997 cleared
180 match check(&f, None).unwrap_err() {
181 Reject::BitmapDiff(d) => assert_eq!((d.odd, d.expected_prime), (997, true)),
182 e => panic!("{e}"),
183 }
184}
185
186#[test]
187fn extra_composite() {
188 let f = with_bitmap(good(), |b| bit(b, 499)); // 999 set
189 match check(&f, None).unwrap_err() {
190 Reject::BitmapDiff(d) => assert_eq!((d.odd, d.expected_prime), (999, false)),
191 e => panic!("{e}"),
192 }
193}
194
195#[test]
196fn tail_garbage() {
197 let f = with_bitmap(good(), |b| bit(b, 505));
198 match check(&f, None).unwrap_err() {
199 Reject::BitmapDiff(d) => assert!(d.tail),
200 e => panic!("{e}"),
201 }
202}
203
204#[test]
205fn truncated_bitmap() {
206 let f = with_bitmap(good(), |b| {
207 b.truncate(b.len() - 8);
208 });
209 assert_eq!(kind(check(&f, None)), "bitmap_length");
210}
211
212#[test]
213fn all_zero_and_all_ones() {
214 let z = with_bitmap(good(), |b| b.iter_mut().for_each(|x| *x = 0));
215 assert_eq!(kind(check(&z, None)), "bitmap_diff");
216 let o = with_bitmap(good(), |b| b.iter_mut().for_each(|x| *x = 0xff));
217 assert_eq!(kind(check(&o, None)), "bitmap_diff");
218}
219
220fn audit_fake(stale: bool) -> Fake {
221 audit_fake_k(stale, 3)
222}
223
224fn audit_fake_k(stale: bool, k: u64) -> Fake {
225 let one = canonical_bytes(LIMIT);
226 let mut all = vec![];
227 for i in 0..k {
228 let mut b = one.clone();
229 if stale && i == 1 {
230 bit(&mut b, 10);
231 }
232 all.extend(b);
233 }
234 Fake {
235 line: None,
236 report: Some(report("aien-fake", k, 0.2, "audit")),
237 bitmap: Some(all),
238 code: 0,
239 }
240}
241
242#[test]
243fn audit_good_and_stale_pass() {
244 check(&audit_fake(false), Some(3)).unwrap();
245 match check(&audit_fake(true), Some(3)).unwrap_err() {
246 Reject::AuditPassDiff { pass, .. } => assert_eq!(pass, 1),
247 e => panic!("{e}"),
248 }
249}
250
251#[test]
252fn exit_code_2() {
253 let mut f = good();
254 f.code = 2;
255 assert_eq!(kind(check(&f, None)), "exit_code");
256}
257
258#[test]
259fn no_stdout_line() {
260 let mut f = good();
261 f.line = None;
262 assert_eq!(kind(check(&f, None)), "no_stdout_line");
263}
264
265#[test]
266fn two_lines() {
267 let mut f = good();
268 let l = f.line.clone().unwrap();
269 f.line = Some(format!("{l}{l}"));
270 assert_eq!(kind(check(&f, None)), "multiple_stdout_lines");
271}
272
273#[test]
274fn malformed_line() {
275 let mut f = good();
276 f.line = Some("aien-fake;10;1.5;1;algorithm=base,faithful=yes,bits=1\n".into());
277 assert_eq!(kind(check(&f, None)), "malformed_line");
278}
279
280#[test]
281fn passes_zero() {
282 let mut f = good();
283 f.line = Some(line("aien-fake", 0, 1.5));
284 f.report = Some(report("aien-fake", 0, 1.5, "timed"));
285 assert_eq!(kind(check(&f, None)), "passes_zero");
286}
287
288#[test]
289fn elapsed_below_min() {
290 let mut f = good();
291 f.line = Some(line("aien-fake", 10, 0.5));
292 f.report = Some(report("aien-fake", 10, 0.5, "timed"));
293 assert_eq!(kind(check(&f, None)), "elapsed_below_min");
294}
295
296#[test]
297fn line_report_mismatch() {
298 let mut f = good();
299 f.report = Some(report("aien-fake", 11, 1.5, "timed"));
300 assert_eq!(kind(check(&f, None)), "line_report_mismatch");
301}
302
303#[test]
304fn label_mismatch() {
305 let mut f = good();
306 f.line = Some(line("aien-other", 10, 1.5));
307 f.report = Some(report("aien-other", 10, 1.5, "timed"));
308 assert_eq!(kind(check(&f, None)), "label_mismatch");
309 // Tags that differ from the declaration are also label mismatches.
310 let mut g = good();
311 g.line = Some("aien-fake;10;1.500000;1;algorithm=other,faithful=yes,bits=1\n".into());
312 assert_eq!(kind(check(&g, None)), "label_mismatch");
313}
314
315#[test]
316fn failed_status_rejected() {
317 let mut f = good();
318 f.report = Some(report("aien-fake", 10, 1.5, "timed").replace("COMPLETE", "EXEC_FAILED"));
319 assert_eq!(kind(check(&f, None)), "status_not_complete");
320}
321
322#[test]
323fn verify_subcommand_logic_and_run_receipt() {
324 // verify: the fake always emits the LIMIT=1000 bitmap, so only that limit can pass.
325 let mut f = audit_fake(false);
326 f.report = Some(report("aien-fake", 3, 0.2, "audit"));
327 let p = script(&f);
328 let spec = ImplSpec { name: "fake".into(), path: p, tags: tags() };
329 let out = verify(&spec, &[LIMIT], 3);
330 assert!(out.failures.is_empty());
331 let out = verify(&spec, &[LIMIT + 2], 3);
332 assert_eq!(out.failures.len(), 1);
333
334 // run is a qualification command, not an audit-only smoke command.
335 // A valid audit with no timed trials must never produce a PASS receipt.
336 let ev = std::env::temp_dir().join(format!("pr-ev-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst)));
337 let args = RunArgs {
338 impls: vec![spec],
339 trials: 0,
340 warmup: 0,
341 limit: LIMIT,
342 min_seconds: MIN,
343 audit_passes: 3,
344 evidence_dir: ev.clone(),
345 sources: BTreeMap::new(),
346 builds: BTreeMap::new(),
347 runner_commit: Some("test".into()),
348 quiet_file: "/nonexistent".into(),
349 argv: vec!["prime_race".into()],
350 };
351 assert!(run(&args).is_err(), "an audit-only run must not qualify as PASS");
352 assert!(!ev.exists(), "rejected protocol must not write a receipt");
353}
354
355#[test]
356fn frozen_run_protocol_refuses_shortcuts_and_self_reported_timing() {
357 let (ev, quiet) = scratch();
358 // No sleep: the report claims 5.5 s but the runner's clock sees milliseconds.
359 let mut args = frozen_args(protocol_script(0, ""), &ev, &quiet);
360 args.trials = 0;
361 assert!(run(&args).is_err());
362 args.trials = 10;
363 args.warmup = 0;
364 assert!(run(&args).is_err());
365 args.warmup = 1;
366 args.audit_passes = 3;
367 assert!(run(&args).is_err());
368 args.audit_passes = 5;
369 args.min_seconds = f64::NAN;
370 assert!(run(&args).is_err());
371 args.min_seconds = 1.0;
372 assert!(run(&args).is_err());
373 assert!(!ev.exists(), "invalid protocol never writes qualification evidence");
374 args.min_seconds = 5.0;
375 assert!(run(&args).err().unwrap().contains("not readable"), "missing operator marker must refuse");
376 fs::write(&quiet, "").unwrap();
377 assert!(run(&args).err().unwrap().contains("is empty"), "empty operator marker must refuse");
378 assert!(!ev.exists());
379
380 fs::write(&quiet, "offline test fixture, not proof of exclusive hardware").unwrap();
381 let r = run(&args).unwrap();
382 assert!(!r.pass, "self-reported elapsed time must not qualify: {}", r.summary);
383 let v: serde_json::Value = serde_json::from_str(&fs::read_to_string(&r.receipt_path).unwrap()).unwrap();
384 assert_eq!(v["verdict"], "FAIL");
385 assert!(v["reason"].as_str().unwrap().contains("wall_clock_short"), "{}", v["reason"]);
386 assert!(v["summary"].is_null());
387 let _ = fs::remove_dir_all(&ev);
388 let _ = fs::remove_file(&quiet);
389}
390
391#[test]
392fn frozen_run_passes_when_runner_clock_agrees() {
393 // Real-time control: 11 timed runs of 6 s each, so this test takes about a minute.
394 let (ev, quiet) = scratch();
395 fs::write(&quiet, "offline test fixture, not proof of exclusive hardware").unwrap();
396 let r = run(&frozen_args(protocol_script(6, ""), &ev, &quiet)).unwrap();
397 assert!(r.pass, "{}", r.summary);
398 let v: serde_json::Value = serde_json::from_str(&fs::read_to_string(&r.receipt_path).unwrap()).unwrap();
399 assert_eq!(v["verdict"], "PASS");
400 assert_eq!(v["protocol"]["trials"], 10);
401 assert!(v["summary"]["fake"].is_object());
402 let marker = "offline test fixture, not proof of exclusive hardware";
403 assert_eq!(v["conditions"]["quiet_flag_contents"], marker);
404 assert_eq!(v["conditions"]["quiet_flag_contents_at_end"], marker);
405 assert!(v["conditions"]["quiet_flag_semantics"].as_str().unwrap().contains("not verified"));
406 for t in v["trials"].as_array().unwrap().iter().filter(|t| t["kind"] == "trial") {
407 assert!(t["wall_s"].as_f64().unwrap() >= 5.0, "{t}");
408 }
409 let _ = fs::remove_dir_all(&ev);
410 let _ = fs::remove_file(&quiet);
411}
412
413#[test]
414fn frozen_run_fails_when_quiet_marker_changes_mid_run() {
415 let (ev, quiet) = scratch();
416 fs::write(&quiet, "window A").unwrap();
417 let disturb = format!("printf 'window B' > '{}'", quiet.display());
418 let r = run(&frozen_args(protocol_script(6, &disturb), &ev, &quiet)).unwrap();
419 assert!(!r.pass);
420 let v: serde_json::Value = serde_json::from_str(&fs::read_to_string(&r.receipt_path).unwrap()).unwrap();
421 assert_eq!(v["verdict"], "FAIL");
422 assert!(v["reason"].as_str().unwrap().contains("removed or changed"), "{}", v["reason"]);
423 assert_eq!(v["conditions"]["quiet_flag_contents"], "window A");
424 assert_eq!(v["conditions"]["quiet_flag_contents_at_end"], "window B");
425 assert!(v["summary"].is_null());
426 let _ = fs::remove_dir_all(&ev);
427 let _ = fs::remove_file(&quiet);
428}
429
430#[test]
431fn run_failure_keeps_evidence_and_no_stats() {
432 // A stale second audit pass under the frozen K=5 must fail at the audit, through `run`.
433 let (ev, quiet) = scratch();
434 fs::write(&quiet, "offline fixture").unwrap();
435 let r = run(&frozen_args(script(&audit_fake_k(true, 5)), &ev, &quiet)).unwrap();
436 assert!(!r.pass);
437 let v: serde_json::Value = serde_json::from_str(&fs::read_to_string(&r.receipt_path).unwrap()).unwrap();
438 assert_eq!(v["verdict"], "FAIL");
439 assert!(v["reason"].as_str().unwrap().contains("audit_pass_diff"), "{}", v["reason"]);
440 assert!(v["summary"].is_null());
441 assert!(fs::read_dir(ev.join("blobs")).unwrap().count() > 0);
442 let _ = fs::remove_dir_all(&ev);
443 let _ = fs::remove_file(&quiet);
444}
445
446#[test]
447fn audit_rejects_stdout_line() {
448 let mut f = audit_fake(false);
449 f.line = Some(line("aien-fake", 3, 0.2));
450 assert_eq!(kind(check(&f, Some(3))), "audit_stdout_line");
451}