trusty_code/bakeoff/preflight.rs
1//! Bundle loading and the five rejections #5441's preflight owes.
2//!
3//! Why: #5441 asks for "a lightweight preflight that rejects stale runner
4//! paths, missing provenance, mock-only evidence, incomplete L1-L3 coverage,
5//! and results produced by a different Trusty Code build". Those five are
6//! stated as properties of retained evidence, so all five are decidable
7//! offline from the bundle plus a handful of pins — no model, no runner, no
8//! network.
9//! What: [`load_bundle`] reads `<root>/L1..L3`, and [`preflight`] applies the
10//! per-level rules (artifacts present and non-empty, metadata parses and agrees
11//! with its own `tcode_report.json`, evidence is real, provenance is complete,
12//! neither checkout was dirty) and the cross-level rules (one build, one
13//! runner, one challenge revision, one set of source digests) plus the caller's
14//! [`Pins`]. Reading is deliberately tolerant of extra files and extra JSON
15//! keys, and intolerant of absent ones.
16//! Test: `bakeoff::tests::*` — one test per rule.
17
18use std::collections::BTreeMap;
19use std::path::{Path, PathBuf};
20
21use crate::bakeoff::metadata::LevelMetadata;
22use crate::bakeoff::{GateReport, LEVELS, REQUIRED_ARTIFACTS, Rule, Violation};
23
24/// Identities the caller is asserting the evidence must match.
25///
26/// Why: cross-level agreement proves the three levels used ONE build and ONE
27/// runner, but not that it was the FROZEN candidate. Only the operator knows
28/// which commit was frozen, so they pin it; an unpinned field is simply not
29/// checked rather than guessed at.
30/// What: three optional expected values, compared verbatim against every
31/// level's metadata.
32/// Test: `bakeoff::tests::a_pinned_commit_mismatch_is_a_build_mismatch`,
33/// `bakeoff::tests::a_pinned_runner_revision_mismatch_is_a_stale_runner`.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct Pins {
37 /// The frozen candidate's git commit.
38 pub commit: Option<String>,
39 /// SHA-256 of the binary built from that commit.
40 pub binary_sha256: Option<String>,
41 /// The bake-off runner revision the invocation was defined against.
42 pub runner_revision: Option<String>,
43}
44
45impl Pins {
46 /// Build a pin set from the three optional expectations.
47 ///
48 /// Why: [`Pins`] is `#[non_exhaustive]`, so the `tcode` binary — a separate
49 /// crate from this library — cannot use a struct literal. A constructor
50 /// keeps the CLI wiring to one call and leaves the struct free to grow.
51 /// What: moves the three arguments in, in the order the CLI flags are
52 /// declared.
53 /// Test: `bakeoff::tests::a_matching_pin_set_passes`.
54 pub fn new(
55 commit: Option<String>,
56 binary_sha256: Option<String>,
57 runner_revision: Option<String>,
58 ) -> Self {
59 Self {
60 commit,
61 binary_sha256,
62 runner_revision,
63 }
64 }
65}
66
67/// One level's readable evidence.
68///
69/// Why: the comparison stage needs the same parsed metadata the preflight read,
70/// and re-reading it would let the two stages disagree about what is on disk.
71/// What: the level directory, its parsed `metadata.json`, and its raw
72/// `tcode_report.json` value.
73/// Test: `bakeoff::tests::a_complete_bundle_passes_preflight`.
74#[derive(Debug, Clone)]
75#[non_exhaustive]
76pub struct LevelEvidence {
77 /// `<bundle>/L<n>`.
78 pub dir: PathBuf,
79 /// The parsed retained metadata.
80 pub metadata: LevelMetadata,
81 /// The level's raw run report, as parsed JSON.
82 pub report: serde_json::Value,
83}
84
85/// A retained bake-off bundle, as far as it could be read.
86///
87/// Why: a bundle that fails preflight is still worth carrying around — the
88/// report names which levels were readable, and a caller comparing against a
89/// baseline needs whatever parsed.
90/// What: the root path, the levels that parsed, and the violations produced
91/// while reading.
92/// Test: `bakeoff::tests::a_missing_level_is_incomplete_coverage`.
93#[derive(Debug, Clone)]
94#[non_exhaustive]
95pub struct Bundle {
96 /// The bundle root the caller named.
97 pub root: PathBuf,
98 /// Levels that parsed, keyed by level number.
99 pub levels: BTreeMap<u8, LevelEvidence>,
100 /// Findings recorded while reading the bundle.
101 pub read_violations: Vec<Violation>,
102}
103
104/// Read `<root>/L1`, `<root>/L2` and `<root>/L3`.
105///
106/// Why: separating reading from judging lets the baseline bundle be loaded
107/// with the same code that loads the candidate, without subjecting a
108/// previously-accepted baseline to a fresh preflight it was never gated on.
109/// What: for each of [`LEVELS`], requires the directory and every entry of
110/// [`REQUIRED_ARTIFACTS`] to exist and be non-empty, then parses
111/// `metadata.json` and `tcode_report.json`. A level that fails any of those
112/// records a violation and is omitted from `levels`.
113/// Test: `bakeoff::tests::a_missing_level_is_incomplete_coverage`,
114/// `bakeoff::tests::an_empty_artifact_is_rejected`,
115/// `bakeoff::tests::malformed_metadata_is_rejected`.
116pub fn load_bundle(root: &Path) -> Bundle {
117 let mut levels = BTreeMap::new();
118 let mut read_violations = Vec::new();
119
120 for level in LEVELS {
121 let dir = root.join(format!("L{level}"));
122 if !dir.is_dir() {
123 read_violations.push(Violation::level(
124 Rule::IncompleteCoverage,
125 level,
126 format!("no level directory at {}", dir.display()),
127 ));
128 continue;
129 }
130
131 let mut artifacts_ok = true;
132 for artifact in REQUIRED_ARTIFACTS {
133 let path = dir.join(artifact);
134 match std::fs::metadata(&path) {
135 Ok(meta) if meta.len() > 0 => {}
136 Ok(_) => {
137 artifacts_ok = false;
138 read_violations.push(Violation::level(
139 Rule::MissingArtifact,
140 level,
141 format!("{artifact} is empty"),
142 ));
143 }
144 Err(e) => {
145 artifacts_ok = false;
146 read_violations.push(Violation::level(
147 Rule::MissingArtifact,
148 level,
149 format!("{artifact} unreadable: {e}"),
150 ));
151 }
152 }
153 }
154 if !artifacts_ok {
155 continue;
156 }
157
158 let metadata = match read_json::<LevelMetadata>(&dir.join("metadata.json")) {
159 Ok(m) => m,
160 Err(detail) => {
161 read_violations.push(Violation::level(Rule::MalformedMetadata, level, detail));
162 continue;
163 }
164 };
165 let report = match read_json::<serde_json::Value>(&dir.join("tcode_report.json")) {
166 Ok(r) => r,
167 Err(detail) => {
168 read_violations.push(Violation::level(Rule::MalformedMetadata, level, detail));
169 continue;
170 }
171 };
172
173 levels.insert(
174 level,
175 LevelEvidence {
176 dir,
177 metadata,
178 report,
179 },
180 );
181 }
182
183 Bundle {
184 root: root.to_path_buf(),
185 levels,
186 read_violations,
187 }
188}
189
190/// Apply every preflight rule to a candidate bundle.
191///
192/// Why: this is the "lightweight preflight" #5441 asks for, and it runs before
193/// any baseline comparison — comparing numbers produced by an unidentifiable
194/// build would only launder the problem into a delta table.
195/// What: replays the read violations, then per level checks the declared level
196/// number, evidence mode, verifier check count, provenance completeness,
197/// checkout cleanliness, the metadata/report build and status agreement, and
198/// the caller's [`Pins`]; then checks that all readable levels agree on build,
199/// runner, challenge revision, and source digests.
200/// Test: `bakeoff::tests::a_complete_bundle_passes_preflight` and the
201/// per-rule rejection tests beside it.
202pub fn preflight(bundle: &Bundle, pins: &Pins) -> GateReport {
203 let mut report = GateReport {
204 levels: bundle.levels.keys().copied().collect(),
205 violations: bundle.read_violations.clone(),
206 notes: Vec::new(),
207 };
208
209 for (&level, evidence) in &bundle.levels {
210 check_level(level, evidence, pins, &mut report);
211 }
212 check_cross_level(bundle, &mut report);
213
214 if report.levels.len() == LEVELS.len() {
215 report.notes.push(format!(
216 "read {} level(s) from {}",
217 LEVELS.len(),
218 bundle.root.display()
219 ));
220 }
221 report
222}
223
224/// Every rule that a single level can violate on its own.
225///
226/// Why: keeps [`preflight`] readable as the list of stages it runs, with the
227/// per-level detail one hop away.
228/// What: pushes violations onto `report` for the level's declared number,
229/// evidence mode, verifier coverage, provenance, checkout cleanliness,
230/// metadata/report agreement, and pin mismatches.
231/// Test: the per-rule rejection tests in `bakeoff::tests`.
232fn check_level(level: u8, evidence: &LevelEvidence, pins: &Pins, report: &mut GateReport) {
233 let meta = &evidence.metadata;
234
235 if meta.level != level {
236 report.violations.push(Violation::level(
237 Rule::MalformedMetadata,
238 level,
239 format!(
240 "metadata declares level {} but sits in L{level}",
241 meta.level
242 ),
243 ));
244 }
245
246 if !meta.evidence_mode.is_real() {
247 report.violations.push(Violation::level(
248 Rule::MockEvidence,
249 level,
250 format!(
251 "evidence_mode is {:?}; only real runs satisfy the exit gate",
252 meta.evidence_mode
253 ),
254 ));
255 }
256 if meta.verifier.checks_total == 0 {
257 report.violations.push(Violation::level(
258 Rule::MockEvidence,
259 level,
260 "verifier recorded 0 checks — no correctness evidence".to_string(),
261 ));
262 }
263
264 let gaps = meta.provenance_gaps();
265 if !gaps.is_empty() {
266 report.violations.push(Violation::level(
267 Rule::MissingProvenance,
268 level,
269 format!("unusable provenance field(s): {}", gaps.join(", ")),
270 ));
271 }
272
273 if meta.runner.dirty {
274 report.violations.push(Violation::level(
275 Rule::DirtyCheckout,
276 level,
277 format!(
278 "runner checkout at revision {} was dirty; the recorded revision does not identify what ran",
279 meta.runner.revision
280 ),
281 ));
282 }
283 if meta.build.dirty {
284 report.violations.push(Violation::level(
285 Rule::DirtyCheckout,
286 level,
287 format!(
288 "candidate checkout at commit {} was dirty; the recorded commit does not identify the binary",
289 meta.build.commit
290 ),
291 ));
292 }
293
294 check_report_agreement(level, evidence, report);
295
296 if let Some(expected) = &pins.commit
297 && &meta.build.commit != expected
298 {
299 report.violations.push(Violation::level(
300 Rule::BuildMismatch,
301 level,
302 format!(
303 "build.commit is {} but the pinned candidate is {expected}",
304 meta.build.commit
305 ),
306 ));
307 }
308 if let Some(expected) = &pins.binary_sha256
309 && &meta.build.binary_sha256 != expected
310 {
311 report.violations.push(Violation::level(
312 Rule::BuildMismatch,
313 level,
314 format!(
315 "build.binary_sha256 is {} but the pinned candidate binary is {expected}",
316 meta.build.binary_sha256
317 ),
318 ));
319 }
320 if let Some(expected) = &pins.runner_revision
321 && &meta.runner.revision != expected
322 {
323 report.violations.push(Violation::level(
324 Rule::StaleRunner,
325 level,
326 format!(
327 "runner.revision is {} but the pinned runner is {expected}",
328 meta.runner.revision
329 ),
330 ));
331 }
332}
333
334/// Cross-check `metadata.json` against the level's own `tcode_report.json`.
335///
336/// Why: the metadata is written by the external runner and the report by the
337/// binary under test. Requiring them to agree is what makes the metadata
338/// evidence rather than an unverified assertion — a runner that stamped the
339/// wrong commit, or reran only some levels against a rebuilt binary, is caught
340/// here and nowhere else.
341/// What: compares `build.version`/`commit`/`commit_date` and `status` against
342/// the report's own values, ignoring report keys the gate does not read.
343/// Test: `bakeoff::tests::report_build_mismatch_is_rejected`,
344/// `bakeoff::tests::metadata_status_must_match_the_run_report`.
345fn check_report_agreement(level: u8, evidence: &LevelEvidence, report: &mut GateReport) {
346 let meta = &evidence.metadata;
347 let reported = evidence.report.get("build");
348 for (field, expected) in [
349 ("version", &meta.build.version),
350 ("commit", &meta.build.commit),
351 ("commit_date", &meta.build.commit_date),
352 ] {
353 let actual = reported.and_then(|b| b.get(field)).and_then(|v| v.as_str());
354 if actual != Some(expected.as_str()) {
355 report.violations.push(Violation::level(
356 Rule::BuildMismatch,
357 level,
358 format!(
359 "tcode_report.json build.{field} is {} but metadata says {expected}",
360 actual.unwrap_or("absent")
361 ),
362 ));
363 }
364 }
365
366 let reported_status = evidence.report.get("status").and_then(|v| v.as_str());
367 if reported_status != Some(meta.run.status.as_str()) {
368 report.violations.push(Violation::level(
369 Rule::MalformedMetadata,
370 level,
371 format!(
372 "tcode_report.json status is {} but metadata says {}",
373 reported_status.unwrap_or("absent"),
374 meta.run.status
375 ),
376 ));
377 }
378}
379
380/// Require every readable level to describe the same experiment.
381///
382/// Why: three levels run against three different builds, runners, or challenge
383/// revisions are three experiments, and comparing their aggregate against a
384/// baseline is meaningless. This is the "results produced by a different Trusty
385/// Code build" rejection in its cross-level form — the one an operator is most
386/// likely to hit by rerunning a single failed level after a rebuild.
387/// What: compares each level's build identity, runner path/revision, challenge
388/// revision, and source digests against the lowest-numbered readable level.
389/// Test: `bakeoff::tests::build_drift_across_levels_is_rejected`,
390/// `bakeoff::tests::source_digest_drift_across_levels_is_rejected`.
391fn check_cross_level(bundle: &Bundle, report: &mut GateReport) {
392 let mut iter = bundle.levels.iter();
393 let Some((&first_level, first)) = iter.next() else {
394 return;
395 };
396 let reference = &first.metadata;
397
398 for (&level, evidence) in iter {
399 let meta = &evidence.metadata;
400 if meta.build_identity() != reference.build_identity() {
401 report.violations.push(Violation::bundle(
402 Rule::BuildMismatch,
403 format!(
404 "L{level} was produced by build {} but L{first_level} by {}",
405 meta.build_identity(),
406 reference.build_identity()
407 ),
408 ));
409 }
410 if meta.runner.path != reference.runner.path
411 || meta.runner.revision != reference.runner.revision
412 {
413 report.violations.push(Violation::bundle(
414 Rule::StaleRunner,
415 format!(
416 "L{level} used runner {}@{} but L{first_level} used {}@{}",
417 meta.runner.path,
418 meta.runner.revision,
419 reference.runner.path,
420 reference.runner.revision
421 ),
422 ));
423 }
424 if meta.challenge_revision != reference.challenge_revision {
425 report.violations.push(Violation::bundle(
426 Rule::StaleRunner,
427 format!(
428 "L{level} ran challenge revision {} but L{first_level} ran {}",
429 meta.challenge_revision, reference.challenge_revision
430 ),
431 ));
432 }
433 if meta.source_digests != reference.source_digests {
434 report.violations.push(Violation::bundle(
435 Rule::StaleRunner,
436 format!(
437 "L{level} consumed different instruction/agent/skill sources than L{first_level}"
438 ),
439 ));
440 }
441 }
442}
443
444/// Read and parse one JSON file, reporting the path in any error.
445///
446/// Why: a bare serde error names a line and column but not the file, and this
447/// gate reads twelve JSON files across two bundles.
448/// What: returns the parsed value, or a one-line human detail on any I/O or
449/// parse failure.
450/// Test: `bakeoff::tests::malformed_metadata_is_rejected`.
451fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, String> {
452 let raw =
453 std::fs::read_to_string(path).map_err(|e| format!("{} unreadable: {e}", path.display()))?;
454 serde_json::from_str(&raw).map_err(|e| format!("{} is not valid: {e}", path.display()))
455}