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
//! M3: running a checked graph, once.
//!
//! The four acceptance tests in `web/content/project/milestones.mdx` are all
//! one property seen from four sides: a step runs when something that could
//! change its result has changed, and not otherwise. They are written here
//! over shell steps on text files, so the property is tested without waiting
//! for an aligner; `tests/test_demo.py` then runs the same four over the real
//! HIV-1 pipeline, which is what the milestone is actually signed off on.
#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::mpsc;
use std::time::Duration;

use ligase::cache::Cache;
use ligase::dim::Dimensions;
use ligase::exec::{self, Host, Options, Outcome, Recipe, RunReport, Stores, Task};
use ligase::graph::{Argument, Graph, NodeId, StepSpec};
use ligase::note::Note;
use ligase::prov::Prov;
use ligase::types::{DataKind, Dataset};
use tempfile::TempDir;

// ------------------------------------------------------------ scaffold --

/// A workspace: a cache, a place for inputs, and a graph being built.
struct Bench {
    dir: TempDir,
    cache: Cache,
    prov: Prov,
    graph: Graph,
    tasks: Vec<Task>,
}

impl Bench {
    fn new() -> Self {
        let dir = TempDir::new().unwrap();
        let root = dir.path().join(".ligase");
        let cache = Cache::open(&root).unwrap();
        let prov = Prov::open(&root).unwrap();
        Self {
            dir,
            cache,
            prov,
            graph: Graph::new(),
            tasks: Vec::new(),
        }
    }

    fn stores(&self) -> Stores<'_> {
        Stores {
            cache: &self.cache,
            prov: &self.prov,
        }
    }

    fn path(&self, name: &str) -> PathBuf {
        self.dir.path().join(name)
    }

    /// An input file holding `contents`, added to the graph.
    fn input(&mut self, name: &str, contents: &str) -> NodeId {
        let path = self.path(name);
        fs::write(&path, contents).unwrap();
        let dataset = Dataset::new(DataKind::Reference, Some(path), Dimensions::default());
        self.graph.add_input(name, dataset)
    }

    /// A shell step over one input, bound to the parameter `in`.
    fn step(&mut self, name: &str, command: &str, input: NodeId) -> NodeId {
        self.shell(name, command, &[("in", input)], &[])
    }

    /// A step producing a FASTA, for the tests that need an output whose
    /// canonical form is more than its bytes.
    fn fasta(&mut self, name: &str, command: &str, input: NodeId) -> NodeId {
        self.shell_of(name, command, &[("in", input)], &[], DataKind::Reference)
    }

    fn shell(
        &mut self,
        name: &str,
        command: &str,
        inputs: &[(&str, NodeId)],
        parameters: &[(&str, &str)],
    ) -> NodeId {
        self.shell_of(name, command, inputs, parameters, DataKind::Alignment)
    }

    fn shell_of(
        &mut self,
        name: &str,
        command: &str,
        inputs: &[(&str, NodeId)],
        parameters: &[(&str, &str)],
        output: DataKind,
    ) -> NodeId {
        let node = self
            .graph
            .add_step(StepSpec {
                name: name.to_owned(),
                output,
                coordinates: None,
                conversion: None,
                arguments: inputs
                    .iter()
                    .map(|(param, node)| Argument {
                        param: (*param).to_owned(),
                        declared: DataKind::Reference,
                        node: *node,
                    })
                    .collect(),
            })
            .unwrap();

        self.tasks.push(Task {
            node,
            code: format!("def {name}(): ..."),
            recipe: Recipe::Shell(command.to_owned()),
            tools: Vec::new(),
            parameters: parameters
                .iter()
                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
                .collect(),
            citations: Vec::new(),
            seed: None,
        });
        node
    }

    /// A step the host runs, over one input bound to the parameter `in`.
    fn callback(&mut self, name: &str, id: u64, input: NodeId) -> NodeId {
        let node = self
            .graph
            .add_step(StepSpec {
                name: name.to_owned(),
                output: DataKind::Alignment,
                coordinates: None,
                conversion: None,
                arguments: vec![Argument {
                    param: "in".to_owned(),
                    declared: DataKind::Reference,
                    node: input,
                }],
            })
            .unwrap();

        self.tasks.push(Task {
            node,
            code: format!("def {name}(): ..."),
            recipe: Recipe::Callback(id),
            tools: Vec::new(),
            parameters: Vec::new(),
            citations: Vec::new(),
            seed: None,
        });
        node
    }

    /// Rewrite a step's recorded code, as editing its body would.
    fn edit(&mut self, node: NodeId, code: &str) {
        let task = self.tasks.iter_mut().find(|t| t.node == node).unwrap();
        task.code = code.to_owned();
    }

    /// Rewrite a step's parameter, as editing `min_freq` would.
    fn set(&mut self, node: NodeId, name: &str, value: &str) {
        let task = self.tasks.iter_mut().find(|t| t.node == node).unwrap();
        task.parameters = vec![(name.to_owned(), value.to_owned())];
    }

    fn run(&self, roots: &[NodeId]) -> RunReport {
        self.run_with(roots, &Options::default(), &Refusing)
    }

    fn run_with(&self, roots: &[NodeId], options: &Options, host: &dyn Host) -> RunReport {
        exec::run(
            &self.graph,
            roots,
            &self.tasks,
            &self.stores(),
            options,
            host,
        )
    }
}

/// A host with no callbacks: every step in these tests is a shell step.
struct Refusing;

impl Host for Refusing {
    fn call(
        &self,
        id: u64,
        _out: &Path,
        _inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<Vec<Note>, String> {
        Err(format!("no callback {id} in this test"))
    }
}

fn outcome(report: &RunReport, node: NodeId) -> Outcome {
    report
        .result(node)
        .unwrap_or_else(|| {
            panic!(
                "node {} is missing from the report: {report:?}",
                node.index()
            )
        })
        .outcome
}

fn contents(report: &RunReport, node: NodeId) -> String {
    fs::read_to_string(&report.result(node).unwrap().output).unwrap()
}

/// How many times the commands in this bench have been run.
fn executions(bench: &Bench) -> usize {
    fs::read_to_string(bench.path("marker")).map_or(0, |log| log.lines().count())
}

/// A command that copies its input, recording that it ran.
fn copy(bench: &Bench, tag: &str) -> String {
    format!(
        "cat {{in}} > {{out}}; echo {tag} >> {}",
        bench.path("marker").display()
    )
}

// ------------------------------------------------------------- running --

#[test]
fn a_pipeline_runs_and_produces_its_outputs() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let one = bench.step("align", "tr acgt ACGT < {in} > {out}", reads);
    let two = bench.step("call", "cat {in} {in} > {out}", one);

    let report = bench.run(&[two]);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(outcome(&report, one), Outcome::Ran);
    assert_eq!(outcome(&report, two), Outcome::Ran);
    assert_eq!(contents(&report, two), "ACGT\nACGT\n");
}

#[test]
fn an_output_is_named_after_its_contents_and_kept_out_of_the_way() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "cat {in} > {out}", reads);

    let report = bench.run(&[align]);
    let result = report.result(align).unwrap();

    assert!(
        result.output.starts_with(bench.cache.root()),
        "outputs belong in the store, not beside the inputs: {}",
        result.output.display()
    );
    assert_eq!(result.hash, ligase::hash::ContentHash::of_bytes(b"ACGT\n"));
}

#[test]
fn a_step_is_given_its_parameters_and_its_inputs_by_name() {
    let mut bench = Bench::new();
    let left = bench.input("left.txt", "left\n");
    let right = bench.input("right.txt", "right\n");
    let joined = bench.shell(
        "join",
        "cat {a} {b} > {out}; echo {label} >> {out}",
        &[("a", left), ("b", right)],
        &[("label", "done")],
    );

    let report = bench.run(&[joined]);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(contents(&report, joined), "left\nright\ndone\n");
}

#[test]
fn a_paired_sample_reaches_its_command_as_two_mates() {
    let mut bench = Bench::new();
    let r1 = bench.path("sample_1.fastq");
    let r2 = bench.path("sample_2.fastq");
    fs::write(&r1, "mate one\n").unwrap();
    fs::write(&r2, "mate two\n").unwrap();
    let reads = bench.graph.add_input(
        "reads",
        Dataset::new(DataKind::Reads, Some(r1), Dimensions::default()).with_mate(r2),
    );
    let align = bench.shell(
        "align",
        "cat {reads.r1} {reads.r2} > {out}",
        &[("reads", reads)],
        &[],
    );

    let report = bench.run(&[align]);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(contents(&report, align), "mate one\nmate two\n");
}

// --------------------------------------------------------------- cache --

#[test]
fn a_second_run_comes_entirely_from_cache() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let one = bench.step("align", &copy(&bench, "align"), reads);
    let two = bench.step("call", &copy(&bench, "call"), one);

    bench.run(&[two]);
    assert_eq!(executions(&bench), 2);

    let again = bench.run(&[two]);

    assert_eq!(outcome(&again, one), Outcome::Cached);
    assert_eq!(outcome(&again, two), Outcome::Cached);
    assert_eq!(executions(&bench), 2, "a cached step should not have run");
    assert_eq!(contents(&again, two), "ACGT\n");
}

#[test]
fn a_cache_survives_the_process_that_wrote_it() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    bench.run(&[align]);

    let reopened = Cache::open(bench.cache.root()).unwrap();
    let report = exec::run(
        &bench.graph,
        &[align],
        &bench.tasks,
        &Stores {
            cache: &reopened,
            prov: &bench.prov,
        },
        &Options::default(),
        &Refusing,
    );

    assert_eq!(outcome(&report, align), Outcome::Cached);
    assert_eq!(executions(&bench), 1);
}

#[test]
fn changing_an_input_reruns_the_steps_that_read_it() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    bench.run(&[align]);

    fs::write(bench.path("reads.txt"), "TGCA\n").unwrap();
    let report = bench.run(&[align]);

    assert_eq!(outcome(&report, align), Outcome::Ran);
    assert_eq!(contents(&report, align), "TGCA\n");
}

#[test]
fn changing_a_parameter_reruns_only_what_is_below_it() {
    // The milestone's third acceptance test, in miniature: `min_freq` moves,
    // `call` and `resistance` rerun, `align` does not.
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    let call = bench.shell(
        "call",
        &format!(
            "sed s/A/{{min_freq}}/ {{in}} > {{out}}; {}",
            touch_marker(&bench, "call")
        ),
        &[("in", align)],
        &[("min_freq", "0.01")],
    );
    let resistance = bench.step("resistance", &copy(&bench, "resistance"), call);
    bench.run(&[resistance]);

    bench.set(call, "min_freq", "0.05");
    let report = bench.run(&[resistance]);

    assert_eq!(outcome(&report, align), Outcome::Cached);
    assert_eq!(outcome(&report, call), Outcome::Ran);
    assert_eq!(outcome(&report, resistance), Outcome::Ran);
    assert_eq!(contents(&report, resistance), "0.05CGT\n");
}

#[test]
fn an_added_sample_is_the_only_work() {
    // The milestone's fourth acceptance test. Each sample is its own branch
    // of the graph, so adding one adds nodes rather than changing any.
    let mut bench = Bench::new();
    let first = bench.input("a.txt", "a\n");
    let second = bench.input("b.txt", "b\n");
    let align_a = bench.step("align", &copy(&bench, "a"), first);
    let align_b = bench.step("align", &copy(&bench, "b"), second);
    bench.run(&[align_a, align_b]);
    assert_eq!(executions(&bench), 2);

    let third = bench.input("c.txt", "c\n");
    let align_c = bench.step("align", &copy(&bench, "c"), third);
    let report = bench.run(&[align_a, align_b, align_c]);

    assert_eq!(outcome(&report, align_a), Outcome::Cached);
    assert_eq!(outcome(&report, align_b), Outcome::Cached);
    assert_eq!(outcome(&report, align_c), Outcome::Ran);
    assert_eq!(executions(&bench), 3, "only the new sample should have run");
}

#[test]
fn two_samples_with_identical_data_share_one_result() {
    // Content addressing, seen from the side: the same bytes through the
    // same step is the same work, whoever asked for it.
    let mut bench = Bench::new();
    let first = bench.input("a.txt", "same\n");
    let second = bench.input("b.txt", "same\n");
    let command = copy(&bench, "align");
    let align_a = bench.step("align", &command, first);
    let align_b = bench.step("align", &command, second);

    let report = bench.run(&[align_a, align_b]);

    assert_eq!(
        executions(&bench),
        1,
        "the same bytes through the same step is one piece of work"
    );
    assert_eq!(
        report.result(align_a).unwrap().output,
        report.result(align_b).unwrap().output
    );
}

#[test]
fn forcing_a_run_ignores_the_cache() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    bench.run(&[align]);

    let options = Options {
        force: true,
        ..Options::default()
    };
    let report = bench.run_with(&[align], &options, &Refusing);

    assert_eq!(outcome(&report, align), Outcome::Ran);
    assert_eq!(executions(&bench), 2);
}

// -------------------------------------------------------- early cutoff --

#[test]
fn an_unchanged_output_stops_the_rerun_there() {
    // A step reran -- its code changed -- but produced the same bytes. Every
    // key below it is therefore unchanged, and the work below it is not
    // redone. In M3 that means byte-identical; M4 widens it to
    // scientifically identical.
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    let call = bench.step("call", &copy(&bench, "call"), align);
    bench.run(&[call]);
    assert_eq!(executions(&bench), 2);

    // A comment-only edit: different code, identical output.
    bench.edit(align, "def align(): ...  # now with a comment");
    let report = bench.run(&[call]);

    assert_eq!(outcome(&report, align), Outcome::Ran);
    assert_eq!(
        outcome(&report, call),
        Outcome::Skipped,
        "the output did not change, so `call` had nothing to redo"
    );
    assert_eq!(executions(&bench), 3, "only `align` should have rerun");
}

#[test]
fn a_changed_output_does_not_stop_the_rerun() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.shell(
        "align",
        "sed s/A/{base}/ {in} > {out}",
        &[("in", reads)],
        &[("base", "A")],
    );
    let call = bench.step("call", &copy(&bench, "call"), align);
    bench.run(&[call]);

    bench.set(align, "base", "T");
    let report = bench.run(&[call]);

    assert_eq!(outcome(&report, align), Outcome::Ran);
    assert_eq!(outcome(&report, call), Outcome::Ran);
    assert_eq!(contents(&report, call), "TCGT\n");
}

// --------------------------------------------------- semantic hashing --

#[test]
fn a_volatile_header_does_not_stop_the_cutoff() {
    // The case that byte equality could not reach, and the reason M4
    // exists. Every real tool writes its own command line into its output
    // -- and that command line holds the output path, which is the staging
    // file named after the step's own key. So the step's bytes move
    // whenever its key does, and before canonicalisation the rerun went all
    // the way to the bottom of the pipeline however identical the science.
    //
    // Here a FASTA's description line stands in for the `@PG` line: the
    // canonical form of a reference is its sequence, so a description that
    // records the output path is exactly as volatile.
    let mut bench = Bench::new();
    let reads = bench.input("reads.fasta", ">1\nACGT\n");
    let align = bench.fasta(
        "align",
        &format!(
            "printf '>1 written to %s\\nACGT\\n' {{out}} > {{out}}; echo align >> {}",
            bench.path("marker").display()
        ),
        reads,
    );
    let call = bench.fasta("call", &copy(&bench, "call"), align);
    bench.run(&[call]);
    assert_eq!(executions(&bench), 2);

    // A comment-only edit: a different key, a different staging path, and
    // so different bytes -- from a step that computed the same sequence.
    bench.edit(align, "def align(): ...  # now with a comment");
    let report = bench.run(&[call]);

    let aligned = report.result(align).expect("align is in the report");
    assert_eq!(aligned.outcome, Outcome::Ran);
    assert_eq!(
        outcome(&report, call),
        Outcome::Skipped,
        "the sequence did not change, so `call` had nothing to redo"
    );
    assert_eq!(executions(&bench), 3, "only `align` should have rerun");
}

#[test]
fn the_report_gives_both_what_an_output_is_and_what_it_means() {
    // The bytes name the object in the store; the canonical hash is what
    // the steps below were keyed on. A run that reported only one of them
    // could not show that a rerun changed the first and not the second.
    let mut bench = Bench::new();
    let reads = bench.input("reads.fasta", ">1\nACGT\n");
    // The description records where the step wrote, as a tool's `@PG CL`
    // does -- so the bytes move whenever the key does.
    let align = bench.fasta(
        "align",
        "printf '>1 written to %s\\nACGT\\n' {out} > {out}",
        reads,
    );

    let first = bench.run(&[align]);
    let before = first.result(align).expect("align is in the report").clone();

    // A different description, the same sequence.
    bench.edit(align, "def align(): ...  # edited");
    let second = bench.run(&[align]);
    let after = second.result(align).expect("align is in the report");

    assert_ne!(before.hash, after.hash, "the bytes should have moved");
    assert_eq!(
        before.canonical, after.canonical,
        "what they mean should not have"
    );
}

#[test]
fn an_input_is_hashed_by_what_it_means_and_not_by_its_layout() {
    // An input rewritten with different line wrapping is the same
    // reference, so nothing downstream of it should rerun.
    let mut bench = Bench::new();
    let reference = bench.input("ref.fasta", ">1\nACGTACGTAC\n");
    let align = bench.fasta("align", &copy(&bench, "align"), reference);
    bench.run(&[align]);
    assert_eq!(executions(&bench), 1);

    // The same sequence, wrapped at five columns and lowercased.
    fs::write(bench.path("ref.fasta"), ">1 rewrapped\nacgta\ncgtac\n").unwrap();
    let report = bench.run(&[align]);

    assert_eq!(outcome(&report, align), Outcome::Cached);
    assert_eq!(executions(&bench), 1, "the reference did not change");
}

// ------------------------------------------------------------ failures --

#[test]
fn a_failing_step_is_reported_against_its_node() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "echo 'no such contig' >&2; exit 3", reads);

    let report = bench.run(&[align]);

    assert!(report.result(align).is_none());
    let [failure] = report.failures.as_slice() else {
        panic!("expected one failure: {report:?}");
    };
    assert_eq!(failure.node, align);
    assert_eq!(failure.step, "align");
    assert!(
        failure.message.contains("no such contig"),
        "the tool's own words are what a user needs: {}",
        failure.message
    );
    assert!(failure.message.contains('3'), "{}", failure.message);
}

#[test]
fn one_sample_failing_does_not_stop_the_others() {
    // Four samples, one bad file. Losing three good results to one bad one
    // is the overnight-run problem this project exists to remove.
    let mut bench = Bench::new();
    let good = bench.input("good.txt", "ACGT\n");
    let bad = bench.input("bad.txt", "");
    let ok = bench.step("align", "cat {in} > {out}", good);
    let broken = bench.step("align", "exit 1", bad);

    let report = bench.run(&[ok, broken]);

    assert_eq!(outcome(&report, ok), Outcome::Ran);
    assert_eq!(report.failures.len(), 1);
    assert_eq!(report.failures[0].node, broken);
}

#[test]
fn a_step_below_a_failure_does_not_run() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "exit 1", reads);
    let call = bench.step("call", &copy(&bench, "call"), align);

    let report = bench.run(&[call]);

    assert!(report.result(call).is_none());
    assert_eq!(executions(&bench), 0);
    assert_eq!(
        report.failures.len(),
        1,
        "one cause, one failure: {report:?}"
    );
}

#[test]
fn a_failed_step_is_not_remembered_as_done() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "cat {in} > {out}; exit 1", reads);
    assert_eq!(bench.run(&[align]).failures.len(), 1);

    // Same key, second time: a half-written output must not be served as a
    // result, and the step must be attempted again.
    let report = bench.run(&[align]);

    assert_eq!(report.failures.len(), 1);
    assert!(report.result(align).is_none());
}

#[test]
fn a_step_with_no_task_is_a_failure_rather_than_a_silent_skip() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "cat {in} > {out}", reads);
    bench.tasks.clear();

    let report = bench.run(&[align]);

    assert_eq!(report.failures.len(), 1);
    assert_eq!(report.failures[0].node, align);
}

#[test]
fn a_placeholder_that_names_nothing_is_a_failure() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "cat {nope} > {out}", reads);

    let report = bench.run(&[align]);

    let [failure] = report.failures.as_slice() else {
        panic!("expected one failure: {report:?}");
    };
    assert!(
        failure.message.contains("nope"),
        "say which placeholder: {}",
        failure.message
    );
}

// ----------------------------------------------------------- callbacks --

/// A host that writes a fixed string, recording what it was asked for.
struct Writing {
    calls: Mutex<Vec<(u64, Vec<String>)>>,
}

impl Host for Writing {
    fn call(
        &self,
        id: u64,
        out: &Path,
        inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<Vec<Note>, String> {
        let seen = inputs
            .iter()
            .map(|(param, paths)| format!("{param}={}", paths.len()))
            .collect();
        self.calls
            .lock()
            .map_err(|e| e.to_string())?
            .push((id, seen));
        fs::write(out, "interpreted\n").map_err(|e| e.to_string())?;
        Ok(Vec::new())
    }
}

#[test]
fn a_python_step_is_run_by_the_host_and_cached_like_any_other() {
    let mut bench = Bench::new();
    let variants = bench.input("calls.vcf", "##fileformat=VCFv4.3\n");
    let node = bench
        .graph
        .add_step(StepSpec {
            name: "resistance".into(),
            output: DataKind::ResistanceReport,
            coordinates: None,
            conversion: None,
            arguments: vec![Argument {
                param: "v".into(),
                declared: DataKind::Reference,
                node: variants,
            }],
        })
        .unwrap();
    bench.tasks.push(Task {
        node,
        code: "def resistance(v): ...".into(),
        recipe: Recipe::Callback(7),
        tools: Vec::new(),
        parameters: Vec::new(),
        citations: Vec::new(),
        seed: None,
    });
    let host = Writing {
        calls: Mutex::new(Vec::new()),
    };

    let first = bench.run_with(&[node], &Options::default(), &host);
    let second = bench.run_with(&[node], &Options::default(), &host);

    assert_eq!(outcome(&first, node), Outcome::Ran);
    assert_eq!(contents(&first, node), "interpreted\n");
    assert_eq!(outcome(&second, node), Outcome::Cached);
    assert_eq!(
        *host.calls.lock().unwrap(),
        vec![(7, vec!["v=1".to_owned()])],
        "the host should have been asked exactly once"
    );
}

// --------------------------------------------------------------- tools --

#[test]
fn a_tool_reports_the_version_that_joins_the_key() {
    let dir = TempDir::new().unwrap();
    let tool = dir.path().join("fake-tool");
    fs::write(&tool, "#!/bin/sh\necho 'fake-tool 1.2.3'\n").unwrap();
    make_executable(&tool);

    let version = exec::tool_version(&tool.to_string_lossy()).unwrap();

    assert!(version.contains("1.2.3"), "{version}");
}

#[test]
fn a_tool_that_is_not_installed_is_named_rather_than_ignored() {
    // Hashing an absent tool as "no version" would let two machines with
    // different tools agree on a key.
    let error = exec::tool_version("ligase-no-such-tool").unwrap_err();

    assert!(error.contains("ligase-no-such-tool"), "{error}");
}

#[test]
fn a_step_whose_tool_is_missing_fails_before_it_runs() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", &copy(&bench, "align"), reads);
    bench.tasks[0].tools = vec!["ligase-no-such-tool".into()];

    let report = bench.run(&[align]);

    assert_eq!(report.failures.len(), 1);
    assert_eq!(executions(&bench), 0);
}

fn make_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt as _;
    fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}

fn touch_marker(bench: &Bench, tag: &str) -> String {
    format!("echo {tag} >> {}", bench.path("marker").display())
}

// -------------------------------------------------------------- report --

#[test]
fn a_report_gives_each_step_that_ran_its_own_cost() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "cat {in} > {out}", reads);
    let call = bench.step("call", "cat {in} > {out}", align);

    let report = bench.run(&[call]);
    let text = exec::render(&bench.graph, &[call], &report);

    assert!(text.contains("ran       `align`"), "{text}");
    assert!(text.contains("ran       `call`"), "{text}");
    assert!(text.trim_end().ends_with("2 steps: 2 ran."), "{text}");
}

#[test]
fn a_report_names_the_samples_a_step_was_cached_for() {
    // Four samples cached is one fact about four samples, and a user who
    // has to expand something to learn which four has a shorter report
    // rather than a better one.
    let mut bench = Bench::new();
    let command = copy(&bench, "align");
    let first = bench.input("a.txt", "a\n");
    let second = bench.input("b.txt", "b\n");
    let align_a = bench.step("align", &command, first);
    let align_b = bench.step("align", &command, second);
    bench.run(&[align_a, align_b]);

    let again = bench.run(&[align_a, align_b]);
    let text = exec::render(&bench.graph, &[align_a, align_b], &again);

    assert!(text.contains("cached    `align` for "), "{text}");
    assert!(text.contains("a.txt"), "{text}");
    assert!(text.contains("b.txt"), "{text}");
    assert!(text.contains("2 steps: 2 from cache."), "{text}");
}

#[test]
fn a_report_says_what_the_tool_said_when_a_step_failed() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    let align = bench.step("align", "echo 'no such contig' >&2; exit 3", reads);

    let report = bench.run(&[align]);
    let text = exec::render(&bench.graph, &[align], &report);

    assert!(text.contains("`align` failed:"), "{text}");
    assert!(text.contains("  no such contig"), "{text}");
    assert!(text.contains("1 step: 1 failed."), "{text}");
}

#[test]
fn a_report_reads_the_same_way_twice() {
    // Two identical runs that print different reports would be a strange
    // thing for a reproducibility tool to do, and under a thread pool the
    // finishing order is nobody's to predict.
    let mut bench = Bench::new();
    let roots: Vec<NodeId> = (0..6)
        .map(|index| {
            let input = bench.input(&format!("{index}.txt"), &format!("{index}\n"));
            bench.step("align", "cat {in} > {out}", input)
        })
        .collect();

    let first = exec::render(&bench.graph, &roots, &bench.run(&roots));
    let second = exec::render(&bench.graph, &roots, &bench.run(&roots));

    assert_eq!(
        first.lines().filter(|line| line.starts_with("ran")).count(),
        6
    );
    assert_eq!(
        second,
        exec::render(&bench.graph, &roots, &bench.run(&roots))
    );
}

#[test]
fn an_empty_run_says_so_rather_than_printing_nothing() {
    let bench = Bench::new();
    let report = bench.run(&[]);

    assert_eq!(exec::summarise(&report), "nothing to run.");
}

// --------------------------------------------------------- worker pool --

/// How long a step waits for the pool to take the work it queued.
///
/// The work is a closure that sends on a channel, so a working pool takes
/// it in microseconds. The wait only ever elapses when nothing can take it
/// at all, and then the step fails and says so — a regression here is a red
/// test rather than a `cargo test` that never returns.
const PATIENCE: Duration = Duration::from_secs(10);

/// A host whose step queues work on the pool it is running on.
///
/// This is the shape of the hang found in M5. A step's inputs are hashed
/// inside the step's own worker, and BLAKE3 hashes a large file in parallel
/// on whichever pool it is called from (D3) — so a step can queue work that
/// only a pool worker can take. If the scheduler is holding its other
/// workers blocked on something of its own, rayon counts them as busy, the
/// queued work is never taken, and the run stops for good.
///
/// `rayon::spawn` queues onto the pool belonging to the thread that calls
/// it, which here is one of the executor's own workers.
struct Nesting;

impl Host for Nesting {
    fn call(
        &self,
        _id: u64,
        out: &Path,
        _inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<Vec<Note>, String> {
        let (taken, wait) = mpsc::channel();
        rayon::spawn(move || {
            let _ = taken.send(());
        });
        wait.recv_timeout(PATIENCE).map_err(|_| {
            "the pool never took work queued from inside a step: a worker is blocked \
             where rayon cannot see that it is idle"
                .to_owned()
        })?;
        fs::write(out, "nested\n").map_err(|error| error.to_string())?;
        Ok(Vec::new())
    }
}

#[test]
fn work_queued_from_inside_a_step_is_taken_while_another_step_waits() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    // Two steps in a chain, two workers: while the first runs, the second
    // cannot, so the other worker has nothing of its own to do and must be
    // free to help.
    let first = bench.callback("nested", 1, reads);
    let second = bench.step("after", "cat {in} > {out}", first);

    let options = Options {
        jobs: 2,
        force: false,
        ..Options::default()
    };
    let report = bench.run_with(&[second], &options, &Nesting);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(contents(&report, first), "nested\n");
    assert_eq!(outcome(&report, second), Outcome::Ran);
}

#[test]
fn work_queued_from_inside_a_step_is_taken_while_its_twin_waits() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");
    // The same step over the same data twice: one key, so one of the two
    // waits for the other rather than racing it. Waiting must not cost a
    // worker either, or the step that is running cannot be helped.
    let left = bench.callback("nested", 1, reads);
    let right = bench.callback("nested", 1, reads);

    let options = Options {
        jobs: 2,
        force: false,
        ..Options::default()
    };
    let report = bench.run_with(&[left, right], &options, &Nesting);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(report.results.len(), 2, "both nodes belong in the report");
    assert_eq!(contents(&report, left), "nested\n");
    assert_eq!(contents(&report, right), "nested\n");
    // One did the work; the other was handed its output.
    let (one, two) = (outcome(&report, left), outcome(&report, right));
    assert!(
        (one == Outcome::Ran && two == Outcome::Cached)
            || (one == Outcome::Cached && two == Outcome::Ran),
        "one should have run and the other been handed its output: {one}, {two}"
    );
}

/// Parameter names for the branches below, since a step's inputs are named.
const BRANCH_PARAMS: [&str; 8] = ["a", "b", "c", "d", "e", "f", "g", "h"];

#[test]
fn every_step_of_a_wide_graph_is_run_by_a_single_worker() {
    let mut bench = Bench::new();
    let reads = bench.input("reads.txt", "ACGT\n");

    // Eight independent branches that converge, each with its own command
    // so that none of them is another's twin. The run is over when the pool
    // is out of work rather than when a count of busy workers reaches zero,
    // so a graph wider than `jobs` is worth saying out loud.
    let mut branches = Vec::new();
    for index in 0..8u8 {
        let name = format!("branch{index}");
        let command = format!("sed 's/$/ {index}/' {{in}} > {{out}}");
        branches.push(bench.step(&name, &command, reads));
    }
    let inputs: Vec<(&str, NodeId)> = branches
        .iter()
        .enumerate()
        .map(|(index, node)| (BRANCH_PARAMS[index], *node))
        .collect();
    let joined = bench.shell(
        "join",
        "cat {a} {b} {c} {d} {e} {f} {g} {h} > {out}",
        &inputs,
        &[],
    );

    let options = Options {
        jobs: 1,
        force: false,
        ..Options::default()
    };
    let report = bench.run_with(&[joined], &options, &Refusing);

    assert!(report.failures.is_empty(), "{report:?}");
    assert_eq!(report.results.len(), 9, "every step belongs in the report");
    for branch in branches {
        assert_eq!(outcome(&report, branch), Outcome::Ran);
    }
    assert_eq!(outcome(&report, joined), Outcome::Ran);
}

// ----------------------------------------- a tool that is a library --

#[test]
fn a_library_tool_is_not_run_and_says_so_until_the_host_supplies_it() {
    // D46. `tool=` meant two things that only coincide for a program: the
    // name a citation resolves from, and something the engine execs to ask
    // its version. RDKit is software that produced a result and a reviewer
    // will want cited, and there is nothing to exec.
    //
    // Unregistered, it must be an *error* naming the tool -- never an empty
    // version. That is `bwa`'s lesson in another costume: a non-answer
    // hashed as a version is identical for every release, so upgrading the
    // library would not move a single cache key.
    // `rdkit` itself, which is in the engine's list of libraries and which
    // nothing in a Rust test registers: there is no Python interpreter here
    // to have imported it.
    let error = exec::tool_version("rdkit").unwrap_err();
    assert!(error.contains("rdkit"), "{error}");
    assert!(
        error.contains("ligase-bio[chem]"),
        "and it says what to install, as `ligase store status` does: {error}"
    );
    assert!(
        !error.contains("could not be run"),
        "a library is not a program that failed to run: {error}"
    );
    assert!(
        error.contains("library"),
        "the message must say what kind of thing this is: {error}"
    );
}

#[test]
fn a_host_supplied_library_version_is_what_joins_the_key() {
    exec::register_library_version("ligase-test-registered", "9.9.9").unwrap();

    let version = exec::tool_version("ligase-test-registered").unwrap();
    assert!(version.contains("9.9.9"), "{version}");
    assert!(
        version.contains("ligase-test-registered"),
        "the tool names itself in its own version, as `ligase` does: {version}"
    );
}

#[test]
fn registering_one_library_twice_over_is_fine_and_disagreeing_is_not() {
    // The version is in cache keys, so two answers for one library inside
    // one process would mean two keys for one computation. Reading
    // `rdkit.__version__` twice cannot disagree, so this cannot happen by
    // accident -- which is why it is worth refusing rather than resolving.
    exec::register_library_version("ligase-test-twice", "1.0").unwrap();
    exec::register_library_version("ligase-test-twice", "1.0")
        .expect("the same answer again is not a conflict");

    let error = exec::register_library_version("ligase-test-twice", "2.0")
        .expect_err("a second, different answer is");
    assert!(error.contains("1.0"), "{error}");
    assert!(error.contains("2.0"), "{error}");
}

#[test]
fn a_library_is_not_asked_whether_a_program_of_that_name_exists() {
    // The point of the taxonomy. `sh` is a program on every machine this
    // runs on, so a library registered under that name must still report
    // the registered version rather than whatever `sh --version` prints.
    exec::register_library_version("sh", "not a shell at all").unwrap();

    let version = exec::tool_version("sh").unwrap();
    assert!(version.contains("not a shell at all"), "{version}");
}