use core::sync::atomic::AtomicBool;
use std::collections::BTreeSet;
use super::{Chosen, chosen, first_difference};
use crate::error::{Error, Result};
use crate::execute::assembly::{Prepared, made_from, prepared};
use crate::execute::perform::{
Ended, Kept, Performed, RemoteRun, Shared, Task, Told, Worked, perform,
};
use crate::execute::record::{restore, shown};
use crate::execute::settle::restorable;
use crate::placement::layout::Layout;
use crate::ports::{
ActionCache, Clock, ContentStore, Dispatcher, ExecStrategy, Manifest, NoRemote, PortSet, Ports,
};
use crate::types::{
ActionKey, CacheRow, Check, Diagnostic, Digest, InfraKind, Label, NodeId, OutcomeClass,
OutputManifest, OutputName, Plan, Sample, TargetGraph, Turn, Verdict, Verification,
};
pub fn verify<P: Ports>(
whole: &TargetGraph,
graph: &TargetGraph,
plan: &Plan,
sample: Sample,
ports: &mut PortSet<P>,
) -> Result<Verification> {
if !made_from(plan, graph) {
return Err(Error::ForeignPlan);
}
let workspace = ports.manifest.workspace()?;
Layout::of(whole, &workspace.out)?;
let layout = Layout::of(graph, &workspace.out)?;
let targets = prepared(graph, plan, &layout, &workspace.ceiling, &ports.host)?;
let PortSet {
cache,
cas,
strategy,
dispatcher,
clock,
..
} = ports;
let (cache, cas, strategy, clock) = (&*cache, &*cas, &*strategy, &*clock);
let PutBack {
restored,
mut unplaced,
not_cached,
} = restore_cached(&targets, plan, &layout, cache, cas)?;
let in_place: BTreeSet<&Label> = targets
.iter()
.zip(&restored)
.filter(|(_, restored)| restored.is_some())
.map(|(target, _)| &target.node.label)
.collect();
let mut checked = Vec::new();
let mut candidates = Vec::new();
for (target, restored) in targets.iter().zip(&restored) {
let Some(restored) = restored else {
continue;
};
match unmet(&target.deps, &in_place) {
Some(because) => checked.push((
target.node.label.clone(),
Check::Skipped {
because: because.clone(),
},
)),
None => candidates.push((target.node.label.clone(), restored.key.clone())),
}
}
let Chosen { rerun, left_out } = chosen(candidates, sample);
let mut tasks = Vec::new();
for ((node, target), restored) in (0_u32..).map(NodeId::new).zip(&targets).zip(&restored) {
if let Some(restored) = restored
&& rerun.binary_search(&target.node.label).is_ok()
{
tasks.push(Task {
node,
role: target.node.role,
key: restored.key.clone(),
action: target.action.clone(),
});
}
}
let asked: Vec<NodeId> = tasks.iter().map(|task| task.node).collect();
let performed = run(tasks, strategy, cas, clock, dispatcher)?;
let lost: Vec<Label> = asked
.iter()
.filter(|node| !performed.iter().any(|done| done.node == **node))
.filter_map(|node| graph.node(*node))
.map(|node| node.label.clone())
.collect();
if !lost.is_empty() {
return Err(Error::DispatcherFault { targets: lost });
}
for done in performed {
let (Some(target), Some(Some(cached))) = (
targets.get(done.node.index()),
restored.get(done.node.index()),
) else {
continue;
};
let label = &target.node.label;
let check = rechecked(
done.ended,
&target.node.outputs,
&cached.manifests,
cas,
label,
)?;
checked.push((label.clone(), check));
}
checked.append(&mut unplaced);
Ok(Verification::new(checked, not_cached, left_out))
}
fn rechecked<C: ContentStore>(
ended: Ended,
names: &[OutputName],
cached: &[OutputManifest],
cas: &C,
label: &Label,
) -> Result<Check> {
Ok(match ended {
Ended::Produced { outputs, .. } => compared(names, cached, &outputs),
Ended::Failed {
class,
diagnostic,
printed,
} => Check::Failed {
class,
diagnostic,
stdout: shown(cas, label, printed.map(|printed| printed.stdout))?,
stderr: shown(cas, label, printed.map(|printed| printed.stderr))?,
},
Ended::Fetched { .. } | Ended::Executed { .. } | Ended::RemoteFailed(_) => Check::Failed {
class: OutcomeClass::InfraFailure {
kind: InfraKind::Run,
},
diagnostic: Some(Diagnostic::new(
"the re-run consulted the remote cache, which a verify never does",
)),
stdout: Vec::new(),
stderr: Vec::new(),
},
})
}
struct Restored {
key: ActionKey,
manifests: Vec<OutputManifest>,
}
struct PutBack {
restored: Vec<Option<Restored>>,
unplaced: Vec<(Label, Check)>,
not_cached: usize,
}
fn restore_cached<A: ActionCache, C: ContentStore>(
targets: &[Prepared<'_>],
plan: &Plan,
layout: &Layout,
cache: &A,
cas: &C,
) -> Result<PutBack> {
let mut put_back = PutBack {
restored: Vec::with_capacity(targets.len()),
unplaced: Vec::new(),
not_cached: 0,
};
for ((node, target), verdict) in (0_u32..).map(NodeId::new).zip(targets).zip(plan.verdicts()) {
let label = &target.node.label;
let cached = match (verdict, cache.row(label)) {
(Verdict::Clean { key }, Some(row)) => {
cached_manifests(row, cas)?.map(|manifests| (key, row, manifests))
}
_ => None,
};
let Some((key, row, manifests)) = cached else {
put_back.not_cached += 1;
put_back.restored.push(None);
continue;
};
let outcome = restore(
label.clone(),
target.node.role,
row,
&manifests,
layout.outputs(node),
cas,
);
if outcome.class.succeeded() {
put_back.restored.push(Some(Restored {
key: key.clone(),
manifests,
}));
} else {
let diagnostic = outcome
.diagnostic
.unwrap_or_else(|| Diagnostic::new("the cached outputs could not be put back"));
put_back
.unplaced
.push((label.clone(), Check::Unplaced { diagnostic }));
put_back.restored.push(None);
}
}
Ok(put_back)
}
fn cached_manifests<C: ContentStore>(
row: &CacheRow,
cas: &C,
) -> Result<Option<Vec<OutputManifest>>> {
let Some(manifests) = restorable(row, |digest| cas.contains(digest), |digest| cas.get(digest))?
else {
return Ok(None);
};
for (manifest, digest) in manifests.iter().zip(row.outputs()) {
if Digest::of(&manifest.to_bytes()?) != *digest {
return Ok(None);
}
}
Ok(Some(manifests))
}
fn unmet<'a>(deps: &[&'a Label], in_place: &BTreeSet<&Label>) -> Option<&'a Label> {
deps.iter()
.copied()
.filter(|dep| !in_place.contains(dep))
.min()
}
fn run<S, C, K, D>(
tasks: Vec<Task>,
strategy: &S,
cas: &C,
clock: &K,
dispatcher: &mut D,
) -> Result<Vec<Performed>>
where
S: ExecStrategy,
C: ContentStore,
K: Clock + Sync,
D: Dispatcher,
{
let stop = AtomicBool::new(false);
let shared = Shared {
stop: &stop,
live: None,
};
let mut waiting = tasks;
let mut performed = Vec::new();
dispatcher.dispatch(
|task, tell| {
perform(
task,
strategy,
cas,
clock,
None::<&RemoteRun<'_, NoRemote>>,
shared,
tell,
)
},
|turn: Turn<Told, Worked>| match turn {
Turn::Begin => core::mem::take(&mut waiting),
Turn::Told(_) | Turn::Done(Worked::NotBegun(_)) => Vec::new(),
Turn::Done(Worked::Performed(done)) => {
performed.push(*done);
Vec::new()
}
},
)?;
Ok(performed)
}
fn compared(names: &[OutputName], cached: &[OutputManifest], kept: &[Kept]) -> Check {
names
.iter()
.zip(cached)
.zip(kept)
.find_map(|((name, cached), kept)| {
first_difference(cached, &kept.manifest).map(|difference| Check::Mismatched {
output: name.clone(),
difference,
})
})
.unwrap_or(Check::Verified)
}
#[cfg(test)]
mod tests {
#![expect(
clippy::unwrap_used,
reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
)]
use std::collections::BTreeSet;
use super::{compared, unmet};
use crate::execute::fixtures::{file, kept, label, outputs, tree};
use crate::types::{Check, EntryChange, FileChange, OutputDifference, TreePath};
#[test]
fn the_lowest_dependency_not_in_place_is_the_one_that_is_unmet() {
let (a, b, c) = (label("//:a"), label("//:b"), label("//:c"));
let in_place = BTreeSet::from([&a]);
assert_eq!(unmet(&[&c, &b, &a], &in_place), Some(&b));
assert_eq!(unmet(&[&a], &in_place), None);
assert_eq!(unmet(&[], &in_place), None);
}
#[test]
fn equal_outputs_are_verified() {
let check = compared(
&outputs(&["x", "y"]),
&[file("one"), tree(&[("a", "1")])],
&[kept(file("one")), kept(tree(&[("a", "1")]))],
);
assert_eq!(check, Check::Verified);
}
#[test]
fn the_first_output_in_declared_order_that_differs_is_named() {
let names = outputs(&["x", "y", "z"]);
let check = compared(
&names,
&[file("one"), tree(&[("a", "1")]), file("three")],
&[
kept(file("one")),
kept(tree(&[("a", "2")])),
kept(file("3")),
],
);
assert_eq!(
check,
Check::Mismatched {
output: names[1].clone(),
difference: OutputDifference::Entry {
path: TreePath::parse("a").unwrap(),
change: EntryChange::Bytes,
},
}
);
}
#[test]
fn a_file_with_other_bytes_is_mismatched_in_bytes() {
let names = outputs(&["x"]);
let check = compared(&names, &[file("one")], &[kept(file("two"))]);
assert_eq!(
check,
Check::Mismatched {
output: names[0].clone(),
difference: OutputDifference::File(FileChange::Bytes),
}
);
}
}