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 / receipt.rs

236 lines · 8438 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//! Evidence storage: content-addressed blobs and receipts (mode 0444, no overwrite).
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19use std::fs::{self, OpenOptions};
20use std::io::{self, Write};
21use std::os::unix::fs::OpenOptionsExt;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24
25/// Lowercase hex of the SHA-256 digest. sha2 0.11 returns a `hybrid_array::Array`, which has no
26/// `LowerHex` impl, so the digest is encoded here.
27pub fn sha256_hex(bytes: &[u8]) -> String {
28 const HEX: &[u8; 16] = b"0123456789abcdef";
29 let digest = Sha256::digest(bytes);
30 let mut out = String::with_capacity(2 * digest.len());
31 for &b in digest.iter() {
32 out.push(HEX[usize::from(b >> 4)] as char);
33 out.push(HEX[usize::from(b & 0x0f)] as char);
34 }
35 out
36}
37
38pub fn sha256_file(path: &Path) -> io::Result<String> {
39 Ok(sha256_hex(&fs::read(path)?))
40}
41
42fn write_new_ro(path: &Path, bytes: &[u8]) -> io::Result<()> {
43 let mut f = OpenOptions::new().write(true).create_new(true).mode(0o444).open(path)?;
44 f.write_all(bytes)?;
45 f.sync_all()
46}
47
48/// Store bytes as blobs/<sha256>; identical content is shared. Returns the digest.
49pub fn store_blob(evidence: &Path, bytes: &[u8]) -> io::Result<String> {
50 let sha = sha256_hex(bytes);
51 let p = evidence.join("blobs").join(&sha);
52 match write_new_ro(&p, bytes) {
53 Ok(()) => {}
54 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
55 Err(e) => return Err(e),
56 }
57 Ok(sha)
58}
59
60/// Write the receipt as <sha256-of-bytes>.json. Refuses to overwrite.
61pub fn write_receipt(evidence: &Path, receipt: &Value) -> io::Result<(PathBuf, String)> {
62 let mut bytes = serde_json::to_vec_pretty(receipt).map_err(io::Error::other)?;
63 bytes.push(b'\n');
64 let sha = sha256_hex(&bytes);
65 let p = evidence.join(format!("{sha}.json"));
66 write_new_ro(&p, &bytes)?;
67 Ok((p, sha))
68}
69
70fn git_toplevel(dir: &Path) -> Option<PathBuf> {
71 let o = Command::new("git").arg("-C").arg(dir).args(["rev-parse", "--show-toplevel"]).output().ok()?;
72 if !o.status.success() {
73 return None;
74 }
75 PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()).canonicalize().ok()
76}
77
78/// Resolve `dir` (which may not exist yet) and refuse anything inside this checkout.
79pub fn check_evidence_dir(dir: &Path) -> Result<PathBuf, String> {
80 let abs = if dir.is_absolute() { dir.to_path_buf() } else { std::env::current_dir().map_err(|e| e.to_string())?.join(dir) };
81 let mut existing = abs.as_path();
82 let mut rest: Vec<&std::ffi::OsStr> = vec![];
83 while !existing.exists() {
84 rest.push(existing.file_name().ok_or("bad evidence dir")?);
85 existing = existing.parent().ok_or("bad evidence dir")?;
86 }
87 let mut resolved = existing.canonicalize().map_err(|e| e.to_string())?;
88 for r in rest.into_iter().rev() {
89 resolved.push(r);
90 }
91 let root = Path::new(env!("CARGO_MANIFEST_DIR")).canonicalize().map_err(|e| e.to_string())?;
92 if resolved.starts_with(&root) {
93 return Err(format!("evidence dir {} is inside the benchmarks checkout", resolved.display()));
94 }
95 if let (Some(a), Some(b)) = (git_toplevel(existing), git_toplevel(&root)) {
96 if a == b {
97 return Err(format!("evidence dir {} is inside the benchmarks checkout", resolved.display()));
98 }
99 }
100 Ok(resolved)
101}
102
103pub struct Stats {
104 pub n: usize,
105 pub median: f64,
106 pub min: f64,
107 pub max: f64,
108 pub mean: f64,
109 pub stddev: f64,
110 pub cv: f64,
111}
112
113pub fn stats(samples: &[f64]) -> Option<Stats> {
114 if samples.is_empty() {
115 return None;
116 }
117 let mut s = samples.to_vec();
118 s.sort_by(|a, b| a.partial_cmp(b).unwrap());
119 let n = s.len();
120 let mean = s.iter().sum::<f64>() / n as f64;
121 let median = if n % 2 == 1 { s[n / 2] } else { (s[n / 2 - 1] + s[n / 2]) / 2.0 };
122 let var = if n > 1 { s.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n as f64 - 1.0) } else { 0.0 };
123 let stddev = var.sqrt();
124 Some(Stats { n, median, min: s[0], max: s[n - 1], mean, stddev, cv: if mean != 0.0 { stddev / mean } else { 0.0 } })
125}
126
127impl Stats {
128 pub fn to_json(&self) -> Value {
129 json!({"n": self.n, "median": self.median, "min": self.min, "max": self.max,
130 "mean": self.mean, "stddev": self.stddev, "cv": self.cv, "unit": "passes_per_second"})
131 }
132}
133
134fn cmd_out(prog: &str, args: &[&str]) -> Option<String> {
135 let o = Command::new(prog).args(args).output().ok()?;
136 if !o.status.success() {
137 return None;
138 }
139 Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
140}
141
142pub fn loadavg() -> String {
143 fs::read_to_string("/proc/loadavg")
144 .map(|s| s.split_whitespace().take(3).collect::<Vec<_>>().join(" "))
145 .unwrap_or_else(|_| "unavailable".into())
146}
147
148pub fn governors() -> Vec<String> {
149 let mut v: Vec<String> = vec![];
150 if let Ok(rd) = fs::read_dir("/sys/devices/system/cpu") {
151 for e in rd.flatten() {
152 if let Ok(g) = fs::read_to_string(e.path().join("cpufreq/scaling_governor")) {
153 let g = g.trim().to_string();
154 if !v.contains(&g) {
155 v.push(g);
156 }
157 }
158 }
159 }
160 v.sort();
161 v
162}
163
164pub fn hardware() -> Value {
165 let cpus: Vec<String> = cmd_out("lscpu", &[])
166 .map(|t| {
167 let mut v: Vec<String> = vec![];
168 for l in t.lines() {
169 if let Some(m) = l.strip_prefix("Model name:") {
170 let m = m.trim().to_string();
171 if !v.contains(&m) {
172 v.push(m);
173 }
174 }
175 }
176 v
177 })
178 .unwrap_or_default();
179 let gpu = cmd_out("nvidia-smi", &["--query-gpu=name,uuid,driver_version", "--format=csv,noheader"]);
180 json!({"cpu_models": cpus, "nvidia_smi": gpu, "kernel": cmd_out("uname", &["-r"])})
181}
182
183pub fn runner_commit(arg: Option<&str>) -> String {
184 if let Some(a) = arg {
185 return a.to_string();
186 }
187 if let Some(c) = option_env!("PRIME_RACE_RUNNER_COMMIT") {
188 return c.to_string();
189 }
190 cmd_out("git", &["-C", env!("CARGO_MANIFEST_DIR"), "rev-parse", "HEAD"]).unwrap_or_else(|| "unknown".into())
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn stats_basic() {
199 let s = stats(&[1.0, 2.0, 3.0, 4.0]).unwrap();
200 assert_eq!(s.median, 2.5);
201 assert_eq!((s.min, s.max, s.mean), (1.0, 4.0, 2.5));
202 assert!((s.stddev - 1.2909944487358056).abs() < 1e-12);
203 }
204
205 #[test]
206 fn sha256_hex_known_answers() {
207 // FIPS 180-2 examples; receipt and blob names depend on this exact lowercase form.
208 assert_eq!(
209 sha256_hex(b""),
210 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
211 );
212 assert_eq!(
213 sha256_hex(b"abc"),
214 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
215 );
216 }
217
218 #[test]
219 fn evidence_dir_inside_checkout_refused() {
220 let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("evidence-x");
221 assert!(check_evidence_dir(&inside).is_err());
222 assert!(check_evidence_dir(&std::env::temp_dir().join("pr-evidence-ok")).is_ok());
223 }
224
225 #[test]
226 fn receipt_noclobber_and_mode() {
227 let d = std::env::temp_dir().join(format!("pr-receipt-{}", std::process::id()));
228 fs::create_dir_all(d.join("blobs")).unwrap();
229 let v = json!({"a": 1});
230 let (p, _) = write_receipt(&d, &v).unwrap();
231 use std::os::unix::fs::PermissionsExt;
232 assert_eq!(fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o444);
233 assert!(write_receipt(&d, &v).is_err());
234 let _ = fs::remove_dir_all(&d);
235 }
236}