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
//! The cache: what has been computed, and what it produced.
//!
//! Two pieces, both under one directory (`.ligase/` by default).
//!
//! **A content-addressed store.** An output's name is the BLAKE3 hash of its
//! bytes, so two steps that produced identical results hold one object
//! between them and an object's name is a claim that can be checked. Stored
//! objects are read-only: the store is the cache's evidence, and a step that
//! wrote back through one would invalidate every key derived from it without
//! anything noticing.
//!
//! **SQLite metadata** (D6). Zero-config, embedded, portable, and readable
//! with `sqlite3` when a result needs explaining — which for a tool whose
//! whole purpose is reproducibility is worth more than a faster key-value
//! store.
//!
//! # The prefilter
//!
//! Hashing every input on every run is what makes content addressing honest,
//! and on a 40 GB BAM it is also what makes it slow. So a file's size and
//! mtime are remembered beside its hash, and a file whose size and mtime are
//! unchanged is not read again (D3). Note what this does and does not claim:
//! a *match* skips work, a *mismatch* only causes a rehash. The hash itself
//! is never taken from a timestamp, so the pathological case — a file
//! rewritten in place within the same mtime granularity, with the same
//! length — is the only one that can mislead, and `--force` exists for it.

use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use rusqlite::{Connection, OptionalExtension, params};

use crate::canon::{self, CANON_VERSION, Canonical, Form, Note};
use crate::hash::ContentHash;
use crate::key::{KEY_VERSION, StepKey};
use crate::remote::request::Method;
use crate::store::published::{self, REMOTES, STEPS};
use crate::store::{BlobStore, ObjectKey, StoreError, TieredStore, suffix_of as suffix};
use crate::types::DataKind;

/// The version of the on-disk layout of the cache directory.
///
/// A directory written by another version is discarded rather than read:
/// everything in it can be recomputed, so there is nothing to migrate and
/// nothing to lose.
///
/// 2 added the `notes` column, for what canonicalising a file noticed
/// (D26). 3 added one to `steps`, for what a step noticed about its own
/// work (D32). 4 added the `remotes` table, for what was fetched from
/// where (D39). 5 added the `records` table beside it, for a recorded
/// query -- a separate table rather than a flag, because a pinned remote's
/// record is replaced and a query's must never be.
const SCHEMA_VERSION: u32 = 5;

/// An output held in the store.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stored {
    /// The hash of its contents, which is also its name.
    pub hash: ContentHash,
    /// Where it sits in the store.
    pub path: PathBuf,
}

/// What a step's cache entry remembers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
    /// The output it produced.
    pub output: Stored,
    /// How long the step took when it did run, in milliseconds.
    pub duration_ms: u64,
    /// What the step noticed about its own work ([`Note`]).
    ///
    /// Empty for almost every step, and for every shell step: only a body
    /// can say what its work rested on. Stored rather than recomputed,
    /// because a cache hit does not rerun the body and a hedge that stopped
    /// appearing on the second run would be worse than none (D32).
    pub notes: Vec<Note>,
}

/// What one step produced, as the cache wants to be told it.
///
/// One struct rather than eight arguments, on `exec::Made`'s precedent: a
/// call with eight positional arguments of which three are strings is a
/// call that can be got wrong silently.
#[derive(Clone, Copy, Debug)]
pub struct Recording<'a> {
    /// The step's cache key.
    pub key: StepKey,
    /// The step's name, for a human reading the index.
    pub step: &'a str,
    /// The output it produced, in the store.
    pub output: &'a Stored,
    /// What that output *means* ([`crate::canon`]).
    ///
    /// Published with the row, so another worker that computed the same key
    /// can tell a difference of bytes from a difference of result (D52).
    pub canonical: ContentHash,
    /// The tools and versions it ran with, as one line.
    pub tools: &'a str,
    /// How long it took.
    pub duration_ms: u64,
    /// What it noticed about its own work ([`Note`]).
    pub notes: &'a [Note],
}

/// What the store turned out to hold when a step was recorded.
///
/// On one machine this is always [`Fresh`](Self::Fresh) and there is
/// nothing to think about. On a shared store another worker may have
/// published the same key first, and because rows are write-once **its**
/// answer is the one in force — so a worker has to be told, both to use
/// the right output and to notice the one case where the two answers do not
/// mean the same thing (D52).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Recorded {
    /// Nothing else had published this key, or what was there was
    /// identical. The local index holds this run's own answer.
    Fresh,
    /// Another machine published first. The local index now holds **its**
    /// answer, so a [`lookup`](Cache::lookup) returns what the store says,
    /// and this is the canonical hash that answer has.
    ///
    /// Equal to the caller's own canonical hash in the ordinary case: two
    /// workers whose bytes differ because a tool wrote its command line or
    /// a timestamp into them still agree about what the output *means*,
    /// which is what every downstream key is built on. Unequal is the case
    /// worth reporting.
    Superseded {
        /// What the store's answer means.
        canonical: ContentHash,
    },
}

/// A published `steps` row, read back.
struct StepRow<'a> {
    fields: &'a [String],
    canonical: ContentHash,
}

/// Read a published `steps` row, or nothing if this build cannot.
fn read_step_row(fields: &[String]) -> Option<StepRow<'_>> {
    let [_hash, _suffix, _duration, _notes, canonical] = fields else {
        return None;
    };
    Some(StepRow {
        fields,
        canonical: ContentHash::parse(canonical)?,
    })
}

/// One object a remote resolved to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteFile {
    /// Its name in the store.
    pub key: ObjectKey,
    /// The URL that answered, after any redirects — which is not the
    /// locator, and is worth keeping precisely because it can differ.
    pub url: String,
    /// How many bytes arrived.
    pub bytes: u64,
}

/// What a past fetch produced.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteRow {
    /// The digest of what the files *mean*, folded over them in order —
    /// which is what a pin is compared against (D4, D21).
    pub digest: ContentHash,
    /// The digest of their *bytes*, folded the same way.
    ///
    /// Kept beside the other so that a source which rewrote a file without
    /// changing its meaning can be noticed rather than either ignored or
    /// treated as a failure.
    pub bytes: ContentHash,
    /// The objects, in order. Mate order for a paired run.
    pub files: Vec<RemoteFile>,
    /// When it was fetched, as seconds since the epoch.
    pub fetched_at: i64,
}

/// One recorded response to one query.
///
/// Identified by the hash of its canonical request, so a step making twenty
/// paginated calls writes twenty of these and finds them again whatever
/// order it asks in next time (D39).
///
/// Note what is **not** here: no request headers, so no `Authorization`
/// token. The transport's [`crate::remote::fetch::Fetched`] has no field
/// for one and neither does this, which is how "a bundle never carries a
/// secret" survives a later field being added by someone who has not read
/// D39.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryRecord {
    /// The hash of the canonical request, which is this record's identity.
    pub request: ContentHash,
    /// Which recording of that request this is: 1, then 2 for the first
    /// refresh, and so on.
    ///
    /// The revision rather than the date is what makes a record unique,
    /// because two records a second apart must still be two records and a
    /// clock is the wrong thing to rest that on.
    pub revision: u32,
    /// When it was recorded, as seconds since the epoch. What "a new dated
    /// record" and "replayed from record of <date>" both read.
    pub recorded_at: i64,
    /// The locator as the pipeline wrote it.
    pub locator: String,
    /// How the body is read.
    pub kind: DataKind,
    /// The method that was used, which is part of the identity and is kept
    /// so a record can be explained as well as found.
    pub method: Method,
    /// The URL that answered, after any redirects — not the locator, and
    /// worth keeping precisely because it can differ.
    pub url: String,
    /// The status it answered with. Always a success: a record of a failure
    /// would replay the failure forever as though it were an answer.
    pub status: u16,
    /// The canonical response body, in the blob store.
    pub body: ObjectKey,
    /// The digest of what the body *means*, read as `kind`, which is what
    /// enters a step key.
    pub digest: ContentHash,
    /// What canonicalising the response noticed: a field dropped from it.
    pub notes: Vec<Note>,
}

/// How much work the prefilter saved.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CacheStats {
    /// Files read and hashed.
    pub hashed: u64,
    /// Files whose hash was already known from their size and mtime.
    pub prefiltered: u64,
    /// Files parsed to find what they mean, rather than only read.
    pub canonicalised: u64,
}

/// Why the cache could not do something.
#[derive(Debug)]
pub enum CacheError {
    /// The cache directory could not be read or written.
    Io {
        /// What was being read or written.
        path: PathBuf,
        /// The underlying failure.
        source: io::Error,
    },
    /// The metadata database could not be read or written.
    Database(rusqlite::Error),
    /// A thread holding the database panicked.
    Poisoned,
    /// The blob tier could not hold or produce an object.
    Store(StoreError),
}

impl fmt::Display for CacheError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::Database(error) => write!(f, "cache metadata: {error}"),
            Self::Poisoned => f.write_str("the cache was left locked by a panicking thread"),
            Self::Store(error) => error.fmt(f),
        }
    }
}

impl std::error::Error for CacheError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Database(error) => Some(error),
            Self::Poisoned => None,
            Self::Store(error) => Some(error),
        }
    }
}

impl From<rusqlite::Error> for CacheError {
    fn from(error: rusqlite::Error) -> Self {
        Self::Database(error)
    }
}

impl From<StoreError> for CacheError {
    fn from(error: StoreError) -> Self {
        Self::Store(error)
    }
}

/// Everything already computed, and where it was put.
#[derive(Debug)]
pub struct Cache {
    root: PathBuf,
    objects: TieredStore,
    database: Mutex<Connection>,
    hashed: AtomicU64,
    prefiltered: AtomicU64,
    canonicalised: AtomicU64,
}

impl Cache {
    /// Open the cache at `root`, creating it if it is not there.
    ///
    /// A cache written by another version of the layout, or holding keys
    /// from another key format, is cleared rather than read: both describe
    /// work that was combined differently, and all of it can be recomputed.
    ///
    /// # Errors
    ///
    /// If the directory cannot be created or the database cannot be opened.
    pub fn open(root: &Path) -> Result<Self, CacheError> {
        Self::open_with(root, crate::store::configured().as_deref())
    }

    /// The same, with the remote tier named directly.
    ///
    /// [`open`](Self::open) reads `LIGASE_STORE`, which is what the CLI
    /// wants: one variable configures every entry point. This is for a
    /// caller that has the URL in its hand already — a test, above all,
    /// which must be able to point at a store without touching a
    /// process-wide variable every other test is reading.
    ///
    /// # Errors
    ///
    /// As [`open`](Self::open), and if the store URL cannot be opened.
    pub fn open_with(root: &Path, store: Option<&str>) -> Result<Self, CacheError> {
        create_dir(root)?;
        let objects = TieredStore::open(&root.join("store"), store)?;
        create_dir(&root.join("tmp"))?;

        let database = Connection::open(root.join("cache.sqlite")).map_err(CacheError::from)?;
        // WAL so a reader and a writer do not block each other, and a
        // timeout so workers contending for the same row wait rather than
        // fail.
        database.pragma_update(None, "journal_mode", "WAL")?;
        database.busy_timeout(std::time::Duration::from_secs(30))?;
        prepare(&database)?;

        Ok(Self {
            root: root.to_path_buf(),
            objects,
            database: Mutex::new(database),
            hashed: AtomicU64::new(0),
            prefiltered: AtomicU64::new(0),
            canonicalised: AtomicU64::new(0),
        })
    }

    /// The directory this cache lives in.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// How much work the prefilter has saved since this cache was opened.
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        CacheStats {
            hashed: self.hashed.load(Ordering::Relaxed),
            prefiltered: self.prefiltered.load(Ordering::Relaxed),
            canonicalised: self.canonicalised.load(Ordering::Relaxed),
        }
    }

    /// What a file *means*, as the hash a cache key is built from (D4).
    ///
    /// The canonical form of a file read as `kind`, which is what two runs
    /// are compared on: records sorted, volatile headers stripped
    /// ([`crate::canon`]).
    ///
    /// Remembered against the hash of the file's bytes rather than against
    /// its path, because that is what it is a fact about — so a file moved,
    /// copied or produced again identically is not parsed twice, and a
    /// second run of a pipeline reads nothing at all.
    ///
    /// # Errors
    ///
    /// If the file cannot be read, or the metadata cannot be written. A
    /// file that reads but does not parse is not an error: its bytes stand
    /// in for its meaning.
    pub fn semantic_hash(&self, kind: DataKind, path: &Path) -> Result<ContentHash, CacheError> {
        Ok(self.semantic(kind, path)?.hash)
    }

    /// The same, with how it was arrived at and what it noticed.
    ///
    /// For a caller that has somewhere to put a [`Note`] — a run report, a
    /// provenance record, a bundle. Notes are remembered with the hash, so
    /// a file served from the cache still reports what was seen the first
    /// time it was read.
    ///
    /// # Errors
    ///
    /// As [`Self::semantic_hash`].
    pub fn semantic(&self, kind: DataKind, path: &Path) -> Result<Canonical, CacheError> {
        let raw = self.content_hash(path)?;

        if let Some(known) = self.remembered_canonical(raw, kind)? {
            return Ok(known);
        }

        let canonical = canon::hash(kind, path, raw).map_err(|source| CacheError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        self.canonicalised.fetch_add(1, Ordering::Relaxed);
        self.remember_canonical(raw, kind, &canonical)?;
        Ok(canonical)
    }

    /// The hash of a file's contents, rereading it only when it may have
    /// changed.
    ///
    /// # Errors
    ///
    /// If the file cannot be read, or the metadata cannot be written.
    pub fn content_hash(&self, path: &Path) -> Result<ContentHash, CacheError> {
        let before = stat(path)?;
        let key = path.to_string_lossy().into_owned();

        if let Some(known) = self.remembered_hash(&key, before)? {
            self.prefiltered.fetch_add(1, Ordering::Relaxed);
            return Ok(known);
        }

        let hash = ContentHash::of_file(path).map_err(|source| CacheError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        self.hashed.fetch_add(1, Ordering::Relaxed);

        // Re-stat after reading: a file written while we hashed it would
        // otherwise be remembered under the stat it had before, and every
        // later run would trust that hash.
        let after = stat(path)?;
        if after == before {
            self.remember_hash(&key, before, hash)?;
        }
        Ok(hash)
    }

    /// Move a finished file into the store, under the hash of its contents.
    ///
    /// The staged file is consumed. An object that is already there is kept
    /// as it is: identical bytes are identical bytes.
    ///
    /// # Errors
    ///
    /// If the file cannot be read, hashed or moved.
    pub fn store(&self, staged: &Path) -> Result<Stored, CacheError> {
        let key = self.objects.put_file(staged, &suffix(staged))?;
        Ok(Stored {
            hash: key.hash,
            path: self.objects.path_of(&key),
        })
    }

    /// What was fetched for this locator, read as this kind, if anything
    /// has been.
    ///
    /// A record is a fact about a past fetch, not a promise about the
    /// present: whoever reads one checks that its objects are still in the
    /// store and that its digest still satisfies whatever the pipeline
    /// declares, because both can have moved since.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn remote(&self, locator: &str, kind: DataKind) -> Result<Option<RemoteRow>, CacheError> {
        let row: Option<(String, String, String, i64)> = self.with_database(|database| {
            database
                .query_row(
                    "SELECT digest, bytes, files, fetched_at FROM remotes
                         WHERE locator = ?1 AND kind = ?2",
                    params![locator, kind.name()],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
                )
                .optional()
        })??;

        let (row, from_store) = match row {
            Some(row) => (Some(row), false),
            None => (self.published_remote(locator, kind)?, true),
        };
        let Some((digest, bytes, files, fetched_at)) = row else {
            return Ok(None);
        };
        // A row this version cannot read is treated as absent, which costs
        // one fetch and cannot serve a half-understood answer.
        let Some(digest) = ContentHash::parse(&digest) else {
            return Ok(None);
        };
        let Some(bytes) = ContentHash::parse(&bytes) else {
            return Ok(None);
        };
        let row = RemoteRow {
            digest,
            bytes,
            files: decode_remote_files(&files),
            fetched_at,
        };
        if from_store {
            self.remember_remote(locator, kind, &row)?;
        }
        Ok(Some(row))
    }

    /// What the store says this locator resolved to, if it says anything.
    ///
    /// Without this a clean checkout pointed at a lab's bucket would find
    /// every object it needed sitting there and download the reads again
    /// anyway, because nothing would connect `sra:SRR8525904` to the
    /// objects it produced.
    fn published_remote(
        &self,
        locator: &str,
        kind: DataKind,
    ) -> Result<Option<(String, String, String, i64)>, CacheError> {
        let Some(fields) =
            published::fetch(&self.objects, REMOTES, &remote_row_key(locator, kind))?
        else {
            return Ok(None);
        };
        let [digest, bytes, files, fetched_at] = fields.as_slice() else {
            return Ok(None);
        };
        Ok(Some((
            digest.clone(),
            bytes.clone(),
            files.clone(),
            fetched_at.parse().unwrap_or_default(),
        )))
    }

    /// Record what was fetched for this locator, read as this kind.
    ///
    /// Replaces any earlier record of the same locator and kind. That is
    /// right for a *pinned* remote, where a later fetch of the same locator
    /// is either the same answer or a failure; it is emphatically not how a
    /// recorded query behaves, and that is why the two are different tables
    /// rather than one with a flag (D39).
    ///
    /// # Errors
    ///
    /// If the metadata cannot be written.
    pub fn record_remote(
        &self,
        locator: &str,
        kind: DataKind,
        row: &RemoteRow,
    ) -> Result<(), CacheError> {
        self.remember_remote(locator, kind, row)?;
        // A locator that resolved twice resolved to the same thing, or the
        // pin would have caught it: whichever row is there is the answer.
        published::put(
            &self.objects,
            REMOTES,
            &remote_row_key(locator, kind),
            &[
                row.digest.to_hex(),
                row.bytes.to_hex(),
                encode_remote_files(&row.files),
                row.fetched_at.to_string(),
            ],
        )?;
        Ok(())
    }

    /// The index half of [`record_remote`](Self::record_remote).
    fn remember_remote(
        &self,
        locator: &str,
        kind: DataKind,
        row: &RemoteRow,
    ) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute(
                "INSERT OR REPLACE INTO remotes
                     (locator, kind, digest, bytes, files, fetched_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    locator,
                    kind.name(),
                    row.digest.to_hex(),
                    row.bytes.to_hex(),
                    encode_remote_files(&row.files),
                    row.fetched_at,
                ],
            )
        })??;
        Ok(())
    }

    /// Forget what was fetched for this locator, read as this kind.
    ///
    /// For a fetch that turned out not to be what was promised: a record of
    /// it would be a record of the wrong bytes, which a later run might
    /// serve without asking.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be written.
    pub fn forget_remote(&self, locator: &str, kind: DataKind) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute(
                "DELETE FROM remotes WHERE locator = ?1 AND kind = ?2",
                params![locator, kind.name()],
            )
        })??;
        Ok(())
    }

    /// Every recording of this request, oldest revision first.
    ///
    /// All of them rather than only the current one, because a refresh
    /// never replaces what it refreshes: an earlier run replays from the
    /// revision it recorded, and a drift report names both.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn query_records(&self, request: ContentHash) -> Result<Vec<QueryRecord>, CacheError> {
        let rows: Vec<Row> = self.with_database(|database| {
            let mut statement = database.prepare(
                "SELECT revision, recorded_at, locator, kind, method, url, status,
                        body, suffix, digest, notes
                     FROM records WHERE request = ?1 ORDER BY revision",
            )?;
            statement
                .query_map(params![request.to_hex()], |row| -> rusqlite::Result<Row> {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                        row.get(7)?,
                        row.get(8)?,
                        row.get(9)?,
                        row.get(10)?,
                    ))
                })?
                .collect::<rusqlite::Result<Vec<Row>>>()
        })??;

        Ok(rows
            .into_iter()
            .filter_map(|row| decode_query_record(request, row))
            .collect())
    }

    /// The current recording of this request, if there is one.
    ///
    /// The highest revision, which is what a replay serves.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn query_record(&self, request: ContentHash) -> Result<Option<QueryRecord>, CacheError> {
        Ok(self.query_records(request)?.pop())
    }

    /// Record a response, as the next revision of its request.
    ///
    /// The revision is assigned here rather than by the caller, so that
    /// "a refresh writes beside" cannot be got wrong by whoever is doing
    /// the refreshing. Returns the record as it was written.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read or written.
    pub fn record_query(&self, record: &QueryRecord) -> Result<QueryRecord, CacheError> {
        let next = self
            .query_records(record.request)?
            .last()
            .map_or(1, |previous| previous.revision + 1);
        let written = QueryRecord {
            revision: next,
            ..record.clone()
        };
        self.with_database(|database| {
            database.execute(
                "INSERT INTO records
                     (request, revision, recorded_at, locator, kind, method, url,
                      status, body, suffix, digest, notes)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                params![
                    written.request.to_hex(),
                    written.revision,
                    written.recorded_at,
                    written.locator,
                    written.kind.name(),
                    written.method.name(),
                    written.url,
                    written.status,
                    written.body.hash.to_hex(),
                    written.body.suffix,
                    written.digest.to_hex(),
                    encode_notes(&written.notes),
                ],
            )
        })??;
        Ok(written)
    }

    /// Every recorded response this cache holds, oldest first.
    ///
    /// For a bundle, which carries them so that a reviewer with no network
    /// and no API key can replay the run (D39).
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn all_query_records(&self) -> Result<Vec<QueryRecord>, CacheError> {
        let requests: Vec<String> = self.with_database(|database| {
            let mut statement =
                database.prepare("SELECT DISTINCT request FROM records ORDER BY request")?;
            statement
                .query_map([], |row| row.get::<_, String>(0))?
                .collect::<rusqlite::Result<Vec<String>>>()
        })??;

        let mut records = Vec::new();
        for request in requests {
            let Some(request) = ContentHash::parse(&request) else {
                continue;
            };
            records.extend(self.query_records(request)?);
        }
        Ok(records)
    }

    /// The blob tier this cache keeps its objects in.
    ///
    /// Exposed because a recorded remote is written here rather than through
    /// a step's output, and because a run report has to be able to say what
    /// the store did.
    #[must_use]
    pub fn objects(&self) -> &TieredStore {
        &self.objects
    }

    /// Every object this index refers to, in no particular order.
    ///
    /// What `ligase store pull` fetches, and what makes it a bounded job
    /// rather than a bucket scan: a store cannot be listed cheaply, and
    /// the index is the one thing that knows which objects this project's
    /// runs actually depend on.
    ///
    /// Note what this means for a cold machine: an empty index refers to
    /// nothing, so there is nothing to pull. `ligase run` is what warms a
    /// cold machine, because the run is what knows the keys it needs. The
    /// help text says so.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn referenced_objects(&self) -> Result<Vec<ObjectKey>, CacheError> {
        let mut keys = Vec::new();

        let steps: Vec<(String, String)> = self.with_database(|database| {
            let mut statement = database.prepare("SELECT output_hash, suffix FROM steps")?;
            statement
                .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
                .collect::<rusqlite::Result<Vec<_>>>()
        })??;
        for (hex, suffix) in steps {
            if let Some(hash) = ContentHash::parse(&hex) {
                keys.push(ObjectKey::new(hash, &suffix));
            }
        }

        let remotes: Vec<String> = self.with_database(|database| {
            let mut statement = database.prepare("SELECT files FROM remotes")?;
            statement
                .query_map([], |row| row.get::<_, String>(0))?
                .collect::<rusqlite::Result<Vec<_>>>()
        })??;
        for files in remotes {
            keys.extend(decode_remote_files(&files).into_iter().map(|file| file.key));
        }

        let bodies: Vec<(String, String)> = self.with_database(|database| {
            let mut statement = database.prepare("SELECT body, suffix FROM records")?;
            statement
                .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
                .collect::<rusqlite::Result<Vec<_>>>()
        })??;
        for (hex, suffix) in bodies {
            if let Some(hash) = ContentHash::parse(&hex) {
                keys.push(ObjectKey::new(hash, &suffix));
            }
        }

        keys.sort_unstable();
        keys.dedup();
        Ok(keys)
    }

    /// Where a step should write while it runs.
    ///
    /// Inside the cache directory, so moving the finished file into the
    /// store is a rename rather than a copy, and so a crash leaves its
    /// debris somewhere a user can delete wholesale.
    #[must_use]
    pub fn staging(&self, key: StepKey, suffix: &str) -> PathBuf {
        self.root.join("tmp").join(format!("{key}{suffix}"))
    }

    /// Where something that is not a step's output should be written.
    ///
    /// For [`crate::audit`], whose two runs are thrown away: beside the
    /// staging files, so the same single directory holds everything a crash
    /// could leave behind.
    #[must_use]
    pub fn scratch(&self, name: &str) -> PathBuf {
        self.root.join("tmp").join(name)
    }

    /// What a step with this key produced, if it has been run before.
    ///
    /// An entry whose object has gone missing — a store deleted by hand,
    /// say — is treated as no entry at all and forgotten.
    ///
    /// # Errors
    ///
    /// If the metadata cannot be read.
    pub fn lookup(&self, key: StepKey) -> Result<Option<Entry>, CacheError> {
        let row: Option<(String, String, i64, String)> = self.with_database(|database| {
            database
                .query_row(
                    "SELECT output_hash, suffix, duration_ms, notes FROM steps WHERE key = ?1",
                    params![key.to_hex()],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
                )
                .optional()
        })??;

        // An index miss is not the end of the question. Everything a hit
        // depends on is published into the store, so a machine whose
        // `cache.sqlite` has been deleted -- or which never had one, being
        // a fresh checkout pointed at a lab's bucket -- can learn it back
        // (D43).
        let (row, from_store) = match row {
            Some(row) => (Some(row), false),
            None => (self.published_entry(key)?, true),
        };

        let Some((hex, suffix, duration_ms, notes)) = row else {
            return Ok(None);
        };
        let Some(hash) = ContentHash::parse(&hex) else {
            self.forget(key)?;
            return Ok(None);
        };

        // Through the store rather than off the filesystem, because the
        // object may be a tier down. `local_path` fetches it, verifies it
        // against the name it was asked for, and only then installs it.
        let object = ObjectKey::new(hash, &suffix);
        let path = match self.objects.local_path(&object) {
            Ok(Some(path)) => path,
            // Gone, or refused for a hash mismatch. Either way there is
            // nothing to serve, so the entry is dropped and the step runs.
            // A refusal is *not* silent: it is counted and named by the
            // store, and the run report prints it.
            Ok(None) | Err(StoreError::Mismatch { .. }) => {
                self.forget(key)?;
                return Ok(None);
            }
            Err(error) => return Err(error.into()),
        };

        if from_store {
            // Learned once, remembered locally. The rebuild is lazy, so a
            // cold machine pays one store read per step it actually needs
            // rather than a scan of the whole bucket.
            self.remember_published(key, &hex, &suffix, duration_ms, &notes)?;
        }

        Ok(Some(Entry {
            output: Stored { hash, path },
            duration_ms: duration_ms.try_into().unwrap_or_default(),
            notes: decode_notes(&notes),
        }))
    }

    /// The entry the store holds for this key, if it holds one.
    fn published_entry(
        &self,
        key: StepKey,
    ) -> Result<Option<(String, String, i64, String)>, CacheError> {
        let Some(fields) = published::fetch(&self.objects, STEPS, &key.to_hex())? else {
            return Ok(None);
        };
        // The canonical hash the row also carries is not read back here:
        // what a hit needs is the object, and `semantic` derives the
        // meaning from it. The field is for the worker that lost a publish
        // race and has to compare (D52).
        let [hash, suffix, duration, notes, _canonical] = fields.as_slice() else {
            return Ok(None);
        };
        Ok(Some((
            hash.clone(),
            suffix.clone(),
            duration.parse().unwrap_or_default(),
            notes.clone(),
        )))
    }

    /// Write back into the index what the store taught us.
    fn remember_published(
        &self,
        key: StepKey,
        hash: &str,
        suffix: &str,
        duration_ms: i64,
        notes: &str,
    ) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute(
                "INSERT OR REPLACE INTO steps
                     (key, step, output_hash, suffix, tools, duration_ms, created_at, notes)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    key.to_hex(),
                    // The step's name and its tools are not published:
                    // they describe how the work was done and nothing a
                    // hit depends on reads them back. A row rebuilt from
                    // the store says so rather than inventing them.
                    "(from the store)",
                    hash,
                    suffix,
                    "",
                    duration_ms,
                    now(),
                    notes,
                ],
            )
        })??;
        Ok(())
    }

    /// Record that a step with this key produced this output.
    ///
    /// Returns what the **store** says this key produced, which on a shared
    /// store is not always what was just passed in: another machine may
    /// have published first. Rows are write-once, so its answer is the one
    /// in force, and this is where that is settled —
    /// [`Recorded::Superseded`] means the local index now holds the
    /// store's answer rather than this one's (D52).
    ///
    /// # Errors
    ///
    /// If the metadata cannot be written.
    pub fn record(&self, made: &Recording<'_>) -> Result<Recorded, CacheError> {
        let (key, output) = (made.key, made.output);
        let duration = i64::try_from(made.duration_ms).unwrap_or(i64::MAX);
        let mine = [
            output.hash.to_hex(),
            suffix(&output.path),
            duration.to_string(),
            encode_notes(made.notes),
            made.canonical.to_hex(),
        ];

        // Into the store first, so that what goes into the local index is
        // whatever turns out to be authoritative. The other order would
        // write this machine's answer and then have to take it back.
        //
        // Written through the tiering, as every row has been since M14:
        // local first, pushed behind it, and a push that fails is counted
        // rather than fatal. The work is done either way.
        published::put(&self.objects, STEPS, &key.to_hex(), &mine)?;

        // Then asked of the store **every machine sees**, which is the
        // only one whose answer means anything here. Rows are write-once,
        // so if another worker published this key first, its row is the
        // one in force -- and asking the tiered store would read this
        // machine's own local copy and never find out (D52).
        //
        // No shared tier is the single-machine case: nobody else can have
        // published, so there is nothing to ask. A shared tier that will
        // not answer is treated the same way, because the honest fallback
        // is to keep the answer this run computed -- which is a correct
        // answer to the key however the race went.
        let theirs = self
            .objects
            .shared()
            .and_then(|shared| {
                published::fetch(shared, STEPS, &key.to_hex())
                    .ok()
                    .flatten()
            })
            .filter(|theirs| theirs != &mine);

        let (fields, verdict) = match theirs.as_deref().and_then(read_step_row) {
            Some(theirs) => (
                theirs.fields,
                Recorded::Superseded {
                    canonical: theirs.canonical,
                },
            ),
            // Ours, or a row this build cannot read: there is nothing to
            // adopt and nothing to compare, so keep our own answer and let
            // the next reader decide.
            None => (&mine[..], Recorded::Fresh),
        };

        let [hash, row_suffix, row_duration, row_notes, ..] = fields else {
            return Err(CacheError::Store(StoreError::Impostor {
                at: key.to_hex(),
                claims: "a step row with too few fields".to_owned(),
            }));
        };
        self.with_database(|database| {
            database.execute(
                "INSERT OR REPLACE INTO steps
                     (key, step, output_hash, suffix, tools, duration_ms, created_at, notes)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                params![
                    key.to_hex(),
                    made.step,
                    hash,
                    row_suffix,
                    made.tools,
                    row_duration.parse::<i64>().unwrap_or(duration),
                    now(),
                    row_notes,
                ],
            )
        })??;

        Ok(verdict)
    }

    fn forget(&self, key: StepKey) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute("DELETE FROM steps WHERE key = ?1", params![key.to_hex()])
        })??;
        Ok(())
    }

    fn remembered_hash(&self, path: &str, stat: Stat) -> Result<Option<ContentHash>, CacheError> {
        let hex: Option<String> = self.with_database(|database| {
            database
                .query_row(
                    "SELECT hash FROM files
                         WHERE path = ?1 AND size = ?2 AND mtime_ns = ?3",
                    params![path, stat.size, stat.mtime_ns],
                    |row| row.get(0),
                )
                .optional()
        })??;
        Ok(hex.as_deref().and_then(ContentHash::parse))
    }

    fn remembered_canonical(
        &self,
        raw: ContentHash,
        kind: DataKind,
    ) -> Result<Option<Canonical>, CacheError> {
        let held: Option<(String, String, String)> = self.with_database(|database| {
            database
                .query_row(
                    "SELECT canonical, form, notes FROM canonical
                         WHERE raw = ?1 AND kind = ?2",
                    params![raw.to_hex(), kind.name()],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
                )
                .optional()
        })??;

        let Some((hex, form, notes)) = held else {
            return Ok(None);
        };
        // A row this version cannot read is treated as absent, which costs
        // one canonicalisation and cannot report the wrong form.
        let Some(form) = Form::parse(&form) else {
            return Ok(None);
        };
        Ok(ContentHash::parse(&hex).map(|hash| Canonical {
            hash,
            form,
            notes: decode_notes(&notes),
        }))
    }

    fn remember_canonical(
        &self,
        raw: ContentHash,
        kind: DataKind,
        canonical: &Canonical,
    ) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute(
                "INSERT OR REPLACE INTO canonical (raw, kind, canonical, form, notes)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![
                    raw.to_hex(),
                    kind.name(),
                    canonical.hash.to_hex(),
                    canonical.form.to_string(),
                    encode_notes(&canonical.notes),
                ],
            )
        })??;
        Ok(())
    }

    fn remember_hash(&self, path: &str, stat: Stat, hash: ContentHash) -> Result<(), CacheError> {
        self.with_database(|database| {
            database.execute(
                "INSERT OR REPLACE INTO files (path, size, mtime_ns, hash)
                 VALUES (?1, ?2, ?3, ?4)",
                params![path, stat.size, stat.mtime_ns, hash.to_hex()],
            )
        })??;
        Ok(())
    }

    fn with_database<T>(&self, work: impl FnOnce(&Connection) -> T) -> Result<T, CacheError> {
        let database = self.database.lock().map_err(|_| CacheError::Poisoned)?;
        Ok(work(&database))
    }
}

/// What the prefilter compares.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Stat {
    size: i64,
    mtime_ns: i64,
}

fn stat(path: &Path) -> Result<Stat, CacheError> {
    let metadata = fs::metadata(path).map_err(|source| CacheError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let mtime_ns = metadata
        .modified()
        .ok()
        .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
        .and_then(|since| i64::try_from(since.as_nanos()).ok())
        // A file whose mtime cannot be read is one the prefilter never
        // matches, which costs a rehash and risks nothing.
        .unwrap_or(-1);
    Ok(Stat {
        size: i64::try_from(metadata.len()).unwrap_or(i64::MAX),
        mtime_ns,
    })
}

fn now() -> String {
    let seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |since| since.as_secs());
    seconds.to_string()
}

fn create_dir(path: &Path) -> Result<(), CacheError> {
    fs::create_dir_all(path).map_err(|source| CacheError::Io {
        path: path.to_path_buf(),
        source,
    })
}

/// Notes as one column: `code<TAB>value`, one note a line.
///
/// Both SAM and VCF forbid a tab or a newline inside a field, so a note's
/// value cannot hold either and nothing has to be escaped. A value that
/// somehow did would lose its tail rather than corrupt the row.
/// One object per line: key, the URL that answered, and the byte count.
///
/// Tab-separated and readable with `sqlite3`, because a cache whose whole
/// purpose is explaining a result should be explicable itself.
/// One `records` row as SQLite hands it back.
///
/// A named alias because the tuple is eleven columns wide and a signature
/// spelling it out twice would be two places for it to drift.
type Row = (
    u32,
    i64,
    String,
    String,
    String,
    String,
    u16,
    String,
    String,
    String,
    String,
);

/// A `records` row as a [`QueryRecord`].
///
/// `None` for a row this version cannot read -- an unknown kind or method,
/// a hash that will not parse -- which is treated as no record at all. That
/// costs one fetch and cannot serve a half-understood answer, which is how
/// `remote` already treats a row it does not recognise.
fn decode_query_record(request: ContentHash, row: Row) -> Option<QueryRecord> {
    let (revision, recorded_at, locator, kind, method, url, status, body, suffix, digest, notes) =
        row;
    Some(QueryRecord {
        request,
        revision,
        recorded_at,
        locator,
        kind: DataKind::ALL
            .iter()
            .copied()
            .find(|known| known.name() == kind)?,
        method: Method::parse(&method)?,
        url,
        status,
        body: ObjectKey::new(ContentHash::parse(&body)?, &suffix),
        digest: ContentHash::parse(&digest)?,
        notes: decode_notes(&notes),
    })
}

fn encode_remote_files(files: &[RemoteFile]) -> String {
    files
        .iter()
        .map(|file| format!("{}\t{}\t{}", file.key, file.url, file.bytes))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The objects a column holds, dropping any line this version cannot read.
fn decode_remote_files(column: &str) -> Vec<RemoteFile> {
    column
        .lines()
        .filter_map(|line| {
            let mut parts = line.split('\t');
            let key = parts.next()?;
            let url = parts.next()?;
            let bytes = parts.next()?.parse().ok()?;
            let hash = ContentHash::parse(key.get(..64)?)?;
            Some(RemoteFile {
                key: ObjectKey::new(hash, key.get(64..).unwrap_or_default()),
                url: url.to_owned(),
                bytes,
            })
        })
        .collect()
}

/// What a published `remotes` row is keyed on.
///
/// Locator *and* kind, exactly as the index is: the same URL read as two
/// kinds is two facts, because a digest is over what a file means and what
/// it means depends on how it is read.
fn remote_row_key(locator: &str, kind: DataKind) -> String {
    format!("{locator}\t{}", kind.name())
}

fn encode_notes(notes: &[Note]) -> String {
    notes
        .iter()
        .map(|note| format!("{}\t{}", note.code(), note.value()))
        .collect::<Vec<_>>()
        .join("\n")
}

/// The notes a column holds, skipping any this version does not know.
fn decode_notes(column: &str) -> Vec<Note> {
    column
        .lines()
        .filter_map(|line| line.split_once('\t'))
        .filter_map(|(code, value)| Note::parse(code, value))
        .collect()
}

/// Create the tables, discarding anything written under another format.
fn prepare(database: &Connection) -> Result<(), CacheError> {
    database.execute(
        "CREATE TABLE IF NOT EXISTS meta (name TEXT PRIMARY KEY, value TEXT NOT NULL)",
        [],
    )?;

    let schema: Option<String> = database
        .query_row(
            "SELECT value FROM meta WHERE name = 'schema_version'",
            [],
            |row| row.get(0),
        )
        .optional()?;
    if schema.is_some_and(|version| version != SCHEMA_VERSION.to_string()) {
        database.execute("DROP TABLE IF EXISTS files", [])?;
        database.execute("DROP TABLE IF EXISTS steps", [])?;
        database.execute("DROP TABLE IF EXISTS canonical", [])?;
        database.execute("DROP TABLE IF EXISTS remotes", [])?;
        database.execute("DROP TABLE IF EXISTS records", [])?;
    }

    database.execute(
        "CREATE TABLE IF NOT EXISTS files (
             path     TEXT PRIMARY KEY,
             size     INTEGER NOT NULL,
             mtime_ns INTEGER NOT NULL,
             hash     TEXT NOT NULL
         )",
        [],
    )?;
    database.execute(
        "CREATE TABLE IF NOT EXISTS steps (
             key         TEXT PRIMARY KEY,
             step        TEXT NOT NULL,
             output_hash TEXT NOT NULL,
             suffix      TEXT NOT NULL,
             tools       TEXT NOT NULL,
             duration_ms INTEGER NOT NULL,
             created_at  TEXT NOT NULL,
             notes       TEXT NOT NULL DEFAULT ''
         )",
        [],
    )?;

    // What was fetched from where, and what it turned out to be (D39).
    // Keyed by locator and kind, because the same URL read as two kinds is
    // two facts: a digest is over what a file *means*, and what it means
    // depends on how it is read.
    //
    // `files` holds one line per object -- key, the URL that answered, and
    // the byte count -- so a run's inputs can be read back with `sqlite3`
    // by anyone explaining a result.
    database.execute(
        "CREATE TABLE IF NOT EXISTS remotes (
             locator    TEXT NOT NULL,
             kind       TEXT NOT NULL,
             digest     TEXT NOT NULL,
             bytes      TEXT NOT NULL,
             files      TEXT NOT NULL,
             fetched_at INTEGER NOT NULL,
             PRIMARY KEY (locator, kind)
         )",
        [],
    )?;

    // Every recorded response, keyed by the hash of its canonical request
    // (D39). A separate table from `remotes` rather than one with a flag,
    // and the difference is the whole of why: `remotes` is
    // `INSERT OR REPLACE`, because a later fetch of a pinned locator is
    // either the same answer or a failure, and a refresh of a query must
    // *never* replace what it refreshes -- every earlier run stays
    // replayable.
    //
    // So the key is `(request, revision)` and a refresh inserts the next
    // revision. Not `(request, recorded_at)`: two records a second apart
    // must still be two records, and keying on a clock would let a refresh
    // inside the same second overwrite the thing it exists not to
    // overwrite. Nothing supersedes anything explicitly either -- revision
    // `n` supersedes `n - 1` by construction, which cannot drift out of
    // step with itself.
    database.execute(
        "CREATE TABLE IF NOT EXISTS records (
             request     TEXT NOT NULL,
             revision    INTEGER NOT NULL,
             recorded_at INTEGER NOT NULL,
             locator     TEXT NOT NULL,
             kind        TEXT NOT NULL,
             method      TEXT NOT NULL,
             url         TEXT NOT NULL,
             status      INTEGER NOT NULL,
             body        TEXT NOT NULL,
             suffix      TEXT NOT NULL,
             digest      TEXT NOT NULL,
             notes       TEXT NOT NULL DEFAULT '',
             PRIMARY KEY (request, revision)
         )",
        [],
    )?;

    // What a file means, against the hash of its bytes. Not keyed by path:
    // this is a fact about the bytes, so a file copied or produced again
    // identically is not parsed a second time.
    //
    // `notes` holds what canonicalising the file noticed, which is almost
    // always nothing. It is stored rather than recomputed because a cache
    // hit does not reopen the file, and a warning that stopped appearing on
    // the second run would be worse than none at all.
    database.execute(
        "CREATE TABLE IF NOT EXISTS canonical (
             raw       TEXT NOT NULL,
             kind      TEXT NOT NULL,
             canonical TEXT NOT NULL,
             form      TEXT NOT NULL,
             notes     TEXT NOT NULL DEFAULT '',
             PRIMARY KEY (raw, kind)
         )",
        [],
    )?;

    // Keys from another key format describe ingredients that were combined
    // differently. The files table survives: a file's hash is a fact about
    // the file, not about how keys are made.
    let keys: Option<String> = database
        .query_row(
            "SELECT value FROM meta WHERE name = 'key_version'",
            [],
            |row| row.get(0),
        )
        .optional()?;
    if keys.is_some_and(|version| version != KEY_VERSION.to_string()) {
        database.execute("DELETE FROM steps", [])?;
    }

    // A canonical hash is a fact about a file *given the rules that made
    // it*, so rules from another version describe something else. The step
    // entries go with it, since their keys were built from those hashes.
    let canon: Option<String> = database
        .query_row(
            "SELECT value FROM meta WHERE name = 'canon_version'",
            [],
            |row| row.get(0),
        )
        .optional()?;
    if canon.is_some_and(|version| version != CANON_VERSION.to_string()) {
        database.execute("DELETE FROM canonical", [])?;
        database.execute("DELETE FROM steps", [])?;
    }

    database.execute(
        "INSERT OR REPLACE INTO meta (name, value) VALUES
             ('schema_version', ?1), ('key_version', ?2), ('canon_version', ?3)",
        params![
            SCHEMA_VERSION.to_string(),
            KEY_VERSION.to_string(),
            CANON_VERSION.to_string(),
        ],
    )?;
    Ok(())
}

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

    use super::*;

    #[test]
    fn a_suffix_keeps_every_extension_a_tool_reads() {
        assert_eq!(suffix(Path::new("out.bam")), ".bam");
        assert_eq!(suffix(Path::new("out.vcf.gz")), ".vcf.gz");
        assert_eq!(suffix(Path::new("out")), "");
        assert_eq!(suffix(Path::new("/tmp/a.b/out.tsv")), ".tsv");
    }
}