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 / src / evidence.rs

1342 lines · 51725 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//! Offline evidence-integrity checks for benchmark records (`aien-bench-record/1`) and SHA256SUMS artifact bundles.
17//!
18//! Nothing here touches the network, a GPU or a live server: it reads files under the
19//! repository root and reports one [`Defect`] per problem (`path: field: reason`).
20//!
21//! Rules for a record (a JSON file whose `schema` is [`RECORD_SCHEMA`]):
22//! - every contract field is present with the right type; `status`, `build.profile` and
23//! `methodology.token_accounting` use their fixed vocabularies;
24//! - `source.commit` is a 40-character lowercase hex commit id;
25//! - no string anywhere is a placeholder ([`PLACEHOLDERS`], compared trimmed and case-blind);
26//! - `metrics` is non-empty and every value is a finite number; every metric key has an entry
27//! in `methodology.definitions`; `methodology.samples >= 1`;
28//! - a percentile metric (a key segment `pNN`) needs enough samples for that percentile to
29//! differ from the maximum: `ceil(100 / (100 - NN))` (p50 needs 2, p95 needs 20, p99 needs 100);
30//! - with `token_accounting == "events_not_tokens"` no metric key may claim tokens;
31//! - every `evidence` entry is a relative path that exists in the repository; only `NOT_RUN`
32//! records may have empty evidence, and they carry no evidence, no metrics and `samples == 0`;
33//! - `VERIFIED` requires `source.dirty == false`;
34//! - a claimed result ([`CLAIM_STATUSES`]: `VERIFIED`, `EXPERIMENTAL`, `FAIL`) binds what was
35//! measured: `backend.binary_sha256` and `backend.model_sha256` (64 lowercase hex; the model
36//! digest may be `none` only when `backend.model` is `none` and the backend counted no
37//! tokens), `methodology.warmup` (integer), `methodology.tolerance` (string; with a parity
38//! `PASS` or `FAIL` it may not be `none` or a stand-in such as `-`) and `parity` (`reference`, `verdict` in
39//! [`PARITY_VERDICTS`]; a `PASS` or `FAIL` verdict names an `evidence` file inside the
40//! repository whose bytes hash to `evidence_sha256`, a `NOT_RUN` verdict needs a
41//! `limitations` entry naming parity). `VERIFIED` requires parity `PASS`; a parity `FAIL`
42//! makes the record `FAIL`; a `NOT_RUN` record carries no parity result. Other statuses
43//! may omit these fields, and any present must be well formed;
44//! - [`NOT_RECORDED`] is an honest "the original run did not record this" for a fixed set of
45//! provenance fields, allowed only in `HISTORICAL` and `SUPERSEDED` records and only when a
46//! `limitations` entry names the field.
47//!
48//! A directory holding a `SHA256SUMS` file is an immutable artifact bundle: every listed file
49//! must exist and match its digest, every file in the directory must be listed, and its JSON
50//! files that are not records get only the checks they share with records (placeholders, and
51//! `*_git_sha` fields must be full commit ids). Bundles are reported, never rewritten.
52//!
53//! A raw samples file written by llm-stream (`schema` [`SAMPLES_SCHEMA`]) is evidence, not a
54//! record: it must name, in `record`, a file beside it. Any other JSON outside a bundle is a
55//! defect.
56
57use crate::harness::llm_stream::{SAMPLES_SCHEMA, WORKLOAD as LLM_WORKLOAD};
58use serde_json::Value;
59use sha2::{Digest, Sha256};
60use std::fmt;
61use std::fs;
62use std::path::{Component, Path, PathBuf};
63
64/// The record contract this module validates.
65pub const RECORD_SCHEMA: &str = "aien-bench-record/1";
66
67/// Status vocabulary, in the order the README explains it.
68pub const STATUSES: [&str; 6] = [
69 "VERIFIED",
70 "EXPERIMENTAL",
71 "HISTORICAL",
72 "NOT_RUN",
73 "FAIL",
74 "SUPERSEDED",
75];
76
77/// String values that stand in for a missing fact (compared trimmed, lowercase).
78pub const PLACEHOLDERS: [&str; 7] = ["tbd", "todo", "unknown", "n/a", "", "example", "xxx"];
79
80/// The one sanctioned value for "the original run did not record this".
81pub const NOT_RECORDED: &str = "not_recorded";
82
83/// Statuses that claim a measured result; their records must bind what was measured (DRA-166).
84pub const CLAIM_STATUSES: [&str; 3] = ["VERIFIED", "EXPERIMENTAL", "FAIL"];
85
86/// Verdicts of the output-parity check of a record (`parity.verdict`).
87pub const PARITY_VERDICTS: [&str; 3] = ["PASS", "FAIL", "NOT_RUN"];
88
89/// `backend.model` and `backend.model_sha256` of a workload that runs no model.
90pub const NO_MODEL: &str = "none";
91
92/// Fields that may hold [`NOT_RECORDED`] (HISTORICAL and SUPERSEDED records only).
93pub const NOT_RECORDED_FIELDS: [&str; 17] = [
94 "source.dirty",
95 "build.profile",
96 "build.rustc",
97 "hardware.host",
98 "hardware.cpu",
99 "hardware.gpu",
100 "backend.engine",
101 "backend.model",
102 "backend.precision",
103 "backend.endpoint",
104 "methodology.clock",
105 "methodology.token_accounting",
106 "methodology.samples",
107 "backend.binary_sha256",
108 "backend.model_sha256",
109 "methodology.warmup",
110 "methodology.tolerance",
111];
112
113const REQUIRED_STRINGS: [&str; 12] = [
114 "source.repo",
115 "source.commit",
116 "build.rustc",
117 "workload.name",
118 "hardware.host",
119 "hardware.cpu",
120 "hardware.gpu",
121 "backend.engine",
122 "backend.model",
123 "backend.precision",
124 "backend.endpoint",
125 "methodology.clock",
126];
127
128const PROFILES: [&str; 2] = ["release", "debug"];
129const TOKEN_ACCOUNTING: [&str; 2] = ["backend_usage", "events_not_tokens"];
130
131/// One problem found in one file.
132#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
133pub struct Defect {
134 pub path: String,
135 pub field: String,
136 pub reason: String,
137}
138
139impl fmt::Display for Defect {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 write!(f, "{}: {}: {}", self.path, self.field, self.reason)
142 }
143}
144
145/// Result of a run over one or more paths.
146#[derive(Debug, Default)]
147pub struct Report {
148 pub defects: Vec<Defect>,
149 pub records: usize,
150 pub bundles: usize,
151 pub bundle_files: usize,
152 /// Informational lines (for example a default directory that does not exist).
153 pub notes: Vec<String>,
154}
155
156/// Fixtures that are wrong on purpose; tests/evidence_records.rs asserts each one's defects.
157pub const BAD_FIXTURES: &str = "tests/fixtures/records/bad/";
158
159/// Every record git tracks under `root`, found from the files themselves rather than a typed
160/// directory list: each tracked JSON file whose `schema` is [`RECORD_SCHEMA`] or the samples
161/// schema or a near miss of either, and each tracked JSON file that does not read or parse,
162/// wherever it sits. [`BAD_FIXTURES`] is left out. Bundles are not discovered here:
163/// other directories also keep a `SHA256SUMS` in their own formats, and the artifact-bundle
164/// contract applies to `artifacts/`. Fails when `git ls-files` cannot run.
165pub fn tracked_targets(root: &Path) -> Result<Vec<String>, String> {
166 let out = std::process::Command::new("git")
167 .arg("-C")
168 .arg(root)
169 .args(["ls-files", "-z", "--", "*.json"])
170 .output()
171 .map_err(|e| format!("git ls-files: {e}"))?;
172 if !out.status.success() {
173 return Err(format!(
174 "git ls-files: {}",
175 String::from_utf8_lossy(&out.stderr).trim()
176 ));
177 }
178 let mut targets = Vec::new();
179 for f in out
180 .stdout
181 .split(|b| *b == 0)
182 .filter_map(|p| std::str::from_utf8(p).ok())
183 .filter(|p| !p.is_empty() && !p.starts_with(BAD_FIXTURES))
184 {
185 // A tracked JSON that cannot be read or parsed, or whose schema is a record or samples
186 // schema or a near miss of one (other case, stray spaces, another version), is a
187 // target, so `verify_paths` reports what is wrong with it instead of it being skipped
188 // without a word. Other `aien-bench-` schemas (preregistrations) are not records.
189 let wanted = match fs::read_to_string(root.join(f))
190 .ok()
191 .and_then(|t| serde_json::from_str::<Value>(&t).ok())
192 {
193 None => true,
194 Some(v) => v.get("schema").and_then(Value::as_str).is_some_and(|s| {
195 let s: String = s
196 .chars()
197 .filter(|c| !c.is_whitespace())
198 .collect::<String>()
199 .to_ascii_lowercase();
200 [RECORD_SCHEMA, SAMPLES_SCHEMA]
201 .iter()
202 .any(|k| s.starts_with(k.split('/').next().unwrap_or(k)))
203 }),
204 };
205 if wanted {
206 targets.push(f.to_string());
207 }
208 }
209 Ok(targets)
210}
211
212/// Validate every target (a file or a directory, relative to `root`).
213/// A target that does not exist is a note, not a defect, so the default `records/` may be absent.
214pub fn verify_paths(root: &Path, targets: &[String]) -> Report {
215 let mut report = Report::default();
216 for target in targets {
217 let clean = target.trim_end_matches('/');
218 let full = root.join(clean);
219 if !full.exists() {
220 report
221 .notes
222 .push(format!("{clean}: skipped: not present under the root"));
223 continue;
224 }
225 let mut files = Vec::new();
226 if full.is_dir() {
227 walk(&full, &mut files);
228 } else {
229 files.push(full.clone());
230 }
231 files.sort();
232 // Bundle directories first: their files are checked by digest.
233 let mut bundle_dirs: Vec<PathBuf> = files
234 .iter()
235 .filter(|f| f.file_name().is_some_and(|n| n == "SHA256SUMS"))
236 .filter_map(|f| f.parent().map(Path::to_path_buf))
237 .collect();
238 bundle_dirs.sort();
239 bundle_dirs.dedup();
240 for dir in &bundle_dirs {
241 report.bundles += 1;
242 report.bundle_files += check_bundle(root, dir, &mut report.defects);
243 }
244 for file in &files {
245 if file.extension().is_none_or(|e| e != "json") {
246 continue;
247 }
248 let display = display_path(root, file);
249 let in_bundle = file
250 .parent()
251 .is_some_and(|p| bundle_dirs.iter().any(|d| d == p));
252 let text = match fs::read_to_string(file) {
253 Ok(t) => t,
254 Err(e) => {
255 push(
256 &mut report.defects,
257 &display,
258 "(file)",
259 format!("cannot read: {e}"),
260 );
261 continue;
262 }
263 };
264 let value: Value = match serde_json::from_str(&text) {
265 Ok(v) => v,
266 Err(e) => {
267 push(
268 &mut report.defects,
269 &display,
270 "(file)",
271 format!("invalid JSON: {e}"),
272 );
273 continue;
274 }
275 };
276 let schema = value.get("schema").and_then(Value::as_str);
277 let is_record = schema == Some(RECORD_SCHEMA);
278 let mut found = Vec::new();
279 if is_record {
280 report.records += 1;
281 check_record(root, &display, &value, &mut found);
282 } else if in_bundle {
283 check_legacy_bundle_json(&display, &value, &mut found);
284 } else if schema == Some(SAMPLES_SCHEMA) {
285 // Raw samples are evidence of a record, not a record: they must name a record
286 // file beside them.
287 match value.get("record").and_then(Value::as_str) {
288 Some(r) if !r.contains('/') && file.with_file_name(r).is_file() => {}
289 Some(r) => push(
290 &mut found,
291 &display,
292 "record",
293 format!("\"{r}\" is not a record file beside these samples"),
294 ),
295 None => push(&mut found, &display, "record", "missing".into()),
296 }
297 } else {
298 match value.get("schema") {
299 None => push(
300 &mut found,
301 &display,
302 "schema",
303 format!(
304 "missing (not an {RECORD_SCHEMA} record and not inside a SHA256SUMS bundle)"
305 ),
306 ),
307 Some(s) => push(
308 &mut found,
309 &display,
310 "schema",
311 format!("{} is not {RECORD_SCHEMA}", s),
312 ),
313 }
314 }
315 found.sort();
316 found.dedup();
317 report.defects.extend(found);
318 }
319 }
320 report
321}
322
323/// Validate one parsed record. `path` is only used for the defect lines.
324pub fn check_record(root: &Path, path: &str, v: &Value, out: &mut Vec<Defect>) {
325 let mut d = |field: &str, reason: String| push(out, path, field, reason);
326 if !v.is_object() {
327 d("(file)", "top level is not a JSON object".into());
328 return;
329 }
330 match v.get("schema").and_then(Value::as_str) {
331 None => d("schema", "missing".into()),
332 Some(s) if s != RECORD_SCHEMA => d("schema", format!("\"{s}\" is not {RECORD_SCHEMA}")),
333 Some(_) => {}
334 }
335 let status = match v.get("status") {
336 None => {
337 d("status", "missing".into());
338 None
339 }
340 Some(Value::String(s)) if STATUSES.contains(&s.as_str()) => Some(s.as_str()),
341 Some(Value::String(s)) => {
342 d(
343 "status",
344 format!("\"{s}\" is not one of {}", STATUSES.join(", ")),
345 );
346 None
347 }
348 Some(_) => {
349 d("status", "must be a string".into());
350 None
351 }
352 };
353 let lenient = matches!(status, Some("HISTORICAL") | Some("SUPERSEDED"));
354
355 let limitations: Vec<&str> = match v.get("limitations") {
356 None => {
357 d("limitations", "missing".into());
358 Vec::new()
359 }
360 Some(Value::Array(a)) => {
361 for (i, x) in a.iter().enumerate() {
362 if !x.is_string() {
363 d(&format!("limitations[{i}]"), "must be a string".into());
364 }
365 }
366 a.iter().filter_map(Value::as_str).collect()
367 }
368 Some(_) => {
369 d("limitations", "must be an array of strings".into());
370 Vec::new()
371 }
372 };
373
374 for f in REQUIRED_STRINGS {
375 match get(v, f) {
376 None => d(f, "missing".into()),
377 Some(x) if !x.is_string() => d(f, "must be a string".into()),
378 Some(_) => {}
379 }
380 }
381 if let Some(c) = get(v, "source.commit").and_then(Value::as_str) {
382 if !is_commit(c) && !is_placeholder(c) {
383 d(
384 "source.commit",
385 format!("\"{c}\" is not a 40-character lowercase hex commit id"),
386 );
387 }
388 }
389 let dirty = match get(v, "source.dirty") {
390 None => {
391 d("source.dirty", "missing".into());
392 None
393 }
394 Some(Value::Bool(b)) => Some(*b),
395 Some(Value::String(s)) if s == NOT_RECORDED => None,
396 Some(_) => {
397 d("source.dirty", "must be true or false".into());
398 None
399 }
400 };
401 check_enum(v, "build.profile", &PROFILES, &mut d);
402 check_enum(v, "methodology.token_accounting", &TOKEN_ACCOUNTING, &mut d);
403
404 let samples = match get(v, "methodology.samples") {
405 None => {
406 d("methodology.samples", "missing".into());
407 Err(())
408 }
409 Some(Value::String(s)) if s == NOT_RECORDED => Ok(None),
410 Some(x) => match x.as_u64() {
411 Some(n) => Ok(Some(n)),
412 None => {
413 d(
414 "methodology.samples",
415 "must be a non-negative integer".into(),
416 );
417 Err(())
418 }
419 },
420 };
421
422 match get(v, "workload") {
423 Some(Value::Object(w)) => {
424 for (k, x) in w {
425 if k != "name" && !is_finite_number(x) {
426 d(&format!("workload.{k}"), "must be a finite number".into());
427 }
428 }
429 }
430 Some(_) => d("workload", "must be an object".into()),
431 None => {}
432 }
433
434 let definitions = match get(v, "methodology.definitions") {
435 None => {
436 d("methodology.definitions", "missing".into());
437 None
438 }
439 Some(Value::Object(m)) => {
440 for (k, x) in m {
441 if !x.is_string() {
442 d(
443 &format!("methodology.definitions.{k}"),
444 "must be a string".into(),
445 );
446 }
447 }
448 Some(m)
449 }
450 Some(_) => {
451 d("methodology.definitions", "must be an object".into());
452 None
453 }
454 };
455
456 let metrics = match v.get("metrics") {
457 None => {
458 d("metrics", "missing".into());
459 None
460 }
461 Some(Value::Object(m)) => Some(m),
462 Some(_) => {
463 d("metrics", "must be an object".into());
464 None
465 }
466 };
467 let token_accounting = get(v, "methodology.token_accounting").and_then(Value::as_str);
468 if let Some(m) = metrics {
469 if m.is_empty() && status.is_some_and(|s| s != "NOT_RUN") {
470 d("metrics", "is empty".into());
471 }
472 if !m.is_empty() && status == Some("NOT_RUN") {
473 d("metrics", "NOT_RUN records carry no measurements".into());
474 }
475 for (k, x) in m {
476 let field = format!("metrics.{k}");
477 if !is_finite_number(x) {
478 d(&field, "must be a finite number".into());
479 }
480 if let Some(defs) = definitions {
481 if !defs.contains_key(k) {
482 d(
483 &format!("methodology.definitions.{k}"),
484 format!("missing definition for metric {k}"),
485 );
486 }
487 }
488 if let Some(q) = percentile_of(k) {
489 let need = min_samples_for(q);
490 match samples {
491 Ok(Some(n)) if n < need => d(
492 &field,
493 format!("p{q} needs at least {need} samples, record has {n}"),
494 ),
495 Ok(None) => d(
496 &field,
497 format!("p{q} needs a recorded sample count (methodology.samples is not_recorded)"),
498 ),
499 _ => {}
500 }
501 }
502 if token_accounting == Some("events_not_tokens") && claims_tokens(k) {
503 d(
504 &field,
505 "token metric with token_accounting events_not_tokens (stream events are not tokens)"
506 .into(),
507 );
508 }
509 }
510 }
511
512 if let Ok(Some(n)) = samples {
513 if status == Some("NOT_RUN") {
514 if n != 0 {
515 d(
516 "methodology.samples",
517 "NOT_RUN records have 0 samples".into(),
518 );
519 }
520 } else if n < 1 {
521 d("methodology.samples", "must be at least 1".into());
522 }
523 }
524
525 match v.get("evidence") {
526 None => d("evidence", "missing".into()),
527 Some(Value::Array(a)) => {
528 if a.is_empty() && status.is_some_and(|s| s != "NOT_RUN") {
529 d(
530 "evidence",
531 "is empty (only NOT_RUN records may have no evidence)".into(),
532 );
533 }
534 if !a.is_empty() && status == Some("NOT_RUN") {
535 d("evidence", "NOT_RUN records carry no evidence".into());
536 }
537 for (i, x) in a.iter().enumerate() {
538 let field = format!("evidence[{i}]");
539 match x.as_str() {
540 None => d(&field, "must be a string".into()),
541 Some(e) if is_placeholder(e) => {}
542 Some(e) if !is_inside_relative(e) => d(
543 &field,
544 format!("\"{e}\" must be a relative path inside the repository"),
545 ),
546 Some(e) if !root.join(e).exists() => {
547 d(&field, format!("path does not exist: {e}"))
548 }
549 Some(e) if !resolves_inside(root, e) => d(
550 &field,
551 format!("\"{e}\" resolves outside the repository (symlink)"),
552 ),
553 Some(_) => {}
554 }
555 }
556 }
557 Some(_) => d("evidence", "must be an array of paths".into()),
558 }
559
560 if status == Some("VERIFIED") && dirty != Some(false) {
561 d("source.dirty", "VERIFIED requires dirty == false".into());
562 }
563
564 // Binding of a claimed result (DRA-166): what was measured, by content digest, with its
565 // warmup, numerical tolerance and output-parity verdict.
566 let claim = status.is_some_and(|s| CLAIM_STATUSES.contains(&s));
567 for f in ["backend.binary_sha256", "backend.model_sha256"] {
568 match get(v, f) {
569 None if claim => d(
570 f,
571 "missing (a claimed result names the sha256 of what was measured)".into(),
572 ),
573 None => {}
574 Some(Value::String(s)) if s == NOT_RECORDED || is_placeholder(s) => {}
575 Some(Value::String(s)) if f == "backend.model_sha256" && s == NO_MODEL => {
576 if get(v, "backend.model").and_then(Value::as_str) != Some(NO_MODEL) {
577 d(
578 f,
579 format!(
580 "\"{NO_MODEL}\" is allowed only when backend.model is \"{NO_MODEL}\""
581 ),
582 );
583 }
584 // Tokens counted by the backend come from a model; it must be named and bound.
585 if token_accounting == Some("backend_usage") {
586 d(
587 f,
588 format!(
589 "\"{NO_MODEL}\" with token_accounting backend_usage (tokens were counted, so a model ran)"
590 ),
591 );
592 }
593 // An LLM streaming workload always runs a model, whatever it counted.
594 if get(v, "workload.name").and_then(Value::as_str) == Some(LLM_WORKLOAD) {
595 d(
596 f,
597 format!(
598 "\"{NO_MODEL}\" with workload {LLM_WORKLOAD} (an LLM workload runs a model)"
599 ),
600 );
601 }
602 }
603 Some(Value::String(s)) if is_sha256(s) => {}
604 Some(Value::String(s)) => d(
605 f,
606 format!("\"{s}\" is not a 64-character lowercase hex sha256"),
607 ),
608 Some(_) => d(f, "must be a string".into()),
609 }
610 }
611 match get(v, "methodology.warmup") {
612 None if claim => d(
613 "methodology.warmup",
614 "missing (iterations run and discarded before measuring)".into(),
615 ),
616 None => {}
617 Some(Value::String(s)) if s == NOT_RECORDED => {}
618 Some(x) if x.as_u64().is_some() => {}
619 Some(_) => d(
620 "methodology.warmup",
621 "must be a non-negative integer".into(),
622 ),
623 }
624 match get(v, "methodology.tolerance") {
625 None if claim => d(
626 "methodology.tolerance",
627 "missing (the numerical tolerance outputs are compared with)".into(),
628 ),
629 Some(x) if !x.is_string() => d("methodology.tolerance", "must be a string".into()),
630 _ => {}
631 }
632 let parity = match v.get("parity") {
633 None => {
634 if claim {
635 d(
636 "parity",
637 "missing (output parity against a reference: reference, verdict, evidence)"
638 .into(),
639 );
640 }
641 None
642 }
643 Some(Value::Object(p)) => {
644 match p.get("reference") {
645 None => d("parity.reference", "missing".into()),
646 Some(x) if !x.is_string() => d("parity.reference", "must be a string".into()),
647 Some(_) => {}
648 }
649 let verdict = match p.get("verdict") {
650 None => {
651 d("parity.verdict", "missing".into());
652 None
653 }
654 Some(Value::String(s)) if PARITY_VERDICTS.contains(&s.as_str()) => Some(s.as_str()),
655 Some(Value::String(s)) => {
656 d(
657 "parity.verdict",
658 format!("\"{s}\" is not one of {}", PARITY_VERDICTS.join(", ")),
659 );
660 None
661 }
662 Some(_) => {
663 d("parity.verdict", "must be a string".into());
664 None
665 }
666 };
667 if matches!(verdict, Some("PASS") | Some("FAIL")) {
668 // "none", a bare mark like "-", or a phrase that says nothing was set.
669 let stand_in = |t: &str| {
670 let t = t.trim().to_ascii_lowercase();
671 t.starts_with("none")
672 || t.starts_with("no tolerance")
673 || t.starts_with("no reference")
674 || t.starts_with("unspecified")
675 || !t.chars().any(char::is_alphanumeric)
676 };
677 if p.get("reference")
678 .and_then(Value::as_str)
679 .is_some_and(stand_in)
680 {
681 d(
682 "parity.reference",
683 "a parity PASS or FAIL names what it was compared with, not \"none\" or a stand-in"
684 .into(),
685 );
686 }
687 if claim
688 && get(v, "methodology.tolerance")
689 .and_then(Value::as_str)
690 .is_some_and(stand_in)
691 {
692 d(
693 "methodology.tolerance",
694 "a parity PASS or FAIL needs a stated tolerance, not \"none\" or a stand-in"
695 .into(),
696 );
697 }
698 let want = p.get("evidence_sha256").and_then(Value::as_str);
699 match p.get("evidence").and_then(Value::as_str) {
700 None => d(
701 "parity.evidence",
702 "missing (a parity verdict names its evidence file)".into(),
703 ),
704 Some(e) if !is_inside_relative(e) => d(
705 "parity.evidence",
706 format!("\"{e}\" must be a relative path inside the repository"),
707 ),
708 Some(e) if root.join(e).exists() && !resolves_inside(root, e) => d(
709 "parity.evidence",
710 format!("\"{e}\" resolves outside the repository (symlink)"),
711 ),
712 Some(e) => match fs::read(root.join(e)) {
713 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
714 d("parity.evidence", format!("path does not exist: {e}"))
715 }
716 Err(_) if root.join(e).is_dir() => d(
717 "parity.evidence",
718 format!("{e} is a directory, not an evidence file"),
719 ),
720 Err(err) => d("parity.evidence", format!("cannot read {e}: {err}")),
721 Ok(bytes) => match want {
722 None => d("parity.evidence_sha256", "missing".into()),
723 Some(w) if !is_sha256(w) => d(
724 "parity.evidence_sha256",
725 format!("\"{w}\" is not a 64-character lowercase hex sha256"),
726 ),
727 Some(w) if hex(&Sha256::digest(&bytes)) != w => d(
728 "parity.evidence_sha256",
729 format!("does not match the bytes of {e}"),
730 ),
731 Some(_) => {}
732 },
733 },
734 }
735 } else if verdict == Some("NOT_RUN")
736 && claim
737 && !limitations.iter().any(|l| names_token(l, "parity"))
738 {
739 d(
740 "parity.verdict",
741 "NOT_RUN must be explained by a limitations entry naming parity".into(),
742 );
743 }
744 verdict
745 }
746 Some(_) => {
747 d("parity", "must be an object".into());
748 None
749 }
750 };
751 match (status, parity) {
752 (Some("VERIFIED"), Some(p)) if p != "PASS" => {
753 d("parity.verdict", "VERIFIED requires parity PASS".into())
754 }
755 (Some(s @ ("VERIFIED" | "EXPERIMENTAL")), Some("FAIL")) => d(
756 "parity.verdict",
757 format!("a parity FAIL makes the record FAIL, not {s}"),
758 ),
759 (Some("NOT_RUN"), Some("PASS" | "FAIL")) => d(
760 "parity.verdict",
761 "NOT_RUN records carry no parity result".into(),
762 ),
763 _ => {}
764 }
765
766 // Placeholders and not_recorded anywhere in the document.
767 let mut strings = Vec::new();
768 collect_strings(v, String::new(), &mut strings);
769 for (field, s) in strings {
770 if is_placeholder(&s) {
771 d(&field, format!("placeholder value \"{s}\""));
772 } else if s == NOT_RECORDED {
773 if !NOT_RECORDED_FIELDS.contains(&field.as_str()) {
774 d(&field, "not_recorded is not allowed in this field".into());
775 } else if status.is_some() && !lenient {
776 d(
777 &field,
778 "not_recorded is only allowed in HISTORICAL or SUPERSEDED records".into(),
779 );
780 } else if !limitations.iter().any(|l| names_token(l, field.as_str())) {
781 d(
782 &field,
783 "not_recorded must be explained by a limitations entry naming this field"
784 .into(),
785 );
786 }
787 }
788 }
789}
790
791/// Check one SHA256SUMS bundle directory; returns the number of files whose digest was checked.
792pub fn check_bundle(root: &Path, dir: &Path, out: &mut Vec<Defect>) -> usize {
793 let display_dir = display_path(root, dir);
794 let sums_path = dir.join("SHA256SUMS");
795 let sums_display = format!("{display_dir}/SHA256SUMS");
796 let text = match fs::read_to_string(&sums_path) {
797 Ok(t) => t,
798 Err(e) => {
799 push(out, &sums_display, "(file)", format!("cannot read: {e}"));
800 return 0;
801 }
802 };
803 let mut listed = Vec::new();
804 let mut checked = 0;
805 for (i, line) in text.lines().enumerate() {
806 if line.trim().is_empty() {
807 continue;
808 }
809 let parsed = line.split_once(char::is_whitespace).and_then(|(h, rest)| {
810 let name = rest.trim_start().trim_start_matches('*');
811 let ok = h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit());
812 (ok && !name.is_empty() && is_inside_relative(name)).then_some((h, name))
813 });
814 let Some((hash, name)) = parsed else {
815 push(
816 out,
817 &sums_display,
818 &format!("line {}", i + 1),
819 "malformed (expected <64 hex> <relative name>)".into(),
820 );
821 continue;
822 };
823 listed.push(name.to_string());
824 let file_display = format!("{display_dir}/{name}");
825 match fs::read(dir.join(name)) {
826 Err(_) => push(
827 out,
828 &file_display,
829 "SHA256SUMS",
830 "listed file is missing".into(),
831 ),
832 Ok(bytes) => {
833 checked += 1;
834 let actual = hex(&Sha256::digest(&bytes));
835 if !actual.eq_ignore_ascii_case(hash) {
836 push(
837 out,
838 &file_display,
839 "sha256",
840 "does not match SHA256SUMS".into(),
841 );
842 }
843 }
844 }
845 }
846 if let Ok(entries) = fs::read_dir(dir) {
847 let mut names: Vec<String> = entries
848 .filter_map(Result::ok)
849 .filter(|e| e.path().is_file())
850 .map(|e| e.file_name().to_string_lossy().into_owned())
851 .filter(|n| n != "SHA256SUMS")
852 .collect();
853 names.sort();
854 for n in names {
855 if !listed.contains(&n) {
856 push(
857 out,
858 &format!("{display_dir}/{n}"),
859 "SHA256SUMS",
860 "file is not listed".into(),
861 );
862 }
863 }
864 }
865 checked
866}
867
868/// Checks a pre-contract bundle JSON shares with records: no placeholders, full commit ids.
869fn check_legacy_bundle_json(path: &str, v: &Value, out: &mut Vec<Defect>) {
870 let mut strings = Vec::new();
871 collect_strings(v, String::new(), &mut strings);
872 for (field, s) in strings {
873 if is_placeholder(&s) {
874 push(out, path, &field, format!("placeholder value \"{s}\""));
875 } else if field.ends_with("_git_sha") && !is_commit(&s) {
876 push(
877 out,
878 path,
879 &field,
880 format!("\"{s}\" is not a 40-character lowercase hex commit id"),
881 );
882 }
883 }
884}
885
886fn check_enum(v: &Value, field: &str, allowed: &[&str], d: &mut impl FnMut(&str, String)) {
887 match get(v, field) {
888 None => d(field, "missing".into()),
889 Some(Value::String(s)) if s == NOT_RECORDED || allowed.contains(&s.as_str()) => {}
890 Some(Value::String(s)) if is_placeholder(s) => {}
891 Some(Value::String(s)) => d(
892 field,
893 format!("\"{s}\" is not one of {}", allowed.join(", ")),
894 ),
895 Some(_) => d(field, "must be a string".into()),
896 }
897}
898
899/// `pNN` key segment (1..=99), for example `ttft_ms_p95` -> 95.
900pub fn percentile_of(key: &str) -> Option<u64> {
901 key.split('_').find_map(|seg| {
902 let digits = seg.strip_prefix('p')?;
903 if digits.is_empty() || digits.len() > 2 || !digits.bytes().all(|b| b.is_ascii_digit()) {
904 return None;
905 }
906 let q: u64 = digits.parse().ok()?;
907 (1..=99).contains(&q).then_some(q)
908 })
909}
910
911/// Smallest sample count for which the nearest-rank `pq` is not forced to be the maximum.
912pub fn min_samples_for(q: u64) -> u64 {
913 let tail = 100 - q;
914 100_u64.div_ceil(tail)
915}
916
917/// Key segments that claim token counts or token timing (`tok`, `tokens`, `itl`); `first_token`
918/// alone is allowed because time to the first content event is still measurable.
919fn claims_tokens(key: &str) -> bool {
920 key.split('_')
921 .any(|s| matches!(s, "tok" | "tokens" | "itl"))
922}
923
924pub(crate) fn is_placeholder(s: &str) -> bool {
925 PLACEHOLDERS.contains(&s.trim().to_ascii_lowercase().as_str())
926}
927
928/// 40 lowercase hex characters.
929pub fn is_commit(s: &str) -> bool {
930 s.len() == 40 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
931}
932
933/// A SHA-256 digest written as 64 lowercase hex characters.
934pub fn is_sha256(s: &str) -> bool {
935 s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
936}
937
938fn is_finite_number(v: &Value) -> bool {
939 v.as_f64().is_some_and(f64::is_finite)
940}
941
942fn is_inside_relative(p: &str) -> bool {
943 let path = Path::new(p);
944 !p.is_empty()
945 && path
946 .components()
947 .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
948}
949
950/// `p` (already lexically inside) still lands inside `root` once symlinks are resolved.
951fn resolves_inside(root: &Path, p: &str) -> bool {
952 match (root.canonicalize(), root.join(p).canonicalize()) {
953 (Ok(r), Ok(t)) => t.starts_with(r),
954 _ => false,
955 }
956}
957
958/// `text` names `token` as a whole word: not inside a longer identifier ("comparity" does not
959/// name "parity"; "methodology.clockwork" does not name "methodology.clock").
960fn names_token(text: &str, token: &str) -> bool {
961 let ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
962 text.match_indices(token).any(|(i, _)| {
963 let before = text[..i].chars().next_back();
964 let after = text[i + token.len()..].chars().next();
965 !before.is_some_and(|c| ident(c) || c == '.') && !after.is_some_and(ident)
966 })
967}
968
969pub(crate) fn get<'a>(v: &'a Value, dotted: &str) -> Option<&'a Value> {
970 dotted.split('.').try_fold(v, |cur, k| cur.get(k))
971}
972
973pub(crate) fn collect_strings(v: &Value, prefix: String, out: &mut Vec<(String, String)>) {
974 match v {
975 Value::String(s) => out.push((prefix, s.clone())),
976 Value::Array(a) => {
977 for (i, x) in a.iter().enumerate() {
978 collect_strings(x, format!("{prefix}[{i}]"), out);
979 }
980 }
981 Value::Object(m) => {
982 for (k, x) in m {
983 let p = if prefix.is_empty() {
984 k.clone()
985 } else {
986 format!("{prefix}.{k}")
987 };
988 collect_strings(x, p, out);
989 }
990 }
991 _ => {}
992 }
993}
994
995pub(crate) fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
996 let Ok(entries) = fs::read_dir(dir) else {
997 return;
998 };
999 for e in entries.filter_map(Result::ok) {
1000 let p = e.path();
1001 let name = e.file_name();
1002 if name == ".git" || name == "target" {
1003 continue;
1004 }
1005 if p.is_dir() {
1006 walk(&p, out);
1007 } else {
1008 out.push(p);
1009 }
1010 }
1011}
1012
1013/// Path relative to `root` with `/` separators (falls back to the path as given).
1014pub fn display_path(root: &Path, p: &Path) -> String {
1015 let rel = p.strip_prefix(root).unwrap_or(p);
1016 rel.components()
1017 .filter_map(|c| match c {
1018 Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
1019 _ => None,
1020 })
1021 .collect::<Vec<_>>()
1022 .join("/")
1023}
1024
1025pub(crate) fn push(out: &mut Vec<Defect>, path: &str, field: &str, reason: String) {
1026 out.push(Defect {
1027 path: path.to_string(),
1028 field: field.to_string(),
1029 reason,
1030 });
1031}
1032
1033fn hex(bytes: &[u8]) -> String {
1034 bytes.iter().map(|b| format!("{b:02x}")).collect()
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039 use super::*;
1040 use serde_json::json;
1041
1042 const PARITY_FILE: &str = "tests/fixtures/records/good/evidence/parity_tokens.txt";
1043
1044 fn base() -> Value {
1045 let root = Path::new(env!("CARGO_MANIFEST_DIR"));
1046 let parity_sha = hex(&Sha256::digest(fs::read(root.join(PARITY_FILE)).unwrap()));
1047 json!({
1048 "schema": RECORD_SCHEMA,
1049 "status": "EXPERIMENTAL",
1050 "source": {"repo": "drakestapleton/benchmarks-mv", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false},
1051 "build": {"profile": "release", "rustc": "rustc 1.0.0"},
1052 "workload": {"name": "w", "concurrency": 1},
1053 "hardware": {"host": "h", "cpu": "c", "gpu": "none_detected"},
1054 "backend": {"engine": "e", "model": "m", "precision": "unlabeled", "endpoint": "in_process",
1055 "binary_sha256": "a".repeat(64), "model_sha256": "b".repeat(64)},
1056 "methodology": {"clock": "monotonic", "definitions": {"x_ms": "d"}, "token_accounting": "backend_usage", "samples": 3,
1057 "warmup": 1, "tolerance": "exact"},
1058 "parity": {"reference": "r", "verdict": "PASS", "evidence": PARITY_FILE, "evidence_sha256": parity_sha},
1059 "metrics": {"x_ms": 1.5},
1060 "evidence": ["Cargo.toml"],
1061 "limitations": []
1062 })
1063 }
1064
1065 fn run(v: &Value) -> Vec<String> {
1066 let root = Path::new(env!("CARGO_MANIFEST_DIR"));
1067 let mut out = Vec::new();
1068 check_record(root, "r.json", v, &mut out);
1069 out.sort();
1070 out.dedup();
1071 out.iter().map(|d| d.to_string()).collect()
1072 }
1073
1074 #[test]
1075 fn base_record_is_clean() {
1076 assert_eq!(run(&base()), Vec::<String>::new());
1077 }
1078
1079 #[test]
1080 fn percentile_minimums() {
1081 assert_eq!(percentile_of("ttft_ms_p95"), Some(95));
1082 assert_eq!(percentile_of("p50"), Some(50));
1083 assert_eq!(percentile_of("step_us_p999"), None);
1084 assert_eq!(percentile_of("prefix_tokens"), None);
1085 assert_eq!(min_samples_for(50), 2);
1086 assert_eq!(min_samples_for(90), 10);
1087 assert_eq!(min_samples_for(95), 20);
1088 assert_eq!(min_samples_for(99), 100);
1089 }
1090
1091 #[test]
1092 fn nested_placeholder_and_case() {
1093 let mut v = base();
1094 v["limitations"] = json!([" N/a "]);
1095 assert_eq!(
1096 run(&v),
1097 vec!["r.json: limitations[0]: placeholder value \" N/a \""]
1098 );
1099 }
1100
1101 #[test]
1102 fn not_run_rules() {
1103 let mut v = base();
1104 v["status"] = json!("NOT_RUN");
1105 assert_eq!(
1106 run(&v),
1107 vec![
1108 "r.json: evidence: NOT_RUN records carry no evidence",
1109 "r.json: methodology.samples: NOT_RUN records have 0 samples",
1110 "r.json: metrics: NOT_RUN records carry no measurements",
1111 "r.json: parity.verdict: NOT_RUN records carry no parity result",
1112 ]
1113 );
1114 v["evidence"] = json!([]);
1115 v["metrics"] = json!({});
1116 v["methodology"]["samples"] = json!(0);
1117 v["parity"] = json!({"reference": "r", "verdict": "NOT_RUN"});
1118 assert_eq!(run(&v), Vec::<String>::new());
1119 }
1120
1121 #[test]
1122 fn binding_rules() {
1123 // a model-free workload (no tokens counted) says so on both fields
1124 let mut v = base();
1125 v["methodology"]["token_accounting"] = json!("events_not_tokens");
1126 v["backend"]["model_sha256"] = json!(NO_MODEL);
1127 assert_eq!(
1128 run(&v),
1129 vec!["r.json: backend.model_sha256: \"none\" is allowed only when backend.model is \"none\""]
1130 );
1131 v["backend"]["model"] = json!(NO_MODEL);
1132 assert_eq!(run(&v), Vec::<String>::new());
1133 // ...but not when the backend counted tokens: a model ran
1134 v["methodology"]["token_accounting"] = json!("backend_usage");
1135 assert_eq!(
1136 run(&v),
1137 vec!["r.json: backend.model_sha256: \"none\" with token_accounting backend_usage (tokens were counted, so a model ran)"]
1138 );
1139 // ...nor for an LLM streaming workload, which always runs a model
1140 v["methodology"]["token_accounting"] = json!("events_not_tokens");
1141 v["workload"]["name"] = json!(LLM_WORKLOAD);
1142 assert_eq!(
1143 run(&v),
1144 vec!["r.json: backend.model_sha256: \"none\" with workload llm_streaming (an LLM workload runs a model)"]
1145 );
1146 // warmup is a count, tolerance a string
1147 let mut v = base();
1148 v["methodology"]["warmup"] = json!(-1);
1149 v["methodology"]["tolerance"] = json!(0.001);
1150 assert_eq!(
1151 run(&v),
1152 vec![
1153 "r.json: methodology.tolerance: must be a string",
1154 "r.json: methodology.warmup: must be a non-negative integer",
1155 ]
1156 );
1157 // parity NOT_RUN in a claim needs a limitation naming parity
1158 let mut v = base();
1159 v["parity"] = json!({"reference": "r", "verdict": "NOT_RUN"});
1160 assert_eq!(
1161 run(&v),
1162 vec!["r.json: parity.verdict: NOT_RUN must be explained by a limitations entry naming parity"]
1163 );
1164 v["limitations"] = json!(["parity: not compared in this run"]);
1165 assert_eq!(run(&v), Vec::<String>::new());
1166 // a parity verdict without its evidence, or outside the repository
1167 let mut v = base();
1168 v["parity"] = json!({"reference": "r", "verdict": "FAIL", "evidence": "../x"});
1169 v["status"] = json!("FAIL");
1170 assert_eq!(
1171 run(&v),
1172 vec!["r.json: parity.evidence: \"../x\" must be a relative path inside the repository"]
1173 );
1174 v["parity"] = json!({"verdict": "PASS"});
1175 assert_eq!(
1176 run(&v),
1177 vec![
1178 "r.json: parity.evidence: missing (a parity verdict names its evidence file)",
1179 "r.json: parity.reference: missing",
1180 ]
1181 );
1182 // HISTORICAL may say not_recorded when a limitation names the field
1183 let mut v = base();
1184 v["status"] = json!("HISTORICAL");
1185 v["backend"]["binary_sha256"] = json!(NOT_RECORDED);
1186 v["limitations"] = json!(["backend.binary_sha256: the run did not hash its binary"]);
1187 assert_eq!(run(&v), Vec::<String>::new());
1188 v["status"] = json!("EXPERIMENTAL");
1189 assert_eq!(
1190 run(&v),
1191 vec!["r.json: backend.binary_sha256: not_recorded is only allowed in HISTORICAL or SUPERSEDED records"]
1192 );
1193 }
1194
1195 #[test]
1196 fn evidence_must_stay_inside_the_repository() {
1197 let mut v = base();
1198 v["evidence"] = json!(["../outside.json", "/etc/hostname"]);
1199 assert_eq!(
1200 run(&v),
1201 vec![
1202 "r.json: evidence[0]: \"../outside.json\" must be a relative path inside the repository",
1203 "r.json: evidence[1]: \"/etc/hostname\" must be a relative path inside the repository",
1204 ]
1205 );
1206 }
1207
1208 #[test]
1209 fn symlink_out_of_the_repository_is_refused() {
1210 let root = std::env::temp_dir().join(format!("bench-evidence-{}", std::process::id()));
1211 let _ = fs::remove_dir_all(&root);
1212 fs::create_dir_all(&root).unwrap();
1213 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join(PARITY_FILE);
1214 fs::copy(&src, root.join("inside.txt")).unwrap();
1215 std::os::unix::fs::symlink(&src, root.join("link.txt")).unwrap();
1216 let sha = hex(&Sha256::digest(fs::read(&src).unwrap()));
1217 let mut v = base();
1218 v["evidence"] = json!(["inside.txt", "link.txt"]);
1219 v["parity"] = json!({"reference": "r", "verdict": "PASS", "evidence": "link.txt", "evidence_sha256": sha});
1220 let mut out = Vec::new();
1221 check_record(&root, "r.json", &v, &mut out);
1222 let mut got: Vec<String> = out.iter().map(|d| d.to_string()).collect();
1223 got.sort();
1224 fs::remove_dir_all(&root).unwrap();
1225 assert_eq!(
1226 got,
1227 vec![
1228 "r.json: evidence[1]: \"link.txt\" resolves outside the repository (symlink)",
1229 "r.json: parity.evidence: \"link.txt\" resolves outside the repository (symlink)",
1230 ]
1231 );
1232 }
1233
1234 #[test]
1235 fn limitation_must_name_the_field_as_a_word() {
1236 assert!(names_token("parity: not compared", "parity"));
1237 assert!(names_token(
1238 "source.dirty, methodology.clock: not recorded",
1239 "methodology.clock"
1240 ));
1241 assert!(!names_token("comparity of nothing", "parity"));
1242 assert!(!names_token(
1243 "methodology.clockwork: x",
1244 "methodology.clock"
1245 ));
1246 assert!(!names_token("xmethodology.clock: x", "methodology.clock"));
1247 let mut v = base();
1248 v["parity"] = json!({"reference": "r", "verdict": "NOT_RUN"});
1249 v["limitations"] = json!(["comparity of nothing"]);
1250 assert_eq!(
1251 run(&v),
1252 vec!["r.json: parity.verdict: NOT_RUN must be explained by a limitations entry naming parity"]
1253 );
1254 }
1255
1256 #[test]
1257 fn parity_verdict_needs_a_stated_tolerance() {
1258 for t in [
1259 "none",
1260 "None: nothing compared",
1261 " none",
1262 "-",
1263 "no tolerance",
1264 "Unspecified",
1265 ] {
1266 let mut v = base();
1267 v["methodology"]["tolerance"] = json!(t);
1268 assert_eq!(
1269 run(&v),
1270 vec!["r.json: methodology.tolerance: a parity PASS or FAIL needs a stated tolerance, not \"none\" or a stand-in"]
1271 );
1272 }
1273 // a real tolerance passes
1274 let mut v = base();
1275 v["methodology"]["tolerance"] = json!("no token may differ (exact match)");
1276 assert!(run(&v).is_empty());
1277 }
1278
1279 #[test]
1280 fn parity_verdict_names_a_real_reference() {
1281 // " " is refused as a placeholder by the general check, so it is not listed here
1282 for r in ["-", "none", "No reference", "unspecified"] {
1283 let mut v = base();
1284 v["parity"]["reference"] = json!(r);
1285 assert_eq!(
1286 run(&v),
1287 vec!["r.json: parity.reference: a parity PASS or FAIL names what it was compared with, not \"none\" or a stand-in"]
1288 );
1289 }
1290 // NOT_RUN with a stand-in reference stays allowed (nothing was compared)
1291 let mut v = base();
1292 v["status"] = json!("EXPERIMENTAL");
1293 v["parity"] = json!({"reference": "-", "verdict": "NOT_RUN"});
1294 v["limitations"] = json!(["parity: not run"]);
1295 assert!(run(&v).is_empty(), "{:?}", run(&v));
1296 }
1297
1298 #[test]
1299 fn parity_evidence_directory_is_named_as_one() {
1300 let mut v = base();
1301 v["parity"]["evidence"] = json!("tests");
1302 assert_eq!(
1303 run(&v),
1304 vec!["r.json: parity.evidence: tests is a directory, not an evidence file"]
1305 );
1306 }
1307
1308 #[test]
1309 fn not_recorded_needs_lenient_status_and_a_limitation() {
1310 let mut v = base();
1311 v["build"]["rustc"] = json!(NOT_RECORDED);
1312 assert_eq!(
1313 run(&v),
1314 vec!["r.json: build.rustc: not_recorded is only allowed in HISTORICAL or SUPERSEDED records"]
1315 );
1316 v["status"] = json!("HISTORICAL");
1317 assert_eq!(
1318 run(&v),
1319 vec!["r.json: build.rustc: not_recorded must be explained by a limitations entry naming this field"]
1320 );
1321 v["limitations"] = json!(["build.rustc: the run did not record the compiler"]);
1322 assert_eq!(run(&v), Vec::<String>::new());
1323 v["workload"]["name"] = json!(NOT_RECORDED);
1324 assert_eq!(
1325 run(&v),
1326 vec!["r.json: workload.name: not_recorded is not allowed in this field"]
1327 );
1328 }
1329
1330 #[test]
1331 fn metric_must_be_number_and_defined() {
1332 let mut v = base();
1333 v["metrics"] = json!({"x_ms": "1.5", "y_ms": 2});
1334 assert_eq!(
1335 run(&v),
1336 vec![
1337 "r.json: methodology.definitions.y_ms: missing definition for metric y_ms",
1338 "r.json: metrics.x_ms: must be a finite number",
1339 ]
1340 );
1341 }
1342}