use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::{Methods, Noticed, Prov, ProvError, Record};
use crate::exec::RunReport;
use crate::graph::{Graph, NodeId};
use crate::hash::ContentHash;
const MANIFEST_HASH: &str = "blake3";
pub struct Request<'a> {
pub graph: &'a Graph,
pub roots: &'a [NodeId],
pub report: &'a RunReport,
pub prov: &'a Prov,
pub methods: &'a Methods,
pub include: &'a [PathBuf],
}
#[derive(Clone, Debug, Default)]
pub struct Summary {
pub root: PathBuf,
pub files: Vec<String>,
pub steps: usize,
pub gaps: usize,
}
#[derive(Debug)]
pub enum BundleError {
Io {
path: PathBuf,
source: io::Error,
},
Prov(ProvError),
Malformed {
path: PathBuf,
detail: String,
},
}
impl fmt::Display for BundleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
Self::Prov(error) => write!(f, "{error}"),
Self::Malformed { path, detail } => write!(f, "{}: {detail}", path.display()),
}
}
}
impl std::error::Error for BundleError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Prov(error) => Some(error),
Self::Malformed { .. } => None,
}
}
}
impl From<ProvError> for BundleError {
fn from(error: ProvError) -> Self {
Self::Prov(error)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Match {
Identical,
Reproduced,
Differs,
Missing,
}
impl fmt::Display for Match {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Identical => "identical",
Self::Reproduced => "reproduced",
Self::Differs => "differs",
Self::Missing => "missing",
})
}
}
#[derive(Clone, Debug)]
pub struct Check {
pub step: String,
pub scope: Option<String>,
pub expected: ContentHash,
pub found: Option<ContentHash>,
pub same_key: bool,
pub verdict: Match,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
Same,
Changed,
Absent,
}
impl fmt::Display for Presence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Same => "same",
Self::Changed => "changed",
Self::Absent => "absent",
})
}
}
#[derive(Clone, Debug)]
pub struct InputCheck {
pub step: String,
pub param: String,
pub path: PathBuf,
pub presence: Presence,
}
#[derive(Clone, Debug, Default)]
pub struct Verification {
pub checks: Vec<Check>,
pub inputs: Vec<InputCheck>,
pub noticed: Vec<Noticed>,
}
impl Verification {
#[must_use]
pub fn reproduced(&self) -> bool {
!self.checks.is_empty()
&& self
.checks
.iter()
.all(|check| matches!(check.verdict, Match::Identical | Match::Reproduced))
}
#[must_use]
pub fn verdict(&self) -> Match {
self.checks
.iter()
.map(|check| check.verdict)
.max()
.unwrap_or(Match::Missing)
}
#[must_use]
pub fn summary(&self) -> String {
let count = |wanted: Match| {
self.checks
.iter()
.filter(|check| check.verdict == wanted)
.count()
};
let mut parts = Vec::new();
for verdict in [
Match::Identical,
Match::Reproduced,
Match::Differs,
Match::Missing,
] {
let found = count(verdict);
if found > 0 {
parts.push(format!("{found} {verdict}"));
}
}
let places = self.checks.len();
let noun = if places == 1 { "result" } else { "results" };
if parts.is_empty() {
return "this bundle records no results.".to_owned();
}
format!("{places} {noun}: {}.", parts.join(", "))
}
#[must_use]
pub fn text(&self) -> String {
let mut lines = Vec::new();
for check in &self.checks {
let named = match &check.scope {
Some(scope) => format!("`{}` ({scope})", check.step),
None => format!("`{}`", check.step),
};
lines.push(format!("{:<16} {named}", check.verdict.to_string()));
match check.verdict {
Match::Identical => lines.push(format!(
" the same key, the same result {}",
short(check.expected)
)),
Match::Reproduced => {
lines.push(format!(
" the result is the same {}",
short(check.expected)
));
lines.push(" the key is not: something in the environment moved".to_owned());
}
Match::Differs => lines.push(format!(
" expected {} and got {}",
short(check.expected),
check.found.map_or_else(|| "nothing".to_owned(), short),
)),
Match::Missing => {
lines.push(" this pipeline did not produce it".to_owned());
}
}
}
let moved: Vec<&InputCheck> = self
.inputs
.iter()
.filter(|input| input.presence != Presence::Same)
.collect();
if !moved.is_empty() {
lines.push(String::new());
lines.push(format!(
"{} of {} inputs are not the ones this bundle was built from:",
moved.len(),
self.inputs.len()
));
for input in moved {
lines.push(format!(
" {:<10} `{}` of `{}`: {}",
input.presence.to_string(),
input.param,
input.step,
input.path.display()
));
}
lines
.push("A changed input explains a changed output, so read these first.".to_owned());
}
if !self.noticed.is_empty() {
lines.push(String::new());
let mut places: Vec<(&str, Option<&str>)> = self
.noticed
.iter()
.map(|item| (item.step.as_str(), item.scope.as_deref()))
.collect();
places.dedup();
lines.push(format!(
"{} of {} results name a file where a sample identifier belongs:",
places.len(),
self.checks.len()
));
for item in &self.noticed {
let named = match &item.scope {
Some(scope) => format!("`{}` ({scope})", item.step),
None => format!("`{}`", item.step),
};
lines.push(format!(" {named}: {}", item.note));
}
lines.push(
"Such a hash depends on the file it was named after, so a `differs` here may \
be that and nothing else."
.to_owned(),
);
let mut given: Vec<&str> = Vec::new();
for item in &self.noticed {
if !given.contains(&item.note.code()) {
given.push(item.note.code());
lines.push(format!(" {}", item.note.advice()));
}
}
}
if !lines.is_empty() {
lines.push(String::new());
}
lines.push(self.summary());
lines.join("\n")
}
}
pub fn write(into: &Path, request: &Request<'_>) -> Result<Summary, BundleError> {
create_dir(into)?;
let scopes = request.graph.scopes(request.roots);
let mut rows = Vec::new();
for result in &request.report.results {
let record = request.prov.lookup(result.key)?;
rows.push((
result,
scopes.get(&result.node).map(|scope| scope.value.clone()),
record,
));
}
let gaps = rows.iter().filter(|(_, _, held)| held.is_none()).count();
let mut methods = String::from("# Methods\n\n");
methods.push_str(&request.methods.text());
methods.push('\n');
put(into, "METHODS.md", &methods)?;
put(into, "README.md", &readme(request.methods))?;
let mut results = Table::new(&["step", "scope", "key", "bytes", "canonical"]);
for (result, scope, _) in &rows {
results.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
&result.hash.to_hex(),
&result.canonical.to_hex(),
]);
}
put(into, "results.tsv", &results.finish())?;
let mut commands = Table::new(&["step", "scope", "key", "command"]);
for (result, scope, record) in &rows {
let command = record
.as_ref()
.and_then(|record| record.command.clone())
.unwrap_or_default();
commands.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
&command,
]);
}
put(into, "commands.tsv", &commands.finish())?;
let mut inputs = Table::new(&[
"step",
"scope",
"param",
"kind",
"path",
"bytes",
"canonical",
]);
for (result, scope, record) in &rows {
let Some(record) = record else { continue };
for input in &record.inputs {
inputs.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&input.param,
input.kind.name(),
&input.path.to_string_lossy(),
&input.bytes.to_hex(),
&input.canonical.to_hex(),
]);
}
}
put(into, "inputs.tsv", &inputs.finish())?;
let mut notes = Table::new(&["step", "scope", "key", "code", "value"]);
for (result, scope, record) in &rows {
let Some(record) = record else { continue };
for note in &record.output_notes {
notes.row(&[
&result.step,
scope.as_deref().unwrap_or(""),
&result.key.to_hex(),
note.code(),
note.value(),
]);
}
}
put(into, "notes.tsv", ¬es.finish())?;
let mut references = Table::new(&[
"param",
"path",
"build",
"accession",
"contigs",
"length",
"checksum",
"fingerprint",
]);
for reference in request.methods.references() {
references.row(&[
&reference.param,
&reference.path.to_string_lossy(),
reference.build.as_deref().unwrap_or(""),
reference.accession.as_deref().unwrap_or(""),
&reference.contigs.to_string(),
&reference.length.to_string(),
reference.checksum.as_deref().unwrap_or(""),
&reference.fingerprint,
]);
}
put(into, "references.tsv", &references.finish())?;
let mut environment = Table::new(&["name", "value"]);
environment.row(&["ligase", &request.methods.engine]);
environment.row(&["platform", &request.methods.platform]);
for (tool, version) in request.methods.tools() {
environment.row(&[&tool, &version]);
}
put(into, "environment.tsv", &environment.finish())?;
create_dir(&into.join("steps"))?;
let mut sources: BTreeMap<String, String> = BTreeMap::new();
for (_, _, record) in &rows {
let Some(record) = record else { continue };
sources.insert(step_file(record, &sources), record.code.clone());
}
for (name, code) in &sources {
put(into, &format!("steps/{name}"), code)?;
}
if !request.include.is_empty() {
create_dir(&into.join("pipeline"))?;
for source in request.include {
let Some(name) = source.file_name() else {
continue;
};
let destination = into.join("pipeline").join(name);
fs::copy(source, &destination).map_err(|error| BundleError::Io {
path: source.clone(),
source: error,
})?;
}
}
let files = manifest(into)?;
Ok(Summary {
root: into.to_path_buf(),
files,
steps: rows.len() - gaps,
gaps,
})
}
pub fn verify(
bundle: &Path,
graph: &Graph,
roots: &[NodeId],
report: &RunReport,
) -> Result<Verification, BundleError> {
let scopes = graph.scopes(roots);
let here: Vec<(String, Option<String>, &crate::exec::StepResult)> = report
.results
.iter()
.map(|result| {
(
result.step.clone(),
scopes.get(&result.node).map(|scope| scope.value.clone()),
result,
)
})
.collect();
let mut verification = Verification::default();
for result in &report.results {
for note in &result.notes {
verification.noticed.push(Noticed {
step: result.step.clone(),
scope: scopes.get(&result.node).map(|scope| scope.value.clone()),
scope_kind: scopes.get(&result.node).map(|scope| scope.kind),
note: note.clone(),
});
}
}
for row in read_table(bundle, "results.tsv", 5)? {
let (step, scope, key, _bytes, canonical) = (&row[0], &row[1], &row[2], &row[3], &row[4]);
let scope = (!scope.is_empty()).then(|| scope.clone());
let expected = parse_hash(bundle, "results.tsv", canonical)?;
let found = here
.iter()
.find(|(name, at, _)| name == step && at == &scope);
let check = match found {
None => Check {
step: step.clone(),
scope,
expected,
found: None,
same_key: false,
verdict: Match::Missing,
},
Some((_, _, result)) => {
let same_key = result.key.to_hex() == *key;
let verdict = if result.canonical == expected {
if same_key {
Match::Identical
} else {
Match::Reproduced
}
} else {
Match::Differs
};
Check {
step: step.clone(),
scope,
expected,
found: Some(result.canonical),
same_key,
verdict,
}
}
};
verification.checks.push(check);
}
for row in read_table(bundle, "inputs.tsv", 7)? {
let (step, param, path, bytes) = (&row[0], &row[2], &row[4], &row[5]);
let path = PathBuf::from(path);
let recorded = parse_hash(bundle, "inputs.tsv", bytes)?;
let presence = if path.is_file() {
match ContentHash::of_file(&path) {
Ok(hash) if hash == recorded => Presence::Same,
Ok(_) => Presence::Changed,
Err(_) => Presence::Absent,
}
} else {
Presence::Absent
};
verification.inputs.push(InputCheck {
step: step.clone(),
param: param.clone(),
path,
presence,
});
}
Ok(verification)
}
fn readme(methods: &Methods) -> String {
let mut out = String::from(
"# Reproducibility bundle\n\n\
Written by Ligase. Everything here describes how a set of results was\n\
produced, and is enough to check whether another machine produces the\n\
same ones.\n\n\
## What is here\n\n\
| File | What it holds |\n\
| --- | --- |\n\
| `METHODS.md` | The methods paragraph, with tool versions and references. |\n\
| `results.tsv` | Every step's output, by content hash. **This is the claim.** |\n\
| `commands.tsv` | The command that produced each one, as it ran. |\n\
| `inputs.tsv` | Every input file, by content hash. |\n\
| `notes.tsv` | What canonicalising an output noticed. Usually empty. |\n\
| `references.tsv` | Every reference, by accession and checksum. |\n\
| `environment.tsv` | The engine, the platform and every tool's version. |\n\
| `steps/` | The source of every step. |\n\
| `pipeline/` | The pipeline file itself, where one was given. |\n\
| `MANIFEST` | Every file above, hashed, so damage is visible. |\n\n\
## What is not here\n\n\
The data. Sequencing runs are gigabytes and a bundle is meant to be\n\
readable, so inputs are *named* rather than carried: every one by\n\
content hash, and every reference by accession and checksum. Fetch\n\
them by those identifiers; nothing else will satisfy the check.\n\n\
## How to check it\n\n\
With the data in place and the pipeline to hand:\n\n\
```\n\
ligase methods --verify <this directory>\n\
```\n\n\
It runs the pipeline and compares every output's canonical hash with\n\
the one recorded here. Three answers are good news and one is not:\n\
`identical` (nothing moved), `reproduced` (a tool version or a\n\
platform moved and the result did not), `differs` (it did), and\n\
`missing` (this pipeline no longer produces that step).\n\n\
A `differs` is worth reading alongside the input lines: an input\n\
reported as `changed` or `absent` explains an output that moved.\n\n",
);
let notices = methods.notices();
if !notices.is_empty() {
out.push_str("## What will not travel\n\n");
out.push_str(¬ices.join("\n\n"));
out.push_str("\n\n");
}
out.push_str("## What produced it\n\n");
out.push_str(&format!(
"Ligase {} on {}.\n",
methods.engine, methods.platform
));
out
}
fn step_file(record: &Record, used: &BTreeMap<String, String>) -> String {
let base = record
.step
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
character
} else {
'_'
}
})
.collect::<String>();
let first = format!("{base}.py");
if used.get(&first).is_none_or(|held| held == &record.code) {
return first;
}
for attempt in 2.. {
let next = format!("{base}.{attempt}.py");
if used.get(&next).is_none_or(|held| held == &record.code) {
return next;
}
}
first
}
fn manifest(root: &Path) -> Result<Vec<String>, BundleError> {
let mut files = Vec::new();
collect(root, root, &mut files)?;
files.sort();
let mut out = format!("# {MANIFEST_HASH}\n");
for name in &files {
let hash = ContentHash::of_file(&root.join(name)).map_err(|error| BundleError::Io {
path: root.join(name),
source: error,
})?;
out.push_str(&format!("{} {name}\n", hash.to_hex()));
}
put(root, "MANIFEST", &out)?;
Ok(files)
}
fn collect(root: &Path, at: &Path, into: &mut Vec<String>) -> Result<(), BundleError> {
let entries = fs::read_dir(at).map_err(|error| BundleError::Io {
path: at.to_path_buf(),
source: error,
})?;
for entry in entries {
let entry = entry.map_err(|error| BundleError::Io {
path: at.to_path_buf(),
source: error,
})?;
let path = entry.path();
if path.is_dir() {
collect(root, &path, into)?;
} else if let Ok(relative) = path.strip_prefix(root) {
into.push(relative.to_string_lossy().replace('\\', "/"));
}
}
Ok(())
}
struct Table {
text: String,
}
impl Table {
fn new(columns: &[&str]) -> Self {
Self {
text: format!("{}\n", columns.join("\t")),
}
}
fn row(&mut self, fields: &[&str]) {
let escaped: Vec<String> = fields.iter().map(|field| escape(field)).collect();
self.text.push_str(&escaped.join("\t"));
self.text.push('\n');
}
fn finish(self) -> String {
self.text
}
}
fn escape(field: &str) -> String {
let mut out = String::with_capacity(field.len());
for character in field.chars() {
match character {
'\\' => out.push_str("\\\\"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
other => out.push(other),
}
}
out
}
fn unescape(field: &str) -> String {
let mut out = String::with_capacity(field.len());
let mut characters = field.chars();
while let Some(character) = characters.next() {
if character != '\\' {
out.push(character);
continue;
}
match characters.next() {
Some('\\') => out.push('\\'),
Some('t') => out.push('\t'),
Some('n') => out.push('\n'),
Some('r') => out.push('\r'),
Some(other) => out.push(other),
None => out.push('\\'),
}
}
out
}
fn read_table(bundle: &Path, name: &str, columns: usize) -> Result<Vec<Vec<String>>, BundleError> {
let path = bundle.join(name);
let text = fs::read_to_string(&path).map_err(|error| BundleError::Io {
path: path.clone(),
source: error,
})?;
let mut lines = text.lines();
let header = lines.next().ok_or_else(|| BundleError::Malformed {
path: path.clone(),
detail: "the file is empty; it should begin with a header row".to_owned(),
})?;
if header.split('\t').count() != columns {
return Err(BundleError::Malformed {
path: path.clone(),
detail: format!(
"the header has {} columns and should have {columns}",
header.split('\t').count()
),
});
}
let mut rows = Vec::new();
for (number, line) in lines.enumerate() {
if line.trim().is_empty() {
continue;
}
let fields: Vec<String> = line.split('\t').map(unescape).collect();
if fields.len() != columns {
return Err(BundleError::Malformed {
path: path.clone(),
detail: format!(
"row {} has {} columns and should have {columns}",
number + 2,
fields.len()
),
});
}
rows.push(fields);
}
Ok(rows)
}
fn parse_hash(bundle: &Path, name: &str, text: &str) -> Result<ContentHash, BundleError> {
ContentHash::parse(text).ok_or_else(|| BundleError::Malformed {
path: bundle.join(name),
detail: format!("`{text}` is not a content hash"),
})
}
fn put(root: &Path, name: &str, contents: &str) -> Result<(), BundleError> {
let path = root.join(name);
fs::write(&path, contents).map_err(|error| BundleError::Io {
path,
source: error,
})
}
fn create_dir(path: &Path) -> Result<(), BundleError> {
fs::create_dir_all(path).map_err(|error| BundleError::Io {
path: path.to_path_buf(),
source: error,
})
}
fn short(hash: ContentHash) -> String {
hash.to_hex().chars().take(12).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_field_survives_a_tab_and_a_newline() {
let awkward = "a\tb\nc\\d";
assert_eq!(escape(awkward), "a\\tb\\nc\\\\d");
assert_eq!(unescape(&escape(awkward)), awkward);
assert!(
!escape(awkward).contains('\t'),
"an escaped field cannot shift a column"
);
}
#[test]
fn an_ordinary_field_is_left_alone() {
assert_eq!(escape("minimap2 2.31-r1287"), "minimap2 2.31-r1287");
}
}