ligase 0.4.0

Type-safe, reproducible computational biology pipelines (core engine)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! A bundle: everything needed to reproduce a result, and to check that it was.
//!
//! `web/content/project/milestones.mdx` asks for "a bundle that reproduces
//! the results on a clean machine". The phrase needs pinning down before it
//! can be built, because taken literally it is impossible: the reference
//! demo's inputs are sequencing runs from the SRA, and a bundle that carried
//! them would be gigabytes. Fetching them is out of scope for v0.1 anyway
//! (D8).
//!
//! So what a bundle carries is everything *except* the data, and the data is
//! named firmly enough that it cannot be substituted: every input by content
//! hash, every reference by accession and checksum. A clean machine is then,
//! to this engine, an empty cache and whatever tools are installed — and
//! what "reproduces the results" means concretely is that a run there
//! produces outputs whose canonical hashes are the ones the bundle recorded.
//!
//! That is a claim, so it can be checked, and [`verify`] checks it. Three
//! outcomes matter and the third is the interesting one:
//!
//! - **identical** — the same key and the same result. Nothing that feeds
//!   the computation moved, so the cache would have served it.
//! - **reproduced** — a *different* key and the same result anyway. A tool
//!   version or a platform moved and the science did not. This is the
//!   outcome a reviewer on another machine actually gets, and the one a
//!   bundle exists to be able to report.
//! - **differs** — a different result. A finding, and the reason the inputs
//!   are checked too: a changed input explains a changed output, and
//!   without that column a verdict here would be uninterpretable.
//!
//! # Why TSV and not JSON
//!
//! No dependency, and a reviewer can open any of these files in a
//! spreadsheet, `grep` it, or read it in a terminal. The engine has no JSON
//! library and does not need one for eight flat tables; the one structured
//! store it has is SQLite, for the same reason (D6). Tabs, newlines and
//! backslashes inside a field are escaped, so a command containing a tab
//! cannot shift a column.

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, day};
use crate::cache::{Cache, QueryRecord};
use crate::exec::RunReport;
use crate::graph::{Graph, NodeId};
use crate::hash::ContentHash;
use crate::remote::request::Method;
use crate::store::{BlobStore, ObjectKey};
use crate::types::DataKind;

/// The hash the manifest uses, named in the manifest itself.
const MANIFEST_HASH: &str = "blake3";

/// What a bundle is built from.
pub struct Request<'a> {
    /// The graph the results came from.
    pub graph: &'a Graph,
    /// The outputs that were asked for.
    pub roots: &'a [NodeId],
    /// The run that produced them.
    pub report: &'a RunReport,
    /// Where to read how each step ran.
    pub prov: &'a Prov,
    /// The methods section, already built.
    pub methods: &'a Methods,
    /// Files to copy in as they are, such as the pipeline itself.
    pub include: &'a [PathBuf],
    /// Where the recorded responses are, when the run had any.
    ///
    /// The cache rather than the rows alone, because a bundle carries a
    /// recorded query's **body** and not merely its digest — that is the
    /// whole of what makes a recorded query reproducible (D39) — so writing
    /// one needs the record index and the blob tier together, which is what
    /// a cache is.
    ///
    /// `None` writes no `records.tsv`, which is right for a run that made
    /// no query: a bundle should not carry an empty table explaining a
    /// feature the run did not use.
    pub queries: Option<&'a Cache>,
    /// Leave the object bodies out, and name the store they are in.
    ///
    /// A *fat* bundle carries a recorded query's response body, which is
    /// the whole of what makes a recorded query reproducible: a reviewer
    /// with no network and no API key replays from it (D39).
    ///
    /// A *thin* one does not, and therefore does not promise that. It is
    /// for a collaborator who can reach the lab's store, where carrying
    /// the bodies would be carrying what they already have. The trade is
    /// stated in the bundle's README and in `store.tsv`, and seeding one
    /// without store access fails before any step runs rather than
    /// quietly replaying half a pipeline.
    pub thin: bool,
}

/// What a bundle turned out to hold.
#[derive(Clone, Debug, Default)]
pub struct Summary {
    /// Where it was written.
    pub root: PathBuf,
    /// The files in it, relative to the root, in manifest order.
    pub files: Vec<String>,
    /// How many steps it accounts for.
    pub steps: usize,
    /// Steps it could not account for, because nothing recorded them.
    pub gaps: usize,
}

/// Why a bundle could not be written or read.
#[derive(Debug)]
pub enum BundleError {
    /// A file could not be read or written.
    Io {
        /// Which file.
        path: PathBuf,
        /// The underlying failure.
        source: io::Error,
    },
    /// Provenance could not be read.
    Prov(ProvError),
    /// The bundle is not one, or is damaged.
    Malformed {
        /// Which file.
        path: PathBuf,
        /// What was wrong with it.
        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)
    }
}

/// How a step's result compared with what the bundle expected.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Match {
    /// The same key and the same result: nothing that feeds it moved.
    Identical,
    /// A different key and the same result: something in the environment
    /// moved and the science did not.
    Reproduced,
    /// A different result.
    Differs,
    /// The bundle expected a step this pipeline did not produce.
    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",
        })
    }
}

/// One step, as the bundle recorded it and as this machine produced it.
#[derive(Clone, Debug)]
pub struct Check {
    /// The step's name.
    pub step: String,
    /// What tells this node apart, where anything does.
    pub scope: Option<String>,
    /// The canonical hash the bundle recorded.
    pub expected: ContentHash,
    /// The canonical hash produced here, if the step produced anything.
    pub found: Option<ContentHash>,
    /// Whether the key matched too.
    pub same_key: bool,
    /// The verdict.
    pub verdict: Match,
}

/// Whether an input is the one the bundle was built from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presence {
    /// Present, and the same content.
    Same,
    /// Present, and different content.
    Changed,
    /// Not where the bundle said it was.
    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",
        })
    }
}

/// One input file, as the bundle recorded it and as it is here.
#[derive(Clone, Debug)]
pub struct InputCheck {
    /// The step it fed.
    pub step: String,
    /// The parameter it filled.
    pub param: String,
    /// Where the bundle said it was.
    pub path: PathBuf,
    /// Whether it is that file.
    pub presence: Presence,
}

/// What checking a bundle against this machine found.
#[derive(Clone, Debug, Default)]
pub struct Verification {
    /// Every step the bundle recorded.
    pub checks: Vec<Check>,
    /// Every input it recorded.
    pub inputs: Vec<InputCheck>,
    /// What canonicalising the outputs produced *here* noticed (D26).
    ///
    /// Read beside a `differs`: a canonical hash that depends on a file
    /// path does not travel, so a result that differs for that reason
    /// differs for a reason that has nothing to do with the science.
    pub noticed: Vec<Noticed>,
}

impl Verification {
    /// Whether every recorded result was reproduced.
    #[must_use]
    pub fn reproduced(&self) -> bool {
        !self.checks.is_empty()
            && self
                .checks
                .iter()
                .all(|check| matches!(check.verdict, Match::Identical | Match::Reproduced))
    }

    /// The worst thing found.
    #[must_use]
    pub fn verdict(&self) -> Match {
        self.checks
            .iter()
            .map(|check| check.verdict)
            .max()
            .unwrap_or(Match::Missing)
    }

    /// One line summarising the check.
    #[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(", "))
    }

    /// The whole report, as the command line prints it.
    #[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());
                }
            }
        }

        // Only the inputs that are not as recorded: a run of four hundred
        // samples should not print four hundred lines to say nothing moved.
        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());
        }

        // Outputs named after a file, which is the other thing that
        // explains a `differs` without any science behind it.
        if !self.noticed.is_empty() {
            lines.push(String::new());
            // Places, not notes: one output with two things wrong with it
            // is one result that will not travel (D15).
            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(),
            );
            // Said once per kind rather than once per result (D15). The
            // whole of why it matters is in the bundle's own README; here
            // there is room for the instruction and not the essay.
            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")
    }
}

/// Write a bundle into `into`, creating it.
///
/// # Errors
///
/// If the directory cannot be written, or provenance cannot be read.
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();

    // ---- the prose
    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, request.thin))?;

    // ---- the claim
    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())?;

    // ---- how each one ran, verbatim
    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())?;

    // ---- what went in
    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())?;

    // ---- what canonicalising the outputs noticed (D26)
    //
    // Its own file rather than a column on `results.tsv`, because that
    // table is the bundle's claim and a reader — or a later version of this
    // engine — parses it by position. Almost always just a header line.
    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", &notes.finish())?;

    // ---- the references, pinned
    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())?;

    // ---- the paper's own claims, and what each rests on (D45)
    //
    // Here for the reason this module's own title gives: a bundle states a
    // claim and can be checked (D25). The bundle's standing claim is about
    // reproducibility; a `Claim` is the paper's, and a bundle that carried
    // every tool version and no record of which sentences rested on them
    // would be missing the half a reviewer reads.
    //
    // One row per computation, with the *whole* key rather than the sixteen
    // characters a sentence prints, because this is the table a reviewer
    // looks a key up in. Written only where there are claims: an empty
    // table is a promise nobody made, and `verify` reads tables by
    // position, so a file that appeared for every bundle would be one more
    // thing a later version has to keep meaning the same.
    if !request.methods.claims.is_empty() {
        let mut claims = Table::new(&["claim", "verdict", "step", "scope", "key", "canonical"]);
        for check in &request.methods.claims {
            match check.bound.as_slice() {
                // An unbacked claim is in the table rather than left out of
                // it, which is the whole of what D24 asks of a gap.
                [] => claims.row(&[
                    &check.claim.text,
                    check.verdict.name(),
                    &check.claim.step,
                    check.claim.scope.as_deref().unwrap_or(""),
                    "",
                    "",
                ]),
                bound => {
                    for row in bound {
                        claims.row(&[
                            &check.claim.text,
                            check.verdict.name(),
                            &check.claim.step,
                            row.scope.as_deref().unwrap_or(""),
                            &row.key.to_hex(),
                            &row.canonical.to_hex(),
                        ]);
                    }
                }
            }
        }
        put(into, "claims.tsv", &claims.finish())?;
    }

    // ---- what was fetched, and from where
    //
    // The locators and their digests, not the bytes. That is the whole
    // point of a *pinned* remote: anyone can obtain it from the source and
    // check it against the digest recorded here, so copying gigabytes of
    // reads into every bundle would buy nothing. A recorded *query* is the
    // opposite case -- its source promises nothing -- and its body travels.
    let mut remotes = Table::new(&["locator", "verdict", "fetched", "digest", "bytes"]);
    for remote in request.methods.remotes() {
        remotes.row(&[
            &remote.locator,
            &remote.verdict.to_string(),
            &day(remote.fetched_at),
            &remote.digest.to_hex(),
            &remote.bytes.to_hex(),
        ]);
    }
    put(into, "remotes.tsv", &remotes.finish())?;

    // ---- and, for a recorded query, the answer itself
    //
    // Not the digest: the body. That is the whole of what makes a recorded
    // query reproducible, because its source promises nothing about what it
    // will answer next -- so the bundle *is* the source, and a reviewer
    // with no network and no API key replays from it (D39).
    //
    // The bodies are named by their own hashes, so the table and the files
    // need no agreement about naming, and two records of identical bytes
    // cost one file.
    if let Some(cache) = request.queries {
        let held = cache.all_query_records().map_err(|error| BundleError::Io {
            path: into.to_path_buf(),
            source: io::Error::other(error.to_string()),
        })?;
        if !held.is_empty() {
            if !request.thin {
                create_dir(&into.join("records"))?;
            }
            let mut records = Table::new(&[
                "request", "revision", "recorded", "locator", "kind", "method", "url", "status",
                "body", "digest",
            ]);
            for record in &held {
                records.row(&[
                    &record.request.to_hex(),
                    &record.revision.to_string(),
                    &day(record.recorded_at),
                    &record.locator,
                    record.kind.name(),
                    record.method.name(),
                    &record.url,
                    &record.status.to_string(),
                    &record.body.to_string(),
                    &record.digest.to_hex(),
                ]);
                // Verified on the way out, not merely copied: a bundle that
                // carried a corrupted body would be a bundle that
                // reproduces the wrong answer and says it reproduced.
                let body =
                    cache
                        .objects()
                        .checked_get(&record.body)
                        .map_err(|error| BundleError::Io {
                            path: into.to_path_buf(),
                            source: io::Error::other(error.to_string()),
                        })?;
                if request.thin {
                    continue;
                }
                let Some(body) = body else { continue };
                let name = format!("records/{}", record.body);
                fs::write(into.join(&name), &body).map_err(|error| BundleError::Io {
                    path: into.join(&name),
                    source: error,
                })?;
            }
            put(into, "records.tsv", &records.finish())?;
        }
    }

    // ---- where the bodies are, for a bundle that does not carry them
    //
    // A thin bundle is only readable where this is: without it a reviewer
    // would have a `records.tsv` naming hashes and nowhere to get them,
    // which is the quiet failure `--thin` has to avoid.
    if request.thin {
        let mut store = Table::new(&["name", "value"]);
        store.row(&["thin", "yes"]);
        store.row(&[
            "store",
            request
                .queries
                .and_then(|cache| cache.objects().remote_url())
                .unwrap_or("(none configured on the machine that wrote this)"),
        ]);
        put(into, "store.tsv", &store.finish())?;
    }

    // ---- what it was run with
    let mut environment = Table::new(&["name", "value"]);
    // A row each rather than one joined row: this is a table, and a run
    // that spanned two platforms has two facts to state, not one sentence
    // about both (D55).
    for engine in &request.methods.engines {
        environment.row(&["ligase", engine]);
    }
    for platform in &request.methods.platforms {
        environment.row(&["platform", platform]);
    }
    for (tool, version) in request.methods.tools() {
        environment.row(&[&tool, &version]);
    }
    put(into, "environment.tsv", &environment.finish())?;

    // ---- the code of every step, so the bundle holds the pipeline's logic
    // even when the file that held it is lost
    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)?;
    }

    // ---- whatever the caller wanted carried along
    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,
            })?;
        }
    }

    // ---- and finally the bundle's own contents, hashed
    let files = manifest(into)?;

    Ok(Summary {
        root: into.to_path_buf(),
        files,
        steps: rows.len() - gaps,
        gaps,
    })
}

/// Check a bundle's recorded results against a run on this machine.
///
/// # Errors
///
/// If the bundle cannot be read, or does not hold the files it must.
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 {
        // Only the notes that can account for a hash that moved. The rest
        // say what a result rested on, which belongs in the run report and
        // the methods section and is no reason for two machines to
        // disagree: offered here, it would send a reader after the wrong
        // thing.
        for note in result
            .notes
            .iter()
            .filter(|note| note.explains_a_difference())
        {
            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);
    }

    // The inputs are checked by content, because that is the only way to
    // tell the file the bundle was built from apart from a file with the
    // same name. A bundle cannot fetch them (D8), so it says what it found.
    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)
}

/// Put a bundle's recorded responses into a cache, so the run replays.
///
/// The precise sense in which "a bundle cannot fetch its own data" is
/// retired: for a recorded query the bundle **is** the source, so a
/// reviewer on a clean machine with no network and no API key seeds a cache
/// from the bundle and the pipeline replays. A pinned remote is unaffected
/// and deliberately so — it is named rather than carried, because anyone
/// can obtain it from the source and check it against its digest.
///
/// Idempotent: a record already held is left as it is, since objects are
/// written once and a request's revisions are what they are. Returns how
/// many records were added.
///
/// A bundle with no `records.tsv` adds nothing and is not an error: most
/// runs make no query.
///
/// # Errors
///
/// If the bundle cannot be read, or the cache cannot be written.
pub fn seed(bundle: &Path, cache: &Cache) -> Result<usize, BundleError> {
    if !bundle.join("records.tsv").is_file() {
        return Ok(0);
    }

    // A thin bundle says so in `store.tsv`, and the difference is not
    // cosmetic: it decides whether a body that is not in the directory
    // means "damaged" or "in the store named here".
    let thin = bundle.join("store.tsv").is_file();
    let mut absent: Vec<String> = Vec::new();

    let mut added = 0;
    for row in read_table(bundle, "records.tsv", 10)? {
        let (request, revision, locator, kind, method, url, status, body, digest) = (
            &row[0], &row[1], &row[3], &row[4], &row[5], &row[6], &row[7], &row[8], &row[9],
        );
        let request = parse_hash(bundle, "records.tsv", request)?;

        let Some(key) = parse_key(body) else { continue };
        let bytes = match fs::read(bundle.join("records").join(body)) {
            Ok(bytes) => bytes,
            // A thin bundle carries no bodies at all, by construction, so
            // the store it names is where they are. Verified on the way
            // in like anything read from a store.
            Err(_) if thin => match cache.objects().checked_get(&key) {
                Ok(Some(bytes)) => bytes,
                Ok(None) => {
                    absent.push(key.to_string());
                    continue;
                }
                Err(error) => {
                    absent.push(format!("{key} ({error})"));
                    continue;
                }
            },
            // A fat bundle with a body file missing is a damaged bundle,
            // and the manifest is what reports that. Here it is simply
            // not seeded: a record whose body cannot be served is worse
            // than no record, because `--replay` would succeed and then
            // fail on the read.
            Err(_) => continue,
        };

        let record = QueryRecord {
            request,
            // Assigned by the cache, which keeps revisions contiguous in
            // the cache being seeded rather than carrying over numbering
            // from the one the bundle was written from.
            revision: revision.parse().unwrap_or(0),
            recorded_at: crate::prov::now(),
            locator: locator.clone(),
            kind: match DataKind::ALL
                .iter()
                .copied()
                .find(|known| known.name() == kind)
            {
                Some(kind) => kind,
                None => continue,
            },
            method: match Method::parse(method) {
                Some(method) => method,
                None => continue,
            },
            url: url.clone(),
            status: status.parse().unwrap_or(200),
            body: key.clone(),
            digest: parse_hash(bundle, "records.tsv", digest)?,
            notes: Vec::new(),
        };

        // The body first: a row whose object is not there yet would be a
        // row a concurrent replay could find and fail on.
        cache
            .objects()
            .put(&key, &bytes)
            .map_err(|error| BundleError::Io {
                path: bundle.to_path_buf(),
                source: io::Error::other(error.to_string()),
            })?;

        let held = cache
            .query_records(request)
            .map_err(|error| BundleError::Io {
                path: bundle.to_path_buf(),
                source: io::Error::other(error.to_string()),
            })?;
        if held.iter().any(|existing| existing.body == key) {
            continue;
        }
        cache
            .record_query(&record)
            .map_err(|error| BundleError::Io {
                path: bundle.to_path_buf(),
                source: io::Error::other(error.to_string()),
            })?;
        added += 1;
    }

    // One failure naming everything missing, rather than one per record
    // and rather than a run that starts and fails on its fourth query.
    // This is what `--thin` trades away, said at the moment it costs
    // something.
    if !absent.is_empty() {
        let store = store_named_by(bundle).unwrap_or_else(|| "(unnamed)".to_owned());
        return Err(BundleError::Malformed {
            path: bundle.join("store.tsv"),
            detail: format!(
                "this is a thin bundle: it names the store {store} and \
                 carries no response bodies of its own. {} could not be \
                 read from there, so the run would replay some queries and \
                 not others, which is the one thing a replay must not do. \
                 Point LIGASE_STORE at a store holding them, or ask for a \
                 bundle written without --thin. Missing: {}",
                plural(absent.len(), "body"),
                absent.join(", ")
            ),
        });
    }
    Ok(added)
}

/// The store a thin bundle names, if it names one.
fn store_named_by(bundle: &Path) -> Option<String> {
    let text = fs::read_to_string(bundle.join("store.tsv")).ok()?;
    text.lines()
        .filter_map(|line| line.split_once('\t'))
        .find(|(name, _)| *name == "store")
        .map(|(_, value)| value.to_owned())
}

/// `1 body`, `3 bodies`.
fn plural(count: usize, word: &str) -> String {
    if count == 1 {
        format!("{count} {word}")
    } else {
        format!("{count} {}", word.trim_end_matches('y').to_owned() + "ies")
    }
}

/// An object key as [`ObjectKey::to_string`] writes it: 64 hex characters
/// and then whatever extension the object is read under.
fn parse_key(text: &str) -> Option<ObjectKey> {
    if text.len() < 64 {
        return None;
    }
    let (hash, suffix) = text.split_at(64);
    Some(ObjectKey::new(ContentHash::parse(hash)?, suffix))
}

/// What a bundle says about itself.
fn readme(methods: &Methods, thin: bool) -> 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\
         | `remotes.tsv` | Every remote input, by locator and digest. |\n\
         | `records.tsv` | Every recorded query, with its response body in `records/`. |\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\
         | `store.tsv` | Where the bodies are, in a thin bundle. |\n\
         | `MANIFEST` | Every file above, hashed, so damage is visible. |\n\n\
         ## What is not here\n\n\
         Most of the data. Sequencing runs are gigabytes and a bundle is\n\
         meant to be readable, so inputs are *named* rather than carried:\n\
         every one by content hash, every reference by accession and\n\
         checksum, and every pinned remote by locator. Fetch them by those\n\
         identifiers; nothing else will satisfy the check.\n\n\
         The one exception is the one that has to be: a recorded query's\n\
         response, which no one could fetch again, and which is therefore\n\
         carried. See `records/` below.\n\n\
         A remote in `remotes.tsv` is *pinned*, which means the source\n\
         promises the same bytes forever: `ligase run` on the pipeline in\n\
         `pipeline/` obtains it and checks it against the digest recorded\n\
         here before any step runs.\n\n\
         A *recorded query* is the other case, and its data **is** here. A\n\
         live source promises nothing about what it will answer next, so\n\
         the response bodies themselves are in `records/`, named by their\n\
         own hashes and listed in `records.tsv`. Verifying this bundle\n\
         replays from them: no network, and no API key.\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",
    );

    // Said here rather than only in `store.tsv`, because the thing a thin
    // bundle stops promising is the thing the paragraph above has just
    // promised, and a reader who got that far has to be told.
    if thin {
        out.push_str(
            "## This is a thin bundle\n\n\
             It carries the manifest and the hashes and **not** the object\n\
             bodies, so it is small and it is not self-contained. Checking\n\
             it needs access to the store named in `store.tsv`, with\n\
             whatever credentials that store wants.\n\n\
             That includes the recorded query responses. A fat bundle --\n\
             `ligase methods --bundle` without `--thin` -- carries them, and\n\
             a reviewer replays it with no network and no API key. **This\n\
             one does not make that promise.** It is for a collaborator who\n\
             can already reach the lab's store; for a reviewer, a referee or\n\
             an archive, write a fat one.\n\n\
             Without store access, `ligase methods --verify` on this\n\
             directory fails before any step runs and names what is\n\
             missing. It will not replay half a pipeline.\n\n",
        );
    }

    // Only when there is one: a standing paragraph about a problem this
    // bundle does not have would be noise in every bundle that is fine.
    let notices = methods.notices();
    if !notices.is_empty() {
        // One heading for both kinds of note: a sample identifier that will
        // not travel, and an assumption a result rests on. Each says which
        // it is in its own words, and a reader of a bundle wants the whole
        // list in one place either way.
        out.push_str("## What was noticed\n\n");
        out.push_str(&notices.join("\n\n"));
        out.push_str("\n\n");
    }

    out.push_str("## What produced it\n\n");
    out.push_str(&format!(
        "Ligase {} on {}.\n",
        methods.engines.join(", "),
        methods.platforms.join(", ")
    ));
    out
}

/// A name for a step's source file, distinct from the ones already used.
///
/// Two groups of one step can have different code — the pipeline was edited
/// between runs — and a bundle that let the second overwrite the first would
/// be describing a run that never happened.
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
}

/// Hash every file in the bundle, and write the manifest.
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(())
}

// ------------------------------------------------------------ the files --

/// A TSV being built, with its header.
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
    }
}

/// Escape a field so it cannot shift a column.
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
}

/// Read back what [`escape`] wrote.
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
}

/// Every row of one of the bundle's tables, unescaped.
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,
    })
}

/// The first twelve characters of a hash, which is plenty to compare by eye.
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");
    }
}