ligase 0.3.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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
//! Running a checked graph, once.
//!
//! The rule is one sentence: a step runs when something that could change
//! its result has changed, and not otherwise. Everything here follows from
//! it.
//!
//! A step's key is `hash(function code, parameters, input content hashes,
//! tool versions)` ([`crate::key`]). If the key is in the cache, the step
//! does not run. If it is not, the step runs and its output is stored under
//! the hash of its bytes ([`crate::cache`]). Because a downstream key is
//! built from its inputs' *content*, a step that reruns and produces the
//! same result leaves every key below it unchanged — which is early cutoff,
//! falling out of content addressing rather than being bolted on.
//!
//! "The same result" is the canonical form of the output, not its bytes
//! ([`crate::canon`], D4). With bytes it could not have worked past the
//! first real tool: `minimap2` writes its command line into `@PG CL`, that
//! command line holds the output path, and the output path is the staging
//! file named after the step's own key — so a step's bytes depended on its
//! own key, and any change at all cascaded to the bottom of the pipeline.
//!
//! # Why the body is not here
//!
//! A step body is Python. Running it inside the scheduler would put the GIL
//! in the hot path of a parallel run, so it is not: the body is called once,
//! before anything executes, and what it returns is a [`Recipe`] — a command
//! to render, or a callback for the one case that genuinely has to run
//! Python. The core then owns the whole run and the GIL is only taken for
//! those callbacks.
//!
//! # Why no worker ever waits
//!
//! A step is run by a rayon job of its own, and a job that finishes starts
//! the steps it released before it ends. Nothing loops looking for work and
//! nothing blocks waiting for it, so a worker with nothing of its own to do
//! is idle *as far as rayon is concerned* — and can therefore be given work
//! that a step queued on the pool from inside itself.
//!
//! That last part is the whole reason (D27). Hashing a step's inputs
//! happens inside the step, and BLAKE3 hashes a large file across the pool
//! it is called from (D3), so a step queues pool work as a matter of course.
//! A scheduler that parked its spare workers on a condition variable of its
//! own left that work with nobody able to take it, and a run could stop for
//! good — which is what happened under heavy load in M5.
//!
//! A worker can still block on something rayon cannot see: a step's own
//! child process, or the GIL in a callback. What it must never block on is
//! something that needs the pool to make progress, because that is the
//! shape a deadlock needs.
//!
//! # What a run records besides its own answer
//!
//! A step that runs writes a provenance record ([`crate::prov`]) naming the
//! command that ran, with its placeholders filled in. This is the one moment
//! that command exists: a cache hit cannot reconstruct it, because M4 drops
//! the `@PG` line that used to hold it (D22). A step served from the cache
//! writes nothing — the record from the run that did the work is still
//! there, which is the point of keeping it outside the cache.
//!
//! # What is deliberately not here
//!
//! Turning those records into prose. A methods paragraph and a bundle are
//! [`crate::prov`]'s business, built from what this module recorded and from
//! the graph, after a run rather than during one.
//!
//! Running a step twice to find out whether it is reproducible at all is
//! [`crate::audit`], which borrows this module's [`produce`] rather than
//! repeating it.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, RwLock};
use std::time::{Duration, Instant};

use rayon::Scope;

use crate::cache::{Cache, Entry, Recorded, Recording, Stored};
use crate::canon::Note;
use crate::graph::{Graph, NodeId, StepSpec};
use crate::hash::ContentHash;
use crate::key::{Ingredients, StepKey};
use crate::prov::{self, InputRecord, Prov, Record, day};
use crate::store::StoreStats;
use crate::store::lease;
use crate::types::{DataKind, Dataset, Origin, RemoteVerdict};
use crate::worker::Worker;

/// How a step's output is produced.
///
/// Both are decided before the run starts, by asking the step's body once.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Recipe {
    /// A shell command, with `{placeholders}` for the step's inputs,
    /// parameters and `{out}`.
    Shell(String),
    /// A callback the host runs, identified by a number the host chose.
    Callback(u64),
}

impl Recipe {
    /// How this recipe enters the cache key.
    fn describe(&self) -> String {
        match self {
            Self::Shell(command) => format!("sh:{command}"),
            // A callback's identity is its function's code, which is
            // already an ingredient; the number is a position in this run's
            // table and means nothing between runs.
            Self::Callback(_) => "callback".to_owned(),
        }
    }
}

/// What the host knows about one step that the graph does not.
#[derive(Clone, Debug)]
pub struct Task {
    /// The node this is the recipe for.
    pub node: NodeId,
    /// The step function's source, as written.
    pub code: String,
    /// How to produce the output.
    pub recipe: Recipe,
    /// External tools whose versions join the key.
    pub tools: Vec<String>,
    /// Plain parameters, as `(name, value)`.
    pub parameters: Vec<(String, String)>,
    /// References the step asks to be cited by, as written.
    ///
    /// Deliberately **not** a cache-key ingredient: a citation cannot
    /// change a result, so nothing about it belongs in
    /// [`crate::key::Ingredients`]. For the same reason it is not stored in
    /// a provenance record either, which would go stale the moment it was
    /// edited — a methods section takes it from the pipeline in front of it
    /// ([`crate::prov::methods`]).
    ///
    /// Which is not the same as saying that adding a citation reruns
    /// nothing. The citation is written on the decorator line, and
    /// `graph.py::_source` hashes a step's source *including* its
    /// decorator, so editing it moves [`Self::code`] and the step reruns —
    /// then early cutoff stops the rerun going any further, exactly as for
    /// a comment-only edit. The field is out of the key; the line it was
    /// typed on is not, and no field here could change that.
    pub citations: Vec<String>,
    /// The parameter that seeds this step, for a step that declared itself
    /// stochastic (D40). `None` for every ordinary step.
    ///
    /// One `Option` rather than a flag beside a name, because the pair
    /// admits a fourth state — stochastic with no seed — that the decorator
    /// has just made an error. Representing it here would mean every reader
    /// of this field having to decide what it meant, so it is
    /// unrepresentable instead: `Some(name)` *is* "declared stochastic,
    /// seeded by `name`".
    ///
    /// The seed's *value* is in [`Self::parameters`], where it is hashed
    /// into the key like any other parameter — which is all `CLAUDE.md`'s
    /// rule that seeds be explicit, typed, hashed parameters requires. What
    /// this adds is the engine knowing *which* parameter it is, so that
    /// [`crate::audit`] can refuse to call the step deterministic and
    /// [`crate::prov::methods`] can say it was seeded rather than merely
    /// parameterised.
    ///
    /// Outside the key and outside a provenance record for the same reason
    /// as [`Self::citations`], and with the same caveat.
    pub seed: Option<String>,
}

/// What happened to one step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
    /// It ran.
    Ran,
    /// Its key was already in the cache, and nothing above it ran.
    Cached,
    /// Its key was already in the cache although something above it ran:
    /// that step produced the same output as before, so there was nothing
    /// to redo here. This is early cutoff.
    Skipped,
}

impl fmt::Display for Outcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Ran => "ran",
            Self::Cached => "cached",
            Self::Skipped => "skipped",
        })
    }
}

/// What one step produced.
#[derive(Clone, Debug)]
pub struct StepResult {
    /// The node it was.
    pub node: NodeId,
    /// The step's name.
    pub step: String,
    /// Whether it ran, was cached, or was skipped.
    pub outcome: Outcome,
    /// Its cache key.
    pub key: StepKey,
    /// The hash of its output's bytes, which is its name in the store.
    pub hash: ContentHash,
    /// The hash of what its output *means* ([`crate::canon`]).
    ///
    /// This is what the steps below it were keyed on, so two runs that
    /// agree here cut off everything downstream however far their bytes
    /// diverged.
    pub canonical: ContentHash,
    /// What canonicalising the output noticed ([`Note`]).
    ///
    /// Empty for almost every step. A note is not a failure: the step ran
    /// and its result stands. It is reported because the fix is in the
    /// pipeline and a user cannot make it without being told (D26).
    pub notes: Vec<Note>,
    /// Where the output is.
    pub output: PathBuf,
    /// How long it took, when it ran.
    pub duration: Duration,
}

/// Why one step did not produce anything.
#[derive(Clone, Debug)]
pub struct StepFailure {
    /// The node it was.
    pub node: NodeId,
    /// The step's name.
    pub step: String,
    /// What went wrong, in the tool's own words where there are any.
    pub message: String,
}

/// What a run did.
///
/// A step whose input failed is in neither list: one cause, one failure.
#[derive(Clone, Debug, Default)]
pub struct RunReport {
    /// Every step that produced an output, in the order they finished.
    pub results: Vec<StepResult>,
    /// Every step that did not.
    pub failures: Vec<StepFailure>,
    /// What the object store did while the run was going on.
    ///
    /// Default — all zeroes — for a run with no remote tier, which prints
    /// nothing: a report must not grow a line for a feature the run did
    /// not use.
    pub store: StoreStats,
    /// The first object the remote served that was not what its name said.
    ///
    /// Counted in [`store`](Self::store) as well, but kept in full here,
    /// because "an object was refused" is the one store event a user has
    /// to *read* rather than count.
    pub refused: Option<String>,
    /// Which worker this was, for a run that was one of several (D51).
    ///
    /// `None` for an ordinary run, which prints nothing about workers: a
    /// report must not grow a line for a feature the run did not use.
    pub worker: Option<String>,
    /// How many steps this run waited for another worker to produce.
    ///
    /// They are [`Outcome::Cached`] like any other hit, because that is
    /// what they turned out to be. This counts them separately because
    /// "four steps came from the cache" and "four steps were computed by
    /// somebody else while I waited" are different pieces of news.
    pub waited: usize,
    /// Steps another worker computed to a different answer (D52).
    ///
    /// Empty for almost every run, and for every run on one machine. Kept
    /// in full rather than counted, for [`refused`](Self::refused)'s
    /// reason: this is the one event in a distributed run a user has to
    /// *read*.
    ///
    /// Deliberately **not** a [`Note`]. A note is recorded with the cache
    /// entry and read back on every later hit, because a note is a fact
    /// about the output — a gene barely read stays barely read. A
    /// divergence is a fact about *this run on this worker*: somebody else
    /// got there first and disagreed. Persisting it would attach it to a
    /// key for good and report it to everyone who ever hit that key.
    pub diverged: Vec<Divergence>,
}

/// Two workers, one step key, two different answers (D52).
///
/// The argument that a lock is unnecessary rests on two workers that agree
/// on a key agreeing on the result. They agree on the bytes almost never —
/// a tool writes its own command line into its output — and that is
/// harmless, because every downstream key is built on the canonical form.
/// This is the case where the *canonical* forms differ too, which the
/// argument does not cover: a kind whose canonical form does not fix the
/// result, or a seeded stochastic tool that is only deterministic given a
/// thread count as well, which two cluster nodes do not share.
///
/// The engine reports it and does not try to resolve it. Pinning such a
/// step to one worker would make the answer depend on how many workers
/// happened to be running and hide a real property of the pipeline;
/// `ligase audit` is the tool for that question, and this is what makes a
/// distributed run raise it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Divergence {
    /// The node that computed it here.
    pub node: NodeId,
    /// The step's name.
    pub step: String,
    /// The key both workers agreed on.
    pub key: StepKey,
    /// What this worker's output means.
    pub ours: ContentHash,
    /// What the output already in the store means, which is the one in
    /// force: the alternative is a run where each worker believes its own
    /// answer, which is the silent failure this project exists to delete.
    pub theirs: ContentHash,
}

impl RunReport {
    /// What one node produced, if it produced anything.
    #[must_use]
    pub fn result(&self, node: NodeId) -> Option<&StepResult> {
        self.results.iter().find(|result| result.node == node)
    }

    /// How many steps had each outcome.
    #[must_use]
    pub fn counts(&self) -> Counts {
        let count = |wanted: Outcome| {
            self.results
                .iter()
                .filter(|result| result.outcome == wanted)
                .count()
        };
        Counts {
            ran: count(Outcome::Ran),
            cached: count(Outcome::Cached),
            skipped: count(Outcome::Skipped),
            failed: self.failures.len(),
        }
    }
}

/// How a run came out, in numbers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
    /// Steps that ran.
    pub ran: usize,
    /// Steps served from the cache.
    pub cached: usize,
    /// Steps skipped because an upstream rerun changed nothing.
    pub skipped: usize,
    /// Steps that failed.
    pub failed: usize,
}

/// Where a run reads what is already known, and writes down what it did.
///
/// Two stores with different lifetimes, handed over together because every
/// run needs both: the cache decides whether a step has to run at all
/// ([`crate::cache`]), and provenance records how it ran when it does
/// ([`crate::prov`]). They are separate because a cache is meant to be
/// thrown away and a record of how a result was produced is not.
#[derive(Clone, Copy, Debug)]
pub struct Stores<'a> {
    /// What has already been computed, and what it produced.
    pub cache: &'a Cache,
    /// How each result was produced.
    pub prov: &'a Prov,
}

/// How to run.
///
/// No longer `Copy`, because [`worker`](Self::worker) is a name. Every
/// caller builds one with `..Options::default()` and passes it by
/// reference, so that costs nothing.
#[derive(Clone, Debug)]
pub struct Options {
    /// How many steps may run at once.
    ///
    /// This is the knob for **one machine**. Several machines is
    /// [`worker`](Self::worker), and the two are not alternatives: threads
    /// coordinate through a mutex at no cost, and workers coordinate
    /// through a store at a cost per step.
    pub jobs: usize,
    /// Run every step, cache or no cache.
    pub force: bool,
    /// Who this worker is, for a run that is one of several (D51).
    ///
    /// `None` is an ordinary run: it computes whatever is not in the cache
    /// and consults no lease. `Some` makes it a worker — it claims each
    /// step through the store, leaves alone whatever another worker holds,
    /// and waits for work it cannot claim rather than duplicating it.
    pub worker: Option<Worker>,
    /// How long a worker may hold a step before another may compute it
    /// too.
    ///
    /// Only read when [`worker`](Self::worker) is set. Both ways of
    /// getting it wrong are costs rather than wrong answers (D53): too
    /// short and a worker duplicates a step whose holder is still working;
    /// too long and a worker that died keeps others waiting until its
    /// deadline. Set it above your longest step.
    pub lease: Duration,
}

/// How long a worker holds a step by default.
///
/// An hour: long enough for most alignment steps, short enough that a
/// crashed worker is not a lost evening. The guide says to raise it.
pub const DEFAULT_LEASE: Duration = Duration::from_secs(3600);

impl Default for Options {
    fn default() -> Self {
        Self {
            jobs: std::thread::available_parallelism().map_or(1, std::num::NonZero::get),
            force: false,
            worker: None,
            lease: DEFAULT_LEASE,
        }
    }
}

/// Whatever can run the callbacks the core cannot.
///
/// A shell step is run by the core. A step whose body is Python has to go
/// back to Python, and this is the only door through which it does.
pub trait Host: Sync {
    /// Produce the output at `out`, from inputs given by parameter name.
    ///
    /// Returns what the body noticed about its own work, which is almost
    /// always nothing. A body is the only thing that can see an assumption
    /// its work rested on — a resistance reading made without coverage
    /// leaves no trace of it in the report it writes — so this is the door
    /// such a finding comes back through (D32). A note never fails a step:
    /// the work was done and its result stands.
    ///
    /// # Errors
    ///
    /// Whatever the callback raised, as a message for the user.
    fn call(
        &self,
        id: u64,
        out: &Path,
        inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<Vec<Note>, String>;
}

/// A host that has no callbacks, for a pipeline of shell steps.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoCallbacks;

impl Host for NoCallbacks {
    fn call(
        &self,
        id: u64,
        _out: &Path,
        _inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<Vec<Note>, String> {
        Err(format!(
            "this step's body is a callback ({id}), and nothing here can run one"
        ))
    }
}

/// A dependency whose version is part of a result but which is not a
/// program to run.
///
/// `tool=` means "something whose version changes the answer". Almost
/// always that is an external program, probed with `--version`. Two are
/// not, and both are compiled into this engine with no process to run and
/// no `--version` to print, while changing answers exactly as a tool does.
///
/// `hivdb` is a body of versioned knowledge — the resistance rules.
/// `ligase` is the engine's own work: a conversion such as
/// `map_identifiers` is code in this crate, so what a step declaring it
/// depends on is the crate. Nothing else would put that in a cache key: a
/// step body that only calls into the engine hashes the same however the
/// engine changes underneath it.
///
/// Naming them here rather than special-casing them inside the probe keeps
/// the exceptions visible, and keeps them to one place.
const BUILT_IN: &[&str] = &["hivdb", "ligase"];

/// The tools that are **libraries**: software with no program to run, whose
/// version only the host knows.
///
/// A third kind, after a program the engine execs and a built-in the engine
/// carries. `tool=` has always meant two things at once — the name a
/// citation resolves from (`prov::cite`), and something to run and ask — and
/// those coincide only for a program. [`BUILT_IN`] is the case where the
/// engine itself is the authority. This is the case where neither is: RDKit
/// is software that produced a result and a reviewer will want it cited, and
/// there is nothing on `PATH` to interrogate.
///
/// The authority is the interpreter that will do the work, which is the
/// *exact* copy of the library the step will call. That is a better answer
/// than execing something of the same name would be, not a worse one — and
/// it is why the version is supplied rather than probed
/// ([`register_library_version`]).
///
/// Named here rather than inferred, for [`BUILT_IN`]'s reason: a tool that
/// is not run must say so where a reader can see the list.
pub(crate) const LIBRARY: &[&str] = &["rdkit"];

/// The library versions the host has supplied, by tool.
///
/// Written once per library per process, before any key is computed, by
/// whatever imported the library. Read when a key is built.
static LIBRARY_VERSIONS: RwLock<BTreeMap<String, String>> = RwLock::new(BTreeMap::new());

/// Tell the engine what version of a library this host holds.
///
/// Called by the layer that imported it — `ligase.chem` for RDKit — at the
/// moment a step declaring that library is built, which is before any cache
/// key is computed. The engine cannot read it for itself: the library lives
/// in the interpreter, not on `PATH`.
///
/// # Errors
///
/// If this library has already been registered with a *different* version.
/// The version is in cache keys, so two answers inside one process would
/// mean two keys for one computation; reading a library's own version twice
/// cannot disagree, so a conflict is a bug worth refusing rather than
/// resolving. Registering the same answer again is not a conflict.
pub fn register_library_version(tool: &str, version: &str) -> Result<(), String> {
    let mut known = LIBRARY_VERSIONS
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    match known.get(tool) {
        Some(already) if already != version => Err(format!(
            "`{tool}` was already registered as `{already}` and is now              `{version}`. A library's version is in every cache key beneath              it, so two answers in one process would mean two keys for one              computation"
        )),
        _ => {
            known.insert(tool.to_owned(), version.to_owned());
            Ok(())
        }
    }
}

/// What the host said this library's version is, if anything.
fn library_version(tool: &str) -> Option<String> {
    LIBRARY_VERSIONS
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(tool)
        .map(|version| format!("{tool} {version}"))
}

/// How to ask one tool what version it is.
///
/// Almost every bioinformatics tool answers `--version` on stdout and exits
/// zero, which is [`DEFAULT_PROBE`]. The ones that do not are the reason
/// this is a type rather than a hardcoded argument, and `bwa` is why it
/// exists at all: see [`PROBES`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct VersionProbe {
    /// What to pass the tool. Empty for a tool whose bare usage banner is
    /// the only place it says its version.
    arguments: &'static [&'static str],
    /// Whether the probe is expected to exit non-zero.
    ///
    /// A tool that prints its version and exits 1 is unusual but not wrong.
    /// What *is* wrong is treating an unexpected failure as an answer, so
    /// this is declared per tool rather than ignored for all of them.
    failure_expected: bool,
    /// The marker of the line that holds the version, where the probe
    /// prints more than the version.
    ///
    /// `None` keeps the whole output, because the parts a tool prints below
    /// the first line — the htslib a samtools was built against, say —
    /// change results too. `Some` is for a probe whose output is a usage
    /// banner: the banner holds a contact address and a command list, none
    /// of which is a version, and all of which would then be hashed as one.
    marker: Option<&'static str>,
}

/// What a tool is asked unless it is named in [`PROBES`].
const DEFAULT_PROBE: VersionProbe = VersionProbe {
    arguments: &["--version"],
    failure_expected: false,
    marker: None,
};

/// The tools that do not answer `--version`.
///
/// `bwa` is the whole reason this table exists, and the reason it is worth
/// reading before adding to it. `bwa --version` prints
/// `[main] unrecognized command '--version'` **to stderr** and exits
/// non-zero. Before this table, [`tool_version`] took that sentence as
/// bwa's version — and that sentence is the same for every bwa ever
/// released, so upgrading the aligner did not move any cache key and every
/// alignment computed by the old one was served for the new one. `tool=`
/// exists to prevent precisely that, so the gap was not cosmetic: it was
/// the guarantee failing silently on one of the two commonest aligners in
/// the field.
///
/// Bare `bwa` prints a usage banner whose third line is
/// `Version: 0.7.19-r1273`, so that is what is asked and that is the line
/// that is kept.
const PROBES: &[(&str, VersionProbe)] = &[(
    "bwa",
    VersionProbe {
        arguments: &[],
        failure_expected: true,
        marker: Some("Version:"),
    },
)];

/// The version a step's dependency reports.
///
/// For a built-in, what the engine carries. For everything else, what the
/// tool's own probe prints — `<tool> --version` for almost all of them,
/// and whatever [`PROBES`] declares for the rest.
///
/// # Errors
///
/// If the tool is not installed, prints nothing, fails when its probe did
/// not expect it to, or stops printing the line its probe looks for.
/// Hashing an absent tool as "no version" would let two machines with
/// different tools agree on a key, which is exactly the failure this is
/// here to prevent — and so would hashing a tool's complaint about the
/// question.
pub fn tool_version(tool: &str) -> Result<String, String> {
    match tool {
        "hivdb" => return crate::hivdb::ruleset::fingerprint(),
        "ligase" => return Ok(format!("ligase {}", env!("CARGO_PKG_VERSION"))),
        _ => {}
    }
    debug_assert!(
        !BUILT_IN.contains(&tool),
        "a built-in tool with no version of its own"
    );

    // A library is never run, even where a program of the same name exists
    // on this machine: what the step will call is the library, so a program
    // that happens to share its name would be a version of the wrong thing.
    if LIBRARY.contains(&tool) || library_version(tool).is_some() {
        return library_version(tool).ok_or_else(|| {
            format!(
                "`{tool}` is a library rather than a program, so there is \
                 nothing to run and ask. Its version comes from whatever \
                 imported it, and nothing has: for RDKit that means \
                 `pip install 'ligase-bio[chem]'` and using \
                 `lg.chem.standardize`, which registers it. Recording a \
                 library with no version would be the same text for every \
                 release of it, and upgrading it would not move a single \
                 cache key"
            )
        });
    }

    let probe = probe_for(tool);
    let output = Command::new(tool)
        .args(probe.arguments)
        .output()
        .map_err(|error| format!("`{tool}` could not be run: {error}"))?;

    version_from(
        tool,
        &probe,
        output.status.success(),
        &String::from_utf8_lossy(&output.stdout),
        &String::from_utf8_lossy(&output.stderr),
    )
}

/// How this tool is asked its version.
fn probe_for(tool: &str) -> VersionProbe {
    PROBES
        .iter()
        .find(|(named, _)| *named == tool)
        .map_or(DEFAULT_PROBE, |(_, probe)| *probe)
}

/// What a probe's output says the version is.
///
/// Separate from running the process so that every refusal below can be
/// tested on a machine with none of these tools installed. A version that
/// is wrong is worse than one that is missing: the missing one stops the
/// run, and the wrong one is hashed into every key beneath it.
fn version_from(
    tool: &str,
    probe: &VersionProbe,
    succeeded: bool,
    stdout: &str,
    stderr: &str,
) -> Result<String, String> {
    let asked = describe_probe(tool, probe);

    if !succeeded && !probe.failure_expected {
        let said = complaint(stdout, stderr);
        return Err(format!(
            "`{asked}` failed, so what it printed is not a version: {said}. \
             A tool that answers the question differently needs an entry in \
             this engine's version-probe table; one recorded from a failed \
             probe would be the same text for every release of the tool, and \
             upgrading it would not move a single cache key"
        ));
    }

    let text = first_nonempty(stdout, stderr);
    if text.is_empty() {
        return Err(format!("`{asked}` printed nothing"));
    }

    match probe.marker {
        None => Ok(text.trim().to_owned()),
        Some(marker) => text
            .lines()
            .find(|line| line.contains(marker))
            .map(|line| line.trim().to_owned())
            .ok_or_else(|| {
                format!(
                    "`{asked}` printed no line containing `{marker}`, so this \
                     engine cannot tell which part of its output is the \
                     version. Keeping the rest would hash a usage banner as a \
                     version; update the version-probe table for `{tool}`"
                )
            }),
    }
}

/// The probe as a command line, for a message to quote.
fn describe_probe(tool: &str, probe: &VersionProbe) -> String {
    if probe.arguments.is_empty() {
        tool.to_owned()
    } else {
        format!("{tool} {}", probe.arguments.join(" "))
    }
}

/// Whichever stream said anything, stdout first.
fn first_nonempty<'a>(stdout: &'a str, stderr: &'a str) -> &'a str {
    if stdout.trim().is_empty() {
        stderr
    } else {
        stdout
    }
}

/// One line of what a failed probe said, for a message that stays readable.
fn complaint(stdout: &str, stderr: &str) -> String {
    let text = first_nonempty(stdout, stderr).trim();
    match text.lines().find(|line| !line.trim().is_empty()) {
        Some(line) => format!("`{}`", line.trim()),
        None => "nothing at all".to_owned(),
    }
}

/// The file extension an output of this kind is given.
///
/// Tools read the format off the name, so this is not cosmetic: a BAM step
/// writing to a name ending `.sam` gets SAM.
#[must_use]
pub const fn output_suffix(kind: DataKind) -> &'static str {
    match kind {
        DataKind::Reads => ".fastq.gz",
        DataKind::Reference => ".fasta",
        DataKind::Alignment => ".bam",
        DataKind::Variants => ".vcf.gz",
        DataKind::Intervals => ".bed",
        DataKind::ResistanceReport => ".tsv",
        DataKind::EntitySet | DataKind::RankedList => ".tsv",
        DataKind::KnowledgeGraph => ".json",
        DataKind::MoleculeSet | DataKind::MoleculeRanking => ".tsv",
    }
}

/// Run every step these outputs depend on.
///
/// Independent steps run at once, up to [`Options::jobs`]. A step whose
/// input failed does not run and is not reported: one cause, one failure.
#[must_use]
pub fn run(
    graph: &Graph,
    roots: &[NodeId],
    tasks: &[Task],
    stores: &Stores<'_>,
    options: &Options,
    host: &dyn Host,
) -> RunReport {
    let nodes: Vec<NodeId> = graph
        .reachable_nodes(roots)
        .into_iter()
        .filter(|node| graph.step(*node).is_some())
        .collect();
    if nodes.is_empty() {
        return RunReport::default();
    }

    let runner = Runner {
        graph,
        cache: stores.cache,
        prov: stores.prov,
        host,
        force: options.force,
        worker: options.worker.clone(),
        lease: options.lease,
        tasks: tasks.iter().map(|task| (task.node, task)).collect(),
        versions: versions(graph, &nodes, tasks),
        state: Mutex::new(State::new(graph, &nodes)),
    };

    let jobs = options.jobs.max(1).min(nodes.len());
    match rayon::ThreadPoolBuilder::new().num_threads(jobs).build() {
        Ok(pool) => {
            // One scope drains everything this worker can take. A step
            // another worker holds is *deferred*, not waited on, so the
            // scope empties with work still outstanding on a machine this
            // process cannot talk to -- which is exactly what the
            // single-machine invariant ("the run is over when the scope is
            // empty") does not cover. Hence the loop.
            let mut patience = Patience::new();
            loop {
                pool.scope(|scope| runner.start(scope));
                if !runner.rearm(&mut patience) {
                    break;
                }
            }
        }
        // A pool we cannot build is not a reason to refuse to run.
        Err(_) => runner.alone(),
    }

    runner.finish()
}

/// How long to wait before asking the store again.
///
/// Waiting happens **between** scopes, with the pool drained and not one
/// rayon worker in flight, which is why it does not spend D27: there is no
/// worker to starve and nothing queued from inside a step to strand. The
/// invariant D27 protects is that a worker must never block on something
/// that needs the pool to make progress, and nothing here is on the pool
/// at all.
///
/// Backing off rather than polling at a fixed interval, and not a flag:
/// each re-arm costs one store read per deferred node, so a worker idling
/// on a wide cohort would otherwise become a load generator. One knob
/// (`--lease`) is enough for a user to get wrong.
struct Patience {
    next: Duration,
}

impl Patience {
    const FIRST: Duration = Duration::from_secs(1);
    const LONGEST: Duration = Duration::from_secs(30);

    const fn new() -> Self {
        Self { next: Self::FIRST }
    }

    fn wait(&mut self) {
        std::thread::sleep(self.next);
        self.next = (self.next * 2).min(Self::LONGEST);
    }
}

/// Each of a step's arguments' files, by the parameter they fill.
///
/// `produced` answers where an upstream step put its output; an argument it
/// has no answer for is a loaded dataset, and its own files are used. Shared
/// with [`crate::audit`], so that a step being audited is handed exactly
/// what a run would have handed it.
///
/// # Errors
///
/// If an argument is bound to nothing, or to data with no file behind it.
pub fn inputs_of(
    graph: &Graph,
    node: NodeId,
    produced: &dyn Fn(NodeId) -> Option<PathBuf>,
) -> Result<Vec<(String, Vec<PathBuf>)>, String> {
    let spec = graph
        .step(node)
        .ok_or_else(|| "this node is not a step".to_owned())?;

    spec.arguments
        .iter()
        .map(|argument| {
            let files = if let Some(path) = produced(argument.node) {
                vec![path]
            } else {
                let dataset = graph
                    .dataset(argument.node)
                    .ok_or_else(|| format!("`{}` is bound to nothing", argument.param))?;
                let files = dataset.files();
                if files.is_empty() {
                    return Err(format!(
                        "`{}` is bound to data with no file behind it",
                        argument.param
                    ));
                }
                files
            };
            Ok((argument.param.clone(), files))
        })
        .collect()
}

/// What running a step took, and what it ran.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Execution {
    /// How long it took.
    pub duration: Duration,
    /// The command that ran, with its placeholders filled in.
    ///
    /// `None` for a callback, which has no command. This is what a
    /// provenance record keeps: it exists only here, because the field a
    /// tool writes it into is dropped before hashing (D22).
    pub command: Option<String>,
    /// What the body said it noticed about its own work ([`Note`]).
    ///
    /// Always empty for a shell step: a command's assumptions are not
    /// something the engine can be told about.
    pub notes: Vec<Note>,
}

/// Produce one step's output at `out`, from inputs already in place.
///
/// The cache is not consulted and nothing is recorded: this is the part of
/// running a step that is just running it, which is why
/// [`crate::audit`] can do it twice.
///
/// # Errors
///
/// Whatever the command or the callback said, or a note that the step
/// finished without writing anything.
pub fn produce(
    recipe: &Recipe,
    inputs: &[(String, Vec<PathBuf>)],
    parameters: &[(String, String)],
    out: &Path,
    host: &dyn Host,
) -> Result<Execution, String> {
    let started = Instant::now();
    let mut ran = None;
    let produced = match recipe {
        Recipe::Shell(template) => {
            let command = fill_template(template, inputs, parameters, out)?;
            let outcome = shell(&command).map(|()| Vec::new());
            ran = Some(command);
            outcome
        }
        Recipe::Callback(id) => host.call(*id, out, inputs),
    };
    let duration = started.elapsed();

    let notes = produced?;
    if !out.is_file() {
        return Err(format!(
            "the step finished without writing its output to {}",
            out.display()
        ));
    }
    Ok(Execution {
        duration,
        command: ran,
        notes,
    })
}

/// What a step said about its work, then what reading its output found.
///
/// One list, because every surface that prints notes prints them together
/// and a reader has no use for the distinction. In this order because a
/// note about how a result was arrived at is the one to read first. Nothing
/// is said twice: the two kinds cannot collide today, but a note repeated
/// in a report is a report that looks broken.
fn noticed(said: Vec<Note>, found: Vec<Note>) -> Vec<Note> {
    let mut notes = said;
    for note in found {
        if !notes.contains(&note) {
            notes.push(note);
        }
    }
    notes
}

/// Every tool named by any of these steps, probed once.
fn versions(
    graph: &Graph,
    nodes: &[NodeId],
    tasks: &[Task],
) -> HashMap<String, Result<String, String>> {
    let wanted: BTreeSet<&str> = tasks
        .iter()
        .filter(|task| nodes.contains(&task.node) && graph.step(task.node).is_some())
        .flat_map(|task| task.tools.iter().map(String::as_str))
        .collect();

    wanted
        .into_iter()
        .map(|tool| (tool.to_owned(), tool_version(tool)))
        .collect()
}

// ------------------------------------------------------------ the loop --

/// What a finished step left for the steps below it.
#[derive(Clone, Debug)]
struct Produced {
    output: Stored,
    /// Whether this step, or anything above it, ran in this run. The step
    /// below uses it to tell a cache hit from early cutoff.
    ran_above: bool,
}

struct State {
    /// The steps that can start now. Nothing waits on this queue: a worker
    /// that finds it empty has nothing to wait for, because every node that
    /// will ever land here is put there by a step that is still running
    /// (D27).
    ready: Vec<NodeId>,
    remaining: HashMap<NodeId, usize>,
    dependents: HashMap<NodeId, Vec<NodeId>>,
    produced: HashMap<NodeId, Produced>,
    results: Vec<StepResult>,
    failures: Vec<StepFailure>,
    running: HashSet<StepKey>,
    /// Nodes waiting for a key that another node is already producing,
    /// under that key. They go back onto `ready` when it is released.
    parked: HashMap<StepKey, Vec<NodeId>>,
    /// Nodes whose key another **worker** holds, on another machine.
    ///
    /// Not `parked`, and the difference is the design in one line.
    /// `running`/`parked` is a *lock*: this process holds it, correctly,
    /// because a process can. A lease is *advisory*, because the store
    /// cannot offer a lock — so these come back on a timer rather than
    /// when something releases them, and a worker that never releases one
    /// cannot stall them for longer than its deadline.
    deferred: Vec<NodeId>,
    /// How many steps this run ended up taking from another worker.
    waited: usize,
    /// Steps another worker computed to a different answer (D52).
    diverged: Vec<Divergence>,
}

impl State {
    fn new(graph: &Graph, nodes: &[NodeId]) -> Self {
        let wanted: HashSet<NodeId> = nodes.iter().copied().collect();
        let mut remaining = HashMap::new();
        let mut dependents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();

        for node in nodes {
            let upstream: BTreeSet<NodeId> = graph
                .step(*node)
                .map(|spec| {
                    spec.arguments
                        .iter()
                        .map(|argument| argument.node)
                        .filter(|from| wanted.contains(from))
                        .collect()
                })
                .unwrap_or_default();
            remaining.insert(*node, upstream.len());
            for from in upstream {
                dependents.entry(from).or_default().push(*node);
            }
        }

        let ready = remaining
            .iter()
            .filter(|(_, count)| **count == 0)
            .map(|(node, _)| *node)
            .collect();

        Self {
            ready,
            remaining,
            dependents,
            produced: HashMap::new(),
            results: Vec::new(),
            failures: Vec::new(),
            running: HashSet::new(),
            parked: HashMap::new(),
            deferred: Vec::new(),
            waited: 0,
            diverged: Vec::new(),
        }
    }

    /// Release the steps that were waiting on this one.
    fn release(&mut self, node: NodeId) {
        let Some(waiting) = self.dependents.get(&node).cloned() else {
            return;
        };
        for next in waiting {
            if let Some(count) = self.remaining.get_mut(&next) {
                *count = count.saturating_sub(1);
                if *count == 0 {
                    self.ready.push(next);
                }
            }
        }
    }
}

struct Runner<'a> {
    graph: &'a Graph,
    cache: &'a Cache,
    prov: &'a Prov,
    host: &'a dyn Host,
    force: bool,
    /// Who this worker is, or `None` for an ordinary run, which consults
    /// no lease.
    worker: Option<Worker>,
    lease: Duration,
    tasks: HashMap<NodeId, &'a Task>,
    versions: HashMap<String, Result<String, String>>,
    state: Mutex<State>,
}

impl Runner<'_> {
    /// Start every step that can start, on the pool.
    ///
    /// The run is over when the scope these are spawned into is empty,
    /// which is when the graph has drained: each step starts the steps it
    /// releases before its own job ends, so the scope cannot empty while
    /// anything can still start.
    fn start<'scope>(&'scope self, scope: &Scope<'scope>) {
        for node in self.released() {
            self.spawn(scope, node);
        }
    }

    /// Run one step on the pool, and whatever it releases after it.
    ///
    /// A worker is never held waiting for the next step. It runs one and
    /// hands the scheduler back, so rayon knows it is idle and can give it
    /// work queued from inside another step — which is what hashing a
    /// step's inputs does (D27).
    fn spawn<'scope>(&'scope self, scope: &Scope<'scope>, node: NodeId) {
        scope.spawn(move |scope| {
            for next in self.run_one(node) {
                self.spawn(scope, next);
            }
        });
    }

    /// Run the whole graph on this thread, one step at a time.
    ///
    /// Only reached when a thread pool cannot be built at all. One thread
    /// means no two steps are ever in flight, so no key is ever claimed
    /// twice and nothing is ever parked.
    fn alone(&self) {
        let mut ready = self.released();
        while let Some(node) = ready.pop() {
            ready.extend(self.run_one(node));
        }
    }

    /// Run one step, write down what happened, and say what can start now.
    ///
    /// The steps returned are the ones whose last input just arrived, plus
    /// any twin that was waiting for this step's key. A step that found its
    /// own key already being produced returns nothing: it is parked on that
    /// key, and the step holding it will hand it back.
    fn run_one(&self, node: NodeId) -> Vec<NodeId> {
        let done = self.execute(node);

        let Ok(mut state) = self.state.lock() else {
            return Vec::new();
        };
        match done {
            Ok(Attempt::Done(result)) => {
                let ran_above = result.outcome == Outcome::Ran || self.ran_above(&state, node);
                state.produced.insert(
                    node,
                    Produced {
                        output: Stored {
                            hash: result.hash,
                            path: result.output.clone(),
                        },
                        ran_above,
                    },
                );
                state.results.push(result);
                state.release(node);
            }
            // Nothing happened yet, and nothing was released. This node is
            // on `parked` under its key, and comes back when it is free.
            Ok(Attempt::Parked) => {}
            // Another worker holds this key. Nothing was released either,
            // and this node comes back on the next re-arm.
            Ok(Attempt::Deferred) => state.deferred.push(node),
            Err(failure) => state.failures.push(failure),
        }
        std::mem::take(&mut state.ready)
    }

    /// Everything on the ready queue, emptying it.
    fn released(&self) -> Vec<NodeId> {
        self.state
            .lock()
            .map_or_else(|_| Vec::new(), |mut state| std::mem::take(&mut state.ready))
    }

    fn ran_above(&self, state: &State, node: NodeId) -> bool {
        self.graph.step(node).is_some_and(|spec| {
            spec.arguments.iter().any(|argument| {
                state
                    .produced
                    .get(&argument.node)
                    .is_some_and(|produced| produced.ran_above)
            })
        })
    }

    fn execute(&self, node: NodeId) -> Result<Attempt, StepFailure> {
        let name = self
            .graph
            .step(node)
            .map_or_else(|| "?".to_owned(), |spec| spec.name.clone());
        self.attempt(node).map_err(|message| StepFailure {
            node,
            step: name,
            message,
        })
    }

    fn attempt(&self, node: NodeId) -> Result<Attempt, String> {
        let spec = self
            .graph
            .step(node)
            .ok_or_else(|| "this node is not a step".to_owned())?;
        let task = *self.tasks.get(&node).ok_or_else(|| {
            "no recipe was recorded for this step, so there is nothing to run".to_owned()
        })?;

        let inputs = self.inputs(node)?;
        let key = self.key(spec, task, &inputs)?;

        if !self.force
            && let Some(entry) = self.cache.lookup(key).map_err(|error| error.to_string())?
        {
            return Ok(Attempt::Done(self.cached_result(node, spec, key, &entry)?));
        }

        // Two nodes can share a key -- the same step over identical data --
        // and running both would be the same work twice. The second parks.
        let Some(_claim) = self.claim(key, node)? else {
            return Ok(Attempt::Parked);
        };
        if !self.force
            && let Some(entry) = self.cache.lookup(key).map_err(|error| error.to_string())?
        {
            return Ok(Attempt::Done(self.cached_result(node, spec, key, &entry)?));
        }

        // And on a shared store another *machine* can be producing it. It
        // is not held off with a lock -- the store cannot offer one, and by
        // D52 it does not need to -- so this is advisory: a key another
        // worker holds is left alone until its deadline.
        let Some(_held) = self.take_lease(key)? else {
            return Ok(Attempt::Deferred);
        };

        let staging = self.cache.staging(key, output_suffix(spec.output));
        let _ = std::fs::remove_file(&staging);

        let produced = produce(&task.recipe, &inputs, &task.parameters, &staging, self.host)
            .inspect_err(|_| {
                let _ = std::fs::remove_file(&staging);
            })?;

        let stored = self
            .cache
            .store(&staging)
            .map_err(|error| error.to_string())?;
        let milliseconds = u64::try_from(produced.duration.as_millis()).unwrap_or(u64::MAX);

        // Canonicalised *before* it is recorded, which is the one ordering
        // change M18 asks of a single-machine run. The published row
        // carries the canonical hash, so a worker whose publish was
        // dropped can tell at no cost whether the machine that got there
        // first means the same thing it does (D52).
        let meaning = self
            .cache
            .semantic(spec.output, &stored.path)
            .map_err(|error| error.to_string())?;
        let mine = meaning.hash;

        let recorded = self
            .cache
            .record(&Recording {
                key,
                step: &spec.name,
                output: &stored,
                canonical: mine,
                tools: &self.tool_summary(task),
                duration_ms: milliseconds,
                notes: &produced.notes,
            })
            .map_err(|error| error.to_string())?;

        // What the step said about its own work, then what reading its
        // output found. Both are notes about the same result and every
        // surface prints them together; the body's come first because they
        // are about how the result was arrived at.
        let notes = noticed(produced.notes, meaning.notes);

        // Whose answer stands. Rows are write-once, so if another machine
        // published this key first, its row is the one in force -- and
        // every machine, including this one, has to use it, or each worker
        // believes its own answer and the run disagrees with itself.
        let (output, canonical, superseded) = match recorded {
            Recorded::Fresh => (stored, mine, false),
            Recorded::Superseded { canonical: theirs } => {
                if theirs != mine {
                    self.note_divergence(Divergence {
                        node,
                        step: spec.name.clone(),
                        key,
                        ours: mine,
                        theirs,
                    });
                }
                // `record` wrote the store's row into the local index, so
                // this reads back *their* output, fetching it if it is a
                // tier down. Gone or refused leaves ours, which is still a
                // correct answer to the key.
                match self.cache.lookup(key).map_err(|error| error.to_string())? {
                    Some(entry) => (entry.output, theirs, true),
                    None => (stored, mine, false),
                }
            }
        };

        // Recorded here and nowhere else: this is the only moment the filled
        // command exists, and a step served from the cache will need it.
        //
        // Where another machine's answer is the one in force, its record is
        // the one that explains it, so that is adopted instead of writing
        // one about bytes that are no longer in force -- the same rule as a
        // cache hit, reached from the other side. If it has not landed yet,
        // ours is better than none.
        let adopted = superseded
            && self
                .prov
                .adopt(self.cache.objects(), key)
                .map_err(|error| error.to_string())?
                .is_some();
        if !adopted {
            self.remember(&Made {
                spec,
                task,
                key,
                inputs: &inputs,
                command: produced.command,
                bytes: output.hash,
                canonical,
                notes: &notes,
                duration_ms: milliseconds,
            })?;
        }

        Ok(Attempt::Done(StepResult {
            node,
            step: spec.name.clone(),
            outcome: Outcome::Ran,
            key,
            hash: output.hash,
            canonical,
            notes,
            output: output.path,
            duration: produced.duration,
        }))
    }

    /// Hold this key for the length of the step, so a twin waits.
    ///
    /// `None` when another node is already producing exactly this. That
    /// node is parked on the key rather than blocked on it: a worker left
    /// waiting here is a worker rayon counts as busy, and so a worker that
    /// cannot help the step it is waiting for (D27). It comes back when the
    /// claim is dropped, by which time the key is in the cache and it is a
    /// cache hit.
    fn claim(&self, key: StepKey, node: NodeId) -> Result<Option<Claim<'_>>, String> {
        let mut state = self.state.lock().map_err(|_| poisoned())?;
        if state.running.contains(&key) {
            state.parked.entry(key).or_default().push(node);
            return Ok(None);
        }
        state.running.insert(key);
        Ok(Some(Claim { runner: self, key }))
    }

    /// Hold this key against the other workers, or say it is taken.
    ///
    /// `None` means another worker holds it and this node should be
    /// deferred. An ordinary run -- no `--worker` -- never consults a
    /// lease at all: it is the only thing computing, so there is nothing to
    /// divide and no reason to pay a store read per step.
    fn take_lease(&self, key: StepKey) -> Result<Option<Leased<'_>>, String> {
        // An ordinary run, or a worker with no shared store: nothing to
        // divide, so no lease and no store read per step.
        let (Some(worker), Some(shared)) = (self.worker.as_ref(), self.cache.objects().shared())
        else {
            return Ok(Some(Leased {
                runner: self,
                held: None,
            }));
        };

        let now = prov::now();
        let deadline = now.saturating_add(i64::try_from(self.lease.as_secs()).unwrap_or(i64::MAX));
        match lease::acquire(shared, key, worker, deadline, now)
            .map_err(|error| error.to_string())?
        {
            lease::Claimed::Acquired { generation } => Ok(Some(Leased {
                runner: self,
                held: Some((key, generation)),
            })),
            lease::Claimed::Held { .. } => Ok(None),
        }
    }

    /// Put the deferred nodes back on the ready queue, after a wait.
    ///
    /// `false` when there is nothing left to come back for, which ends the
    /// run. The wait happens here, between scopes, with the pool drained
    /// -- see [`Patience`].
    fn rearm(&self, patience: &mut Patience) -> bool {
        {
            let Ok(state) = self.state.lock() else {
                return false;
            };
            if state.deferred.is_empty() {
                return false;
            }
        }

        // Released before the sleep, so that nothing holds the run's one
        // lock for thirty seconds.
        patience.wait();

        let Ok(mut state) = self.state.lock() else {
            return false;
        };
        let waiting = std::mem::take(&mut state.deferred);
        // They were waiting on another worker, and whatever they come back
        // as -- a hit, or work this one takes over -- that is what they
        // waited for.
        state.waited = state.waited.saturating_add(waiting.len());
        state.ready.extend(waiting);
        true
    }

    fn note_divergence(&self, divergence: Divergence) {
        if let Ok(mut state) = self.state.lock() {
            state.diverged.push(divergence);
        }
    }

    fn cached_result(
        &self,
        node: NodeId,
        spec: &StepSpec,
        key: StepKey,
        entry: &Entry,
    ) -> Result<StepResult, String> {
        let output = &entry.output;
        let outcome = {
            let upstream_ran = self
                .state
                .lock()
                .is_ok_and(|state| self.ran_above(&state, node));
            if upstream_ran {
                Outcome::Skipped
            } else {
                Outcome::Cached
            }
        };
        // Remembered with the hash, so a step served from the cache still
        // reports what was seen when its output was first read.
        let meaning = self
            .cache
            .semantic(spec.output, &output.path)
            .map_err(|error| error.to_string())?;

        // A hit this machine never computed has no local provenance, which
        // on a shared store is the normal case rather than an oddity: the
        // whole point is that somebody else ran it. Take their record
        // along with their output, or `ligase methods` can say nothing
        // about a pipeline that completed perfectly.
        if self
            .prov
            .lookup(key)
            .map_err(|error| error.to_string())?
            .is_none()
        {
            self.prov
                .adopt(self.cache.objects(), key)
                .map_err(|error| error.to_string())?;
        }

        Ok(StepResult {
            node,
            step: spec.name.clone(),
            outcome,
            key,
            hash: output.hash,
            canonical: meaning.hash,
            // Both kinds remembered rather than recomputed: a cache hit
            // neither reruns the body nor reopens the file, and a note that
            // stopped appearing on the second run would be worse than none.
            notes: noticed(entry.notes.clone(), meaning.notes),
            output: output.path.clone(),
            duration: Duration::ZERO,
        })
    }

    /// Each argument's files, by the parameter they fill.
    fn inputs(&self, node: NodeId) -> Result<Vec<(String, Vec<PathBuf>)>, String> {
        let state = self.state.lock().map_err(|_| poisoned())?;
        inputs_of(self.graph, node, &|from| {
            state
                .produced
                .get(&from)
                .map(|produced| produced.output.path.clone())
        })
    }

    fn key(
        &self,
        spec: &StepSpec,
        task: &Task,
        inputs: &[(String, Vec<PathBuf>)],
    ) -> Result<StepKey, String> {
        let mut hashed = Vec::with_capacity(inputs.len());
        // The arguments and the inputs are in the same order: the inputs
        // were built from the arguments.
        for (argument, (param, files)) in spec.arguments.iter().zip(inputs) {
            let kind = self
                .graph
                .dataset(argument.node)
                .map_or(argument.declared, Dataset::kind);
            let mut each = Vec::with_capacity(files.len());
            for file in files {
                each.push(
                    self.cache
                        // What a file means, not what bytes it holds (D4).
                        .semantic_hash(kind, file)
                        .map_err(|error| format!("`{param}`: {error}"))?,
                );
            }
            hashed.push((param.clone(), ContentHash::of_hashes(&each)));
        }

        let mut tools = Vec::with_capacity(task.tools.len());
        for tool in &task.tools {
            let version = self
                .versions
                .get(tool)
                .cloned()
                .unwrap_or_else(|| tool_version(tool))?;
            tools.push((tool.clone(), version));
        }

        Ok(Ingredients {
            step: spec.name.clone(),
            code: task.code.clone(),
            recipe: task.recipe.describe(),
            output: spec.output,
            parameters: task.parameters.clone(),
            inputs: hashed,
            tools,
        }
        .key())
    }

    /// Write down how this step produced what it just produced.
    ///
    /// Every hash here is already known to the cache — the inputs were
    /// hashed to build the key moments ago — so this costs lookups rather
    /// than reads.
    fn remember(&self, made: &Made<'_>) -> Result<(), String> {
        let mut inputs = Vec::new();
        let mut references = Vec::new();
        let mut remotes = Vec::new();

        // The arguments and the inputs are in the same order: the inputs
        // were built from the arguments.
        for (argument, (param, files)) in made.spec.arguments.iter().zip(made.inputs) {
            let dataset = self.graph.dataset(argument.node);
            let kind = dataset.map_or(argument.declared, Dataset::kind);

            for file in files {
                let bytes = self
                    .cache
                    .content_hash(file)
                    .map_err(|error| format!("`{param}`: {error}"))?;
                let canonical = self
                    .cache
                    .semantic_hash(kind, file)
                    .map_err(|error| format!("`{param}`: {error}"))?;
                inputs.push(InputRecord {
                    param: param.clone(),
                    kind,
                    path: file.clone(),
                    bytes,
                    canonical,
                });
            }

            // Where an input was fetched from, if it was fetched. A remote
            // the pipeline declared once but passed to three steps is
            // recorded against each of them, because a record is about one
            // computation; the methods report is what de-duplicates.
            if let Some(dataset) = dataset
                && let Some(origin) = dataset.origin()
            {
                remotes.push(origin.clone());
            }

            // A reference is pinned by what its own file says: the accession
            // in its defline and the checksum computed from its sequence.
            if kind == DataKind::Reference
                && let Some(dataset) = dataset
                && let Some(identity) = dataset.dimensions().reference.value()
                && let Some(path) = dataset.path()
            {
                references.push(prov::pin(param, path, identity));
            }
        }

        let mut tools = Vec::with_capacity(made.task.tools.len());
        for tool in &made.task.tools {
            if let Some(Ok(version)) = self.versions.get(tool) {
                tools.push((tool.clone(), version.clone()));
            }
        }

        self.prov
            .record(&Record {
                key: made.key,
                step: made.spec.name.clone(),
                code: made.task.code.clone(),
                command: made.command.clone(),
                output_kind: made.spec.output,
                output_bytes: made.bytes,
                output_canonical: made.canonical,
                output_notes: made.notes.to_vec(),
                parameters: made.task.parameters.clone(),
                inputs,
                references,
                remotes,
                tools,
                engine: crate::version().to_owned(),
                platform: prov::platform(),
                recorded_at: prov::now(),
                duration_ms: made.duration_ms,
            })
            .map_err(|error| error.to_string())?;

        // And into the store, beside the output it explains. A colleague
        // whose run takes this output from a shared bucket takes the
        // record with it, instead of a result nobody can write up
        // (`prov::shared`).
        self.prov
            .publish(self.cache.objects(), made.key)
            .map_err(|error| error.to_string())
    }

    fn tool_summary(&self, task: &Task) -> String {
        task.tools
            .iter()
            .map(|tool| match self.versions.get(tool) {
                Some(Ok(version)) => format!("{tool} {}", first_line(version)),
                _ => tool.clone(),
            })
            .collect::<Vec<_>>()
            .join("; ")
    }

    fn finish(self) -> RunReport {
        let Ok(state) = self.state.into_inner() else {
            return RunReport::default();
        };
        let mut results = state.results;
        let mut failures = state.failures;
        // Workers finish in whatever order the machine allows; a report that
        // changed between two identical runs would be a strange thing for a
        // reproducibility tool to print.
        results.sort_by_key(|result| result.node.index());
        failures.sort_by_key(|failure| failure.node.index());
        let mut diverged = state.diverged;
        diverged.sort_by_key(|divergence| divergence.node.index());
        RunReport {
            results,
            failures,
            store: self.cache.objects().stats(),
            refused: self.cache.objects().rejection(),
            worker: self.worker.map(|worker| worker.name().to_owned()),
            waited: state.waited,
            diverged,
        }
    }
}

/// A step key held against the other workers for the length of one step.
///
/// Given back on drop, **whether the step succeeded or failed**, because
/// either way this worker has stopped working on that key and saying so is
/// the honest state to leave behind.
///
/// Holding it after a success looked like a saving — the entry is there, so
/// every reader short-circuits before it ever probes a lease — and it was
/// wrong twice over. It leaves a live claim behind for a step nobody is
/// computing, which is a lie the store then tells for an hour; and
/// `--force`, which skips the entry by design, walks straight into it and
/// waits for a worker that finished long ago. One small row per step is
/// the right price for a lease state that is true.
///
/// `held` is `None` for an ordinary run and for a worker with no shared
/// store, neither of which takes a lease: the guard still exists so one
/// code path serves all three.
struct Leased<'a> {
    runner: &'a Runner<'a>,
    held: Option<(StepKey, u32)>,
}

impl Drop for Leased<'_> {
    fn drop(&mut self) {
        let Some((key, generation)) = self.held.take() else {
            return;
        };
        let Some(shared) = self.runner.cache.objects().shared() else {
            return;
        };
        // Nothing useful to do about a release that cannot be written: the
        // lease expires on its own deadline, which is the slower of the two
        // correct outcomes rather than a wrong one.
        let _ = lease::relinquish(shared, key, generation, prov::now());
    }
}

/// What one turn at a step came to.
enum Attempt {
    /// The step is finished, by running or straight from the cache.
    Done(StepResult),
    /// Another node in *this* run is producing this step's key, so this one
    /// is parked on it and will be started again once that key is free.
    Parked,
    /// Another **worker** holds this step's key. This one is deferred: it
    /// comes back on a timer, by which point the key is either in the
    /// store or free again (D53).
    Deferred,
}

/// What a step just produced, as a provenance record wants it.
struct Made<'a> {
    spec: &'a StepSpec,
    task: &'a Task,
    key: StepKey,
    inputs: &'a [(String, Vec<PathBuf>)],
    command: Option<String>,
    bytes: ContentHash,
    canonical: ContentHash,
    notes: &'a [Note],
    duration_ms: u64,
}

/// A key held for the length of one step.
struct Claim<'a> {
    runner: &'a Runner<'a>,
    key: StepKey,
}

impl Drop for Claim<'_> {
    fn drop(&mut self) {
        if let Ok(mut state) = self.runner.state.lock() {
            state.running.remove(&self.key);
            // Whoever was waiting for this key can go now. They are put
            // back on the ready queue rather than woken, because the step
            // that just finished is the one that starts them -- which is
            // why the queue never needs waiting on.
            if let Some(waiting) = state.parked.remove(&self.key) {
                state.ready.extend(waiting);
            }
        }
    }
}

fn poisoned() -> String {
    "the run was left locked by a panicking step".to_owned()
}

fn first_line(text: &str) -> &str {
    text.lines().next().unwrap_or(text).trim()
}

// --------------------------------------------------------- the command --

/// Run a command through the shell, as written.
fn shell(command: &str) -> Result<(), String> {
    let output = Command::new("sh")
        .arg("-c")
        .arg(command)
        .output()
        .map_err(|error| format!("the command could not be started: {error}"))?;

    if output.status.success() {
        return Ok(());
    }

    let code = output
        .status
        .code()
        .map_or_else(|| "a signal".to_owned(), |code| code.to_string());
    let mut message = format!("the command failed with exit status {code}");
    for stream in [&output.stderr, &output.stdout] {
        let text = String::from_utf8_lossy(stream);
        let text = text.trim();
        if !text.is_empty() {
            message.push('\n');
            message.push_str(text);
        }
    }
    Err(message)
}

/// Fill a command's placeholders.
///
/// `{name}` is an input or a parameter, `{name.r1}` and `{name.r2}` the
/// mates of a paired input, and `{out}` the file the step must write. A
/// literal brace is written `{{` or `}}`, which is what an `awk '{{print}}'`
/// needs; without the escape there is no way to tell an awk program from a
/// placeholder, and a silently mistyped placeholder is worse than a rule.
///
/// Every substituted value becomes exactly one shell word, whatever is in
/// it: a path with a space in it is a path, not two arguments.
fn fill_template(
    template: &str,
    inputs: &[(String, Vec<PathBuf>)],
    parameters: &[(String, String)],
    out: &Path,
) -> Result<String, String> {
    let mut command = String::with_capacity(template.len());
    let mut rest = template;

    while let Some(at) = rest.find(['{', '}']) {
        command.push_str(&rest[..at]);
        let after = &rest[at..];
        let brace = &after[..1];
        let inside = &after[1..];

        // A doubled brace is a literal one.
        if inside.starts_with(brace) {
            command.push_str(brace);
            rest = &inside[1..];
            continue;
        }
        if brace == "}" {
            return Err(unbalanced(template));
        }

        let Some(end) = inside.find('}') else {
            return Err(unbalanced(template));
        };
        let name = &inside[..end];
        if !is_name(name) {
            return Err(unbalanced(template));
        }
        command.push_str(&quote(&resolve(name, inputs, parameters, out)?));
        rest = &inside[end + 1..];
    }

    command.push_str(rest);
    Ok(command)
}

/// Whether what sits between braces is meant to be a placeholder at all.
///
/// An `awk '{print $1}'` is not a mistyped placeholder, so it is not
/// reported as one -- it is reported as a brace that needs escaping, which
/// is the thing the user has to change either way.
fn is_name(text: &str) -> bool {
    !text.is_empty()
        && text
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
}

fn unbalanced(template: &str) -> String {
    format!(
        "this command has a `{{` that is not a placeholder; write `{{{{` and `}}}}` for \
         literal braces, as an `awk '{{{{print $1}}}}'` needs: {template}"
    )
}

fn resolve(
    name: &str,
    inputs: &[(String, Vec<PathBuf>)],
    parameters: &[(String, String)],
    out: &Path,
) -> Result<String, String> {
    if name == "out" {
        return Ok(out.to_string_lossy().into_owned());
    }

    let (base, field) = match name.split_once('.') {
        Some((base, field)) => (base, Some(field)),
        None => (name, None),
    };

    if let Some((_, files)) = inputs.iter().find(|(param, _)| param == base) {
        let first = || {
            files
                .first()
                .map(|path| path.to_string_lossy().into_owned())
                .ok_or_else(|| format!("`{{{name}}}`: `{base}` has no file behind it"))
        };
        return match field {
            None | Some("r1") => first(),
            Some("r2") => files
                .get(1)
                .map(|path| path.to_string_lossy().into_owned())
                .ok_or_else(|| {
                    format!(
                        "`{{{name}}}`: `{base}` is a single-end sample, so it has no second mate"
                    )
                }),
            Some(other) => Err(format!(
                "`{{{name}}}`: an input has `r1` and `r2`, not `{other}`"
            )),
        };
    }

    if field.is_none()
        && let Some((_, value)) = parameters.iter().find(|(param, _)| param == base)
    {
        return Ok(value.clone());
    }

    let mut known: Vec<&str> = inputs.iter().map(|(param, _)| param.as_str()).collect();
    known.extend(parameters.iter().map(|(param, _)| param.as_str()));
    known.push("out");
    known.sort_unstable();
    Err(format!(
        "`{{{name}}}` is not a parameter of this step; it has {}",
        known.join(", ")
    ))
}

/// The store's own lines in a run report, if it did anything.
fn store_lines(report: &RunReport) -> Vec<String> {
    let store = report.store;
    if store.quiet() && report.refused.is_none() {
        return Vec::new();
    }

    let mut lines = vec![String::new()];
    if store.fetched > 0 {
        lines.push(format!(
            "store     {} from the remote store",
            plural_count(store.fetched, "object")
        ));
    }
    if store.pushed > 0 {
        lines.push(format!(
            "store     {} written through to it",
            plural_count(store.pushed, "object")
        ));
    }
    if let Some(refused) = &report.refused {
        lines.push(format!("refused   {refused}"));
        if store.rejected > 1 {
            lines.push(format!(
                "refused   and {} further {}",
                store.rejected - 1,
                if store.rejected == 2 {
                    "object"
                } else {
                    "objects"
                }
            ));
        }
        lines.push("          the steps that produced them have been run again".to_owned());
    }
    if store.unreachable > 0 {
        lines.push(format!(
            "store     {} to the remote store did not answer, so this run \
             used the local",
            plural_count(store.unreachable, "call")
        ));
        lines.push(
            "          store alone. Nothing here is wrong; work that a \
             colleague had"
                .to_owned(),
        );
        lines.push(
            "          already done may have been done again. \
             `ligase store push` sends"
                .to_owned(),
        );
        lines.push("          this run's objects up once it is back.".to_owned());
    }
    lines
}

/// Which worker this was, what it waited for, and what it disagreed about.
///
/// Empty for an ordinary run — which is every run that did not ask to be
/// one of several — because a report must not grow a line for a feature the
/// run did not use.
fn worker_lines(report: &RunReport) -> Vec<String> {
    let Some(worker) = &report.worker else {
        return Vec::new();
    };

    let counts = report.counts();
    let mut parts = Vec::new();
    if counts.ran > 0 {
        parts.push(format!("{} ran here", counts.ran));
    }
    // Steps this worker waited on are cache hits like any other, so the
    // hits it did not wait for are what is left. "Four came from the
    // cache" and "four were computed by somebody else while I waited" are
    // different news, and a worker's report should give the second.
    let unwaited = (counts.cached + counts.skipped).saturating_sub(report.waited);
    if unwaited > 0 {
        parts.push(format!("{unwaited} from the store"));
    }
    if report.waited > 0 {
        parts.push(format!("{} waited for other workers", report.waited));
    }

    let mut lines = vec![String::new()];
    if parts.is_empty() {
        lines.push(format!("worker    {worker}: nothing to do"));
    } else {
        lines.push(format!("worker    {worker}: {}", parts.join(", ")));
    }

    // The one event in a distributed run a user has to read rather than
    // count. Named rather than totalled, because the question after
    // "something diverged" is always "which step".
    for divergence in &report.diverged {
        lines.push(String::new());
        lines.push(format!(
            "diverged  `{}` was computed by another worker to a different result",
            divergence.step
        ));
        lines.push(format!("          this run made  {}", divergence.ours));
        lines.push(format!("          the store holds {}", divergence.theirs));
        lines.push(
            "          The store's answer is the one in force, here and              everywhere, so"
                .to_owned(),
        );
        lines.push(
            "          nothing below this step disagrees between              machines. But the step"
                .to_owned(),
        );
        lines.push(
            "          does not produce one answer from one set of              inputs: either its"
                .to_owned(),
        );
        lines.push(
            "          canonical form does not fix its result, or its              tool is stochastic"
                .to_owned(),
        );
        lines.push(
            "          in something other than its seed -- a thread              count, most often."
                .to_owned(),
        );
        lines.push("          `ligase audit` is how to find out which.".to_owned());
    }

    lines
}

/// `1 object`, `3 objects`.
fn plural_count(count: u64, word: &str) -> String {
    if count == 1 {
        format!("{count} {word}")
    } else {
        format!("{count} {word}s")
    }
}

/// One shell word, whatever is in it.
fn quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', r"'\''"))
}

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

/// One line summarising a run.
///
/// Counts places rather than names, for the same reason a check summary
/// does (D15): one written step is many steps under fan-out.
#[must_use]
pub fn summarise(report: &RunReport) -> String {
    let counts = report.counts();
    let steps = counts.ran + counts.cached + counts.skipped + counts.failed;
    if steps == 0 {
        return "nothing to run.".to_owned();
    }

    let mut parts = Vec::new();
    if counts.ran > 0 {
        parts.push(format!("{} ran", counts.ran));
    }
    if counts.cached > 0 {
        parts.push(format!("{} from cache", counts.cached));
    }
    if counts.skipped > 0 {
        parts.push(format!("{} skipped", counts.skipped));
    }
    if counts.failed > 0 {
        parts.push(format!("{} failed", counts.failed));
    }

    format!("{steps} {}: {}.", plural(steps, "step"), parts.join(", "))
}

/// The whole run as the command line prints it.
///
/// A step that ran gets its own line, with what it cost. Steps that did not
/// are grouped by what happened to them and their samples are *named*
/// rather than counted, because a user who has to expand something to find
/// out which samples were cached has a shorter report rather than a better
/// one — the same rule the check report follows (D15).
#[must_use]
pub fn render(graph: &Graph, roots: &[NodeId], report: &RunReport) -> String {
    let scopes = graph.scopes(roots);
    let mut lines = Vec::new();

    // Steps that ran, in graph order, each with its own cost. The costs
    // line up, because reading down a column is how a user finds the step
    // that took the night.
    let ran: Vec<(String, String)> = report
        .results
        .iter()
        .filter(|result| result.outcome == Outcome::Ran)
        .map(|result| {
            (
                format!(
                    "{}{}",
                    quoted(&result.step),
                    scope_suffix(scopes.get(&result.node))
                ),
                duration(result.duration),
            )
        })
        .collect();
    let widest = ran.iter().map(|(label, _)| label.len()).max().unwrap_or(0);
    for (label, cost) in &ran {
        lines.push(format!("ran       {label:<widest$}   {cost}"));
    }

    // Steps that did not, gathered by name and outcome.
    for wanted in [Outcome::Cached, Outcome::Skipped] {
        let mut groups: Vec<(String, Vec<String>)> = Vec::new();
        for result in report
            .results
            .iter()
            .filter(|result| result.outcome == wanted)
        {
            let samples = scopes
                .get(&result.node)
                .map(|scope| scope.value.clone())
                .into_iter()
                .collect::<Vec<String>>();
            match groups.iter_mut().find(|(step, _)| *step == result.step) {
                Some((_, seen)) => seen.extend(samples),
                None => groups.push((result.step.clone(), samples)),
            }
        }

        for (step, samples) in groups {
            let label = match wanted {
                Outcome::Skipped => "skipped  ",
                _ => "cached   ",
            };
            lines.push(match samples.as_slice() {
                [] => format!("{label} {}", quoted(&step)),
                [one] => format!("{label} {} ({one})", quoted(&step)),
                many => format!("{label} {} for {}", quoted(&step), many.join(", ")),
            });
        }
    }

    // What the store did. Nothing at all when no remote tier was
    // configured, because a report must not grow a line for a feature the
    // run did not use -- but when one was, every one of these is something
    // a user would otherwise have to infer from how long the run took.
    //
    // The `unreachable` line is the important one. A run that recomputed
    // for an hour because a bucket was briefly away is not *wrong*, and a
    // user who is not told is misled.
    lines.extend(store_lines(report));

    // Who this was, and what the other workers did for it. Nothing at all
    // for an ordinary run, by the same rule as the store lines.
    lines.extend(worker_lines(report));

    // What the outputs' canonical forms noticed. Not failures: every one of
    // these steps ran and its result stands. They are here because the fix
    // is in the pipeline and a user cannot make it without being told
    // (D26), and before the failures because a failure is the thing to read
    // first.
    let noted: Vec<(&StepResult, &Note)> = report
        .results
        .iter()
        .flat_map(|result| result.notes.iter().map(move |note| (result, note)))
        .collect();
    if !noted.is_empty() {
        lines.push(String::new());
        for (result, note) in &noted {
            lines.push(format!(
                "noticed   {}{}: {note}",
                quoted(&result.step),
                scope_suffix(scopes.get(&result.node))
            ));
        }
        // Said once per kind, not once per step: four samples named after
        // four files have one thing wrong with them (D15).
        let mut given: Vec<&str> = Vec::new();
        for (_, note) in &noted {
            if !given.contains(&note.code()) {
                given.push(note.code());
                lines.push(format!("          {}", note.advice()));
            }
        }
    }

    // Where this run's inputs came from, which for a query is the whole
    // question: "it worked" and "it worked without asking anybody" are
    // different statements, and D39 asks that the report always say which
    // of the two this was.
    let mut remotes: Vec<(&Origin, &[Note])> = Vec::new();
    for node in graph.reachable_nodes(roots) {
        if let Some(dataset) = graph.dataset(node)
            && let Some(origin) = dataset.origin()
            && !remotes
                .iter()
                .any(|(held, _)| held.locator == origin.locator)
        {
            remotes.push((origin, dataset.notes()));
        }
    }
    if !remotes.is_empty() {
        lines.push(String::new());
        for (origin, notes) in remotes {
            let what = match origin.verdict {
                RemoteVerdict::Pinned => format!("pinned, fetched {}", day(origin.fetched_at)),
                RemoteVerdict::Replayed => {
                    format!("replayed from record of {}", day(origin.fetched_at))
                }
                RemoteVerdict::Live => format!("answered live on {}", day(origin.fetched_at)),
            };
            lines.push(format!("input     {} -- {what}", quoted(&origin.locator)));
            // What resolving it noticed: drift a refresh found, a field
            // dropped from a recorded response, a source that rewrote a
            // pinned file. Printed here rather than in the `noticed` block
            // above, which is about what a *step* saw in its own output.
            for note in notes {
                lines.push(format!("          {note}"));
            }
        }
    }

    for failure in &report.failures {
        lines.push(String::new());
        lines.push(format!(
            "{}{} failed:",
            quoted(&failure.step),
            scope_suffix(scopes.get(&failure.node))
        ));
        for line in failure.message.lines() {
            lines.push(format!("  {line}"));
        }
    }

    if !lines.is_empty() {
        lines.push(String::new());
    }
    lines.push(summarise(report));
    lines.join("\n")
}

/// How a step whose name is ambiguous is told apart, where it is.
fn scope_suffix(scope: Option<&crate::check::Scope>) -> String {
    scope.map_or_else(String::new, |scope| {
        format!(" ({} {})", scope.kind, scope.value)
    })
}

fn quoted(step: &str) -> String {
    format!("`{step}`")
}

/// A duration as a reader wants it, not as a float.
fn duration(elapsed: Duration) -> String {
    let seconds = elapsed.as_secs_f64();
    if seconds < 1.0 {
        return format!("{}ms", elapsed.as_millis());
    }
    if seconds < 60.0 {
        return format!("{seconds:.1}s");
    }
    let whole = elapsed.as_secs();
    format!("{}m {}s", whole / 60, whole % 60)
}

fn plural(count: usize, word: &str) -> String {
    if count == 1 {
        word.to_owned()
    } else {
        format!("{word}s")
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use super::*;

    fn inputs() -> Vec<(String, Vec<PathBuf>)> {
        vec![
            ("ref".into(), vec![PathBuf::from("/refs/HXB2.fasta")]),
            (
                "reads".into(),
                vec![PathBuf::from("/data/s_1.fq"), PathBuf::from("/data/s_2.fq")],
            ),
        ]
    }

    fn parameters() -> Vec<(String, String)> {
        vec![("min_freq".into(), "0.01".into())]
    }

    fn fill(template: &str) -> Result<String, String> {
        fill_template(
            template,
            &inputs(),
            &parameters(),
            Path::new("/tmp/out.bam"),
        )
    }

    #[test]
    fn an_input_a_mate_a_parameter_and_the_output_are_filled_in() {
        assert_eq!(
            fill("minimap2 -ax sr {ref} {reads.r1} {reads.r2} -f {min_freq} -o {out}").unwrap(),
            "minimap2 -ax sr '/refs/HXB2.fasta' '/data/s_1.fq' '/data/s_2.fq' \
             -f '0.01' -o '/tmp/out.bam'"
        );
    }

    #[test]
    fn an_input_without_a_mate_named_is_its_first_file() {
        assert_eq!(fill("cat {reads}").unwrap(), "cat '/data/s_1.fq'");
    }

    #[test]
    fn a_doubled_brace_is_a_literal_one() {
        assert_eq!(
            fill("awk '{{print $1}}' {ref}").unwrap(),
            "awk '{print $1}' '/refs/HXB2.fasta'"
        );
    }

    #[test]
    fn an_unknown_placeholder_lists_what_the_step_does_have() {
        let error = fill("cat {refrence}").unwrap_err();
        assert!(error.contains("refrence"), "{error}");
        assert!(error.contains("min_freq"), "{error}");
        assert!(error.contains("ref"), "{error}");
    }

    #[test]
    fn an_unmatched_brace_says_how_to_write_a_literal_one() {
        assert!(fill("awk '{print $1}' {ref}").unwrap_err().contains("{{"));
        assert!(fill("cat {ref").unwrap_err().contains("{{"));
    }

    #[test]
    fn a_single_end_sample_asked_for_a_second_mate_says_so() {
        let single = vec![("reads".to_owned(), vec![PathBuf::from("/data/s.fq")])];
        let error =
            fill_template("cat {reads.r2}", &single, &[], Path::new("/tmp/out")).unwrap_err();
        assert!(error.contains("single-end"), "{error}");
    }

    #[test]
    fn a_value_with_a_space_in_it_stays_one_word() {
        let spaced = vec![("ref".to_owned(), vec![PathBuf::from("/my refs/HXB2.fa")])];
        assert_eq!(
            fill_template("cat {ref}", &spaced, &[], Path::new("/tmp/out")).unwrap(),
            "cat '/my refs/HXB2.fa'"
        );
    }

    #[test]
    fn a_quote_in_a_value_cannot_end_the_quoting() {
        let nasty = vec![("ref".to_owned(), vec![PathBuf::from("/refs/it's.fa")])];
        assert_eq!(
            fill_template("cat {ref}", &nasty, &[], Path::new("/tmp/out")).unwrap(),
            r"cat '/refs/it'\''s.fa'"
        );
    }

    #[test]
    fn a_callback_enters_the_key_as_itself_rather_than_as_its_number() {
        assert_eq!(
            Recipe::Callback(1).describe(),
            Recipe::Callback(2).describe()
        );
        assert_ne!(
            Recipe::Shell("a".into()).describe(),
            Recipe::Shell("b".into()).describe()
        );
    }

    // ------------------------------------------------ version probes --
    //
    // Over `version_from` rather than over installed tools, so every
    // refusal is tested on a machine that has none of them. The one test
    // that does need a tool is in `tests/versions.rs`.

    #[test]
    fn the_usual_tool_answers_on_stdout_and_is_kept_whole() {
        let version = version_from(
            "samtools",
            &DEFAULT_PROBE,
            true,
            "samtools 1.24\nUsing htslib 1.24\n",
            "",
        )
        .unwrap();

        // Both lines: the htslib a samtools was built against changes
        // results, so dropping it would be dropping part of the version.
        assert_eq!(version, "samtools 1.24\nUsing htslib 1.24");
    }

    #[test]
    fn a_tool_that_prints_only_to_stderr_is_still_read() {
        assert_eq!(
            version_from("tool", &DEFAULT_PROBE, true, "", "tool 2.0\n").unwrap(),
            "tool 2.0"
        );
    }

    #[test]
    fn a_probe_that_fails_unexpectedly_is_an_error_and_not_a_version() {
        // This is the defect the probe table exists for: `bwa --version`
        // exits non-zero and complains, and that complaint used to be
        // recorded as bwa's version -- identically for every release, so
        // upgrading the aligner moved no cache key at all.
        let error = version_from(
            "bwa",
            &DEFAULT_PROBE,
            false,
            "",
            "[main] unrecognized command '--version'\n",
        )
        .unwrap_err();

        assert!(error.contains("failed"), "{error}");
        assert!(error.contains("unrecognized command"), "{error}");
        assert!(
            error.contains("would not move a single cache key"),
            "the message has to say why a wrong version is worse than a \
             missing one: {error}"
        );
    }

    #[test]
    fn a_probe_that_was_expected_to_fail_is_read_anyway() {
        let probe = probe_for("bwa");
        assert!(probe.failure_expected, "bwa's probe exits non-zero");

        let version = version_from(
            "bwa",
            &probe,
            false,
            "",
            "\nProgram: bwa (alignment via Burrows-Wheeler transformation)\n\
             Version: 0.7.19-r1273\n\
             Contact: Heng Li <hli@ds.dfci.harvard.edu>\n\n\
             Usage:   bwa <command> [options]\n",
        )
        .unwrap();

        // The banner's other lines are not a version. A contact address
        // hashed into a cache key is noise that never changes; the command
        // list is noise that changes when the usage text is reworded.
        assert_eq!(version, "Version: 0.7.19-r1273");
    }

    #[test]
    fn a_probe_whose_marker_has_gone_is_an_error_rather_than_a_banner() {
        let error = version_from(
            "bwa",
            &probe_for("bwa"),
            false,
            "",
            "Usage: bwa <command> [options]\n",
        )
        .unwrap_err();

        assert!(error.contains("no line containing `Version:`"), "{error}");
        assert!(error.contains("version-probe table"), "{error}");
    }

    #[test]
    fn a_probe_that_prints_nothing_is_an_error() {
        let error = version_from("tool", &DEFAULT_PROBE, true, "", "").unwrap_err();
        assert_eq!(error, "`tool --version` printed nothing");
    }

    #[test]
    fn a_probe_with_no_arguments_is_quoted_as_the_bare_command() {
        assert_eq!(describe_probe("bwa", &probe_for("bwa")), "bwa");
        assert_eq!(
            describe_probe("samtools", &DEFAULT_PROBE),
            "samtools --version"
        );
    }
}