use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use crate::cache::Cache;
use crate::canon;
use crate::check::Scope;
use crate::exec::{self, Host, Options, StepFailure, Stores, Task, output_suffix};
use crate::graph::{Graph, NodeId};
use crate::hash::ContentHash;
#[derive(Clone, Copy, Debug)]
pub struct Subject<'a> {
pub step: &'a str,
pub sample: Option<&'a str>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Verdict {
Deterministic,
Reproducible,
NotReproducible,
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Deterministic => "deterministic",
Self::Reproducible => "reproducible",
Self::NotReproducible => "not reproducible",
})
}
}
#[derive(Clone, Debug)]
pub struct StepAudit {
pub node: NodeId,
pub step: String,
pub scope: Option<String>,
pub verdict: Verdict,
pub first: ContentHash,
pub second: ContentHash,
pub first_canonical: ContentHash,
pub second_canonical: ContentHash,
pub first_duration: Duration,
pub second_duration: Duration,
}
impl StepAudit {
#[must_use]
pub fn describe(&self) -> String {
match &self.scope {
Some(scope) => format!("`{}` ({scope})", self.step),
None => format!("`{}`", self.step),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct AuditReport {
pub audited: Vec<StepAudit>,
pub failures: Vec<StepFailure>,
}
impl AuditReport {
#[must_use]
pub fn verdict(&self) -> Verdict {
self.audited
.iter()
.map(|step| step.verdict)
.max()
.unwrap_or(Verdict::Deterministic)
}
#[must_use]
pub fn summary(&self) -> String {
let count = |wanted: Verdict| {
self.audited
.iter()
.filter(|step| step.verdict == wanted)
.count()
};
let mut parts = Vec::new();
for verdict in [
Verdict::Deterministic,
Verdict::Reproducible,
Verdict::NotReproducible,
] {
let found = count(verdict);
if found > 0 {
parts.push(format!("{found} {verdict}"));
}
}
if !self.failures.is_empty() {
parts.push(format!("{} failed", self.failures.len()));
}
let places = self.audited.len() + self.failures.len();
let noun = if places == 1 { "step" } else { "steps" };
if parts.is_empty() {
return format!("{places} {noun}.");
}
format!("{places} {noun}: {}.", parts.join(", "))
}
#[must_use]
pub fn text(&self) -> String {
let mut lines = Vec::new();
for step in &self.audited {
lines.push(format!(
"{:<16} {}",
step.verdict.to_string(),
step.describe()
));
match step.verdict {
Verdict::Deterministic => {
lines.push(format!(
" the same bytes both times {}",
short(step.first)
));
}
Verdict::Reproducible => {
lines.push(format!(
" the bytes differ {} / {}",
short(step.first),
short(step.second)
));
lines.push(format!(
" what they mean does not {}",
short(step.first_canonical)
));
}
Verdict::NotReproducible => {
lines.push(format!(
" the two runs mean different things {} / {}",
short(step.first_canonical),
short(step.second_canonical)
));
}
}
}
for failure in &self.failures {
lines.push(format!("{:<16} `{}`", "failed", failure.step));
for line in failure.message.lines() {
lines.push(format!(" {line}"));
}
}
if !lines.is_empty() {
lines.push(String::new());
}
lines.push(self.summary());
lines.join("\n")
}
}
pub fn audit(
graph: &Graph,
roots: &[NodeId],
tasks: &[Task],
stores: &Stores<'_>,
options: &Options,
host: &dyn Host,
subject: &Subject<'_>,
) -> Result<AuditReport, String> {
let step = subject.step;
let scopes = graph.scopes(roots);
let mut chosen: Vec<NodeId> = graph
.reachable_nodes(roots)
.into_iter()
.filter(|node| graph.step(*node).is_some_and(|spec| spec.name == step))
.collect();
if chosen.is_empty() {
return Err(unknown_step(graph, roots, step));
}
if let Some(wanted) = subject.sample {
let every = chosen.clone();
chosen.retain(|node| scopes.get(node).is_some_and(|scope| scope.value == wanted));
if chosen.is_empty() {
return Err(unknown_sample(&scopes, &every, step, wanted));
}
}
let run = exec::run(graph, roots, tasks, stores, options, host);
let produced: Vec<(NodeId, PathBuf)> = run
.results
.iter()
.map(|result| (result.node, result.output.clone()))
.collect();
let mut report = AuditReport::default();
for node in chosen {
let name = graph
.step(node)
.map_or_else(|| step.to_owned(), |spec| spec.name.clone());
let scope = scopes.get(&node).map(Scope::describe);
if let Some(failure) = run.failures.iter().find(|failure| failure.node == node) {
report.failures.push(failure.clone());
continue;
}
match twice(graph, node, tasks, stores.cache, host, &produced) {
Ok(mut audited) => {
audited.step = name;
audited.scope = scope;
report.audited.push(audited);
}
Err(message) => report.failures.push(StepFailure {
node,
step: name,
message,
}),
}
}
report.audited.sort_by_key(|step| step.node.index());
report.failures.sort_by_key(|failure| failure.node.index());
Ok(report)
}
fn twice(
graph: &Graph,
node: NodeId,
tasks: &[Task],
cache: &Cache,
host: &dyn Host,
produced: &[(NodeId, PathBuf)],
) -> Result<StepAudit, String> {
let spec = graph
.step(node)
.ok_or_else(|| "this node is not a step".to_owned())?;
let task = tasks
.iter()
.find(|task| task.node == node)
.ok_or_else(|| "no recipe was recorded for this step".to_owned())?;
let inputs = exec::inputs_of(graph, node, &|from| {
produced
.iter()
.find(|(at, _)| *at == from)
.map(|(_, path)| path.clone())
})?;
let suffix = output_suffix(spec.output);
let mut runs = Vec::with_capacity(2);
for attempt in 1..=2 {
let out = cache.scratch(&format!("audit-{}-{attempt}{suffix}", node.index()));
let _ = std::fs::remove_file(&out);
let outcome = exec::produce(&task.recipe, &inputs, &task.parameters, &out, host).and_then(
|produced| {
let bytes = ContentHash::of_file(&out).map_err(|error| error.to_string())?;
let meaning = canon::hash(spec.output, &out, bytes)
.map_err(|error| error.to_string())?
.hash;
Ok((bytes, meaning, produced.duration))
},
);
let _ = std::fs::remove_file(&out);
runs.push(outcome?);
}
let (first, first_canonical, first_duration) = runs[0];
let (second, second_canonical, second_duration) = runs[1];
let verdict = if first == second {
Verdict::Deterministic
} else if first_canonical == second_canonical {
Verdict::Reproducible
} else {
Verdict::NotReproducible
};
Ok(StepAudit {
node,
step: spec.name.clone(),
scope: None,
verdict,
first,
second,
first_canonical,
second_canonical,
first_duration,
second_duration,
})
}
fn unknown_step(graph: &Graph, roots: &[NodeId], step: &str) -> String {
let mut names: Vec<&str> = graph.step_names(roots);
names.sort_unstable();
names.dedup();
format!(
"no step named `{step}` in this pipeline; it has {}",
names
.iter()
.map(|name| format!("`{name}`"))
.collect::<Vec<_>>()
.join(", ")
)
}
fn unknown_sample(
scopes: &HashMap<NodeId, Scope>,
nodes: &[NodeId],
step: &str,
sample: &str,
) -> String {
let mut values: Vec<&str> = nodes
.iter()
.filter_map(|node| scopes.get(node))
.map(|scope| scope.value.as_str())
.collect();
values.sort_unstable();
values.dedup();
if values.is_empty() {
return format!(
"no node of `{step}` is for `{sample}`; this pipeline has only one `{step}`, so \
there is nothing to narrow"
);
}
format!(
"no node of `{step}` is for `{sample}`; there are {}",
values.join(", ")
)
}
fn short(hash: ContentHash) -> String {
hash.to_hex()[..12].to_owned()
}