trusty_code/bakeoff/mod.rs
1//! L1-L3 bake-off milestone exit gate (#5441).
2//!
3//! Why: every Trusty Code milestone is supposed to close only after a real
4//! coding-harness bake-off completes levels 1-3 with no unexplained regression
5//! against the previous accepted baseline. The first independent qualification
6//! attempt showed why prose alone cannot enforce that: three levels ran and
7//! every verifier check passed, yet the evidence was still disqualified because
8//! the retained metadata named no candidate commit, no binary hash, no
9//! runner/challenge revision and no source digests, nothing mechanically
10//! rejected that, and L3's +27% wall-clock / +50% turns had no recorded
11//! disposition. This module is the missing mechanism.
12//!
13//! What: a pure, offline evidence gate over a retained bundle. [`preflight`]
14//! rejects the five conditions #5441 names — incomplete L1-L3 coverage, missing
15//! artifacts or provenance, mock-only evidence, a stale runner, and results
16//! produced by a different `tcode` build — and [`compare`] diffs a candidate
17//! bundle against the previous accepted baseline, blocking correctness or
18//! completion regressions outright while requiring a written disposition for
19//! cost/token/turn/duration changes outside tolerance. Both produce
20//! [`Violation`]s collected into one [`GateReport`]. Nothing here runs a model,
21//! spawns the runner, or touches the network: the expensive real-model L1-L3
22//! run happens once after a milestone candidate is frozen, and this gate reads
23//! only what that run retained. The operator surface is `tcode bakeoff-gate`
24//! (wired in `src/cli/bakeoff.rs`); the bundle layout and a worked invocation
25//! are in `docs/reference/bakeoff-exit-gate.md`.
26//!
27//! Test: `bakeoff::tests::*`, plus the binary-level
28//! `tests/bakeoff_gate_e2e.rs`.
29//!
30//! [`preflight`]: crate::bakeoff::preflight()
31//! [`compare`]: crate::bakeoff::compare
32//! [`Violation`]: crate::bakeoff::Violation
33//! [`GateReport`]: crate::bakeoff::GateReport
34
35use std::fmt;
36
37use serde::Serialize;
38
39pub mod compare;
40pub mod metadata;
41pub mod preflight;
42
43pub use compare::{Baseline, ComparisonInputs, compare_against_baseline};
44pub use metadata::LevelMetadata;
45pub use preflight::{Bundle, Pins, load_bundle, preflight};
46
47/// The three levels a milestone exit gate must cover.
48///
49/// Why: #5441 requires all three; "we ran L1 and L2" is incomplete coverage,
50/// not partial credit.
51/// What: the level numbers, in the order the report lists them.
52/// Test: `bakeoff::tests::a_missing_level_is_incomplete_coverage`.
53pub const LEVELS: [u8; 3] = [1, 2, 3];
54
55/// Files every level directory must contain, non-empty.
56///
57/// Why: #5441 requires the raw `tcode_report.json`, stderr, prompt, solution,
58/// verifier output, and `metadata.json` to be preserved per level. A retained
59/// bundle missing any of them cannot be re-examined later, which is the whole
60/// point of retaining it.
61/// What: the fixed filenames the gate looks for inside `<bundle>/L<n>/`.
62/// Test: `bakeoff::tests::a_missing_artifact_is_rejected`,
63/// `bakeoff::tests::an_empty_artifact_is_rejected`.
64pub const REQUIRED_ARTIFACTS: [&str; 6] = [
65 "metadata.json",
66 "tcode_report.json",
67 "prompt.txt",
68 "stderr.log",
69 "solution.diff",
70 "verifier.json",
71];
72
73/// Optional bundle-level file recording accepted performance changes.
74///
75/// Why: #5441 lets a performance change outside tolerance pass with "a
76/// documented disposition" — so the disposition has to live somewhere the gate
77/// can read, not in a PR comment.
78/// What: a JSON object at the bundle root mapping a metric key (`L3.turns`) to
79/// the operator's written acceptance.
80/// Test: `bakeoff::tests::a_documented_disposition_clears_a_performance_change`.
81pub const DISPOSITIONS_FILE: &str = "dispositions.json";
82
83/// The single terminal status a bake-off level may finish with.
84///
85/// Why: `partial`, `deadline_exceeded` and `no_changes` are all real, useful
86/// distinctions for a `run-task` caller, but none of them is a milestone-grade
87/// completion. Treating anything but `success` as clean would let a
88/// completion regression through the gate that #5441 exists to block.
89/// What: the literal `run_task::report` status string for [`crate::run_task::ExitCode::Success`].
90/// Test: `bakeoff::tests::a_status_regression_blocks_closure`.
91pub const CLEAN_STATUS: &str = "success";
92
93/// Why a bundle failed the gate.
94///
95/// Why: the gate's output is read by an operator deciding whether to close a
96/// milestone, so each finding needs a stable machine-readable key as well as
97/// prose. A single opaque "gate failed" string would send them back to diffing
98/// JSON by hand — the exact cost the first qualification attempt paid.
99/// What: one variant per rejection reason; [`Rule::as_str`] is the stable key
100/// the JSON report emits.
101/// Test: `bakeoff::tests::rule_keys_are_distinct`.
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
103#[serde(rename_all = "snake_case")]
104#[non_exhaustive]
105pub enum Rule {
106 /// A required level (1, 2, or 3) is absent from the bundle.
107 IncompleteCoverage,
108 /// A required per-level artifact is missing or empty.
109 MissingArtifact,
110 /// `metadata.json` did not parse, or contradicts its own level's
111 /// `tcode_report.json`.
112 MalformedMetadata,
113 /// The level declares mock/offline evidence, or its verifier ran nothing.
114 MockEvidence,
115 /// A provenance field is empty, `"unknown"`, or zero.
116 MissingProvenance,
117 /// The runner or candidate checkout had uncommitted changes, so its
118 /// recorded revision does not identify what ran.
119 DirtyCheckout,
120 /// The runner path/revision is inconsistent across levels or differs from
121 /// the pinned revision.
122 StaleRunner,
123 /// Levels disagree about which `tcode` build produced them, or the build
124 /// differs from the pinned candidate.
125 BuildMismatch,
126 /// Verifier pass rate or terminal status regressed against the baseline.
127 CorrectnessRegression,
128 /// A level the baseline covered is absent from the candidate.
129 MissingDeliverable,
130 /// A cost/token/turn/duration change exceeded tolerance with no recorded
131 /// disposition.
132 UndispositionedChange,
133}
134
135impl Rule {
136 /// The stable snake_case key for this rule.
137 ///
138 /// Why: the JSON report and the human report must name a rule identically,
139 /// and a caller grepping CI output needs a key that survives rewording.
140 /// What: the same literal the `Serialize` impl emits.
141 /// Test: `bakeoff::tests::rule_keys_are_distinct`.
142 pub fn as_str(self) -> &'static str {
143 match self {
144 Rule::IncompleteCoverage => "incomplete_coverage",
145 Rule::MissingArtifact => "missing_artifact",
146 Rule::MalformedMetadata => "malformed_metadata",
147 Rule::MockEvidence => "mock_evidence",
148 Rule::MissingProvenance => "missing_provenance",
149 Rule::DirtyCheckout => "dirty_checkout",
150 Rule::StaleRunner => "stale_runner",
151 Rule::BuildMismatch => "build_mismatch",
152 Rule::CorrectnessRegression => "correctness_regression",
153 Rule::MissingDeliverable => "missing_deliverable",
154 Rule::UndispositionedChange => "undispositioned_change",
155 }
156 }
157}
158
159impl fmt::Display for Rule {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 f.write_str(self.as_str())
162 }
163}
164
165/// One reason the gate is refusing to pass.
166///
167/// Why: every finding must say which level it came from, so an operator fixes
168/// the right rerun rather than all three.
169/// What: the rule, the level it applies to (`None` for bundle-wide findings),
170/// and a one-line detail naming the concrete field or number.
171/// Test: `bakeoff::tests::a_missing_artifact_is_rejected`.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
173#[non_exhaustive]
174pub struct Violation {
175 /// Which rule fired.
176 pub rule: Rule,
177 /// The bake-off level, when the finding is level-scoped.
178 pub level: Option<u8>,
179 /// What specifically was wrong.
180 pub detail: String,
181}
182
183impl Violation {
184 /// Build a level-scoped violation.
185 ///
186 /// Why: the two constructors keep call sites to one line, which matters in
187 /// [`preflight()`] where nearly every branch produces one.
188 /// What: sets `level` to `Some(level)`.
189 /// Test: `bakeoff::tests::a_missing_artifact_is_rejected`.
190 pub fn level(rule: Rule, level: u8, detail: impl Into<String>) -> Self {
191 Self {
192 rule,
193 level: Some(level),
194 detail: detail.into(),
195 }
196 }
197
198 /// Build a bundle-wide violation.
199 ///
200 /// Why: cross-level findings (build drift, runner drift) belong to no
201 /// single level.
202 /// What: sets `level` to `None`.
203 /// Test: `bakeoff::tests::build_drift_across_levels_is_rejected`.
204 pub fn bundle(rule: Rule, detail: impl Into<String>) -> Self {
205 Self {
206 rule,
207 level: None,
208 detail: detail.into(),
209 }
210 }
211}
212
213impl fmt::Display for Violation {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 match self.level {
216 Some(level) => write!(f, "[{}] L{}: {}", self.rule, level, self.detail),
217 None => write!(f, "[{}] bundle: {}", self.rule, self.detail),
218 }
219 }
220}
221
222/// The gate's verdict over one bundle, optionally compared to a baseline.
223///
224/// Why: preflight and comparison findings land in one document so the operator
225/// sees the whole picture in one run instead of fixing provenance, rerunning,
226/// and only then discovering a correctness regression.
227/// What: the levels that were readable, every violation, and the informational
228/// notes (accepted dispositions, within-tolerance deltas) that explain what the
229/// gate looked at and let pass.
230/// Test: `bakeoff::tests::a_complete_bundle_passes_preflight`.
231#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
232#[non_exhaustive]
233pub struct GateReport {
234 /// Levels whose `metadata.json` parsed, ascending.
235 pub levels: Vec<u8>,
236 /// Every reason the gate is refusing to pass.
237 pub violations: Vec<Violation>,
238 /// Findings that did not block: accepted dispositions, deltas inside
239 /// tolerance, and what the gate compared against.
240 pub notes: Vec<String>,
241}
242
243impl GateReport {
244 /// Whether the milestone may close on this evidence.
245 ///
246 /// Why: one predicate, so the CLI exit code and every test agree.
247 /// What: true when no violation was recorded.
248 /// Test: `bakeoff::tests::a_complete_bundle_passes_preflight`.
249 pub fn passed(&self) -> bool {
250 self.violations.is_empty()
251 }
252
253 /// Fold another report's findings into this one.
254 ///
255 /// Why: the comparison stage runs after preflight and must not discard what
256 /// preflight already found.
257 /// What: appends levels-preserving; violations and notes are concatenated.
258 /// Test: `bakeoff::tests::comparison_findings_join_preflight_findings`.
259 pub fn absorb(&mut self, other: GateReport) {
260 self.violations.extend(other.violations);
261 self.notes.extend(other.notes);
262 }
263
264 /// Render the verdict for a terminal.
265 ///
266 /// Why: an operator reading CI output wants the verdict on line one and the
267 /// concrete findings under it, not a JSON blob.
268 /// What: a `PASS`/`FAIL` header naming the covered levels, then one line per
269 /// violation, then the notes.
270 /// Test: `bakeoff::tests::human_render_names_every_violation`.
271 pub fn render_human(&self) -> String {
272 let mut out = String::new();
273 let levels = if self.levels.is_empty() {
274 "none".to_string()
275 } else {
276 self.levels
277 .iter()
278 .map(|l| format!("L{l}"))
279 .collect::<Vec<_>>()
280 .join(",")
281 };
282 out.push_str(&format!(
283 "bakeoff-gate: {} ({} violation(s); levels read: {levels})\n",
284 if self.passed() { "PASS" } else { "FAIL" },
285 self.violations.len(),
286 ));
287 for violation in &self.violations {
288 out.push_str(&format!(" {violation}\n"));
289 }
290 for note in &self.notes {
291 out.push_str(&format!(" note: {note}\n"));
292 }
293 out
294 }
295
296 /// Render the verdict as one machine-readable JSON document.
297 ///
298 /// Why: the gate is meant to be callable from the external runner and from
299 /// CI, both of which want to branch on structure rather than parse prose.
300 /// What: `{"passed", "levels", "violations", "notes"}`, pretty-printed.
301 /// Test: `bakeoff::tests::json_render_carries_the_verdict_and_rules`.
302 pub fn render_json(&self) -> String {
303 let value = serde_json::json!({
304 "passed": self.passed(),
305 "levels": self.levels,
306 "violations": self.violations,
307 "notes": self.notes,
308 });
309 serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
310 }
311}
312
313#[cfg(test)]
314mod tests;