use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, RwLock};
use std::time::{Duration, Instant};
use rayon::Scope;
use crate::cache::{Cache, Entry, Recorded, Recording, Stored};
use crate::canon::Note;
use crate::graph::{Graph, NodeId, StepSpec};
use crate::hash::ContentHash;
use crate::key::{Ingredients, StepKey};
use crate::prov::{self, InputRecord, Prov, Record, day};
use crate::store::StoreStats;
use crate::store::lease;
use crate::types::{DataKind, Dataset, Origin, RemoteVerdict};
use crate::worker::Worker;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Recipe {
Shell(String),
Callback(u64),
}
impl Recipe {
fn describe(&self) -> String {
match self {
Self::Shell(command) => format!("sh:{command}"),
Self::Callback(_) => "callback".to_owned(),
}
}
}
#[derive(Clone, Debug)]
pub struct Task {
pub node: NodeId,
pub code: String,
pub recipe: Recipe,
pub tools: Vec<String>,
pub parameters: Vec<(String, String)>,
pub citations: Vec<String>,
pub seed: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
Ran,
Cached,
Skipped,
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Ran => "ran",
Self::Cached => "cached",
Self::Skipped => "skipped",
})
}
}
#[derive(Clone, Debug)]
pub struct StepResult {
pub node: NodeId,
pub step: String,
pub outcome: Outcome,
pub key: StepKey,
pub hash: ContentHash,
pub canonical: ContentHash,
pub notes: Vec<Note>,
pub output: PathBuf,
pub duration: Duration,
}
#[derive(Clone, Debug)]
pub struct StepFailure {
pub node: NodeId,
pub step: String,
pub message: String,
}
#[derive(Clone, Debug, Default)]
pub struct RunReport {
pub results: Vec<StepResult>,
pub failures: Vec<StepFailure>,
pub store: StoreStats,
pub refused: Option<String>,
pub worker: Option<String>,
pub waited: usize,
pub diverged: Vec<Divergence>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Divergence {
pub node: NodeId,
pub step: String,
pub key: StepKey,
pub ours: ContentHash,
pub theirs: ContentHash,
}
impl RunReport {
#[must_use]
pub fn result(&self, node: NodeId) -> Option<&StepResult> {
self.results.iter().find(|result| result.node == node)
}
#[must_use]
pub fn counts(&self) -> Counts {
let count = |wanted: Outcome| {
self.results
.iter()
.filter(|result| result.outcome == wanted)
.count()
};
Counts {
ran: count(Outcome::Ran),
cached: count(Outcome::Cached),
skipped: count(Outcome::Skipped),
failed: self.failures.len(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
pub ran: usize,
pub cached: usize,
pub skipped: usize,
pub failed: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct Stores<'a> {
pub cache: &'a Cache,
pub prov: &'a Prov,
}
#[derive(Clone, Debug)]
pub struct Options {
pub jobs: usize,
pub force: bool,
pub worker: Option<Worker>,
pub lease: Duration,
}
pub const DEFAULT_LEASE: Duration = Duration::from_secs(3600);
impl Default for Options {
fn default() -> Self {
Self {
jobs: std::thread::available_parallelism().map_or(1, std::num::NonZero::get),
force: false,
worker: None,
lease: DEFAULT_LEASE,
}
}
}
pub trait Host: Sync {
fn call(
&self,
id: u64,
out: &Path,
inputs: &[(String, Vec<PathBuf>)],
) -> Result<Vec<Note>, String>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NoCallbacks;
impl Host for NoCallbacks {
fn call(
&self,
id: u64,
_out: &Path,
_inputs: &[(String, Vec<PathBuf>)],
) -> Result<Vec<Note>, String> {
Err(format!(
"this step's body is a callback ({id}), and nothing here can run one"
))
}
}
const BUILT_IN: &[&str] = &["hivdb", "ligase"];
pub(crate) const LIBRARY: &[&str] = &["rdkit"];
static LIBRARY_VERSIONS: RwLock<BTreeMap<String, String>> = RwLock::new(BTreeMap::new());
pub fn register_library_version(tool: &str, version: &str) -> Result<(), String> {
let mut known = LIBRARY_VERSIONS
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match known.get(tool) {
Some(already) if already != version => Err(format!(
"`{tool}` was already registered as `{already}` and is now `{version}`. A library's version is in every cache key beneath it, so two answers in one process would mean two keys for one computation"
)),
_ => {
known.insert(tool.to_owned(), version.to_owned());
Ok(())
}
}
}
fn library_version(tool: &str) -> Option<String> {
LIBRARY_VERSIONS
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(tool)
.map(|version| format!("{tool} {version}"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct VersionProbe {
arguments: &'static [&'static str],
failure_expected: bool,
marker: Option<&'static str>,
}
const DEFAULT_PROBE: VersionProbe = VersionProbe {
arguments: &["--version"],
failure_expected: false,
marker: None,
};
const PROBES: &[(&str, VersionProbe)] = &[(
"bwa",
VersionProbe {
arguments: &[],
failure_expected: true,
marker: Some("Version:"),
},
)];
pub fn tool_version(tool: &str) -> Result<String, String> {
match tool {
"hivdb" => return crate::hivdb::ruleset::fingerprint(),
"ligase" => return Ok(format!("ligase {}", env!("CARGO_PKG_VERSION"))),
_ => {}
}
debug_assert!(
!BUILT_IN.contains(&tool),
"a built-in tool with no version of its own"
);
if LIBRARY.contains(&tool) || library_version(tool).is_some() {
return library_version(tool).ok_or_else(|| {
format!(
"`{tool}` is a library rather than a program, so there is \
nothing to run and ask. Its version comes from whatever \
imported it, and nothing has: for RDKit that means \
`pip install 'ligase-bio[chem]'` and using \
`lg.chem.standardize`, which registers it. Recording a \
library with no version would be the same text for every \
release of it, and upgrading it would not move a single \
cache key"
)
});
}
let probe = probe_for(tool);
let output = Command::new(tool)
.args(probe.arguments)
.output()
.map_err(|error| format!("`{tool}` could not be run: {error}"))?;
version_from(
tool,
&probe,
output.status.success(),
&String::from_utf8_lossy(&output.stdout),
&String::from_utf8_lossy(&output.stderr),
)
}
fn probe_for(tool: &str) -> VersionProbe {
PROBES
.iter()
.find(|(named, _)| *named == tool)
.map_or(DEFAULT_PROBE, |(_, probe)| *probe)
}
fn version_from(
tool: &str,
probe: &VersionProbe,
succeeded: bool,
stdout: &str,
stderr: &str,
) -> Result<String, String> {
let asked = describe_probe(tool, probe);
if !succeeded && !probe.failure_expected {
let said = complaint(stdout, stderr);
return Err(format!(
"`{asked}` failed, so what it printed is not a version: {said}. \
A tool that answers the question differently needs an entry in \
this engine's version-probe table; one recorded from a failed \
probe would be the same text for every release of the tool, and \
upgrading it would not move a single cache key"
));
}
let text = first_nonempty(stdout, stderr);
if text.is_empty() {
return Err(format!("`{asked}` printed nothing"));
}
match probe.marker {
None => Ok(text.trim().to_owned()),
Some(marker) => text
.lines()
.find(|line| line.contains(marker))
.map(|line| line.trim().to_owned())
.ok_or_else(|| {
format!(
"`{asked}` printed no line containing `{marker}`, so this \
engine cannot tell which part of its output is the \
version. Keeping the rest would hash a usage banner as a \
version; update the version-probe table for `{tool}`"
)
}),
}
}
fn describe_probe(tool: &str, probe: &VersionProbe) -> String {
if probe.arguments.is_empty() {
tool.to_owned()
} else {
format!("{tool} {}", probe.arguments.join(" "))
}
}
fn first_nonempty<'a>(stdout: &'a str, stderr: &'a str) -> &'a str {
if stdout.trim().is_empty() {
stderr
} else {
stdout
}
}
fn complaint(stdout: &str, stderr: &str) -> String {
let text = first_nonempty(stdout, stderr).trim();
match text.lines().find(|line| !line.trim().is_empty()) {
Some(line) => format!("`{}`", line.trim()),
None => "nothing at all".to_owned(),
}
}
#[must_use]
pub const fn output_suffix(kind: DataKind) -> &'static str {
match kind {
DataKind::Reads => ".fastq.gz",
DataKind::Reference => ".fasta",
DataKind::Alignment => ".bam",
DataKind::Variants => ".vcf.gz",
DataKind::Intervals => ".bed",
DataKind::ResistanceReport => ".tsv",
DataKind::EntitySet | DataKind::RankedList => ".tsv",
DataKind::KnowledgeGraph => ".json",
DataKind::MoleculeSet | DataKind::MoleculeRanking => ".tsv",
}
}
#[must_use]
pub fn run(
graph: &Graph,
roots: &[NodeId],
tasks: &[Task],
stores: &Stores<'_>,
options: &Options,
host: &dyn Host,
) -> RunReport {
let nodes: Vec<NodeId> = graph
.reachable_nodes(roots)
.into_iter()
.filter(|node| graph.step(*node).is_some())
.collect();
if nodes.is_empty() {
return RunReport::default();
}
let runner = Runner {
graph,
cache: stores.cache,
prov: stores.prov,
host,
force: options.force,
worker: options.worker.clone(),
lease: options.lease,
tasks: tasks.iter().map(|task| (task.node, task)).collect(),
versions: versions(graph, &nodes, tasks),
state: Mutex::new(State::new(graph, &nodes)),
};
let jobs = options.jobs.max(1).min(nodes.len());
match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
Ok(pool) => {
let mut patience = Patience::new();
loop {
pool.scope(|scope| runner.start(scope));
if !runner.rearm(&mut patience) {
break;
}
}
}
Err(_) => runner.alone(),
}
runner.finish()
}
struct Patience {
next: Duration,
}
impl Patience {
const FIRST: Duration = Duration::from_secs(1);
const LONGEST: Duration = Duration::from_secs(30);
const fn new() -> Self {
Self { next: Self::FIRST }
}
fn wait(&mut self) {
std::thread::sleep(self.next);
self.next = (self.next * 2).min(Self::LONGEST);
}
}
pub fn inputs_of(
graph: &Graph,
node: NodeId,
produced: &dyn Fn(NodeId) -> Option<PathBuf>,
) -> Result<Vec<(String, Vec<PathBuf>)>, String> {
let spec = graph
.step(node)
.ok_or_else(|| "this node is not a step".to_owned())?;
spec.arguments
.iter()
.map(|argument| {
let files = if let Some(path) = produced(argument.node) {
vec![path]
} else {
let dataset = graph
.dataset(argument.node)
.ok_or_else(|| format!("`{}` is bound to nothing", argument.param))?;
let files = dataset.files();
if files.is_empty() {
return Err(format!(
"`{}` is bound to data with no file behind it",
argument.param
));
}
files
};
Ok((argument.param.clone(), files))
})
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Execution {
pub duration: Duration,
pub command: Option<String>,
pub notes: Vec<Note>,
}
pub fn produce(
recipe: &Recipe,
inputs: &[(String, Vec<PathBuf>)],
parameters: &[(String, String)],
out: &Path,
host: &dyn Host,
) -> Result<Execution, String> {
let started = Instant::now();
let mut ran = None;
let produced = match recipe {
Recipe::Shell(template) => {
let command = fill_template(template, inputs, parameters, out)?;
let outcome = shell(&command).map(|()| Vec::new());
ran = Some(command);
outcome
}
Recipe::Callback(id) => host.call(*id, out, inputs),
};
let duration = started.elapsed();
let notes = produced?;
if !out.is_file() {
return Err(format!(
"the step finished without writing its output to {}",
out.display()
));
}
Ok(Execution {
duration,
command: ran,
notes,
})
}
fn noticed(said: Vec<Note>, found: Vec<Note>) -> Vec<Note> {
let mut notes = said;
for note in found {
if !notes.contains(¬e) {
notes.push(note);
}
}
notes
}
fn versions(
graph: &Graph,
nodes: &[NodeId],
tasks: &[Task],
) -> HashMap<String, Result<String, String>> {
let wanted: BTreeSet<&str> = tasks
.iter()
.filter(|task| nodes.contains(&task.node) && graph.step(task.node).is_some())
.flat_map(|task| task.tools.iter().map(String::as_str))
.collect();
wanted
.into_iter()
.map(|tool| (tool.to_owned(), tool_version(tool)))
.collect()
}
#[derive(Clone, Debug)]
struct Produced {
output: Stored,
ran_above: bool,
}
struct State {
ready: Vec<NodeId>,
remaining: HashMap<NodeId, usize>,
dependents: HashMap<NodeId, Vec<NodeId>>,
produced: HashMap<NodeId, Produced>,
results: Vec<StepResult>,
failures: Vec<StepFailure>,
running: HashSet<StepKey>,
parked: HashMap<StepKey, Vec<NodeId>>,
deferred: Vec<NodeId>,
waited: usize,
diverged: Vec<Divergence>,
}
impl State {
fn new(graph: &Graph, nodes: &[NodeId]) -> Self {
let wanted: HashSet<NodeId> = nodes.iter().copied().collect();
let mut remaining = HashMap::new();
let mut dependents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for node in nodes {
let upstream: BTreeSet<NodeId> = graph
.step(*node)
.map(|spec| {
spec.arguments
.iter()
.map(|argument| argument.node)
.filter(|from| wanted.contains(from))
.collect()
})
.unwrap_or_default();
remaining.insert(*node, upstream.len());
for from in upstream {
dependents.entry(from).or_default().push(*node);
}
}
let ready = remaining
.iter()
.filter(|(_, count)| **count == 0)
.map(|(node, _)| *node)
.collect();
Self {
ready,
remaining,
dependents,
produced: HashMap::new(),
results: Vec::new(),
failures: Vec::new(),
running: HashSet::new(),
parked: HashMap::new(),
deferred: Vec::new(),
waited: 0,
diverged: Vec::new(),
}
}
fn release(&mut self, node: NodeId) {
let Some(waiting) = self.dependents.get(&node).cloned() else {
return;
};
for next in waiting {
if let Some(count) = self.remaining.get_mut(&next) {
*count = count.saturating_sub(1);
if *count == 0 {
self.ready.push(next);
}
}
}
}
}
struct Runner<'a> {
graph: &'a Graph,
cache: &'a Cache,
prov: &'a Prov,
host: &'a dyn Host,
force: bool,
worker: Option<Worker>,
lease: Duration,
tasks: HashMap<NodeId, &'a Task>,
versions: HashMap<String, Result<String, String>>,
state: Mutex<State>,
}
impl Runner<'_> {
fn start<'scope>(&'scope self, scope: &Scope<'scope>) {
for node in self.released() {
self.spawn(scope, node);
}
}
fn spawn<'scope>(&'scope self, scope: &Scope<'scope>, node: NodeId) {
scope.spawn(move |scope| {
for next in self.run_one(node) {
self.spawn(scope, next);
}
});
}
fn alone(&self) {
let mut ready = self.released();
while let Some(node) = ready.pop() {
ready.extend(self.run_one(node));
}
}
fn run_one(&self, node: NodeId) -> Vec<NodeId> {
let done = self.execute(node);
let Ok(mut state) = self.state.lock() else {
return Vec::new();
};
match done {
Ok(Attempt::Done(result)) => {
let ran_above = result.outcome == Outcome::Ran || self.ran_above(&state, node);
state.produced.insert(
node,
Produced {
output: Stored {
hash: result.hash,
path: result.output.clone(),
},
ran_above,
},
);
state.results.push(result);
state.release(node);
}
Ok(Attempt::Parked) => {}
Ok(Attempt::Deferred) => state.deferred.push(node),
Err(failure) => state.failures.push(failure),
}
std::mem::take(&mut state.ready)
}
fn released(&self) -> Vec<NodeId> {
self.state
.lock()
.map_or_else(|_| Vec::new(), |mut state| std::mem::take(&mut state.ready))
}
fn ran_above(&self, state: &State, node: NodeId) -> bool {
self.graph.step(node).is_some_and(|spec| {
spec.arguments.iter().any(|argument| {
state
.produced
.get(&argument.node)
.is_some_and(|produced| produced.ran_above)
})
})
}
fn execute(&self, node: NodeId) -> Result<Attempt, StepFailure> {
let name = self
.graph
.step(node)
.map_or_else(|| "?".to_owned(), |spec| spec.name.clone());
self.attempt(node).map_err(|message| StepFailure {
node,
step: name,
message,
})
}
fn attempt(&self, node: NodeId) -> Result<Attempt, String> {
let spec = self
.graph
.step(node)
.ok_or_else(|| "this node is not a step".to_owned())?;
let task = *self.tasks.get(&node).ok_or_else(|| {
"no recipe was recorded for this step, so there is nothing to run".to_owned()
})?;
let inputs = self.inputs(node)?;
let key = self.key(spec, task, &inputs)?;
if !self.force
&& let Some(entry) = self.cache.lookup(key).map_err(|error| error.to_string())?
{
return Ok(Attempt::Done(self.cached_result(node, spec, key, &entry)?));
}
let Some(_claim) = self.claim(key, node)? else {
return Ok(Attempt::Parked);
};
if !self.force
&& let Some(entry) = self.cache.lookup(key).map_err(|error| error.to_string())?
{
return Ok(Attempt::Done(self.cached_result(node, spec, key, &entry)?));
}
let Some(_held) = self.take_lease(key)? else {
return Ok(Attempt::Deferred);
};
let staging = self.cache.staging(key, output_suffix(spec.output));
let _ = std::fs::remove_file(&staging);
let produced = produce(&task.recipe, &inputs, &task.parameters, &staging, self.host)
.inspect_err(|_| {
let _ = std::fs::remove_file(&staging);
})?;
let stored = self
.cache
.store(&staging)
.map_err(|error| error.to_string())?;
let milliseconds = u64::try_from(produced.duration.as_millis()).unwrap_or(u64::MAX);
let meaning = self
.cache
.semantic(spec.output, &stored.path)
.map_err(|error| error.to_string())?;
let mine = meaning.hash;
let recorded = self
.cache
.record(&Recording {
key,
step: &spec.name,
output: &stored,
canonical: mine,
tools: &self.tool_summary(task),
duration_ms: milliseconds,
notes: &produced.notes,
})
.map_err(|error| error.to_string())?;
let notes = noticed(produced.notes, meaning.notes);
let (output, canonical, superseded) = match recorded {
Recorded::Fresh => (stored, mine, false),
Recorded::Superseded { canonical: theirs } => {
if theirs != mine {
self.note_divergence(Divergence {
node,
step: spec.name.clone(),
key,
ours: mine,
theirs,
});
}
match self.cache.lookup(key).map_err(|error| error.to_string())? {
Some(entry) => (entry.output, theirs, true),
None => (stored, mine, false),
}
}
};
let adopted = superseded
&& self
.prov
.adopt(self.cache.objects(), key)
.map_err(|error| error.to_string())?
.is_some();
if !adopted {
self.remember(&Made {
spec,
task,
key,
inputs: &inputs,
command: produced.command,
bytes: output.hash,
canonical,
notes: ¬es,
duration_ms: milliseconds,
})?;
}
Ok(Attempt::Done(StepResult {
node,
step: spec.name.clone(),
outcome: Outcome::Ran,
key,
hash: output.hash,
canonical,
notes,
output: output.path,
duration: produced.duration,
}))
}
fn claim(&self, key: StepKey, node: NodeId) -> Result<Option<Claim<'_>>, String> {
let mut state = self.state.lock().map_err(|_| poisoned())?;
if state.running.contains(&key) {
state.parked.entry(key).or_default().push(node);
return Ok(None);
}
state.running.insert(key);
Ok(Some(Claim { runner: self, key }))
}
fn take_lease(&self, key: StepKey) -> Result<Option<Leased<'_>>, String> {
let (Some(worker), Some(shared)) = (self.worker.as_ref(), self.cache.objects().shared())
else {
return Ok(Some(Leased {
runner: self,
held: None,
}));
};
let now = prov::now();
let deadline = now.saturating_add(i64::try_from(self.lease.as_secs()).unwrap_or(i64::MAX));
match lease::acquire(shared, key, worker, deadline, now)
.map_err(|error| error.to_string())?
{
lease::Claimed::Acquired { generation } => Ok(Some(Leased {
runner: self,
held: Some((key, generation)),
})),
lease::Claimed::Held { .. } => Ok(None),
}
}
fn rearm(&self, patience: &mut Patience) -> bool {
{
let Ok(state) = self.state.lock() else {
return false;
};
if state.deferred.is_empty() {
return false;
}
}
patience.wait();
let Ok(mut state) = self.state.lock() else {
return false;
};
let waiting = std::mem::take(&mut state.deferred);
state.waited = state.waited.saturating_add(waiting.len());
state.ready.extend(waiting);
true
}
fn note_divergence(&self, divergence: Divergence) {
if let Ok(mut state) = self.state.lock() {
state.diverged.push(divergence);
}
}
fn cached_result(
&self,
node: NodeId,
spec: &StepSpec,
key: StepKey,
entry: &Entry,
) -> Result<StepResult, String> {
let output = &entry.output;
let outcome = {
let upstream_ran = self
.state
.lock()
.is_ok_and(|state| self.ran_above(&state, node));
if upstream_ran {
Outcome::Skipped
} else {
Outcome::Cached
}
};
let meaning = self
.cache
.semantic(spec.output, &output.path)
.map_err(|error| error.to_string())?;
if self
.prov
.lookup(key)
.map_err(|error| error.to_string())?
.is_none()
{
self.prov
.adopt(self.cache.objects(), key)
.map_err(|error| error.to_string())?;
}
Ok(StepResult {
node,
step: spec.name.clone(),
outcome,
key,
hash: output.hash,
canonical: meaning.hash,
notes: noticed(entry.notes.clone(), meaning.notes),
output: output.path.clone(),
duration: Duration::ZERO,
})
}
fn inputs(&self, node: NodeId) -> Result<Vec<(String, Vec<PathBuf>)>, String> {
let state = self.state.lock().map_err(|_| poisoned())?;
inputs_of(self.graph, node, &|from| {
state
.produced
.get(&from)
.map(|produced| produced.output.path.clone())
})
}
fn key(
&self,
spec: &StepSpec,
task: &Task,
inputs: &[(String, Vec<PathBuf>)],
) -> Result<StepKey, String> {
let mut hashed = Vec::with_capacity(inputs.len());
for (argument, (param, files)) in spec.arguments.iter().zip(inputs) {
let kind = self
.graph
.dataset(argument.node)
.map_or(argument.declared, Dataset::kind);
let mut each = Vec::with_capacity(files.len());
for file in files {
each.push(
self.cache
.semantic_hash(kind, file)
.map_err(|error| format!("`{param}`: {error}"))?,
);
}
hashed.push((param.clone(), ContentHash::of_hashes(&each)));
}
let mut tools = Vec::with_capacity(task.tools.len());
for tool in &task.tools {
let version = self
.versions
.get(tool)
.cloned()
.unwrap_or_else(|| tool_version(tool))?;
tools.push((tool.clone(), version));
}
Ok(Ingredients {
step: spec.name.clone(),
code: task.code.clone(),
recipe: task.recipe.describe(),
output: spec.output,
parameters: task.parameters.clone(),
inputs: hashed,
tools,
}
.key())
}
fn remember(&self, made: &Made<'_>) -> Result<(), String> {
let mut inputs = Vec::new();
let mut references = Vec::new();
let mut remotes = Vec::new();
for (argument, (param, files)) in made.spec.arguments.iter().zip(made.inputs) {
let dataset = self.graph.dataset(argument.node);
let kind = dataset.map_or(argument.declared, Dataset::kind);
for file in files {
let bytes = self
.cache
.content_hash(file)
.map_err(|error| format!("`{param}`: {error}"))?;
let canonical = self
.cache
.semantic_hash(kind, file)
.map_err(|error| format!("`{param}`: {error}"))?;
inputs.push(InputRecord {
param: param.clone(),
kind,
path: file.clone(),
bytes,
canonical,
});
}
if let Some(dataset) = dataset
&& let Some(origin) = dataset.origin()
{
remotes.push(origin.clone());
}
if kind == DataKind::Reference
&& let Some(dataset) = dataset
&& let Some(identity) = dataset.dimensions().reference.value()
&& let Some(path) = dataset.path()
{
references.push(prov::pin(param, path, identity));
}
}
let mut tools = Vec::with_capacity(made.task.tools.len());
for tool in &made.task.tools {
if let Some(Ok(version)) = self.versions.get(tool) {
tools.push((tool.clone(), version.clone()));
}
}
self.prov
.record(&Record {
key: made.key,
step: made.spec.name.clone(),
code: made.task.code.clone(),
command: made.command.clone(),
output_kind: made.spec.output,
output_bytes: made.bytes,
output_canonical: made.canonical,
output_notes: made.notes.to_vec(),
parameters: made.task.parameters.clone(),
inputs,
references,
remotes,
tools,
engine: crate::version().to_owned(),
platform: prov::platform(),
recorded_at: prov::now(),
duration_ms: made.duration_ms,
})
.map_err(|error| error.to_string())?;
self.prov
.publish(self.cache.objects(), made.key)
.map_err(|error| error.to_string())
}
fn tool_summary(&self, task: &Task) -> String {
task.tools
.iter()
.map(|tool| match self.versions.get(tool) {
Some(Ok(version)) => format!("{tool} {}", first_line(version)),
_ => tool.clone(),
})
.collect::<Vec<_>>()
.join("; ")
}
fn finish(self) -> RunReport {
let Ok(state) = self.state.into_inner() else {
return RunReport::default();
};
let mut results = state.results;
let mut failures = state.failures;
results.sort_by_key(|result| result.node.index());
failures.sort_by_key(|failure| failure.node.index());
let mut diverged = state.diverged;
diverged.sort_by_key(|divergence| divergence.node.index());
RunReport {
results,
failures,
store: self.cache.objects().stats(),
refused: self.cache.objects().rejection(),
worker: self.worker.map(|worker| worker.name().to_owned()),
waited: state.waited,
diverged,
}
}
}
struct Leased<'a> {
runner: &'a Runner<'a>,
held: Option<(StepKey, u32)>,
}
impl Drop for Leased<'_> {
fn drop(&mut self) {
let Some((key, generation)) = self.held.take() else {
return;
};
let Some(shared) = self.runner.cache.objects().shared() else {
return;
};
let _ = lease::relinquish(shared, key, generation, prov::now());
}
}
enum Attempt {
Done(StepResult),
Parked,
Deferred,
}
struct Made<'a> {
spec: &'a StepSpec,
task: &'a Task,
key: StepKey,
inputs: &'a [(String, Vec<PathBuf>)],
command: Option<String>,
bytes: ContentHash,
canonical: ContentHash,
notes: &'a [Note],
duration_ms: u64,
}
struct Claim<'a> {
runner: &'a Runner<'a>,
key: StepKey,
}
impl Drop for Claim<'_> {
fn drop(&mut self) {
if let Ok(mut state) = self.runner.state.lock() {
state.running.remove(&self.key);
if let Some(waiting) = state.parked.remove(&self.key) {
state.ready.extend(waiting);
}
}
}
}
fn poisoned() -> String {
"the run was left locked by a panicking step".to_owned()
}
fn first_line(text: &str) -> &str {
text.lines().next().unwrap_or(text).trim()
}
fn shell(command: &str) -> Result<(), String> {
let output = Command::new("sh")
.arg("-c")
.arg(command)
.output()
.map_err(|error| format!("the command could not be started: {error}"))?;
if output.status.success() {
return Ok(());
}
let code = output
.status
.code()
.map_or_else(|| "a signal".to_owned(), |code| code.to_string());
let mut message = format!("the command failed with exit status {code}");
for stream in [&output.stderr, &output.stdout] {
let text = String::from_utf8_lossy(stream);
let text = text.trim();
if !text.is_empty() {
message.push('\n');
message.push_str(text);
}
}
Err(message)
}
fn fill_template(
template: &str,
inputs: &[(String, Vec<PathBuf>)],
parameters: &[(String, String)],
out: &Path,
) -> Result<String, String> {
let mut command = String::with_capacity(template.len());
let mut rest = template;
while let Some(at) = rest.find(['{', '}']) {
command.push_str(&rest[..at]);
let after = &rest[at..];
let brace = &after[..1];
let inside = &after[1..];
if inside.starts_with(brace) {
command.push_str(brace);
rest = &inside[1..];
continue;
}
if brace == "}" {
return Err(unbalanced(template));
}
let Some(end) = inside.find('}') else {
return Err(unbalanced(template));
};
let name = &inside[..end];
if !is_name(name) {
return Err(unbalanced(template));
}
command.push_str("e(&resolve(name, inputs, parameters, out)?));
rest = &inside[end + 1..];
}
command.push_str(rest);
Ok(command)
}
fn is_name(text: &str) -> bool {
!text.is_empty()
&& text
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
}
fn unbalanced(template: &str) -> String {
format!(
"this command has a `{{` that is not a placeholder; write `{{{{` and `}}}}` for \
literal braces, as an `awk '{{{{print $1}}}}'` needs: {template}"
)
}
fn resolve(
name: &str,
inputs: &[(String, Vec<PathBuf>)],
parameters: &[(String, String)],
out: &Path,
) -> Result<String, String> {
if name == "out" {
return Ok(out.to_string_lossy().into_owned());
}
let (base, field) = match name.split_once('.') {
Some((base, field)) => (base, Some(field)),
None => (name, None),
};
if let Some((_, files)) = inputs.iter().find(|(param, _)| param == base) {
let first = || {
files
.first()
.map(|path| path.to_string_lossy().into_owned())
.ok_or_else(|| format!("`{{{name}}}`: `{base}` has no file behind it"))
};
return match field {
None | Some("r1") => first(),
Some("r2") => files
.get(1)
.map(|path| path.to_string_lossy().into_owned())
.ok_or_else(|| {
format!(
"`{{{name}}}`: `{base}` is a single-end sample, so it has no second mate"
)
}),
Some(other) => Err(format!(
"`{{{name}}}`: an input has `r1` and `r2`, not `{other}`"
)),
};
}
if field.is_none()
&& let Some((_, value)) = parameters.iter().find(|(param, _)| param == base)
{
return Ok(value.clone());
}
let mut known: Vec<&str> = inputs.iter().map(|(param, _)| param.as_str()).collect();
known.extend(parameters.iter().map(|(param, _)| param.as_str()));
known.push("out");
known.sort_unstable();
Err(format!(
"`{{{name}}}` is not a parameter of this step; it has {}",
known.join(", ")
))
}
fn store_lines(report: &RunReport) -> Vec<String> {
let store = report.store;
if store.quiet() && report.refused.is_none() {
return Vec::new();
}
let mut lines = vec![String::new()];
if store.fetched > 0 {
lines.push(format!(
"store {} from the remote store",
plural_count(store.fetched, "object")
));
}
if store.pushed > 0 {
lines.push(format!(
"store {} written through to it",
plural_count(store.pushed, "object")
));
}
if let Some(refused) = &report.refused {
lines.push(format!("refused {refused}"));
if store.rejected > 1 {
lines.push(format!(
"refused and {} further {}",
store.rejected - 1,
if store.rejected == 2 {
"object"
} else {
"objects"
}
));
}
lines.push(" the steps that produced them have been run again".to_owned());
}
if store.unreachable > 0 {
lines.push(format!(
"store {} to the remote store did not answer, so this run \
used the local",
plural_count(store.unreachable, "call")
));
lines.push(
" store alone. Nothing here is wrong; work that a \
colleague had"
.to_owned(),
);
lines.push(
" already done may have been done again. \
`ligase store push` sends"
.to_owned(),
);
lines.push(" this run's objects up once it is back.".to_owned());
}
lines
}
fn worker_lines(report: &RunReport) -> Vec<String> {
let Some(worker) = &report.worker else {
return Vec::new();
};
let counts = report.counts();
let mut parts = Vec::new();
if counts.ran > 0 {
parts.push(format!("{} ran here", counts.ran));
}
let unwaited = (counts.cached + counts.skipped).saturating_sub(report.waited);
if unwaited > 0 {
parts.push(format!("{unwaited} from the store"));
}
if report.waited > 0 {
parts.push(format!("{} waited for other workers", report.waited));
}
let mut lines = vec![String::new()];
if parts.is_empty() {
lines.push(format!("worker {worker}: nothing to do"));
} else {
lines.push(format!("worker {worker}: {}", parts.join(", ")));
}
for divergence in &report.diverged {
lines.push(String::new());
lines.push(format!(
"diverged `{}` was computed by another worker to a different result",
divergence.step
));
lines.push(format!(" this run made {}", divergence.ours));
lines.push(format!(" the store holds {}", divergence.theirs));
lines.push(
" The store's answer is the one in force, here and everywhere, so"
.to_owned(),
);
lines.push(
" nothing below this step disagrees between machines. But the step"
.to_owned(),
);
lines.push(
" does not produce one answer from one set of inputs: either its"
.to_owned(),
);
lines.push(
" canonical form does not fix its result, or its tool is stochastic"
.to_owned(),
);
lines.push(
" in something other than its seed -- a thread count, most often."
.to_owned(),
);
lines.push(" `ligase audit` is how to find out which.".to_owned());
}
lines
}
fn plural_count(count: u64, word: &str) -> String {
if count == 1 {
format!("{count} {word}")
} else {
format!("{count} {word}s")
}
}
fn quote(value: &str) -> String {
format!("'{}'", value.replace('\'', r"'\''"))
}
#[must_use]
pub fn summarise(report: &RunReport) -> String {
let counts = report.counts();
let steps = counts.ran + counts.cached + counts.skipped + counts.failed;
if steps == 0 {
return "nothing to run.".to_owned();
}
let mut parts = Vec::new();
if counts.ran > 0 {
parts.push(format!("{} ran", counts.ran));
}
if counts.cached > 0 {
parts.push(format!("{} from cache", counts.cached));
}
if counts.skipped > 0 {
parts.push(format!("{} skipped", counts.skipped));
}
if counts.failed > 0 {
parts.push(format!("{} failed", counts.failed));
}
format!("{steps} {}: {}.", plural(steps, "step"), parts.join(", "))
}
#[must_use]
pub fn render(graph: &Graph, roots: &[NodeId], report: &RunReport) -> String {
let scopes = graph.scopes(roots);
let mut lines = Vec::new();
let ran: Vec<(String, String)> = report
.results
.iter()
.filter(|result| result.outcome == Outcome::Ran)
.map(|result| {
(
format!(
"{}{}",
quoted(&result.step),
scope_suffix(scopes.get(&result.node))
),
duration(result.duration),
)
})
.collect();
let widest = ran.iter().map(|(label, _)| label.len()).max().unwrap_or(0);
for (label, cost) in &ran {
lines.push(format!("ran {label:<widest$} {cost}"));
}
for wanted in [Outcome::Cached, Outcome::Skipped] {
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
for result in report
.results
.iter()
.filter(|result| result.outcome == wanted)
{
let samples = scopes
.get(&result.node)
.map(|scope| scope.value.clone())
.into_iter()
.collect::<Vec<String>>();
match groups.iter_mut().find(|(step, _)| *step == result.step) {
Some((_, seen)) => seen.extend(samples),
None => groups.push((result.step.clone(), samples)),
}
}
for (step, samples) in groups {
let label = match wanted {
Outcome::Skipped => "skipped ",
_ => "cached ",
};
lines.push(match samples.as_slice() {
[] => format!("{label} {}", quoted(&step)),
[one] => format!("{label} {} ({one})", quoted(&step)),
many => format!("{label} {} for {}", quoted(&step), many.join(", ")),
});
}
}
lines.extend(store_lines(report));
lines.extend(worker_lines(report));
let noted: Vec<(&StepResult, &Note)> = report
.results
.iter()
.flat_map(|result| result.notes.iter().map(move |note| (result, note)))
.collect();
if !noted.is_empty() {
lines.push(String::new());
for (result, note) in ¬ed {
lines.push(format!(
"noticed {}{}: {note}",
quoted(&result.step),
scope_suffix(scopes.get(&result.node))
));
}
let mut given: Vec<&str> = Vec::new();
for (_, note) in ¬ed {
if !given.contains(¬e.code()) {
given.push(note.code());
lines.push(format!(" {}", note.advice()));
}
}
}
let mut remotes: Vec<(&Origin, &[Note])> = Vec::new();
for node in graph.reachable_nodes(roots) {
if let Some(dataset) = graph.dataset(node)
&& let Some(origin) = dataset.origin()
&& !remotes
.iter()
.any(|(held, _)| held.locator == origin.locator)
{
remotes.push((origin, dataset.notes()));
}
}
if !remotes.is_empty() {
lines.push(String::new());
for (origin, notes) in remotes {
let what = match origin.verdict {
RemoteVerdict::Pinned => format!("pinned, fetched {}", day(origin.fetched_at)),
RemoteVerdict::Replayed => {
format!("replayed from record of {}", day(origin.fetched_at))
}
RemoteVerdict::Live => format!("answered live on {}", day(origin.fetched_at)),
};
lines.push(format!("input {} -- {what}", quoted(&origin.locator)));
for note in notes {
lines.push(format!(" {note}"));
}
}
}
for failure in &report.failures {
lines.push(String::new());
lines.push(format!(
"{}{} failed:",
quoted(&failure.step),
scope_suffix(scopes.get(&failure.node))
));
for line in failure.message.lines() {
lines.push(format!(" {line}"));
}
}
if !lines.is_empty() {
lines.push(String::new());
}
lines.push(summarise(report));
lines.join("\n")
}
fn scope_suffix(scope: Option<&crate::check::Scope>) -> String {
scope.map_or_else(String::new, |scope| {
format!(" ({} {})", scope.kind, scope.value)
})
}
fn quoted(step: &str) -> String {
format!("`{step}`")
}
fn duration(elapsed: Duration) -> String {
let seconds = elapsed.as_secs_f64();
if seconds < 1.0 {
return format!("{}ms", elapsed.as_millis());
}
if seconds < 60.0 {
return format!("{seconds:.1}s");
}
let whole = elapsed.as_secs();
format!("{}m {}s", whole / 60, whole % 60)
}
fn plural(count: usize, word: &str) -> String {
if count == 1 {
word.to_owned()
} else {
format!("{word}s")
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn inputs() -> Vec<(String, Vec<PathBuf>)> {
vec![
("ref".into(), vec![PathBuf::from("/refs/HXB2.fasta")]),
(
"reads".into(),
vec![PathBuf::from("/data/s_1.fq"), PathBuf::from("/data/s_2.fq")],
),
]
}
fn parameters() -> Vec<(String, String)> {
vec![("min_freq".into(), "0.01".into())]
}
fn fill(template: &str) -> Result<String, String> {
fill_template(
template,
&inputs(),
¶meters(),
Path::new("/tmp/out.bam"),
)
}
#[test]
fn an_input_a_mate_a_parameter_and_the_output_are_filled_in() {
assert_eq!(
fill("minimap2 -ax sr {ref} {reads.r1} {reads.r2} -f {min_freq} -o {out}").unwrap(),
"minimap2 -ax sr '/refs/HXB2.fasta' '/data/s_1.fq' '/data/s_2.fq' \
-f '0.01' -o '/tmp/out.bam'"
);
}
#[test]
fn an_input_without_a_mate_named_is_its_first_file() {
assert_eq!(fill("cat {reads}").unwrap(), "cat '/data/s_1.fq'");
}
#[test]
fn a_doubled_brace_is_a_literal_one() {
assert_eq!(
fill("awk '{{print $1}}' {ref}").unwrap(),
"awk '{print $1}' '/refs/HXB2.fasta'"
);
}
#[test]
fn an_unknown_placeholder_lists_what_the_step_does_have() {
let error = fill("cat {refrence}").unwrap_err();
assert!(error.contains("refrence"), "{error}");
assert!(error.contains("min_freq"), "{error}");
assert!(error.contains("ref"), "{error}");
}
#[test]
fn an_unmatched_brace_says_how_to_write_a_literal_one() {
assert!(fill("awk '{print $1}' {ref}").unwrap_err().contains("{{"));
assert!(fill("cat {ref").unwrap_err().contains("{{"));
}
#[test]
fn a_single_end_sample_asked_for_a_second_mate_says_so() {
let single = vec![("reads".to_owned(), vec![PathBuf::from("/data/s.fq")])];
let error =
fill_template("cat {reads.r2}", &single, &[], Path::new("/tmp/out")).unwrap_err();
assert!(error.contains("single-end"), "{error}");
}
#[test]
fn a_value_with_a_space_in_it_stays_one_word() {
let spaced = vec![("ref".to_owned(), vec![PathBuf::from("/my refs/HXB2.fa")])];
assert_eq!(
fill_template("cat {ref}", &spaced, &[], Path::new("/tmp/out")).unwrap(),
"cat '/my refs/HXB2.fa'"
);
}
#[test]
fn a_quote_in_a_value_cannot_end_the_quoting() {
let nasty = vec![("ref".to_owned(), vec![PathBuf::from("/refs/it's.fa")])];
assert_eq!(
fill_template("cat {ref}", &nasty, &[], Path::new("/tmp/out")).unwrap(),
r"cat '/refs/it'\''s.fa'"
);
}
#[test]
fn a_callback_enters_the_key_as_itself_rather_than_as_its_number() {
assert_eq!(
Recipe::Callback(1).describe(),
Recipe::Callback(2).describe()
);
assert_ne!(
Recipe::Shell("a".into()).describe(),
Recipe::Shell("b".into()).describe()
);
}
#[test]
fn the_usual_tool_answers_on_stdout_and_is_kept_whole() {
let version = version_from(
"samtools",
&DEFAULT_PROBE,
true,
"samtools 1.24\nUsing htslib 1.24\n",
"",
)
.unwrap();
assert_eq!(version, "samtools 1.24\nUsing htslib 1.24");
}
#[test]
fn a_tool_that_prints_only_to_stderr_is_still_read() {
assert_eq!(
version_from("tool", &DEFAULT_PROBE, true, "", "tool 2.0\n").unwrap(),
"tool 2.0"
);
}
#[test]
fn a_probe_that_fails_unexpectedly_is_an_error_and_not_a_version() {
let error = version_from(
"bwa",
&DEFAULT_PROBE,
false,
"",
"[main] unrecognized command '--version'\n",
)
.unwrap_err();
assert!(error.contains("failed"), "{error}");
assert!(error.contains("unrecognized command"), "{error}");
assert!(
error.contains("would not move a single cache key"),
"the message has to say why a wrong version is worse than a \
missing one: {error}"
);
}
#[test]
fn a_probe_that_was_expected_to_fail_is_read_anyway() {
let probe = probe_for("bwa");
assert!(probe.failure_expected, "bwa's probe exits non-zero");
let version = version_from(
"bwa",
&probe,
false,
"",
"\nProgram: bwa (alignment via Burrows-Wheeler transformation)\n\
Version: 0.7.19-r1273\n\
Contact: Heng Li <hli@ds.dfci.harvard.edu>\n\n\
Usage: bwa <command> [options]\n",
)
.unwrap();
assert_eq!(version, "Version: 0.7.19-r1273");
}
#[test]
fn a_probe_whose_marker_has_gone_is_an_error_rather_than_a_banner() {
let error = version_from(
"bwa",
&probe_for("bwa"),
false,
"",
"Usage: bwa <command> [options]\n",
)
.unwrap_err();
assert!(error.contains("no line containing `Version:`"), "{error}");
assert!(error.contains("version-probe table"), "{error}");
}
#[test]
fn a_probe_that_prints_nothing_is_an_error() {
let error = version_from("tool", &DEFAULT_PROBE, true, "", "").unwrap_err();
assert_eq!(error, "`tool --version` printed nothing");
}
#[test]
fn a_probe_with_no_arguments_is_quoted_as_the_bare_command() {
assert_eq!(describe_probe("bwa", &probe_for("bwa")), "bwa");
assert_eq!(
describe_probe("samtools", &DEFAULT_PROBE),
"samtools --version"
);
}
}