interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / tools / aien-test / src / cache.rs

1448 lines · 55243 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//! The digest cache (ADR 0028 Decision 7, Slice C).
17//!
18//! A gate's result is reused, not rerun, only when an earlier fresh receipt
19//! describes the very same experiment: the manifest bytes, the program, every
20//! declared input, the machine and the receipts the gate depends on all have
21//! identical digests (the "cache key"). Anything else runs the gate again.
22//!
23//! The cache is keyed on the receipt bytes and digests exactly as the runner
24//! writes them today. It adds no receipt member and changes no receipt format
25//! (ADR 0029 will own that). Where the ADR says "index" this slice reads the
26//! receipts themselves: every receipt already carries `volatile.cache.key`,
27//! so a separate `index.jsonl` would only be a second copy that could drift.
28//!
29//! Choices where the ADR is silent or contradicts itself (recorded in the PR):
30//! - A reused receipt is the source receipt's `core` with one change: its
31//! `commit` is the commit being checked. The ADR says "identical core" and
32//! also "records that this commit was checked"; both cannot hold, and
33//! `why`, `run` and the dependency lookups all match receipts by commit.
34//! - Dependencies enter the key as receipt digests, resolved to the original
35//! fresh receipt when the dependency itself was reused. Without that step a
36//! reused dependency would get a new digest and every dependent would miss.
37//! - A source receipt must pass extra checks the key cannot express (see
38//! [`Unusable`]); failing any one of them is a miss, never a hit.
39//! - `args` after `--` are not in the ADR key. A run with replacement args
40//! never consults the cache, and its key carries the args so it can never
41//! be mistaken for a run with the manifest's own args.
42
43use crate::evidence::{canonical_digest, Index, Store, StoreError, Stored, SCHEMA};
44use crate::runner;
45use crate::verdict::Verdict;
46use serde_json::{json, Value};
47use std::collections::BTreeMap;
48use std::path::Path;
49
50/// `volatile.cache.mode` (ADR Decision 4).
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Mode {
53 /// The cache may be consulted.
54 Allow,
55 /// The manifest says `cache: never`.
56 Never,
57 /// Lookups were switched off for this run (`--no-cache`, replacement
58 /// args, or a tree with uncommitted changes).
59 Disabled,
60}
61
62impl Mode {
63 pub fn as_str(self) -> &'static str {
64 match self {
65 Mode::Allow => "allow",
66 Mode::Never => "never",
67 Mode::Disabled => "disabled",
68 }
69 }
70}
71
72/// The mode the manifest and the command line ask for. `cache: never` wins
73/// over everything: it is the gate author's rule, not a flag.
74pub fn policy(cache_allowed: bool, no_cache: bool) -> Mode {
75 if !cache_allowed {
76 Mode::Never
77 } else if no_cache {
78 Mode::Disabled
79 } else {
80 Mode::Allow
81 }
82}
83
84/// The members the cache key is made of.
85#[derive(Debug, Clone)]
86pub struct Experiment {
87 pub manifest_digest: String,
88 pub binary_sha256: Option<String>,
89 pub build_inputs_digest: String,
90 pub machine_digest: String,
91 /// `(gate, receipt digest)` as recorded in `core.dependencies`.
92 pub dependencies: Vec<(String, String)>,
93 pub pins: Value,
94 /// Replacement arguments given after `--`, if any.
95 pub args_override: Option<Vec<String>>,
96}
97
98/// A receipt digest, followed through `reused_from` to the fresh receipt it
99/// stands for. A digest the store does not hold is returned as it is.
100pub fn origin_digest(index: &Index, digest: &str) -> String {
101 match index.get(digest) {
102 Some(r) if r.value["volatile"]["cache"]["reused"] == true => r.value["volatile"]["cache"]
103 ["reused_from"]
104 .as_str()
105 .unwrap_or(digest)
106 .to_string(),
107 _ => digest.to_string(),
108 }
109}
110
111/// `cache.key`: sha256 over the canonical bytes of the key object.
112pub fn key(e: &Experiment, index: &Index) -> Result<String, StoreError> {
113 let deps: Vec<Value> = e
114 .dependencies
115 .iter()
116 .map(|(gate, receipt)| json!({ "gate": gate, "receipt": origin_digest(index, receipt) }))
117 .collect();
118 let mut obj = json!({
119 "manifest_digest": e.manifest_digest,
120 "binary_sha256": e.binary_sha256,
121 "build_inputs_digest": e.build_inputs_digest,
122 "machine_digest": e.machine_digest,
123 "dependencies": deps,
124 "runner_schema": SCHEMA,
125 "pins": e.pins,
126 });
127 if let Some(args) = &e.args_override {
128 obj["args_override"] = json!(args);
129 }
130 canonical_digest(&obj)
131}
132
133/// The key members of a stored receipt, read from its `core`.
134fn experiment_of(src: &Stored) -> Option<Experiment> {
135 let core = &src.value["core"];
136 let text = |k: &str| core[k].as_str().map(str::to_string);
137 let deps = core["dependencies"]
138 .as_array()?
139 .iter()
140 .map(|d| {
141 Some((
142 d["gate"].as_str()?.to_string(),
143 d["receipt"].as_str()?.to_string(),
144 ))
145 })
146 .collect::<Option<Vec<_>>>()?;
147 Some(Experiment {
148 manifest_digest: text("manifest_digest")?,
149 binary_sha256: text("binary_sha256"),
150 build_inputs_digest: text("build_inputs_digest")?,
151 machine_digest: text("machine_digest")?,
152 dependencies: deps,
153 pins: core.get("pins")?.clone(),
154 args_override: None,
155 })
156}
157
158/// Why an earlier receipt that carries the right key still cannot be reused.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum Unusable {
161 /// It was itself a reuse; only fresh results are sources.
162 AlreadyReused,
163 /// Its verdict describes a situation, not an experiment (NOT_RUN,
164 /// BLOCKED_*, MISSING_IMPLEMENTATION).
165 NotAnExperiment,
166 /// The tree was dirty before or after the run.
167 UncleanTree,
168 /// HEAD moved during the run.
169 HeadMoved,
170 /// The run went past its time limit.
171 TimedOut,
172 /// The key written in the receipt is not what its own contents hash to.
173 KeyMismatch,
174 /// The machine descriptor does not hash to the machine digest.
175 MachineMismatch,
176 /// The captured environment differs from the current one.
177 EnvDiffers,
178 /// A stdout or stderr blob it names is missing from the store.
179 BlobMissing,
180}
181
182impl Unusable {
183 pub fn text(self) -> &'static str {
184 match self {
185 Unusable::AlreadyReused => "it was itself a reuse, not a fresh run",
186 Unusable::NotAnExperiment => "its verdict is not PASS or FAIL",
187 Unusable::UncleanTree => "the tree had uncommitted changes when it ran",
188 Unusable::HeadMoved => "HEAD moved while it ran",
189 Unusable::TimedOut => "it ran past its time limit",
190 Unusable::KeyMismatch => "its recorded key does not match its own contents",
191 Unusable::MachineMismatch => "its machine descriptor does not match its machine digest",
192 Unusable::EnvDiffers => "the captured environment differs from the current one",
193 Unusable::BlobMissing => "a log it refers to is missing from the evidence store",
194 }
195 }
196}
197
198/// May `src` (which carries `key`) stand in for a run now? Fail closed: the
199/// first problem found makes it unusable.
200pub fn usable(
201 src: &Stored,
202 key: &str,
203 index: &Index,
204 store: &Store,
205 env: &Value,
206) -> Result<(), Unusable> {
207 let (core, vol) = (&src.value["core"], &src.value["volatile"]);
208 if vol["cache"]["reused"] != false {
209 return Err(Unusable::AlreadyReused);
210 }
211 if !matches!(src.verdict(), Some(Verdict::Pass | Verdict::Fail)) {
212 return Err(Unusable::NotAnExperiment);
213 }
214 if core["tree_clean_before"] != true || core["tree_clean_after"] != true {
215 return Err(Unusable::UncleanTree);
216 }
217 if core["commit_unchanged_after"] != true {
218 return Err(Unusable::HeadMoved);
219 }
220 if vol["timeout_exceeded"] != false {
221 return Err(Unusable::TimedOut);
222 }
223 // Recompute the key from the receipt's own contents; never trust the
224 // stored value alone.
225 let recomputed = experiment_of(src).and_then(|e| self::key(&e, index).ok());
226 if recomputed.as_deref() != Some(key) {
227 return Err(Unusable::KeyMismatch);
228 }
229 let machine_digest = core.get("machine").and_then(|m| canonical_digest(m).ok());
230 if machine_digest.as_deref() != core["machine_digest"].as_str() {
231 return Err(Unusable::MachineMismatch);
232 }
233 if &core["env"] != env {
234 return Err(Unusable::EnvDiffers);
235 }
236 for member in ["stdout_sha256", "stderr_sha256"] {
237 match core[member].as_str() {
238 Some(sha) if store.blob_exists(sha) => {}
239 _ => return Err(Unusable::BlobMissing),
240 }
241 }
242 Ok(())
243}
244
245/// Why there is no hit.
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum Miss {
248 /// No receipt in the store carries this key.
249 NoReceipt,
250 /// The newest receipt with this key cannot be reused.
251 Unusable { digest: String, why: Unusable },
252}
253
254impl Miss {
255 pub fn text(&self) -> String {
256 match self {
257 Miss::NoReceipt => "no earlier receipt has this key".to_string(),
258 Miss::Unusable { digest, why } => format!(
259 "the newest receipt with this key ({}) cannot be reused: {}",
260 digest.chars().take(12).collect::<String>(),
261 why.text()
262 ),
263 }
264 }
265}
266
267#[derive(Debug)]
268pub enum Lookup<'a> {
269 Hit(&'a Stored),
270 Miss(Miss),
271}
272
273/// The newest usable fresh receipt whose `cache.key` is `key`.
274pub fn lookup<'a>(index: &'a Index, store: &Store, key: &str, env: &Value) -> Lookup<'a> {
275 let mut first_rejection: Option<Miss> = None;
276 for r in index.receipts().iter().rev() {
277 if r.value["volatile"]["cache"]["key"] != key {
278 continue;
279 }
280 match usable(r, key, index, store, env) {
281 Ok(()) => return Lookup::Hit(r),
282 Err(why) => {
283 first_rejection.get_or_insert(Miss::Unusable {
284 digest: r.digest.clone(),
285 why,
286 });
287 }
288 }
289 }
290 Lookup::Miss(first_rejection.unwrap_or(Miss::NoReceipt))
291}
292
293/// The `core` of a reuse receipt: the source's core, with `commit` set to the
294/// commit being checked.
295pub fn reused_core(src: &Stored, commit: &str) -> Value {
296 let mut core = src.value["core"].clone();
297 core["commit"] = json!(commit);
298 core
299}
300
301/// The `volatile.cache` member.
302pub fn cache_member(key: &str, reused_from: Option<&str>, mode: Mode) -> Value {
303 json!({
304 "key": key,
305 "reused": reused_from.is_some(),
306 "reused_from": reused_from,
307 "mode": mode.as_str(),
308 })
309}
310
311/// Which key members of `src` differ from `now`, in plain words.
312pub fn differences(src: &Stored, now: &Experiment, index: &Index) -> Vec<&'static str> {
313 let then = match experiment_of(src) {
314 Some(t) => t,
315 None => return vec!["the receipt itself (it is missing key members)"],
316 };
317 let resolve = |e: &Experiment| -> Vec<(String, String)> {
318 e.dependencies
319 .iter()
320 .map(|(g, r)| (g.clone(), origin_digest(index, r)))
321 .collect()
322 };
323 let mut out = Vec::new();
324 if then.manifest_digest != now.manifest_digest {
325 out.push("the gate manifest");
326 }
327 if then.binary_sha256 != now.binary_sha256 {
328 out.push("the program (run.exec)");
329 }
330 if then.build_inputs_digest != now.build_inputs_digest {
331 out.push("the declared input files");
332 }
333 if then.machine_digest != now.machine_digest {
334 out.push("the machine");
335 }
336 if resolve(&then) != resolve(now) {
337 out.push("a dependency's receipt");
338 }
339 if then.pins != now.pins {
340 out.push("the pinned dependencies");
341 }
342 out
343}
344
345fn short(s: &str) -> String {
346 s.chars().take(12).collect()
347}
348
349/// For `why`: what a run of `target` and of everything it depends on would do
350/// about the cache right now, one list of plain lines per gate (node number).
351/// Nothing is run and nothing is written.
352pub fn explain_chain(
353 root: &Path,
354 graph: &crate::graph::Graph,
355 index: &Index,
356 opts: &runner::Options,
357 commit: &str,
358 target: usize,
359) -> BTreeMap<usize, Vec<String>> {
360 let store = Store::new(&opts.evidence_dir);
361 let env = runner::captured_env();
362 let dirty = runner::working_tree_dirty(root);
363 let chain = graph.with_dependencies(&[target]);
364 let mut out: BTreeMap<usize, Vec<String>> = BTreeMap::new();
365 // The receipt a dependency would stand on after a run: Some only if that
366 // dependency would itself be reused.
367 let mut stands_on: BTreeMap<usize, Option<String>> = BTreeMap::new();
368 for &i in graph.order() {
369 if !chain.contains(&i) {
370 continue;
371 }
372 let node = graph.node(i);
373 let m = &node.manifest;
374 let mut lines: Vec<String> = Vec::new();
375 let mode = policy(m.cache_allowed, opts.no_cache);
376 let mut reuse: Option<String> = None;
377 match (mode, dirty.as_ref()) {
378 (Mode::Never, _) => {
379 lines.push("cache: never (the manifest says cache: never), so it always runs".to_string())
380 }
381 (Mode::Disabled, _) => lines.push("cache: switched off by --no-cache, so it would run".to_string()),
382 (_, Err(e)) => lines.push(format!("cache: not used, the tree state is unknown ({e})")),
383 (_, Ok(&true)) => lines.push(
384 "cache: not used, the tree has uncommitted changes (a run is refused until it is clean)"
385 .to_string(),
386 ),
387 (Mode::Allow, Ok(&false)) => {
388 let waiting: Vec<&str> = m
389 .depends_on
390 .iter()
391 .filter(|d| {
392 graph
393 .index_of(d)
394 .is_none_or(|di| stands_on.get(&di).is_none_or(|s| s.is_none()))
395 })
396 .map(String::as_str)
397 .collect();
398 if let Some(first) = waiting.first() {
399 lines.push(format!(
400 "cache: miss, it depends on {first}, which would run again, so its receipt would change"
401 ));
402 } else {
403 match runner::identity(root, &node.path, m, &opts.hardware, opts.sandbox) {
404 Err(e) => lines.push(format!("cache: miss, cannot digest the inputs ({e})")),
405 Ok(id) => {
406 let deps: Vec<(String, String)> = m
407 .depends_on
408 .iter()
409 .filter_map(|d| {
410 let di = graph.index_of(d)?;
411 Some((d.clone(), stands_on.get(&di)?.clone()?))
412 })
413 .collect();
414 let now = Experiment {
415 manifest_digest: m.digest.clone(),
416 binary_sha256: id.binary_sha.clone(),
417 build_inputs_digest: id.inputs_digest.clone(),
418 machine_digest: id.machine_digest.clone(),
419 dependencies: deps,
420 pins: opts.pins.clone(),
421 args_override: None,
422 };
423 match key(&now, index) {
424 Err(e) => lines.push(format!("cache: miss, cannot build the key ({e})")),
425 Ok(k) => match lookup(index, &store, &k, &env) {
426 Lookup::Hit(src) => {
427 lines.push(format!(
428 "cache: hit, a run would reuse receipt {} ({}, made at commit {}); key {}",
429 short(&src.digest),
430 src.verdict().map_or("UNKNOWN", |v| v.as_str()),
431 short(src.commit()),
432 short(&k)
433 ));
434 reuse = Some(src.digest.clone());
435 }
436 Lookup::Miss(miss) => {
437 lines.push(format!("cache: miss, {} (key {})", miss.text(), short(&k)));
438 if let Some(prev) = index.latest(&node.id) {
439 let d = differences(prev, &now, index);
440 if !d.is_empty() {
441 lines.push(format!(
442 "cache: since its newest receipt {} these changed: {}",
443 short(&prev.digest),
444 d.join(", ")
445 ));
446 }
447 }
448 }
449 },
450 }
451 }
452 }
453 }
454 }
455 }
456 if let Some(r) = index.latest_at(&node.id, commit) {
457 if r.value["volatile"]["cache"]["reused"] == true {
458 lines.push(format!(
459 "the receipt for this commit ({}) was reused from {}, not run; it is not qualification evidence",
460 short(&r.digest),
461 short(r.value["volatile"]["cache"]["reused_from"].as_str().unwrap_or(""))
462 ));
463 }
464 }
465 stands_on.insert(i, reuse);
466 out.insert(i, lines);
467 }
468 out
469}
470
471// ---- across heads ------------------------------------------------------
472//
473// The key above has no commit in it, but the worker gives every head its own
474// evidence store (`evidence/<repo>/<sha>`), so a result made for one head was
475// never found by another. The shared store below closes that gap without a
476// second cache: a fresh receipt that `usable` accepts is copied, with its log
477// blobs and the dependency receipts its key rests on, into
478// `<state>/gate-cache/<repo>/` (itself a `Store`) under a pointer
479// `keys/<key>`. A head that misses in its own store imports that closure into
480// its own store and then takes the ordinary hit path: the reuse receipt says
481// `reused_from` (the source digest) and `reused_from_commit` (the source
482// head), the bundle entry is `cached` with the same two facts. Nothing is
483// reused that `lookup` would not reuse inside one head.
484//
485// Only a gate whose result is a function of its key may cross heads; see
486// [`cross_head`]. A gate whose author has not promised complete inputs
487// (`cache: inputs_complete`) crosses heads only between byte-identical trees:
488// SC-TEST reads the root README.md and lists only crates/, tools/, scripts/
489// (tests/local_ci.rs, the U gate). The judge binary and the exec helper are part of the
490// machine object (`runner::identity`), so an entry never outlives either.
491
492/// Why a gate's result stays inside the head it was made for. A gate that
493/// gets one of these still uses the per-head cache exactly as before.
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum Local {
496 /// `cache: never`: the author's rule.
497 CacheNever,
498 /// gb10 or nvrm: the result depends on chip state (clocks, memory left,
499 /// other holders of the GPU), which no input file describes.
500 ChipState,
501 /// bare_metal or aarch64-only boot gates: the machine is the input.
502 BareMetal,
503 /// `requires: operator`: a person ran a step the manifest cannot see.
504 Operator,
505 /// `cache_scope: hardware`: the author says the result belongs to one
506 /// piece of hardware (timing and chip gates use it).
507 HardwareScope,
508 /// `exactness: APPROXIMATE` or `ADVISORY`: the result is not exact, so
509 /// equal inputs do not promise an equal result (timing, sampling).
510 NotExact,
511}
512
513impl Local {
514 pub fn text(self) -> &'static str {
515 match self {
516 Local::CacheNever => "the manifest says cache: never",
517 Local::ChipState => "a GPU gate: its result depends on chip state no input describes",
518 Local::BareMetal => "a bare-metal gate: the machine itself is the input",
519 Local::Operator => "an operator step: a person did something the inputs cannot show",
520 Local::HardwareScope => {
521 "cache_scope: hardware, the result belongs to one piece of hardware"
522 }
523 Local::NotExact => {
524 "not EXACT or BOUNDED, so equal inputs do not promise an equal result"
525 }
526 }
527 }
528}
529
530/// How far a gate's result may travel to other heads with the same key.
531#[derive(Debug, Clone, Copy, PartialEq, Eq)]
532pub enum Reach {
533 /// `cache: inputs_complete` and real inputs: any head whose declared
534 /// inputs (and the rest of the key) are identical.
535 Inputs,
536 /// Any other cacheable gate: only a head whose whole tree is identical
537 /// (a squash merge of an up-to-date PR, a re-push, a duplicate PR). Its
538 /// manifest promises no more, so the whole tree is its input.
539 Tree,
540}
541
542/// May this gate's result be reused by another head with the same key, and
543/// how far? The first reason it may not wins (fail closed).
544pub fn cross_head(m: &crate::manifest::Manifest) -> Result<Reach, Local> {
545 use crate::manifest::{CacheScope, Exactness};
546 let req = |r: &str| m.requires.iter().any(|x| x == r);
547 if !m.cache_allowed {
548 return Err(Local::CacheNever);
549 }
550 if req("gb10") || req("nvrm") {
551 return Err(Local::ChipState);
552 }
553 if req("bare_metal") || req("analog_eligible") {
554 return Err(Local::BareMetal);
555 }
556 if req("operator") {
557 return Err(Local::Operator);
558 }
559 if m.cache_scope == CacheScope::Hardware {
560 return Err(Local::HardwareScope);
561 }
562 if !matches!(m.exactness, Exactness::Exact | Exactness::Bounded) {
563 return Err(Local::NotExact);
564 }
565 let whole = |i: &str| {
566 let t = i.trim().trim_start_matches("./").trim_end_matches('/');
567 t.is_empty() || t == "." || t.split('/').next().is_some_and(|c| c.contains('*'))
568 };
569 // No promise, no inputs, or the whole tree as an input: the key cannot
570 // tell two trees apart, so the tree id must.
571 if !m.inputs_complete || m.inputs.is_empty() || m.inputs.iter().any(|i| whole(i)) {
572 return Ok(Reach::Tree);
573 }
574 Ok(Reach::Inputs)
575}
576
577/// The name of a shared entry: the key alone for [`Reach::Inputs`], the key
578/// and the tree id for [`Reach::Tree`].
579pub fn slot(key: &str, reach: Reach, tree: &str) -> String {
580 match reach {
581 Reach::Inputs => key.to_string(),
582 Reach::Tree => format!("{key}-{tree}"),
583 }
584}
585
586/// The cross-head store of one repository: `<dir>/<digest>.json`,
587/// `<dir>/blobs/`, `<dir>/keys/<key>` (one line: the receipt digest) and
588/// `<dir>/locks/<key>.lock`.
589#[derive(Debug, Clone)]
590pub struct Shared {
591 dir: std::path::PathBuf,
592}
593
594/// Held while one head decides about a key and, on a miss, runs the gate and
595/// publishes the result, so a second judge of the same key waits and reuses
596/// instead of running it again.
597pub struct KeyLock {
598 _lock: crate::resources::TargetLock,
599}
600
601impl Shared {
602 pub fn new(dir: &Path) -> Shared {
603 Shared {
604 dir: dir.to_path_buf(),
605 }
606 }
607
608 pub fn dir(&self) -> &Path {
609 &self.dir
610 }
611
612 fn store(&self) -> Store {
613 Store::new(&self.dir)
614 }
615
616 fn pointer(&self, slot: &str) -> std::path::PathBuf {
617 self.dir.join("keys").join(slot)
618 }
619
620 pub fn lock(&self, slot: &str) -> std::io::Result<KeyLock> {
621 let path = self.dir.join("locks").join(format!("{slot}.lock"));
622 Ok(KeyLock {
623 _lock: crate::resources::lock_target_dir(&path)?,
624 })
625 }
626
627 /// The source receipt the pointer for `key` names, if the store holds it
628 /// intact and it really carries that key.
629 pub fn source(&self, slot: &str, key: &str) -> Option<Stored> {
630 let digest = std::fs::read_to_string(self.pointer(slot)).ok()?;
631 let src = self.store().get_receipt(digest.trim())?;
632 (src.value["volatile"]["cache"]["key"] == key).then_some(src)
633 }
634
635 /// Copy `digest` and everything its key rests on from `from` to `to`:
636 /// the receipt, its log blobs, every dependency receipt it names and, for
637 /// a dependency that was itself reused, the receipt it was reused from.
638 fn copy_closure(from: &Store, to: &Store, digest: &str) -> Result<(), String> {
639 let mut todo = vec![digest.to_string()];
640 let mut seen = std::collections::BTreeSet::new();
641 while let Some(d) = todo.pop() {
642 if !seen.insert(d.clone()) {
643 continue;
644 }
645 let r = from
646 .get_receipt(&d)
647 .ok_or_else(|| format!("receipt {} is missing or damaged", short(&d)))?;
648 for member in ["stdout_sha256", "stderr_sha256"] {
649 if let Some(sha) = r.value["core"][member].as_str() {
650 if let Some(bytes) = from.read_blob(sha) {
651 to.put_blob(&bytes).map_err(|e| e.to_string())?;
652 }
653 }
654 }
655 to.put_receipt(&r.value).map_err(|e| e.to_string())?;
656 if let Some(deps) = r.value["core"]["dependencies"].as_array() {
657 todo.extend(
658 deps.iter()
659 .filter_map(|x| x["receipt"].as_str().map(str::to_string)),
660 );
661 }
662 if let Some(src) = r.value["volatile"]["cache"]["reused_from"].as_str() {
663 todo.push(src.to_string());
664 }
665 }
666 Ok(())
667 }
668
669 /// Bring the shared source of `key` into a head's own store. Ok(None)
670 /// when there is none; the head's own `lookup` then decides as always.
671 pub fn import(&self, slot: &str, key: &str, head: &Store) -> Result<Option<String>, String> {
672 let Some(src) = self.source(slot, key) else {
673 return Ok(None);
674 };
675 Self::copy_closure(&self.store(), head, &src.digest)?;
676 Ok(Some(src.digest))
677 }
678
679 /// Publish the fresh receipt `digest` of a head's store for `key`. The
680 /// caller has checked it with `usable`; the pointer is written last, by
681 /// rename, so a reader sees either no entry or a whole one.
682 pub fn publish(&self, slot: &str, digest: &str, head: &Store) -> Result<(), String> {
683 Self::copy_closure(head, &self.store(), digest)?;
684 let keys = self.dir.join("keys");
685 std::fs::create_dir_all(&keys)
686 .map_err(|e| format!("cannot create {}: {e}", keys.display()))?;
687 let tmp = keys.join(format!(".tmp-{slot}-{}", std::process::id()));
688 std::fs::write(&tmp, format!("{digest}\n"))
689 .map_err(|e| format!("cannot write key pointer: {e}"))?;
690 std::fs::rename(&tmp, self.pointer(slot))
691 .map_err(|e| format!("cannot publish key pointer: {e}"))
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use crate::graph;
699 use crate::resources::{GpuConfig, Hardware};
700 use crate::runner::{self, CacheNote, Options, Outcome};
701 use crate::testutil::{git, init_repo, write_file, TempDir};
702 use std::collections::BTreeSet;
703 use std::fs;
704 use std::path::PathBuf;
705 use std::time::Duration;
706
707 const SCRIPT: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n";
708 const FAILING_SCRIPT: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\nexit 1\n";
709
710 fn gate_text(id: &str, deps: &[&str], counter: &Path, extra: &str) -> String {
711 let dep_block = if deps.is_empty() {
712 String::new()
713 } else {
714 format!(
715 "depends_on:\n{}",
716 deps.iter()
717 .map(|d| format!(" - {d}\n"))
718 .collect::<String>()
719 )
720 };
721 format!(
722 "gate: {id}\nmanifest_version: 1\nowner: t\nrequires:\n - host\n{dep_block}inputs:\n - data/\nrun:\n exec: tools/run.sh\n args: [\"{}\"]\nexpects:\n exit: 0\n observe: [\"n == 3\"]\n verdict: PASS\ntimeout: 20s\n{extra}",
723 counter.display()
724 )
725 }
726
727 struct Fx {
728 repo: TempDir,
729 ev: TempDir,
730 scratch: TempDir,
731 }
732
733 impl Fx {
734 fn new(script: &str) -> Fx {
735 let scratch = TempDir::new("c-scratch");
736 let counter = scratch.path().join("a.count");
737 let gate = gate_text("C-A", &[], &counter, "");
738 let repo = init_repo(
739 "c-repo",
740 &[
741 ("tools/run.sh", script, true),
742 ("tests/a.gate", gate.as_str(), false),
743 ("data/in.txt", "one\n", false),
744 ("README", "hello\n", false),
745 ],
746 );
747 Fx {
748 repo,
749 ev: TempDir::new("c-ev"),
750 scratch,
751 }
752 }
753 fn counter(&self, name: &str) -> PathBuf {
754 self.scratch.path().join(format!("{name}.count"))
755 }
756 /// How many times the gate's program really ran.
757 fn runs(&self, name: &str) -> usize {
758 fs::read_to_string(self.counter(name)).map_or(0, |s| s.lines().count())
759 }
760 fn opts(&self) -> Options {
761 let mut o = Options::new(self.ev.path().join("out"));
762 o.kill_grace = Duration::from_millis(300);
763 o.hardware = Hardware {
764 gb10_present: false,
765 qemu_available: false,
766 };
767 o.gpu = GpuConfig::rooted_at(self.scratch.path());
768 o
769 }
770 fn store(&self) -> Store {
771 Store::new(&self.ev.path().join("out"))
772 }
773 fn run(&self, opts: &Options) -> Outcome {
774 runner::run_gate(
775 self.repo.path(),
776 &self.repo.path().join("tests/a.gate"),
777 opts,
778 )
779 .unwrap()
780 }
781 fn commit(&self, rel: &str, content: &str) {
782 write_file(self.repo.path(), rel, content, false);
783 git(self.repo.path(), &["add", "-A"]);
784 git(self.repo.path(), &["commit", "-q", "-m", rel]);
785 }
786 fn head(&self) -> String {
787 runner::head(self.repo.path()).unwrap()
788 }
789 fn receipt(&self, o: &Outcome) -> Value {
790 serde_json::from_slice(&fs::read(o.receipt_path.as_ref().unwrap()).unwrap()).unwrap()
791 }
792 }
793
794 fn reused_from(o: &Outcome) -> Option<&str> {
795 match &o.cache {
796 CacheNote::Reused { from, .. } => Some(from),
797 _ => None,
798 }
799 }
800
801 fn fresh_pass(fx: &Fx) -> Outcome {
802 let o = fx.run(&fx.opts());
803 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason);
804 assert_eq!(reused_from(&o), None);
805 o
806 }
807
808 // ---- hit -----------------------------------------------------------
809
810 #[test]
811 fn identical_experiment_is_reused_and_not_rerun() {
812 let fx = Fx::new(SCRIPT);
813 let first = fresh_pass(&fx);
814 assert_eq!(fx.runs("a"), 1);
815 let second = fx.run(&fx.opts());
816 assert_eq!(second.verdict, Verdict::Pass);
817 assert_eq!(
818 reused_from(&second),
819 first.receipt_digest.as_deref(),
820 "must name the receipt it took the result from"
821 );
822 assert_eq!(fx.runs("a"), 1, "the program must not run again");
823 let (r1, r2) = (fx.receipt(&first), fx.receipt(&second));
824 assert_ne!(first.receipt_digest, second.receipt_digest);
825 assert_eq!(r2["volatile"]["cache"]["reused"], true);
826 assert_eq!(
827 r2["volatile"]["cache"]["reused_from"],
828 json!(first.receipt_digest)
829 );
830 assert_eq!(
831 r2["volatile"]["cache"]["key"],
832 r1["volatile"]["cache"]["key"]
833 );
834 assert_eq!(r2["volatile"]["cache"]["mode"], "allow");
835 assert_eq!(r1["volatile"]["cache"]["reused"], false);
836 assert_eq!(r1["volatile"]["cache"]["mode"], "allow");
837 assert_eq!(r1["core"], r2["core"], "same commit: identical core");
838 }
839
840 #[test]
841 fn reuse_across_commits_records_the_commit_that_was_checked() {
842 let fx = Fx::new(SCRIPT);
843 let first = fresh_pass(&fx);
844 let old_head = fx.head();
845 // A change to a file the gate does not depend on.
846 fx.commit("README", "changed\n");
847 assert_ne!(fx.head(), old_head);
848 let second = fx.run(&fx.opts());
849 assert_eq!(reused_from(&second), first.receipt_digest.as_deref());
850 assert_eq!(fx.runs("a"), 1);
851 let (mut c1, mut c2) = (
852 fx.receipt(&first)["core"].clone(),
853 fx.receipt(&second)["core"].clone(),
854 );
855 assert_eq!(c1["commit"], old_head);
856 assert_eq!(
857 c2["commit"],
858 fx.head(),
859 "the reuse receipt is for this commit"
860 );
861 c1["commit"] = Value::Null;
862 c2["commit"] = Value::Null;
863 assert_eq!(c1, c2, "everything else in core is the source's");
864 }
865
866 #[test]
867 fn a_failed_result_is_reused_too_and_still_fails() {
868 let fx = Fx::new(FAILING_SCRIPT);
869 let first = fx.run(&fx.opts());
870 assert_eq!(first.verdict, Verdict::Fail);
871 let second = fx.run(&fx.opts());
872 assert_eq!(second.verdict, Verdict::Fail);
873 assert_eq!(second.reason, first.reason);
874 assert_eq!(reused_from(&second), first.receipt_digest.as_deref());
875 assert_eq!(fx.runs("a"), 1);
876 }
877
878 // ---- misses --------------------------------------------------------
879
880 #[test]
881 fn miss_when_a_declared_input_changes() {
882 let fx = Fx::new(SCRIPT);
883 fresh_pass(&fx);
884 fx.commit("data/in.txt", "two\n");
885 let second = fx.run(&fx.opts());
886 assert_eq!(second.verdict, Verdict::Pass);
887 assert!(
888 matches!(second.cache, CacheNote::Miss(_)),
889 "{:?}",
890 second.cache
891 );
892 assert_eq!(fx.runs("a"), 2, "the program must run again");
893 // And the new result is now the one that is reused.
894 let third = fx.run(&fx.opts());
895 assert_eq!(reused_from(&third), second.receipt_digest.as_deref());
896 assert_eq!(fx.runs("a"), 2);
897 }
898
899 #[test]
900 fn miss_when_the_program_changes() {
901 let fx = Fx::new(SCRIPT);
902 fresh_pass(&fx);
903 fx.commit("tools/run.sh", &format!("{SCRIPT}# edited\n"));
904 let second = fx.run(&fx.opts());
905 assert!(
906 matches!(second.cache, CacheNote::Miss(_)),
907 "{:?}",
908 second.cache
909 );
910 assert_eq!(fx.runs("a"), 2);
911 }
912
913 #[test]
914 fn miss_when_the_manifest_changes_even_by_a_comment() {
915 let fx = Fx::new(SCRIPT);
916 fresh_pass(&fx);
917 let text = fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap();
918 fx.commit("tests/a.gate", &format!("# note\n{text}"));
919 let second = fx.run(&fx.opts());
920 assert!(
921 matches!(second.cache, CacheNote::Miss(_)),
922 "{:?}",
923 second.cache
924 );
925 assert_eq!(fx.runs("a"), 2);
926 }
927
928 #[test]
929 fn miss_when_the_machine_differs() {
930 let fx = Fx::new(SCRIPT);
931 fresh_pass(&fx);
932 let mut o = fx.opts();
933 o.hardware.qemu_available = true;
934 let second = fx.run(&o);
935 assert!(
936 matches!(second.cache, CacheNote::Miss(_)),
937 "{:?}",
938 second.cache
939 );
940 assert_eq!(fx.runs("a"), 2);
941 }
942
943 #[test]
944 fn a_dirty_tree_is_refused_not_answered_from_the_cache() {
945 let fx = Fx::new(SCRIPT);
946 fresh_pass(&fx);
947 write_file(fx.repo.path(), "README", "dirty\n", false);
948 let second = fx.run(&fx.opts());
949 assert_eq!(second.verdict, Verdict::NotRun);
950 assert_eq!(second.reason, "dirty_tree");
951 assert_eq!(reused_from(&second), None);
952 assert_eq!(fx.runs("a"), 1);
953 }
954
955 #[test]
956 fn miss_on_a_dirty_tree_even_when_the_run_is_allowed() {
957 let fx = Fx::new(SCRIPT);
958 fresh_pass(&fx);
959 write_file(fx.repo.path(), "README", "dirty\n", false);
960 let mut o = fx.opts();
961 o.allow_dirty = true;
962 let second = fx.run(&o);
963 assert_eq!(second.verdict, Verdict::Pass);
964 assert!(
965 matches!(second.cache, CacheNote::Skipped(_)),
966 "{:?}",
967 second.cache
968 );
969 assert_eq!(fx.runs("a"), 2, "a dirty tree always runs");
970 let r = fx.receipt(&second);
971 assert_eq!(r["volatile"]["cache"]["mode"], "disabled");
972 assert_eq!(r["volatile"]["cache"]["reused"], false);
973 }
974
975 #[test]
976 fn a_receipt_from_a_dirty_tree_is_never_a_source() {
977 let fx = Fx::new(SCRIPT);
978 write_file(fx.repo.path(), "README", "dirty\n", false);
979 let mut o = fx.opts();
980 o.allow_dirty = true;
981 let dirty_run = fx.run(&o);
982 assert_eq!(dirty_run.verdict, Verdict::Pass);
983 git(fx.repo.path(), &["checkout", "--", "README"]);
984 let clean_run = fx.run(&fx.opts());
985 assert!(
986 matches!(clean_run.cache, CacheNote::Miss(_)),
987 "{:?}",
988 clean_run.cache
989 );
990 assert_eq!(fx.runs("a"), 2);
991 }
992
993 #[test]
994 fn miss_when_there_is_no_receipt_or_the_receipt_is_gone() {
995 let fx = Fx::new(SCRIPT);
996 // Nothing in the store at all.
997 let first = fx.run(&fx.opts());
998 assert!(
999 matches!(first.cache, CacheNote::Miss(_)),
1000 "{:?}",
1001 first.cache
1002 );
1003 assert_eq!(fx.runs("a"), 1);
1004 // The only receipt is removed.
1005 fs::remove_file(first.receipt_path.as_ref().unwrap()).unwrap();
1006 let second = fx.run(&fx.opts());
1007 assert!(
1008 matches!(second.cache, CacheNote::Miss(_)),
1009 "{:?}",
1010 second.cache
1011 );
1012 assert_eq!(fx.runs("a"), 2);
1013 }
1014
1015 #[test]
1016 fn miss_when_a_log_the_receipt_names_is_missing() {
1017 let fx = Fx::new(SCRIPT);
1018 let first = fresh_pass(&fx);
1019 let sha = fx.receipt(&first)["core"]["stdout_sha256"]
1020 .as_str()
1021 .unwrap()
1022 .to_string();
1023 fs::remove_file(fx.ev.path().join("out/blobs").join(format!("{sha}.log"))).unwrap();
1024 let second = fx.run(&fx.opts());
1025 assert!(
1026 matches!(second.cache, CacheNote::Miss(_)),
1027 "{:?}",
1028 second.cache
1029 );
1030 assert_eq!(fx.runs("a"), 2);
1031 }
1032
1033 #[test]
1034 fn a_receipt_that_is_itself_a_reuse_is_not_a_source() {
1035 let fx = Fx::new(SCRIPT);
1036 let first = fresh_pass(&fx);
1037 let second = fx.run(&fx.opts());
1038 assert!(reused_from(&second).is_some());
1039 // Only the reuse receipt is left.
1040 fs::remove_file(first.receipt_path.as_ref().unwrap()).unwrap();
1041 let third = fx.run(&fx.opts());
1042 assert!(
1043 matches!(third.cache, CacheNote::Miss(_)),
1044 "{:?}",
1045 third.cache
1046 );
1047 assert_eq!(fx.runs("a"), 2);
1048 }
1049
1050 // ---- forced rerun and never ---------------------------------------
1051
1052 #[test]
1053 fn no_cache_forces_a_fresh_run_and_says_so_in_the_receipt() {
1054 let fx = Fx::new(SCRIPT);
1055 let first = fresh_pass(&fx);
1056 let mut o = fx.opts();
1057 o.no_cache = true;
1058 let second = fx.run(&o);
1059 assert_eq!(second.verdict, Verdict::Pass);
1060 assert!(
1061 matches!(second.cache, CacheNote::Skipped(_)),
1062 "{:?}",
1063 second.cache
1064 );
1065 assert_eq!(fx.runs("a"), 2);
1066 let r = fx.receipt(&second);
1067 assert_eq!(r["volatile"]["cache"]["mode"], "disabled");
1068 assert_eq!(r["volatile"]["cache"]["reused"], false);
1069 assert_eq!(r["volatile"]["cache"]["reused_from"], Value::Null);
1070 // The fresh result is a valid source for a later ordinary run.
1071 let third = fx.run(&fx.opts());
1072 assert_eq!(reused_from(&third), second.receipt_digest.as_deref());
1073 assert_ne!(reused_from(&third), first.receipt_digest.as_deref());
1074 assert_eq!(fx.runs("a"), 2);
1075 }
1076
1077 #[test]
1078 fn a_gate_that_says_cache_never_always_runs() {
1079 let fx = Fx::new(SCRIPT);
1080 let counter = fx.counter("a");
1081 let text = gate_text("C-A", &[], &counter, "cache: never\n");
1082 fx.commit("tests/a.gate", &text);
1083 let first = fx.run(&fx.opts());
1084 assert_eq!(first.verdict, Verdict::Pass);
1085 let second = fx.run(&fx.opts());
1086 assert!(
1087 matches!(second.cache, CacheNote::Skipped(_)),
1088 "{:?}",
1089 second.cache
1090 );
1091 assert_eq!(fx.runs("a"), 2);
1092 assert_eq!(fx.receipt(&second)["volatile"]["cache"]["mode"], "never");
1093 }
1094
1095 #[test]
1096 fn replacement_args_never_use_or_feed_the_cache() {
1097 let fx = Fx::new(SCRIPT);
1098 let other = fx.counter("other");
1099 let mut o = fx.opts();
1100 o.args_override = Some(vec![other.display().to_string()]);
1101 // 1. A run with replacement args does not reuse an ordinary run.
1102 fresh_pass(&fx);
1103 let with_args = fx.run(&o);
1104 assert!(
1105 matches!(with_args.cache, CacheNote::Skipped(_)),
1106 "{:?}",
1107 with_args.cache
1108 );
1109 assert_eq!(fx.runs("other"), 1);
1110 // 2. And an ordinary run does not reuse the replacement-args run:
1111 // remove the ordinary receipt, the other one must not stand in.
1112 let fx2 = Fx::new(SCRIPT);
1113 let other2 = fx2.counter("other");
1114 let mut o2 = fx2.opts();
1115 o2.args_override = Some(vec![other2.display().to_string()]);
1116 let first = fx2.run(&o2);
1117 assert_eq!(first.verdict, Verdict::Pass);
1118 let plain = fx2.run(&fx2.opts());
1119 assert!(
1120 matches!(plain.cache, CacheNote::Miss(_)),
1121 "{:?}",
1122 plain.cache
1123 );
1124 assert_eq!(fx2.runs("a"), 1, "the ordinary run really ran");
1125 }
1126
1127 // ---- dependencies ---------------------------------------------------
1128
1129 fn two_gate_fixture() -> Fx {
1130 let fx = Fx::new(SCRIPT);
1131 let b = gate_text("C-B", &["C-A"], &fx.counter("b"), "");
1132 fx.commit("tests/b.gate", &b);
1133 fx
1134 }
1135
1136 fn run_all(fx: &Fx, opts: &Options) -> BTreeMap<String, Outcome> {
1137 let g = graph::load(fx.repo.path()).unwrap();
1138 let all: BTreeSet<usize> = (0..g.len()).collect();
1139 runner::run_graph(fx.repo.path(), &g, &all, opts)
1140 .unwrap()
1141 .results
1142 .into_iter()
1143 .collect()
1144 }
1145
1146 #[test]
1147 fn a_whole_graph_is_reused_including_gates_that_rest_on_a_reused_gate() {
1148 let fx = two_gate_fixture();
1149 let first = run_all(&fx, &fx.opts());
1150 assert!(first.values().all(|o| o.verdict == Verdict::Pass));
1151 assert_eq!((fx.runs("a"), fx.runs("b")), (1, 1));
1152 let second = run_all(&fx, &fx.opts());
1153 assert_eq!(
1154 reused_from(&second["C-A"]),
1155 first["C-A"].receipt_digest.as_deref()
1156 );
1157 assert_eq!(
1158 reused_from(&second["C-B"]),
1159 first["C-B"].receipt_digest.as_deref(),
1160 "B rests on a reused A and must still be a hit"
1161 );
1162 assert_eq!((fx.runs("a"), fx.runs("b")), (1, 1));
1163 }
1164
1165 #[test]
1166 fn a_change_under_a_dependency_reruns_it_and_everything_that_rests_on_it() {
1167 let fx = two_gate_fixture();
1168 run_all(&fx, &fx.opts());
1169 // Gate A's own input (data/ is shared by both gates here, so give B a
1170 // different one first to see that only the chain moves).
1171 let b = gate_text("C-B", &["C-A"], &fx.counter("b"), "").replace("data/", "other/");
1172 fx.commit("other/x.txt", "x\n");
1173 fx.commit("tests/b.gate", &b);
1174 run_all(&fx, &fx.opts());
1175 assert_eq!((fx.runs("a"), fx.runs("b")), (1, 2), "only B changed");
1176 fx.commit("data/in.txt", "two\n");
1177 let after = run_all(&fx, &fx.opts());
1178 assert!(after.values().all(|o| reused_from(o).is_none()));
1179 assert_eq!(
1180 (fx.runs("a"), fx.runs("b")),
1181 (2, 3),
1182 "A changed, so B reruns too"
1183 );
1184 }
1185
1186 // ---- the key itself -------------------------------------------------
1187
1188 fn base() -> Experiment {
1189 Experiment {
1190 manifest_digest: "m".repeat(64),
1191 binary_sha256: Some("b".repeat(64)),
1192 build_inputs_digest: "i".repeat(64),
1193 machine_digest: "c".repeat(64),
1194 dependencies: vec![("G".to_string(), "d".repeat(64))],
1195 pins: json!([]),
1196 args_override: None,
1197 }
1198 }
1199
1200 #[test]
1201 fn the_key_is_deterministic() {
1202 let idx = Index::default();
1203 assert_eq!(key(&base(), &idx).unwrap(), key(&base(), &idx).unwrap());
1204 assert_eq!(key(&base(), &idx).unwrap().len(), 64);
1205 }
1206
1207 #[test]
1208 fn every_key_member_changes_the_key() {
1209 let idx = Index::default();
1210 let k0 = key(&base(), &idx).unwrap();
1211 let mut variants: Vec<(&str, Experiment)> = Vec::new();
1212 let mut e = base();
1213 e.manifest_digest = "x".repeat(64);
1214 variants.push(("manifest", e));
1215 let mut e = base();
1216 e.binary_sha256 = Some("x".repeat(64));
1217 variants.push(("binary", e));
1218 let mut e = base();
1219 e.binary_sha256 = None;
1220 variants.push(("no binary", e));
1221 let mut e = base();
1222 e.build_inputs_digest = "x".repeat(64);
1223 variants.push(("inputs", e));
1224 let mut e = base();
1225 e.machine_digest = "x".repeat(64);
1226 variants.push(("machine", e));
1227 let mut e = base();
1228 e.dependencies = vec![("G".to_string(), "x".repeat(64))];
1229 variants.push(("dependency receipt", e));
1230 let mut e = base();
1231 e.dependencies = vec![];
1232 variants.push(("no dependency", e));
1233 let mut e = base();
1234 e.pins = json!([{ "name": "p", "commit": "c" }]);
1235 variants.push(("pins", e));
1236 let mut e = base();
1237 e.args_override = Some(vec!["x".to_string()]);
1238 variants.push(("replacement args", e));
1239 for (what, e) in variants {
1240 assert_ne!(key(&e, &idx).unwrap(), k0, "{what} must change the key");
1241 }
1242 }
1243
1244 #[test]
1245 fn policy_cache_never_beats_everything() {
1246 assert_eq!(policy(true, false), Mode::Allow);
1247 assert_eq!(policy(true, true), Mode::Disabled);
1248 assert_eq!(policy(false, false), Mode::Never);
1249 assert_eq!(policy(false, true), Mode::Never);
1250 assert_eq!(Mode::Allow.as_str(), "allow");
1251 assert_eq!(Mode::Never.as_str(), "never");
1252 assert_eq!(Mode::Disabled.as_str(), "disabled");
1253 }
1254
1255 // ---- receipts that carry the right key but cannot be trusted ---------
1256
1257 /// A store holding one forged copy of `first`'s receipt (and its logs), so
1258 /// the original cannot mask the result.
1259 fn forged(fx: &Fx, first: &Outcome, edit: impl FnOnce(&mut Value)) -> (TempDir, Value) {
1260 let original = fx.receipt(first);
1261 let dir = TempDir::new("c-forged");
1262 let blobs = dir.path().join("blobs");
1263 fs::create_dir_all(&blobs).unwrap();
1264 for e in fs::read_dir(fx.ev.path().join("out/blobs"))
1265 .unwrap()
1266 .flatten()
1267 {
1268 fs::copy(e.path(), blobs.join(e.file_name())).unwrap();
1269 }
1270 let mut v = original.clone();
1271 edit(&mut v);
1272 Store::new(dir.path()).put_receipt(&v).unwrap();
1273 (dir, original)
1274 }
1275
1276 fn lookup_in(dir: &TempDir, original: &Value) -> Result<Unusable, ()> {
1277 let store = Store::new(dir.path());
1278 let index = Index::load(&store);
1279 let k = original["volatile"]["cache"]["key"].as_str().unwrap();
1280 match lookup(&index, &store, k, &runner::captured_env()) {
1281 Lookup::Hit(_) => Err(()),
1282 Lookup::Miss(Miss::Unusable { why, .. }) => Ok(why),
1283 Lookup::Miss(Miss::NoReceipt) => panic!("the forged receipt must be found by its key"),
1284 }
1285 }
1286
1287 #[test]
1288 fn the_unedited_copy_is_a_hit_so_the_forgery_tests_mean_something() {
1289 let fx = Fx::new(SCRIPT);
1290 let first = fresh_pass(&fx);
1291 let (dir, original) = forged(&fx, &first, |_| {});
1292 assert_eq!(lookup_in(&dir, &original), Err(()));
1293 }
1294
1295 #[test]
1296 fn not_run_and_blocked_receipts_are_never_sources() {
1297 let fx = Fx::new(SCRIPT);
1298 let first = fresh_pass(&fx);
1299 for verdict in [
1300 "NOT_RUN",
1301 "BLOCKED_HARDWARE",
1302 "BLOCKED_OPERATOR",
1303 "MISSING_IMPLEMENTATION",
1304 ] {
1305 let (dir, o) = forged(&fx, &first, |v| {
1306 v["core"]["derived_verdict"] = json!(verdict)
1307 });
1308 assert_eq!(
1309 lookup_in(&dir, &o),
1310 Ok(Unusable::NotAnExperiment),
1311 "{verdict}"
1312 );
1313 }
1314 }
1315
1316 #[test]
1317 fn unclean_moved_or_timed_out_receipts_are_never_sources() {
1318 let fx = Fx::new(SCRIPT);
1319 let first = fresh_pass(&fx);
1320 let (dir, o) = forged(&fx, &first, |v| {
1321 v["core"]["tree_clean_before"] = json!(false)
1322 });
1323 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::UncleanTree));
1324 let (dir, o) = forged(&fx, &first, |v| {
1325 v["core"]["tree_clean_after"] = json!(false)
1326 });
1327 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::UncleanTree));
1328 let (dir, o) = forged(&fx, &first, |v| {
1329 v["core"]["commit_unchanged_after"] = json!(false)
1330 });
1331 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::HeadMoved));
1332 let (dir, o) = forged(&fx, &first, |v| {
1333 v["volatile"]["timeout_exceeded"] = json!(true)
1334 });
1335 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::TimedOut));
1336 }
1337
1338 #[test]
1339 fn a_stored_key_that_its_own_contents_do_not_hash_to_is_not_trusted() {
1340 let fx = Fx::new(SCRIPT);
1341 let first = fresh_pass(&fx);
1342 // The receipt claims the key but its inputs digest says otherwise.
1343 let (dir, o) = forged(&fx, &first, |v| {
1344 v["core"]["build_inputs_digest"] = json!("0".repeat(64))
1345 });
1346 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::KeyMismatch));
1347 let (dir, o) = forged(&fx, &first, |v| {
1348 v["core"]["manifest_digest"] = json!("0".repeat(64))
1349 });
1350 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::KeyMismatch));
1351 }
1352
1353 #[test]
1354 fn a_machine_descriptor_that_does_not_match_its_digest_is_not_trusted() {
1355 let fx = Fx::new(SCRIPT);
1356 let first = fresh_pass(&fx);
1357 let (dir, o) = forged(&fx, &first, |v| {
1358 v["core"]["machine"]["cpu_count"] = json!(9999)
1359 });
1360 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::MachineMismatch));
1361 }
1362
1363 #[test]
1364 fn a_different_captured_environment_is_not_the_same_experiment() {
1365 let fx = Fx::new(SCRIPT);
1366 let first = fresh_pass(&fx);
1367 let (dir, o) = forged(&fx, &first, |v| {
1368 v["core"]["env"]["RUSTFLAGS"] = json!("-C opt-level=3")
1369 });
1370 assert_eq!(lookup_in(&dir, &o), Ok(Unusable::EnvDiffers));
1371 }
1372
1373 // ---- why --------------------------------------------------------------
1374
1375 fn why_lines(fx: &Fx) -> String {
1376 let g = graph::load(fx.repo.path()).unwrap();
1377 let store = fx.store();
1378 let index = Index::load(&store);
1379 let target = g.index_of("C-A").unwrap();
1380 let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), target);
1381 facts[&target].join("\n")
1382 }
1383
1384 #[test]
1385 fn why_explains_a_hit_and_then_a_miss_and_what_changed() {
1386 let fx = Fx::new(SCRIPT);
1387 let before = why_lines(&fx);
1388 assert!(before.contains("cache: miss"), "{before}");
1389 assert!(
1390 before.contains("no earlier receipt has this key"),
1391 "{before}"
1392 );
1393 let first = fresh_pass(&fx);
1394 fx.commit("README", "changed\n");
1395 let hit = why_lines(&fx);
1396 assert!(hit.contains("cache: hit"), "{hit}");
1397 assert!(
1398 hit.contains(&first.receipt_digest.clone().unwrap()[..12]),
1399 "{hit}"
1400 );
1401 fx.commit("data/in.txt", "two\n");
1402 let miss = why_lines(&fx);
1403 assert!(miss.contains("cache: miss"), "{miss}");
1404 assert!(
1405 miss.contains("these changed: the declared input files"),
1406 "{miss}"
1407 );
1408 }
1409
1410 #[test]
1411 fn why_says_so_when_a_receipt_was_reused_and_when_the_tree_is_dirty() {
1412 let fx = Fx::new(SCRIPT);
1413 fresh_pass(&fx);
1414 let reused = fx.run(&fx.opts());
1415 assert!(reused_from(&reused).is_some());
1416 let text = why_lines(&fx);
1417 assert!(text.contains("was reused from"), "{text}");
1418 assert!(text.contains("not qualification evidence"), "{text}");
1419 write_file(fx.repo.path(), "README", "dirty\n", false);
1420 let dirty = why_lines(&fx);
1421 assert!(dirty.contains("uncommitted changes"), "{dirty}");
1422 assert!(!dirty.contains("cache: hit"), "{dirty}");
1423 }
1424
1425 #[test]
1426 fn why_for_a_dependent_follows_a_reused_dependency() {
1427 let fx = two_gate_fixture();
1428 run_all(&fx, &fx.opts());
1429 fx.commit("README", "changed\n");
1430 let g = graph::load(fx.repo.path()).unwrap();
1431 let index = Index::load(&fx.store());
1432 let b = g.index_of("C-B").unwrap();
1433 let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), b);
1434 assert!(
1435 facts[&b].join("\n").contains("cache: hit"),
1436 "{:?}",
1437 facts[&b]
1438 );
1439 fx.commit("data/in.txt", "two\n");
1440 let index = Index::load(&fx.store());
1441 let facts = explain_chain(fx.repo.path(), &g, &index, &fx.opts(), &fx.head(), b);
1442 let text = facts[&b].join("\n");
1443 assert!(
1444 text.contains("depends on C-A, which would run again"),
1445 "{text}"
1446 );
1447 }
1448}