Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/benchmarks-mv/blob/main/prime-drag-race/src/runner.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `benchmarks-mv / prime-drag-race / src / runner.rs` 299 lines ยท 12558 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 //! `verify` (correctness sweep) and `run` (trial protocol + receipt). 17 use super::exec::{execute, Executed}; 18 use super::receipt::*; 19 use super::reference; 20 use super::validate::{validate_run, Expect, Reject, Tags, Validated}; 21 use super::{CONTRACT_VERSION, RECEIPT_SCHEMA}; 22 use serde_json::{json, Value}; 23 use std::collections::BTreeMap; 24 use std::fs; 25 use std::path::PathBuf; 26 27 #[derive(Clone)] 28 pub struct ImplSpec { 29 pub name: String, 30 pub path: PathBuf, 31 pub tags: Tags, 32 } 33 34 pub fn run_and_validate( 35 spec: &ImplSpec, 36 limit: u64, 37 min_seconds: f64, 38 audit: Option, 39 ) -> (Option, Result) { 40 let exp = Expect { name: spec.name.clone(), limit, min_seconds, audit, tags: spec.tags.clone() }; 41 match execute(&spec.path, limit, min_seconds, audit) { 42 Ok(ex) => { 43 let mut v = validate_run(&exp, &ex); 44 // Timed runs: the implementation's self-reported elapsed time must agree with the 45 // runner's own monotonic clock, which also has to meet the requested minimum. 46 if let (None, Ok(val)) = (audit, &v) { 47 if ex.wall_s < min_seconds || ex.wall_s < val.elapsed { 48 v = Err(Reject::WallClockShort { wall: ex.wall_s, elapsed: val.elapsed, min: min_seconds }); 49 } 50 } 51 (Some(ex), v) 52 } 53 Err(e) => (None, Err(Reject::Spawn(e.to_string()))), 54 } 55 } 56 57 pub struct VerifyOutcome { 58 pub checked: usize, 59 pub failures: Vec<(u64, Reject)>, 60 } 61 62 pub fn verify(spec: &ImplSpec, limits: &[u64], audit: u32) -> VerifyOutcome { 63 let mut failures = vec![]; 64 for &l in limits { 65 let (_, r) = run_and_validate(spec, l, 0.0, Some(audit)); 66 if let Err(e) = r { 67 eprintln!("FAIL limit {l}: {e}"); 68 failures.push((l, e)); 69 } 70 } 71 VerifyOutcome { checked: limits.len(), failures } 72 } 73 74 pub struct RunArgs { 75 pub impls: Vec, 76 pub trials: u32, 77 pub warmup: u32, 78 pub limit: u64, 79 pub min_seconds: f64, 80 pub audit_passes: u32, 81 pub evidence_dir: PathBuf, 82 pub sources: BTreeMap, 83 pub builds: BTreeMap, 84 pub runner_commit: Option, 85 pub quiet_file: PathBuf, 86 pub argv: Vec, 87 } 88 89 pub struct RunResult { 90 pub pass: bool, 91 pub receipt_path: PathBuf, 92 pub receipt_sha: String, 93 pub summary: String, 94 pub upstream_lines: Vec, 95 } 96 97 fn record( 98 evidence: &std::path::Path, 99 spec: &ImplSpec, 100 kind: &str, 101 index: u32, 102 limit: u64, 103 min_seconds: f64, 104 audit: Option, 105 ) -> std::io::Result<(Value, Result)> { 106 let before = loadavg(); 107 let (ex, res) = run_and_validate(spec, limit, min_seconds, audit); 108 let after = loadavg(); 109 let mut rec = json!({ 110 "impl": spec.name, "kind": kind, "index": index, "limit": limit, 111 "loadavg_before": before, "loadavg_after": after, 112 }); 113 if let Some(ex) = &ex { 114 rec["exit_code"] = json!(ex.exit_code); 115 rec["wall_s"] = json!(ex.wall_s); 116 rec["raw_line"] = json!(String::from_utf8_lossy(&ex.stdout).trim_end_matches('\n')); 117 rec["stdout_sha256"] = json!(store_blob(evidence, &ex.stdout)?); 118 rec["stderr_sha256"] = json!(store_blob(evidence, &ex.stderr)?); 119 if let Some(r) = &ex.report { 120 rec["report_sha256"] = json!(store_blob(evidence, r)?); 121 rec["report"] = serde_json::from_slice(r).unwrap_or(Value::Null); 122 } 123 if let Some(b) = &ex.bitmap { 124 rec["bitmap_sha256"] = json!(store_blob(evidence, b)?); 125 } 126 } 127 match &res { 128 Ok(v) => { 129 rec["verdict"] = json!("PASS"); 130 rec["passes"] = json!(v.passes); 131 rec["elapsed_s"] = json!(v.elapsed); 132 if audit.is_none() { 133 rec["passes_per_s"] = json!(v.passes as f64 / v.elapsed); 134 } 135 } 136 Err(e) => { 137 rec["verdict"] = json!("FAIL"); 138 rec["reject_kind"] = json!(e.kind()); 139 rec["reject_reason"] = json!(e.to_string()); 140 } 141 } 142 Ok((rec, res)) 143 } 144 145 pub fn run(a: &RunArgs) -> Result { 146 // `run` produces qualification receipts, not smoke or audit-only verdicts. 147 // Keep the frozen protocol in CONTRACT.md authoritative at the API boundary, 148 // even for callers that bypass the CLI defaults. 149 if a.impls.is_empty() || a.audit_passes != 5 || a.warmup != 1 || a.trials != 10 150 || !a.min_seconds.is_finite() || a.min_seconds < 5.0 151 { 152 return Err("qualification requires implementations, one audit (K=5), one warm-up, 10 timed trials and min_seconds >= 5".into()); 153 } 154 // A marker is necessary evidence of the operator's quiet window, not proof 155 // that the machine was actually exclusive; that remains an operator gate. 156 let quiet = fs::read_to_string(&a.quiet_file) 157 .map_err(|e| format!("quiet flag {} is not readable: {e}", a.quiet_file.display()))?; 158 let quiet_start = quiet.trim().to_string(); 159 if quiet_start.is_empty() { 160 return Err(format!("quiet flag {} is empty", a.quiet_file.display())); 161 } 162 let evidence = check_evidence_dir(&a.evidence_dir)?; 163 fs::create_dir_all(evidence.join("blobs")).map_err(|e| e.to_string())?; 164 let io = |e: std::io::Error| e.to_string(); 165 166 let mut bin_sha = BTreeMap::new(); 167 for s in &a.impls { 168 bin_sha.insert(s.name.clone(), sha256_file(&s.path).map_err(io)?); 169 } 170 let mut records: Vec = vec![]; 171 let mut samples: BTreeMap> = a.impls.iter().map(|s| (s.name.clone(), vec![])).collect(); 172 let mut failure: Option = None; 173 let mut upstream: Vec = vec![]; 174 175 let mut step = |spec: &ImplSpec, kind: &str, idx: u32, audit: Option, records: &mut Vec| -> Result, String> { 176 let (rec, res) = record(&evidence, spec, kind, idx, a.limit, a.min_seconds, audit).map_err(io)?; 177 records.push(rec.clone()); 178 match res { 179 Ok(v) => { 180 if kind == "trial" { 181 samples.get_mut(&spec.name).unwrap().push(v.passes as f64 / v.elapsed); 182 upstream.push(rec["raw_line"].as_str().unwrap_or("").to_string()); 183 } 184 Ok(None) 185 } 186 Err(e) => Ok(Some(format!("{} {kind} {idx}: {e}", spec.name))), 187 } 188 }; 189 190 'all: { 191 for s in &a.impls { 192 if let Some(f) = step(s, "audit", 0, Some(a.audit_passes), &mut records)? { 193 failure = Some(f); 194 break 'all; 195 } 196 } 197 for w in 0..a.warmup { 198 for s in &a.impls { 199 if let Some(f) = step(s, "warmup", w, None, &mut records)? { 200 failure = Some(f); 201 break 'all; 202 } 203 } 204 } 205 for t in 0..a.trials { 206 for s in &a.impls { 207 if let Some(f) = step(s, "trial", t, None, &mut records)? { 208 failure = Some(f); 209 break 'all; 210 } 211 } 212 } 213 } 214 215 // The window must still hold after the last trial: a removed or rewritten marker means the 216 // operator's quiet window did not cover the whole run, so the run cannot qualify. 217 let quiet_end = fs::read_to_string(&a.quiet_file).ok().map(|s| s.trim().to_string()); 218 if failure.is_none() && quiet_end.as_deref() != Some(quiet_start.as_str()) { 219 failure = Some(format!("quiet flag {} was removed or changed during the run", a.quiet_file.display())); 220 } 221 let pass = failure.is_none(); 222 let mut impls = serde_json::Map::new(); 223 let mut summary_json = serde_json::Map::new(); 224 let mut human = String::new(); 225 for s in &a.impls { 226 let rep = records.iter().find(|r| r["impl"] == json!(s.name) && r.get("report").is_some_and(|x| !x.is_null())); 227 let env = rep.and_then(|r| r["report"].get("environment").cloned()); 228 let det = rep.and_then(|r| r["report"].get("build").cloned()); 229 impls.insert( 230 s.name.clone(), 231 json!({ 232 "name": s.name, 233 "labels": {"line_label": format!("aien-{}", s.name), "algorithm": s.tags.algorithm, 234 "faithful": s.tags.faithful, "bits": s.tags.bits, "threads": s.tags.threads}, 235 "environment": env, 236 "binary_sha256": bin_sha[&s.name], 237 "source": a.sources.get(&s.name), 238 "build_command": a.builds.get(&s.name), 239 "build_reported_by_binary": det, 240 }), 241 ); 242 if pass { 243 if let Some(st) = stats(&samples[&s.name]) { 244 human.push_str(&format!( 245 "{:<16} median {:>12.2} min {:>12.2} max {:>12.2} mean {:>12.2} sd {:>10.2} cv {:.4} (n={})\n", 246 s.name, st.median, st.min, st.max, st.mean, st.stddev, st.cv, st.n 247 )); 248 summary_json.insert(s.name.clone(), st.to_json()); 249 } 250 } 251 } 252 let runner_sha = std::env::current_exe().ok().and_then(|p| sha256_file(&p).ok()); 253 let receipt = json!({ 254 "schema": RECEIPT_SCHEMA, 255 "contract_version": CONTRACT_VERSION, 256 "verdict": if pass { "PASS" } else { "FAIL" }, 257 "reason": failure.clone().unwrap_or_else(|| "every audit and trial validated PASS".into()), 258 "created_utc": chrono::Utc::now().to_rfc3339(), 259 "implementation": Value::Object(impls), 260 "runner": {"commit": runner_commit(a.runner_commit.as_deref()), "binary_sha256": runner_sha}, 261 "hardware": hardware(), 262 "conditions": { 263 "quiet_flag_file": a.quiet_file.display().to_string(), 264 "quiet_flag_contents": quiet_start, 265 "quiet_flag_contents_at_end": quiet_end, 266 "quiet_flag_semantics": "operator-asserted marker, checked present at start and unchanged at end; exclusivity of the machine is not verified by the runner", 267 "governors": governors(), 268 "loadavg_at_start": records.first().map(|r| r["loadavg_before"].clone()), 269 "loadavg_at_end": records.last().map(|r| r["loadavg_after"].clone()), 270 }, 271 "correctness": { 272 "reference_method": "deterministic Miller-Rabin on every odd n <= limit (bases 2,3,5,7 below `3215031751`, else first 12 primes, u128 mulmod); full bitmap compare", 273 "limit": a.limit, 274 "audit_passes": a.audit_passes, 275 "sweep": "run `prime_race verify` separately; not part of this receipt", 276 }, 277 "protocol": {"trials": a.trials, "warmup": a.warmup, "min_seconds": a.min_seconds, 278 "order": "round-robin interleaved across implementations, sequential"}, 279 "trials": records, 280 "summary": if pass { Value::Object(summary_json) } else { Value::Null }, 281 "upstream_lines": upstream, 282 "reproduction": {"runner_argv": a.argv}, 283 "nonconforming": "NONCONFORMING for upstream PlummersSoftwareLLC/Primes drag-race (pinned `a2899c96752b65ac1b08a0e1418ab7e708040ed0`): AGPL-3.0-or-later license vs required BSD-3-Clause, language eligibility. Experimental.", 284 }); 285 let (p, sha) = write_receipt(&evidence, &receipt).map_err(io)?; 286 if !pass { 287 human.push_str(&format!("FAIL: {}\n", failure.unwrap())); 288 } 289 Ok(RunResult { pass, receipt_path: p, receipt_sha: sha, summary: human, upstream_lines: upstream_clone(&receipt) }) 290 } 291 292 fn upstream_clone(r: &Value) -> Vec { 293 r["upstream_lines"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default() 294 } 295 296 /// Sanity helper used by the CLI: expected pi for a limit from the reference. 297 pub fn reference_count(limit: u64) -> u64 { 298 reference::prime_count(&reference::canonical_bytes(limit), limit) 299 }