cargo-affected 0.3.0

Run only the tests affected by git changes, using LLVM coverage.
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
//! SQLite storage for test-to-function-range coverage mappings.
//!
//! Schema:
//! - `meta` — key/value pairs (e.g. last collection timestamp)
//! - `test_regions` — `(binary_id, test_name, source_file, line_start,
//!   line_end, env_fingerprint, collect_sha)` rows. One row per hit function
//!   per test, per covered file. `collect_sha` is the git HEAD at the time
//!   the row's coverage was observed; queries diff the working tree against
//!   that sha so stored line numbers line up with diff hunks. Crate roots
//!   (`lib.rs` / `main.rs` / `tests/*.rs`) are stored with sentinel range
//!   `(1, i64::MAX)` so any hunk in a crate root overlaps and selects the
//!   test — same effect as the old per-test implicit dep, no special-case
//!   branch.
//! - `fingerprints` — `(fingerprint, last_seen)`. Last-seen drives LRU
//!   eviction up to `FINGERPRINT_KEEP`.
//!
//! `collect_sha` lives per-row (rather than per-fingerprint) so `collect
//! --diff` can leave unaffected tests anchored at their original sha while
//! re-anchoring the rerun ones at the new HEAD. Multiple shas can coexist for
//! the same fingerprint; query callers iterate over distinct shas to compute
//! ranges anchored at each.
//!
//! `env_fingerprint` (see `fingerprint.rs`) is a SHA-256 hex of inputs that
//! would globally invalidate cached coverage (Cargo.lock, Cargo.toml files,
//! rustc version, RUSTFLAGS, CARGO_BUILD_TARGET). Every query is scoped to the
//! caller's current fingerprint, so a mismatch naturally reads as "no data"
//! without any special-case invalidation path.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result};
use rusqlite::Connection;

use crate::coverage::{HitRange, CRATE_ROOT_SENTINEL_END};
use crate::fingerprint::FingerprintComponent;
use crate::project::LineRange;

/// How long to wait for a conflicting lock before giving up. Long enough to
/// ride out a concurrent `collect`'s commit phase; short enough that a
/// genuinely stuck process surfaces as an error rather than hanging forever.
const BUSY_TIMEOUT: Duration = Duration::from_secs(30);

/// Translate `SQLITE_BUSY` (which can only surface after `BUSY_TIMEOUT` has
/// already been exhausted) into a message that points at the actual cause.
/// Non-busy rusqlite errors pass through unchanged.
fn translate_busy(err: rusqlite::Error, ctx: &'static str) -> anyhow::Error {
    if matches!(
        &err,
        rusqlite::Error::SqliteFailure(e, _) if e.code == rusqlite::ErrorCode::DatabaseBusy
    ) {
        anyhow::anyhow!(
            "another cargo-affected process appears to be holding the \
             database lock — try again in a moment"
        )
    } else {
        anyhow::Error::from(err).context(ctx)
    }
}

/// Umbrella directory for all cargo-affected artifacts (DB, profraw files).
/// Lives under `target/` so it shares the gitignore and lifecycle
/// (cargo clean wipes it) of other build artifacts.
pub fn affected_dir(project_root: &Path) -> PathBuf {
    project_root.join("target").join("affected")
}

/// Canonical DB location within the affected dir.
pub fn db_path(project_root: &Path) -> PathBuf {
    affected_dir(project_root).join("coverage.db")
}

const SCHEMA: &str = "\
CREATE TABLE IF NOT EXISTS meta (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS test_regions (
    binary_id TEXT NOT NULL,
    test_name TEXT NOT NULL,
    source_file TEXT NOT NULL,
    line_start INTEGER NOT NULL,
    line_end INTEGER NOT NULL,
    env_fingerprint TEXT NOT NULL,
    collect_sha TEXT NOT NULL,
    PRIMARY KEY (binary_id, test_name, source_file, line_start, line_end, env_fingerprint, collect_sha)
);
-- Range-overlap query: equality on (source_file, env_fingerprint, collect_sha)
-- plus a bound on line_start. The fifth column (line_end) lets the planner
-- skip rows once it has line_start beyond the hunk end. SQLite's composite
-- index can use equality + one range bound efficiently; the second range
-- bound is best-effort. Benchmark on real workspaces if status/run latency
-- matters.
CREATE INDEX IF NOT EXISTS idx_test_regions_lookup
    ON test_regions(source_file, env_fingerprint, collect_sha, line_start, line_end);
CREATE TABLE IF NOT EXISTS fingerprints (
    fingerprint TEXT PRIMARY KEY,
    last_seen TEXT NOT NULL
);
-- Per-fingerprint per-input component hashes. Lets a 'fingerprint
-- mismatch' miss be diagnosed at the component level: 'this PR's
-- manifest:tests/helpers/wt-perf/Cargo.toml differs from every cached
-- fingerprint, but Cargo.lock and rustc match'. Composite hash in
-- env_fingerprint already encodes the same information; this is the
-- diagnostic decomposition.
CREATE TABLE IF NOT EXISTS fingerprint_components (
    env_fingerprint TEXT NOT NULL,
    label TEXT NOT NULL,
    content_hash TEXT NOT NULL,
    PRIMARY KEY (env_fingerprint, label)
);
";

/// Identifier for a single test: nextest's stable `binary_id`
/// (e.g. `mock-stub::builds`) paired with the test name inside that binary.
///
/// Before binary_id was tracked, two tests with the same name in different
/// binaries collapsed into one DB row and one test's coverage was silently
/// overwritten. The (binary_id, test_name) tuple is nextest's actual unit of
/// test identity, so we use it everywhere — storage keys, filter expressions,
/// counts.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TestId {
    pub binary_id: String,
    pub test_name: String,
}

impl TestId {
    pub fn new(binary_id: impl Into<String>, test_name: impl Into<String>) -> Self {
        Self {
            binary_id: binary_id.into(),
            test_name: test_name.into(),
        }
    }
}

/// One row in the `fingerprints` table, materialized with its component
/// hashes from `fingerprint_components`. Returned by
/// [`Db::stored_fingerprint_snapshots`] for the diagnostic report.
#[derive(Debug, Clone)]
pub struct StoredFingerprintRow {
    pub fingerprint: String,
    pub last_seen: String,
    pub components: Vec<FingerprintComponent>,
}

/// One hit recorded by [`Db::tests_covering_ranges`]: which test got pulled
/// in, and the reason for it. A single test can appear multiple times if it
/// matched several rows or several hunks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestHit {
    pub test_id: TestId,
    pub reason: HitReason,
}

/// Why a test was selected. The triple (`file`, `matched_hunk`, `kind`)
/// describes one path through the selection logic; `stored_range` names the
/// row that matched (absent for [`HitKind::StructuralBackstop`], where the
/// whole point is that nothing matched).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HitReason {
    /// `collect_sha` the diff was anchored against. Hunks live in this
    /// sha's coordinate system; the reason is only meaningful paired with it.
    pub collect_sha: String,
    /// Source file the hunk applies to.
    pub file: String,
    /// Selection-path classification.
    pub kind: HitKind,
    /// The diff hunk that triggered the selection. Inclusive `(start, end)`.
    pub matched_hunk: (i64, i64),
    /// The stored row that overlapped the hunk. `None` when [`HitKind::StructuralBackstop`]
    /// fired (no row overlapped — the test was pulled in by file-presence alone).
    pub stored_range: Option<(i64, i64)>,
}

/// How a test ended up in the selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HitKind {
    /// A stored function-range row overlapped the hunk's line range.
    LineOverlap,
    /// No stored row overlapped the hunk; the test was pulled in because
    /// its DB rows reference this file (struct-field, derive, const, use,
    /// mod edits land in lines no test covered directly).
    StructuralBackstop,
    /// The stored row was a crate-root sentinel
    /// ([`crate::coverage::CRATE_ROOT_SENTINEL_END`]) — an "any hunk in
    /// this file selects this test" link the function-level coverage
    /// can't observe directly.
    CrateRootSentinel,
    /// The test was force-selected by a `[workspace.metadata.affected]` rule whose
    /// globs matched a changed (typically non-Rust) input the coverage model
    /// can't link to a test — an insta `.snap`, a doc, a template. Produced by
    /// [`crate::config::resolve_config_hits`], not by coverage overlap.
    ConfigRule,
}

/// How many distinct fingerprints to retain. `gc()` evicts the least-recently-
/// used fingerprints beyond this cap, always keeping the caller's current one.
/// Chosen to comfortably cover typical workflows (a handful of branches plus
/// the occasional toolchain bump) while keeping the DB from accumulating
/// forever if a user rapidly cycles through many build environments.
pub const FINGERPRINT_KEEP: usize = 10;

/// Upsert `fingerprint`'s `last_seen` to now. Creates the row if absent; this
/// is safe for writes (we just inserted data under this fingerprint) but
/// callers doing bare reads of a fingerprint that has no data should gate the
/// call on actually finding rows.
///
/// Takes `&Connection`; pass `&tx` from inside a transaction (rusqlite's
/// `Transaction<'_>` derefs to `Connection`, so the write joins the open
/// transaction rather than auto-committing).
fn touch_fingerprint(conn: &Connection, fingerprint: &str) -> Result<()> {
    conn.execute(
        "INSERT INTO fingerprints (fingerprint, last_seen) VALUES (?1, ?2) \
         ON CONFLICT(fingerprint) DO UPDATE SET last_seen = excluded.last_seen",
        rusqlite::params![fingerprint, chrono_free_timestamp()],
    )?;
    Ok(())
}

/// Build `?N, ?N+1, ...` for an `IN (...)` clause with `count` placeholders
/// starting at `start_idx`. SQLite has no parameter list for `IN`, so we
/// have to expand explicitly. Callers pair this with `params_from_iter` so
/// the values are still bound positionally — no string interpolation of
/// untrusted data.
fn in_placeholders(start_idx: usize, count: usize) -> String {
    (0..count)
        .map(|i| format!("?{}", i + start_idx))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Delete every `test_regions` row matching one of `tests`, scoped to
/// `fingerprint`. One DELETE per chunk instead of one per test, so a `--diff`
/// touching many tests doesn't hammer SQLite with N round-trips. Chunked so
/// the parameter count stays well under SQLite's default
/// `SQLITE_MAX_VARIABLE_NUMBER` (999 on older builds, 32766 on modern ones).
fn batch_delete_tests<'a>(
    tx: &rusqlite::Transaction<'_>,
    fingerprint: &str,
    tests: impl IntoIterator<Item = &'a TestId>,
) -> Result<()> {
    let tests: Vec<&TestId> = tests.into_iter().collect();
    if tests.is_empty() {
        return Ok(());
    }
    // 400 pairs → 801 bound parameters, comfortably below the conservative
    // 999 limit. SQLite's row-tuple `IN ((?, ?), …)` syntax isn't universally
    // supported across versions, so we expand into an OR predicate, which the
    // planner reduces to the same lookup.
    const CHUNK: usize = 400;
    for chunk in tests.chunks(CHUNK) {
        let predicate = (0..chunk.len())
            .map(|i| format!("(binary_id = ?{} AND test_name = ?{})", 2 + i * 2, 3 + i * 2))
            .collect::<Vec<_>>()
            .join(" OR ");
        let sql = format!(
            "DELETE FROM test_regions \
             WHERE env_fingerprint = ?1 AND ({predicate})"
        );
        let params = std::iter::once(fingerprint).chain(
            chunk
                .iter()
                .flat_map(|t| [t.binary_id.as_str(), t.test_name.as_str()]),
        );
        tx.execute(&sql, rusqlite::params_from_iter(params))?;
    }
    Ok(())
}

/// Replace every `fingerprint_components` row for `fingerprint` with the
/// supplied `components`. Idempotent: a re-run with the same inputs leaves
/// the table in the same state. Called from both `store_coverage` and
/// `update_coverage_for_tests` so the components table stays in sync with
/// `test_regions` writes within the same transaction.
fn upsert_components(
    tx: &rusqlite::Transaction<'_>,
    fingerprint: &str,
    components: &[FingerprintComponent],
) -> Result<()> {
    tx.execute(
        "DELETE FROM fingerprint_components WHERE env_fingerprint = ?1",
        [fingerprint],
    )?;
    let mut stmt = tx.prepare(
        "INSERT INTO fingerprint_components (env_fingerprint, label, content_hash) \
         VALUES (?1, ?2, ?3)",
    )?;
    for component in components {
        stmt.execute(rusqlite::params![
            fingerprint,
            component.label.as_str(),
            component.hash.as_str(),
        ])?;
    }
    Ok(())
}

/// Insert every `(test_id, range)` pair as a `test_regions` row anchored at
/// `collect_sha`. Shared between [`Db::store_coverage`] and
/// [`Db::update_coverage_for_tests`] — both insert the same shape.
fn insert_mappings(
    tx: &rusqlite::Transaction<'_>,
    fingerprint: &str,
    collect_sha: &str,
    mappings: &[(TestId, BTreeSet<HitRange>)],
) -> Result<()> {
    let mut stmt = tx.prepare(
        "INSERT OR IGNORE INTO test_regions \
         (binary_id, test_name, source_file, line_start, line_end, env_fingerprint, collect_sha) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
    )?;
    for (test_id, ranges) in mappings {
        for range in ranges {
            stmt.execute(rusqlite::params![
                test_id.binary_id,
                test_id.test_name,
                range.file.as_str(),
                range.line_start,
                range.line_end,
                fingerprint,
                collect_sha,
            ])?;
        }
    }
    Ok(())
}

pub struct Db {
    conn: Connection,
}

impl Db {
    /// Open (or create) the database at `project_root/target/affected/coverage.db`.
    ///
    /// Migrates older schemas (pre-fingerprint, pre-binary_id, pre-range,
    /// pre-per-row-collect_sha) by dropping the old `test_files` /
    /// `test_regions` tables and rebuilding `fingerprints` if its column
    /// shape is wrong. Old rows can't be retroactively tagged with missing
    /// columns, and `target/affected/` is cargo-clean territory, so the
    /// reset is safe — the user re-collects.
    pub fn open(project_root: &Path) -> Result<Self> {
        let path = db_path(project_root);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }
        let conn = Connection::open(&path)
            .with_context(|| format!("failed to open database at {}", path.display()))?;
        conn.busy_timeout(BUSY_TIMEOUT)
            .context("failed to configure SQLite busy_timeout")?;
        // WAL halves insert latency on the bulk store_coverage path, which is
        // ~5–10× larger row counts under function-level granularity. NORMAL
        // sync is durable across crashes (only at risk of losing the very
        // last commit on power-loss) — fine for a coverage cache.
        conn.pragma_update(None, "journal_mode", "WAL")
            .context("failed to set journal_mode=WAL")?;
        conn.pragma_update(None, "synchronous", "NORMAL")
            .context("failed to set synchronous=NORMAL")?;
        migrate_legacy_tables(&conn)?;
        conn.execute_batch(SCHEMA)
            .map_err(|e| translate_busy(e, "failed to initialize database schema"))?;
        Ok(Self { conn })
    }

    /// Replace coverage data for the current fingerprint with a fresh
    /// collection, anchoring every new row at `collect_sha` (the git HEAD
    /// when this collection ran). `components` are the per-input hashes
    /// that make up `fingerprint`; stored in `fingerprint_components` for
    /// later "which input changed?" diagnostics.
    ///
    /// Leaves rows from other fingerprints alone — they remain queryable if
    /// the user switches environments.
    pub fn store_coverage(
        &mut self,
        fingerprint: &str,
        components: &[FingerprintComponent],
        collect_sha: &str,
        mappings: &[(TestId, BTreeSet<HitRange>)],
    ) -> Result<()> {
        let tx = self.conn.transaction()?;
        tx.execute(
            "DELETE FROM test_regions WHERE env_fingerprint = ?1",
            [fingerprint],
        )?;
        insert_mappings(&tx, fingerprint, collect_sha, mappings)?;
        upsert_components(&tx, fingerprint, components)?;
        touch_fingerprint(&tx, fingerprint)?;
        write_last_collected(&tx)?;
        tx.commit()
            .map_err(|e| translate_busy(e, "failed to commit coverage data"))?;
        Ok(())
    }

    /// Replace coverage data for just the tests in `mappings` (regardless of
    /// the sha they're currently anchored at) with rows anchored at
    /// `new_collect_sha`. Other tests' rows under the same fingerprint stay
    /// put — that's the whole point of `collect --diff`. Component hashes
    /// are refreshed to match `components` (the current build environment).
    pub fn update_coverage_for_tests(
        &mut self,
        fingerprint: &str,
        components: &[FingerprintComponent],
        new_collect_sha: &str,
        mappings: &[(TestId, BTreeSet<HitRange>)],
    ) -> Result<()> {
        let tx = self.conn.transaction()?;
        batch_delete_tests(&tx, fingerprint, mappings.iter().map(|(t, _)| t))?;
        insert_mappings(&tx, fingerprint, new_collect_sha, mappings)?;
        upsert_components(&tx, fingerprint, components)?;
        touch_fingerprint(&tx, fingerprint)?;
        write_last_collected(&tx)?;
        tx.commit()
            .map_err(|e| translate_busy(e, "failed to commit coverage update"))?;
        Ok(())
    }

    /// Drop rows for tests under `fingerprint` whose `(binary_id, test_name)`
    /// is not in `present`. Used by `collect --diff` to clear out tests that
    /// were renamed or deleted between collects. Returns the number of
    /// distinct tests pruned.
    pub fn prune_missing_tests(
        &mut self,
        fingerprint: &str,
        present: &BTreeSet<TestId>,
    ) -> Result<usize> {
        // Read with a plain `&Connection` so the no-op case (everything in
        // the listing is already in the DB) doesn't open a write
        // transaction at all. WAL gives us a snapshot read that won't see
        // mid-flight changes from another collect.
        let stored: BTreeSet<TestId> = {
            let mut stmt = self.conn.prepare(
                "SELECT DISTINCT binary_id, test_name FROM test_regions \
                 WHERE env_fingerprint = ?1",
            )?;
            let rows: BTreeSet<TestId> = stmt
                .query_map([fingerprint], |row| {
                    Ok(TestId::new(row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                })?
                .collect::<rusqlite::Result<_>>()?;
            rows
        };
        let to_drop: Vec<TestId> = stored.difference(present).cloned().collect();
        if to_drop.is_empty() {
            return Ok(0);
        }
        let tx = self.conn.transaction()?;
        batch_delete_tests(&tx, fingerprint, to_drop.iter())?;
        tx.commit()
            .map_err(|e| translate_busy(e, "failed to commit prune"))?;
        Ok(to_drop.len())
    }

    /// Find tests under `(fingerprint, collect_sha)` that overlap any of the
    /// given line ranges in `file`. Per hunk: range-overlap; if a hunk
    /// overlaps no stored range, broaden to "any test with rows for this
    /// file at this sha" (the structural-edit backstop for struct-field,
    /// derive, const, use, mod edits).
    ///
    /// Each returned [`TestHit`] carries the [`HitReason`] explaining
    /// selection — which file, which hunk, and which kind of match
    /// ([`HitKind::LineOverlap`], [`HitKind::CrateRootSentinel`], or
    /// [`HitKind::StructuralBackstop`]). One unique test can appear
    /// multiple times if it matched several rows or several hunks, so
    /// callers that need the deduplicated test set should collect with
    /// `into_iter().map(|h| h.test_id).collect::<BTreeSet<_>>()` or
    /// aggregate by the strongest reason — see selection.rs for the
    /// canonical aggregation. Backstop hits are emitted ONCE per unique
    /// test per hunk (not once per stored row) so per-reason counters
    /// remain meaningful.
    ///
    /// Scoping by `collect_sha` matters because `collect --diff` lets rows
    /// from different collect points coexist for the same fingerprint —
    /// hunks must be matched against rows whose line numbers share a
    /// coordinate system. Callers iterate over the distinct shas returned by
    /// [`Db::collect_shas`] and union the results.
    ///
    /// Pulls all rows for `(file, fingerprint, collect_sha)` once and walks
    /// them in Rust rather than running 2 queries per hunk: rows-per-file is
    /// bounded by hit functions in the file (small), and SQLite round-trips
    /// dominate the per-hunk cost.
    pub fn tests_covering_ranges(
        &self,
        fingerprint: &str,
        collect_sha: &str,
        file: &str,
        hunks: &[LineRange],
    ) -> Result<Vec<TestHit>> {
        let mut hits = Vec::new();
        if hunks.is_empty() {
            return Ok(hits);
        }

        let mut stmt = self.conn.prepare(
            "SELECT binary_id, test_name, line_start, line_end FROM test_regions \
             WHERE source_file = ?1 AND env_fingerprint = ?2 AND collect_sha = ?3",
        )?;
        let rows: Vec<(TestId, i64, i64)> = stmt
            .query_map(rusqlite::params![file, fingerprint, collect_sha], |row| {
                Ok((
                    TestId::new(row.get::<_, String>(0)?, row.get::<_, String>(1)?),
                    row.get::<_, i64>(2)?,
                    row.get::<_, i64>(3)?,
                ))
            })?
            .collect::<rusqlite::Result<_>>()?;
        if rows.is_empty() {
            return Ok(hits);
        }

        for hunk in hunks {
            // Range-overlap: a stored row [ls, le] overlaps a hunk [hs, he]
            // iff ls <= he AND le >= hs (closed intervals).
            let mut overlapped = false;
            for (test, ls, le) in &rows {
                if *ls <= hunk.end && *le >= hunk.start {
                    let kind = if *le == CRATE_ROOT_SENTINEL_END && *ls == 1 {
                        HitKind::CrateRootSentinel
                    } else {
                        HitKind::LineOverlap
                    };
                    hits.push(TestHit {
                        test_id: test.clone(),
                        reason: HitReason {
                            collect_sha: collect_sha.to_string(),
                            file: file.to_string(),
                            kind,
                            matched_hunk: (hunk.start, hunk.end),
                            stored_range: Some((*ls, *le)),
                        },
                    });
                    overlapped = true;
                }
            }
            if !overlapped {
                // Backstop: emit one hit per unique test for this file
                // (rows can have many ranges per test; we don't want to
                // multiply that into the reason counts).
                let mut seen: BTreeSet<&TestId> = BTreeSet::new();
                for (test, _, _) in &rows {
                    if !seen.insert(test) {
                        continue;
                    }
                    hits.push(TestHit {
                        test_id: test.clone(),
                        reason: HitReason {
                            collect_sha: collect_sha.to_string(),
                            file: file.to_string(),
                            kind: HitKind::StructuralBackstop,
                            matched_hunk: (hunk.start, hunk.end),
                            stored_range: None,
                        },
                    });
                }
            }
        }
        Ok(hits)
    }

    /// Mark `fingerprint` as recently used, refreshing its `last_seen`
    /// timestamp for LRU eviction by [`Db::gc`]. Read-side callers
    /// (`run`, `status`) should invoke this once per invocation rather
    /// than once per query — `tests_covering_ranges` no longer touches
    /// it implicitly, since it can be called many times per command.
    pub fn touch(&self, fingerprint: &str) -> Result<()> {
        touch_fingerprint(&self.conn, fingerprint)
    }

    /// Distinct `collect_sha` values present in `test_regions` for this
    /// fingerprint. Empty when no coverage has been collected yet for the
    /// current environment.
    pub fn collect_shas(&self, fingerprint: &str) -> Result<BTreeSet<String>> {
        let mut stmt = self.conn.prepare(
            "SELECT DISTINCT collect_sha FROM test_regions WHERE env_fingerprint = ?1",
        )?;
        let shas = stmt
            .query_map([fingerprint], |row| row.get::<_, String>(0))?
            .collect::<rusqlite::Result<_>>()?;
        Ok(shas)
    }

    /// Count of distinct tests tracked under the current fingerprint.
    pub fn test_count(&self, fingerprint: &str) -> Result<usize> {
        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM \
             (SELECT DISTINCT binary_id, test_name FROM test_regions WHERE env_fingerprint = ?1)",
            [fingerprint],
            |r| r.get(0),
        )?;
        Ok(count as usize)
    }

    /// Count of (test, file, range) rows under the current fingerprint.
    pub fn region_count(&self, fingerprint: &str) -> Result<usize> {
        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM test_regions WHERE env_fingerprint = ?1",
            [fingerprint],
            |r| r.get(0),
        )?;
        Ok(count as usize)
    }

    /// All distinct `source_file` values referenced by `test_regions`
    /// rows under `(fingerprint, any sha in shas)`. Returns the set of
    /// files the cache "knows about" at the reachable shas — used by
    /// the diagnostic report to set `tracked_by_coverage` on each
    /// changed file in one query rather than N×files lookups.
    pub fn tracked_files_at_shas(
        &self,
        fingerprint: &str,
        shas: &BTreeSet<String>,
    ) -> Result<BTreeSet<String>> {
        if shas.is_empty() {
            return Ok(BTreeSet::new());
        }
        let sql = format!(
            "SELECT DISTINCT source_file FROM test_regions \
             WHERE env_fingerprint = ?1 AND collect_sha IN ({})",
            in_placeholders(2, shas.len()),
        );
        let mut stmt = self.conn.prepare(&sql)?;
        let params = std::iter::once(fingerprint).chain(shas.iter().map(String::as_str));
        let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| {
            row.get::<_, String>(0)
        })?;
        rows.collect::<rusqlite::Result<BTreeSet<String>>>()
            .map_err(Into::into)
    }

    /// Whether a source file has coverage data under the current fingerprint.
    pub fn file_tracked(&self, fingerprint: &str, file: &str) -> Result<bool> {
        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM test_regions \
             WHERE env_fingerprint = ?1 AND source_file = ?2",
            [fingerprint, file],
            |r| r.get(0),
        )?;
        Ok(count > 0)
    }

    /// Snapshot of every stored fingerprint with its `last_seen`
    /// timestamp and component hashes. Used by the diagnostic report to
    /// compute "which input differs?" diffs against the current
    /// fingerprint. Empty when the DB has never been written to.
    pub fn stored_fingerprint_snapshots(&self) -> Result<Vec<StoredFingerprintRow>> {
        let mut stmt = self.conn.prepare(
            "SELECT fingerprint, last_seen FROM fingerprints \
             ORDER BY last_seen DESC, fingerprint ASC",
        )?;
        let mut fps: Vec<(String, String)> = stmt
            .query_map([], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        drop(stmt);

        let mut out = Vec::with_capacity(fps.len());
        let mut comp_stmt = self.conn.prepare(
            "SELECT label, content_hash FROM fingerprint_components \
             WHERE env_fingerprint = ?1 ORDER BY label",
        )?;
        for (fp, last_seen) in fps.drain(..) {
            let components: Vec<FingerprintComponent> = comp_stmt
                .query_map([&fp], |row| {
                    Ok(FingerprintComponent {
                        label: row.get::<_, String>(0)?,
                        hash: row.get::<_, String>(1)?,
                    })
                })?
                .collect::<rusqlite::Result<Vec<_>>>()?;
            out.push(StoredFingerprintRow {
                fingerprint: fp,
                last_seen,
                components,
            });
        }
        Ok(out)
    }

    /// `test_regions` row counts per `collect_sha`, scoped to one
    /// fingerprint. Used by the report to show how much data is
    /// anchored at each sha. One query — diagnostic, not a hot path.
    pub fn row_counts_by_sha(
        &self,
        fingerprint: &str,
    ) -> Result<BTreeMap<String, usize>> {
        let mut stmt = self.conn.prepare(
            "SELECT collect_sha, COUNT(*) FROM test_regions \
             WHERE env_fingerprint = ?1 \
             GROUP BY collect_sha",
        )?;
        let rows = stmt.query_map([fingerprint], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
        })?;
        let mut out = BTreeMap::new();
        for r in rows {
            let (sha, count) = r?;
            out.insert(sha, count as usize);
        }
        Ok(out)
    }

    /// Distinct (binary_id, test_name) pairs under `fingerprint`, ignoring
    /// `collect_sha`. Used by selection to distinguish "stranded" tests
    /// (in DB but only at currently-missing shas) from "genuinely new"
    /// tests (not in DB at all): if a listed test appears here but not
    /// in [`Db::all_tests_at_shas`] for the reachable subset, it's stranded.
    pub fn all_tests_for_fingerprint(
        &self,
        fingerprint: &str,
    ) -> Result<BTreeSet<TestId>> {
        let mut stmt = self.conn.prepare(
            "SELECT DISTINCT binary_id, test_name FROM test_regions \
             WHERE env_fingerprint = ?1",
        )?;
        let rows = stmt.query_map([fingerprint], |row| {
            Ok(TestId::new(row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })?;
        rows.collect::<rusqlite::Result<BTreeSet<TestId>>>()
            .map_err(Into::into)
    }

    /// Distinct (binary_id, test_name) pairs under `fingerprint` whose rows
    /// are anchored at one of `shas`. Used by selection to compute "tests
    /// known to the cache *and reachable*" — tests anchored only at diverged
    /// shas appear missing here, so selection surfaces them as stranded and
    /// reruns them.
    pub fn all_tests_at_shas(
        &self,
        fingerprint: &str,
        shas: &BTreeSet<String>,
    ) -> Result<BTreeSet<TestId>> {
        if shas.is_empty() {
            return Ok(BTreeSet::new());
        }
        let sql = format!(
            "SELECT DISTINCT binary_id, test_name FROM test_regions \
             WHERE env_fingerprint = ?1 AND collect_sha IN ({})",
            in_placeholders(2, shas.len()),
        );
        let mut stmt = self.conn.prepare(&sql)?;
        let params = std::iter::once(fingerprint).chain(shas.iter().map(String::as_str));
        let rows = stmt.query_map(rusqlite::params_from_iter(params), |row| {
            Ok(TestId::new(row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })?;
        rows.collect::<rusqlite::Result<BTreeSet<TestId>>>()
            .map_err(Into::into)
    }

    /// Count of `test_regions` rows under `fingerprint` whose `collect_sha`
    /// is one of `shas`. Used by `status` to quantify diverged-row bloat so
    /// the user knows when `cargo affected clean` is worth running.
    pub fn region_count_at_shas(
        &self,
        fingerprint: &str,
        shas: &BTreeSet<String>,
    ) -> Result<usize> {
        if shas.is_empty() {
            return Ok(0);
        }
        let sql = format!(
            "SELECT COUNT(*) FROM test_regions \
             WHERE env_fingerprint = ?1 AND collect_sha IN ({})",
            in_placeholders(2, shas.len()),
        );
        let params = std::iter::once(fingerprint).chain(shas.iter().map(String::as_str));
        let count: i64 = self
            .conn
            .query_row(&sql, rusqlite::params_from_iter(params), |r| r.get(0))?;
        Ok(count as usize)
    }

    /// Whether the DB holds any coverage data at all (any fingerprint).
    /// Test-only: production code distinguishes `MissNoCoverage` from
    /// `MissFingerprint` via [`Db::stored_fingerprint_snapshots`], which
    /// lets the same query also drive the components-diff diagnostic.
    #[cfg(test)]
    pub fn has_any_coverage(&self) -> Result<bool> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM test_regions", [], |r| r.get(0))?;
        Ok(count > 0)
    }

    /// Remove all coverage data (every fingerprint) and reset the `meta` table.
    ///
    /// Used by `cargo affected clean`. Going through SQL (rather than unlinking
    /// the file) means we acquire the normal write lock — so a concurrent
    /// `collect` finishes cleanly before its data is discarded, instead of
    /// being orphaned onto an unlinked inode.
    pub fn clear(&mut self) -> Result<()> {
        let tx = self
            .conn
            .transaction()
            .map_err(|e| translate_busy(e, "failed to start clear transaction"))?;
        tx.execute("DELETE FROM test_regions", [])?;
        tx.execute("DELETE FROM fingerprints", [])?;
        tx.execute("DELETE FROM fingerprint_components", [])?;
        tx.execute("DELETE FROM meta", [])?;
        tx.commit()
            .map_err(|e| translate_busy(e, "failed to commit clear"))?;
        Ok(())
    }

    /// Evict the least-recently-used fingerprints beyond `keep`, never
    /// evicting `current`. Returns the number evicted.
    pub fn gc(&mut self, current: &str, keep: usize) -> Result<usize> {
        let tx = self
            .conn
            .transaction()
            .map_err(|e| translate_busy(e, "failed to start gc transaction"))?;

        let to_evict: Vec<String> = {
            let mut stmt = tx.prepare(
                "SELECT fingerprint FROM fingerprints \
                 WHERE fingerprint != ?1 \
                 ORDER BY last_seen DESC, fingerprint ASC \
                 LIMIT -1 OFFSET ?2",
            )?;
            let rows = stmt.query_map(
                rusqlite::params![current, keep.saturating_sub(1) as i64],
                |r| r.get::<_, String>(0),
            )?;
            rows.collect::<rusqlite::Result<Vec<String>>>()?
        };

        for fp in &to_evict {
            tx.execute("DELETE FROM test_regions WHERE env_fingerprint = ?1", [fp])?;
            tx.execute("DELETE FROM fingerprints WHERE fingerprint = ?1", [fp])?;
            tx.execute(
                "DELETE FROM fingerprint_components WHERE env_fingerprint = ?1",
                [fp],
            )?;
        }

        tx.commit()
            .map_err(|e| translate_busy(e, "failed to commit gc"))?;
        Ok(to_evict.len())
    }

    /// Count of distinct tracked fingerprints (after any GC).
    pub fn fingerprint_count(&self) -> Result<usize> {
        let count: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM fingerprints", [], |r| r.get(0))?;
        Ok(count as usize)
    }

    /// Return the last collection timestamp, if any.
    pub fn last_collected(&self) -> Result<Option<String>> {
        let result = self.conn.query_row(
            "SELECT value FROM meta WHERE key = 'last_collected'",
            [],
            |r| r.get::<_, String>(0),
        );
        match result {
            Ok(v) => Ok(Some(v)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }
}

/// Warn (to stderr) about changed `.rs` files that have no coverage data under
/// the current fingerprint.
pub fn warn_untracked_rs_files(
    db: &Db,
    fingerprint: &str,
    changed_files: &[String],
) -> Result<()> {
    for file in changed_files {
        if file.ends_with(".rs") && !db.file_tracked(fingerprint, file)? {
            eprintln!(
                "warning: {file} has no coverage data \
                 — run `cargo affected collect` to include it"
            );
        }
    }
    Ok(())
}

/// Drop legacy `test_files` and rebuild any table whose columns predate the
/// current schema. Old rows can't be retroactively tagged with missing
/// columns, and `target/affected/` is cargo-clean territory, so resetting
/// is safe.
fn migrate_legacy_tables(conn: &Connection) -> Result<()> {
    conn.execute("DROP TABLE IF EXISTS test_files", [])?;
    conn.execute("DROP INDEX IF EXISTS idx_source_file_fp", [])?;

    // `test_regions` must carry every required column, including the per-row
    // `collect_sha` introduced for `collect --diff`. Anything older has rows
    // we can't retroactively anchor.
    if table_exists(conn, "test_regions")? {
        let columns = table_columns(conn, "test_regions")?;
        let needed = [
            "binary_id",
            "test_name",
            "source_file",
            "line_start",
            "line_end",
            "env_fingerprint",
            "collect_sha",
        ];
        if !needed.iter().all(|c| columns.iter().any(|col| col == c)) {
            conn.execute("DROP TABLE test_regions", [])?;
            conn.execute("DROP INDEX IF EXISTS idx_test_regions_lookup", [])?;
        }
    }

    // `fingerprints` previously carried a `collect_sha` column; rows there
    // referred to a single sha for the whole fingerprint. With per-row
    // `collect_sha` on `test_regions`, the column is dead weight — drop the
    // table so the new schema (without that column) is used. Last-seen will
    // be re-populated on next collect/query.
    if table_exists(conn, "fingerprints")? {
        let columns = table_columns(conn, "fingerprints")?;
        if columns.iter().any(|c| c == "collect_sha") {
            conn.execute("DROP TABLE fingerprints", [])?;
        }
    }

    // The `fingerprint_components` table was added to support the
    // diagnostic JSON report ("which input differs?"). Existing rows in
    // `test_regions` from a pre-components binary have no component data
    // we can retroactively recover, so reset the coverage tables and let
    // the next `collect` repopulate everything. Likewise if the components
    // table itself has the wrong shape.
    let coverage_needs_reset = if table_exists(conn, "fingerprint_components")? {
        let columns = table_columns(conn, "fingerprint_components")?;
        let needed = ["env_fingerprint", "label", "content_hash"];
        !needed.iter().all(|c| columns.iter().any(|col| col == c))
    } else {
        // No components table at all: any test_regions rows reference
        // fingerprints we can't decompose. Drop them.
        table_exists(conn, "test_regions")?
    };

    if coverage_needs_reset {
        drop_coverage_tables(conn)?;
    }

    // Invariant: every fingerprint referenced by `test_regions` must have
    // matching `fingerprint_components` rows. A mismatch means an old
    // binary wrote rows after the new schema was created (or vice versa);
    // either way we can't trust the components table to answer "what
    // differs?" for those rows. Reset.
    if table_exists(conn, "test_regions")? && table_exists(conn, "fingerprint_components")? {
        let orphan: i64 = conn.query_row(
            "SELECT COUNT(*) FROM ( \
                SELECT 1 FROM test_regions tr \
                WHERE NOT EXISTS ( \
                    SELECT 1 FROM fingerprint_components fc \
                    WHERE fc.env_fingerprint = tr.env_fingerprint \
                ) LIMIT 1 \
             )",
            [],
            |r| r.get(0),
        )?;
        if orphan > 0 {
            drop_coverage_tables(conn)?;
        }
    }
    Ok(())
}

/// Drop every table that holds coverage state (test rows, fingerprints,
/// component hashes). The next collect rebuilds them from scratch via the
/// `CREATE TABLE IF NOT EXISTS` schema.
fn drop_coverage_tables(conn: &Connection) -> Result<()> {
    conn.execute("DROP TABLE IF EXISTS test_regions", [])?;
    conn.execute("DROP INDEX IF EXISTS idx_test_regions_lookup", [])?;
    conn.execute("DROP TABLE IF EXISTS fingerprints", [])?;
    conn.execute("DROP TABLE IF EXISTS fingerprint_components", [])?;
    Ok(())
}

fn table_exists(conn: &Connection, table: &str) -> Result<bool> {
    let count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
        [table],
        |r| r.get(0),
    )?;
    Ok(count > 0)
}

fn table_columns(conn: &Connection, table: &str) -> Result<Vec<String>> {
    let sql = format!("PRAGMA table_info({table})");
    let mut stmt = conn.prepare(&sql)?;
    let cols: Vec<String> = stmt
        .query_map([], |row| row.get::<_, String>(1))?
        .collect::<std::result::Result<_, _>>()?;
    Ok(cols)
}

fn write_last_collected(tx: &rusqlite::Transaction<'_>) -> Result<()> {
    let timestamp = chrono_free_timestamp();
    tx.execute(
        "INSERT OR REPLACE INTO meta (key, value) VALUES ('last_collected', ?1)",
        [&timestamp],
    )?;
    Ok(())
}

/// ISO-8601 UTC timestamp without external dependencies.
fn chrono_free_timestamp() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let time_of_day = secs % 86400;
    let hours = time_of_day / 3600;
    let minutes = (time_of_day % 3600) / 60;
    let seconds = time_of_day % 60;

    let (year, month, day) = days_to_civil(secs / 86400);
    format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
}

/// Convert days since Unix epoch to (year, month, day).
///
/// Algorithm from <http://howardhinnant.github.io/date_algorithms.html>.
fn days_to_civil(days: u64) -> (u64, u64, u64) {
    let z = days + 719468;
    let era = z / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

#[cfg(test)]
mod tests {
    use super::*;
    use camino::Utf8PathBuf;

    const FP_A: &str = "aaaaaaaa";
    const FP_B: &str = "bbbbbbbb";
    const SHA_A: &str = "0000000000000000000000000000000000000000";
    const SHA_B: &str = "1111111111111111111111111111111111111111";
    const BIN_A: &str = "crate_a";
    const BIN_B: &str = "crate_b";

    fn tid(binary_id: &str, test_name: &str) -> TestId {
        TestId::new(binary_id, test_name)
    }

    fn rng(file: &str, line_start: i64, line_end: i64) -> HitRange {
        HitRange {
            file: Utf8PathBuf::from(file),
            line_start,
            line_end,
        }
    }

    fn hunk(start: i64, end: i64) -> LineRange {
        LineRange { start, end }
    }

    /// Synthetic per-fingerprint components for tests. Production uses
    /// `fingerprint::compute`; tests just need the components table to
    /// have rows so the migration's invariant check stays satisfied.
    fn comps_for(fp: &str) -> Vec<FingerprintComponent> {
        vec![FingerprintComponent {
            label: "cargo_lock".to_string(),
            hash: format!("hash-of-{fp}-cargo_lock"),
        }]
    }

    /// Collapse the per-row [`TestHit`] stream into the deduplicated
    /// `(binary_id, test_name)` set the existing tests assert against.
    /// The hit-reason aggregation lives in `selection.rs`; this helper is
    /// just for readability inside the storage-layer tests.
    fn ids(hits: Vec<TestHit>) -> BTreeSet<TestId> {
        hits.into_iter().map(|h| h.test_id).collect()
    }

    #[test]
    fn roundtrip_with_range_overlap() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let a_ranges = BTreeSet::from([
            rng("src/lib.rs", 10, 20),
            rng("src/utils.rs", 5, 15),
        ]);
        let b_ranges = BTreeSet::from([rng("src/lib.rs", 50, 60)]);
        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "test_a"), a_ranges), (tid(BIN_A, "test_b"), b_ranges)],
        )?;

        assert_eq!(db.test_count(FP_A)?, 2);
        assert_eq!(db.region_count(FP_A)?, 3);
        assert_eq!(db.collect_shas(FP_A)?, BTreeSet::from([SHA_A.to_string()]));

        // Hunk overlapping test_a's lib.rs range.
        let hits = ids(db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(15, 18)])?);
        assert_eq!(hits, BTreeSet::from([tid(BIN_A, "test_a")]));

        // Hunk overlapping test_b's lib.rs range.
        let hits = ids(db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(55, 55)])?);
        assert_eq!(hits, BTreeSet::from([tid(BIN_A, "test_b")]));

        // Multiple hunks in same file → union.
        let hits = ids(
            db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(15, 18), hunk(55, 55)])?,
        );
        assert_eq!(
            hits,
            BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_b")])
        );

        Ok(())
    }

    /// Backstop: a hunk that overlaps no stored range broadens to all tests
    /// with rows for the file. Models a struct-field edit between two
    /// functions — neither function's range overlaps line 25, but both tests
    /// touched lib.rs and so both must be selected to be safe.
    #[test]
    fn structural_edit_backstop() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        // test_a covers lines 10-20; test_b covers lines 50-60. Nothing
        // touches line 25 (the "struct field" edit zone).
        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 10, 20)])),
                (tid(BIN_A, "test_b"), BTreeSet::from([rng("src/lib.rs", 50, 60)])),
            ],
        )?;

        // No range overlaps line 25 → backstop fires → every test touching
        // lib.rs is selected.
        let hits = ids(db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(25, 25)])?);
        assert_eq!(
            hits,
            BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_b")])
        );

        // Backstop applies per-hunk: a body-edit hunk + a structural-edit
        // hunk in the same file still selects everyone.
        let hits = ids(db.tests_covering_ranges(
            FP_A,
            SHA_A,
            "src/lib.rs",
            &[hunk(15, 15), hunk(25, 25)],
        )?);
        assert_eq!(
            hits,
            BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_b")])
        );

        Ok(())
    }

    /// Crate roots stored with sentinel `(1, i64::MAX)` are overlapped by
    /// any hunk in the file, so every test that "covers" the crate root via
    /// the implicit-dep path is selected.
    #[test]
    fn crate_root_sentinel_overlaps_any_hunk() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let mappings = vec![
            (
                tid(BIN_A, "test_a"),
                BTreeSet::from([HitRange::sentinel(Utf8PathBuf::from("src/lib.rs"))]),
            ),
            (
                tid(BIN_A, "test_b"),
                BTreeSet::from([HitRange::sentinel(Utf8PathBuf::from("src/lib.rs"))]),
            ),
        ];
        db.store_coverage(FP_A, &comps_for(FP_A), SHA_A, &mappings)?;

        let hits = ids(db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(7, 7)])?);
        assert_eq!(
            hits,
            BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_b")])
        );
        Ok(())
    }

    #[test]
    fn different_fingerprint_reads_empty() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 1, 10)]))],
        )?;

        assert_eq!(db.test_count(FP_B)?, 0);
        assert_eq!(db.region_count(FP_B)?, 0);
        assert!(db
            .tests_covering_ranges(FP_B, SHA_A, "src/lib.rs", &[hunk(1, 5)])?
            .is_empty());  // Vec<TestHit>::is_empty()
        assert!(!db.file_tracked(FP_B, "src/lib.rs")?);
        assert!(db
            .all_tests_at_shas(FP_B, &BTreeSet::from([SHA_A.to_string()]))?
            .is_empty());
        assert!(db.collect_shas(FP_B)?.is_empty());
        assert!(db.has_any_coverage()?);
        Ok(())
    }

    #[test]
    fn full_collect_preserves_other_fingerprints() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))],
        )?;
        db.store_coverage(
            FP_B,
            &comps_for(FP_B),
            SHA_B,
            &[(tid(BIN_A, "test_b"), BTreeSet::from([rng("src/other.rs", 10, 15)]))],
        )?;

        // Rewriting FP_A leaves FP_B alone.
        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/new.rs", 1, 1)]))],
        )?;

        assert_eq!(db.test_count(FP_A)?, 1);
        assert_eq!(db.test_count(FP_B)?, 1);
        assert_eq!(
            ids(db.tests_covering_ranges(FP_B, SHA_B, "src/other.rs", &[hunk(10, 12)])?),
            BTreeSet::from([tid(BIN_A, "test_b")])
        );
        assert_eq!(
            ids(db.tests_covering_ranges(FP_A, SHA_A, "src/new.rs", &[hunk(1, 1)])?),
            BTreeSet::from([tid(BIN_A, "test_a")])
        );
        assert!(db
            .tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(1, 5)])?
            .is_empty());
        Ok(())
    }

    /// Two tests with the same name in different binaries must round-trip
    /// independently.
    #[test]
    fn same_test_name_in_different_binaries() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (tid(BIN_A, "builds"), BTreeSet::from([rng("crate_a/tests/builds.rs", 1, 5)])),
                (tid(BIN_B, "builds"), BTreeSet::from([rng("crate_b/tests/builds.rs", 1, 5)])),
            ],
        )?;

        assert_eq!(db.test_count(FP_A)?, 2);
        let a = ids(db.tests_covering_ranges(FP_A, SHA_A, "crate_a/tests/builds.rs", &[hunk(2, 3)])?);
        assert_eq!(a, BTreeSet::from([tid(BIN_A, "builds")]));
        let b = ids(db.tests_covering_ranges(FP_A, SHA_A, "crate_b/tests/builds.rs", &[hunk(2, 3)])?);
        assert_eq!(b, BTreeSet::from([tid(BIN_B, "builds")]));
        Ok(())
    }

    #[test]
    fn clear_wipes_all_fingerprints() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let mappings =
            vec![(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))];
        db.store_coverage(FP_A, &comps_for(FP_A), SHA_A, &mappings)?;
        db.store_coverage(FP_B, &comps_for(FP_B), SHA_B, &mappings)?;
        assert!(db.has_any_coverage()?);

        db.clear()?;
        assert!(!db.has_any_coverage()?);
        assert_eq!(db.test_count(FP_A)?, 0);
        assert_eq!(db.test_count(FP_B)?, 0);
        assert!(db.last_collected()?.is_none());

        // Still usable.
        db.store_coverage(FP_A, &comps_for(FP_A), SHA_A, &mappings)?;
        assert_eq!(db.test_count(FP_A)?, 1);
        Ok(())
    }

    #[test]
    fn gc_keeps_current_and_most_recent_others() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let mappings =
            vec![(tid(BIN_A, "t"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))];

        for fp in ["fp1", "fp2", "fp3", "fp4"] {
            db.store_coverage(fp, &comps_for(fp), SHA_A, &mappings)?;
            db.conn.execute(
                "UPDATE fingerprints SET last_seen = ?2 WHERE fingerprint = ?1",
                rusqlite::params![fp, format!("2020-01-01T00:00:{:02}Z", fp.as_bytes()[2] - b'0')],
            )?;
        }
        assert_eq!(db.fingerprint_count()?, 4);

        let evicted = db.gc("fp4", 2)?;
        assert_eq!(evicted, 2);
        assert_eq!(db.fingerprint_count()?, 2);
        assert_eq!(db.test_count("fp1")?, 0);
        assert_eq!(db.test_count("fp2")?, 0);
        assert_eq!(db.test_count("fp3")?, 1);
        assert_eq!(db.test_count("fp4")?, 1);
        Ok(())
    }

    #[test]
    fn pre_range_schema_is_dropped() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = db_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap())?;

        // Old file-level schema with rows.
        {
            let conn = Connection::open(&path)?;
            conn.execute_batch(
                "\
                CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
                CREATE TABLE test_files (
                    binary_id TEXT NOT NULL,
                    test_name TEXT NOT NULL,
                    source_file TEXT NOT NULL,
                    env_fingerprint TEXT NOT NULL,
                    PRIMARY KEY (binary_id, test_name, source_file, env_fingerprint)
                );
                INSERT INTO test_files VALUES ('bin1', 't1', 'src/lib.rs', 'fp_x');
                CREATE TABLE fingerprints (
                    fingerprint TEXT PRIMARY KEY,
                    last_seen TEXT NOT NULL
                );
                INSERT INTO fingerprints VALUES ('fp_x', '2020-01-01T00:00:00Z');
                ",
            )?;
        }

        // Open with new code: old `test_files` is gone, no rows survive.
        let db = Db::open(dir.path())?;
        assert!(!db.has_any_coverage()?);
        Ok(())
    }

    /// Pre-`--diff` schema put `collect_sha` on `fingerprints` and left it
    /// off `test_regions`. Both shapes must be dropped so the new per-row
    /// layout takes over cleanly.
    #[test]
    fn pre_diff_schema_is_dropped() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = db_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap())?;

        {
            let conn = Connection::open(&path)?;
            conn.execute_batch(
                "\
                CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
                CREATE TABLE test_regions (
                    binary_id TEXT NOT NULL,
                    test_name TEXT NOT NULL,
                    source_file TEXT NOT NULL,
                    line_start INTEGER NOT NULL,
                    line_end INTEGER NOT NULL,
                    env_fingerprint TEXT NOT NULL,
                    PRIMARY KEY (binary_id, test_name, source_file, line_start, line_end, env_fingerprint)
                );
                INSERT INTO test_regions VALUES ('bin1', 't1', 'src/lib.rs', 1, 5, 'fp_x');
                CREATE TABLE fingerprints (
                    fingerprint TEXT PRIMARY KEY,
                    last_seen TEXT NOT NULL,
                    collect_sha TEXT
                );
                INSERT INTO fingerprints VALUES ('fp_x', '2020-01-01T00:00:00Z', 'deadbeef');
                ",
            )?;
        }

        let db = Db::open(dir.path())?;
        assert!(!db.has_any_coverage()?);
        assert_eq!(db.fingerprint_count()?, 0);
        Ok(())
    }

    /// `update_coverage_for_tests` replaces just the rerun tests' rows,
    /// re-anchored at the new sha; everyone else stays put with their old
    /// sha.
    #[test]
    fn diff_update_replaces_only_rerun_tests() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (tid(BIN_A, "test_a"), BTreeSet::from([rng("src/a.rs", 1, 5)])),
                (tid(BIN_A, "test_b"), BTreeSet::from([rng("src/b.rs", 1, 5)])),
                (tid(BIN_A, "test_c"), BTreeSet::from([rng("src/c.rs", 1, 5)])),
            ],
        )?;
        assert_eq!(db.collect_shas(FP_A)?, BTreeSet::from([SHA_A.to_string()]));

        // Rerun only test_a, with new ranges anchored at SHA_B.
        db.update_coverage_for_tests(
            FP_A,
            &comps_for(FP_A),
            SHA_B,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/a.rs", 10, 20)]))],
        )?;

        // Both shas now coexist for FP_A.
        assert_eq!(
            db.collect_shas(FP_A)?,
            BTreeSet::from([SHA_A.to_string(), SHA_B.to_string()]),
        );

        // test_a is queryable at SHA_B with its new range.
        assert_eq!(
            ids(db.tests_covering_ranges(FP_A, SHA_B, "src/a.rs", &[hunk(15, 15)])?),
            BTreeSet::from([tid(BIN_A, "test_a")]),
        );
        // …and gone from SHA_A: its old (1,5) row was deleted.
        assert!(db
            .tests_covering_ranges(FP_A, SHA_A, "src/a.rs", &[hunk(1, 5)])?
            .is_empty());

        // test_b/test_c untouched — still anchored at SHA_A.
        assert_eq!(
            ids(db.tests_covering_ranges(FP_A, SHA_A, "src/b.rs", &[hunk(1, 5)])?),
            BTreeSet::from([tid(BIN_A, "test_b")]),
        );
        assert_eq!(
            ids(db.tests_covering_ranges(FP_A, SHA_A, "src/c.rs", &[hunk(1, 5)])?),
            BTreeSet::from([tid(BIN_A, "test_c")]),
        );

        Ok(())
    }

    /// `prune_missing_tests` drops rows for tests that aren't in the current
    /// listing — renamed or deleted between collects.
    #[test]
    fn diff_prune_drops_absent_tests() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (tid(BIN_A, "test_a"), BTreeSet::from([rng("src/a.rs", 1, 5)])),
                (tid(BIN_A, "test_b"), BTreeSet::from([rng("src/b.rs", 1, 5)])),
                (tid(BIN_A, "test_c"), BTreeSet::from([rng("src/c.rs", 1, 5)])),
            ],
        )?;

        let present = BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_c")]);
        let evicted = db.prune_missing_tests(FP_A, &present)?;
        assert_eq!(evicted, 1);
        assert_eq!(db.test_count(FP_A)?, 2);
        assert!(db
            .tests_covering_ranges(FP_A, SHA_A, "src/b.rs", &[hunk(1, 5)])?
            .is_empty());
        assert_eq!(
            ids(db.tests_covering_ranges(FP_A, SHA_A, "src/a.rs", &[hunk(1, 5)])?),
            BTreeSet::from([tid(BIN_A, "test_a")]),
        );
        Ok(())
    }

    /// `region_count_at_shas` scopes by both fingerprint and sha, used for
    /// the stale-row count `status` shows on partial divergence.
    #[test]
    fn region_count_scoped_by_shas() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (tid(BIN_A, "ta"), BTreeSet::from([rng("src/a.rs", 1, 5)])),
                (tid(BIN_A, "tb"), BTreeSet::from([rng("src/b.rs", 1, 5)])),
            ],
        )?;
        db.update_coverage_for_tests(
            FP_A,
            &comps_for(FP_A),
            SHA_B,
            &[(tid(BIN_A, "ta"), BTreeSet::from([rng("src/a.rs", 10, 20)]))],
        )?;

        // FP_A now: tb at SHA_A (1 row), ta at SHA_B (1 row).
        assert_eq!(
            db.region_count_at_shas(FP_A, &BTreeSet::from([SHA_A.to_string()]))?,
            1,
        );
        assert_eq!(
            db.region_count_at_shas(FP_A, &BTreeSet::from([SHA_B.to_string()]))?,
            1,
        );
        assert_eq!(
            db.region_count_at_shas(
                FP_A,
                &BTreeSet::from([SHA_A.to_string(), SHA_B.to_string()]),
            )?,
            2,
        );
        // Empty input → 0 (and skips the IN-clause path).
        assert_eq!(db.region_count_at_shas(FP_A, &BTreeSet::new())?, 0);
        // Wrong fingerprint → 0.
        assert_eq!(
            db.region_count_at_shas(FP_B, &BTreeSet::from([SHA_A.to_string()]))?,
            0,
        );
        Ok(())
    }

    /// Reads back the (label, hash) component rows for a fingerprint via
    /// the same query the report builder will use, so we exercise the
    /// SQL shape too.
    fn read_components(db: &Db, fingerprint: &str) -> Vec<(String, String)> {
        let mut stmt = db
            .conn
            .prepare(
                "SELECT label, content_hash FROM fingerprint_components \
                 WHERE env_fingerprint = ?1 ORDER BY label",
            )
            .unwrap();
        stmt.query_map([fingerprint], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })
        .unwrap()
        .collect::<rusqlite::Result<Vec<_>>>()
        .unwrap()
    }

    #[test]
    fn store_coverage_writes_components() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let comps = vec![
            FingerprintComponent {
                label: "cargo_lock".to_string(),
                hash: "h-lock".to_string(),
            },
            FingerprintComponent {
                label: "rustc".to_string(),
                hash: "h-rustc".to_string(),
            },
        ];
        db.store_coverage(
            FP_A,
            &comps,
            SHA_A,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))],
        )?;

        assert_eq!(
            read_components(&db, FP_A),
            vec![
                ("cargo_lock".to_string(), "h-lock".to_string()),
                ("rustc".to_string(), "h-rustc".to_string()),
            ],
        );
        Ok(())
    }

    /// Re-storing under the same fingerprint replaces — not duplicates —
    /// the component rows.
    #[test]
    fn store_coverage_replaces_components_idempotently() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let mappings =
            vec![(tid(BIN_A, "t"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))];

        db.store_coverage(
            FP_A,
            &[FingerprintComponent {
                label: "cargo_lock".to_string(),
                hash: "first".to_string(),
            }],
            SHA_A,
            &mappings,
        )?;
        db.store_coverage(
            FP_A,
            &[FingerprintComponent {
                label: "cargo_lock".to_string(),
                hash: "second".to_string(),
            }],
            SHA_A,
            &mappings,
        )?;

        assert_eq!(
            read_components(&db, FP_A),
            vec![("cargo_lock".to_string(), "second".to_string())],
        );
        Ok(())
    }

    #[test]
    fn gc_evicts_components() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        let mappings =
            vec![(tid(BIN_A, "t"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))];

        for fp in ["fp1", "fp2", "fp3", "fp4"] {
            db.store_coverage(fp, &comps_for(fp), SHA_A, &mappings)?;
            db.conn.execute(
                "UPDATE fingerprints SET last_seen = ?2 WHERE fingerprint = ?1",
                rusqlite::params![fp, format!("2020-01-01T00:00:{:02}Z", fp.as_bytes()[2] - b'0')],
            )?;
        }
        // Sanity: every fingerprint has a components row.
        for fp in ["fp1", "fp2", "fp3", "fp4"] {
            assert_eq!(read_components(&db, fp).len(), 1);
        }

        db.gc("fp4", 2)?;
        // Evicted fingerprints' component rows must be gone too.
        assert!(read_components(&db, "fp1").is_empty());
        assert!(read_components(&db, "fp2").is_empty());
        // Survivors retained.
        assert_eq!(read_components(&db, "fp3").len(), 1);
        assert_eq!(read_components(&db, "fp4").len(), 1);
        Ok(())
    }

    #[test]
    fn clear_wipes_components() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "t"), BTreeSet::from([rng("src/lib.rs", 1, 5)]))],
        )?;
        assert!(!read_components(&db, FP_A).is_empty());

        db.clear()?;
        assert!(read_components(&db, FP_A).is_empty());
        Ok(())
    }

    /// A pre-components DB (test_regions populated, no fingerprint_components
    /// table at all) must be reset on open. There's no way to retroactively
    /// generate component hashes for the existing rows.
    #[test]
    fn migration_resets_pre_components_db() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = db_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap())?;

        // Build the pre-components schema by hand: same shape as the
        // current `test_regions`/`fingerprints`, no `fingerprint_components`.
        {
            let conn = Connection::open(&path)?;
            conn.execute_batch(
                "\
                CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
                CREATE TABLE test_regions (
                    binary_id TEXT NOT NULL,
                    test_name TEXT NOT NULL,
                    source_file TEXT NOT NULL,
                    line_start INTEGER NOT NULL,
                    line_end INTEGER NOT NULL,
                    env_fingerprint TEXT NOT NULL,
                    collect_sha TEXT NOT NULL,
                    PRIMARY KEY (binary_id, test_name, source_file, line_start, line_end, env_fingerprint, collect_sha)
                );
                INSERT INTO test_regions VALUES ('bin1', 't1', 'src/lib.rs', 1, 5, 'old_fp', 'sha');
                CREATE TABLE fingerprints (
                    fingerprint TEXT PRIMARY KEY,
                    last_seen TEXT NOT NULL
                );
                INSERT INTO fingerprints VALUES ('old_fp', '2020-01-01T00:00:00Z');
                ",
            )?;
        }

        let db = Db::open(dir.path())?;
        assert!(!db.has_any_coverage()?);
        assert_eq!(db.fingerprint_count()?, 0);
        Ok(())
    }

    /// If `fingerprint_components` exists but has the wrong column shape,
    /// drop it and reset coverage. Same destructive cutover as every other
    /// shape mismatch.
    #[test]
    fn migration_resets_on_components_column_mismatch() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = db_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap())?;

        {
            let conn = Connection::open(&path)?;
            conn.execute_batch(
                "\
                CREATE TABLE test_regions (
                    binary_id TEXT NOT NULL,
                    test_name TEXT NOT NULL,
                    source_file TEXT NOT NULL,
                    line_start INTEGER NOT NULL,
                    line_end INTEGER NOT NULL,
                    env_fingerprint TEXT NOT NULL,
                    collect_sha TEXT NOT NULL,
                    PRIMARY KEY (binary_id, test_name, source_file, line_start, line_end, env_fingerprint, collect_sha)
                );
                INSERT INTO test_regions VALUES ('bin1', 't1', 'src/lib.rs', 1, 5, 'fp', 'sha');
                CREATE TABLE fingerprint_components (
                    env_fingerprint TEXT NOT NULL,
                    label_OLD TEXT NOT NULL,    -- wrong column name
                    content_hash TEXT NOT NULL,
                    PRIMARY KEY (env_fingerprint, label_OLD)
                );
                ",
            )?;
        }

        let db = Db::open(dir.path())?;
        assert!(!db.has_any_coverage()?);
        Ok(())
    }

    /// Mixed old/new binary use can leave `test_regions` rows referencing
    /// fingerprints absent from `fingerprint_components`. The invariant
    /// check catches that and resets.
    #[test]
    fn migration_resets_on_orphan_test_regions_rows() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = db_path(dir.path());
        std::fs::create_dir_all(path.parent().unwrap())?;

        {
            let conn = Connection::open(&path)?;
            conn.execute_batch(
                "\
                CREATE TABLE test_regions (
                    binary_id TEXT NOT NULL,
                    test_name TEXT NOT NULL,
                    source_file TEXT NOT NULL,
                    line_start INTEGER NOT NULL,
                    line_end INTEGER NOT NULL,
                    env_fingerprint TEXT NOT NULL,
                    collect_sha TEXT NOT NULL,
                    PRIMARY KEY (binary_id, test_name, source_file, line_start, line_end, env_fingerprint, collect_sha)
                );
                CREATE TABLE fingerprint_components (
                    env_fingerprint TEXT NOT NULL,
                    label TEXT NOT NULL,
                    content_hash TEXT NOT NULL,
                    PRIMARY KEY (env_fingerprint, label)
                );
                INSERT INTO test_regions VALUES ('bin1', 't1', 'src/lib.rs', 1, 5, 'orphan_fp', 'sha');
                -- No matching fingerprint_components row for orphan_fp.
                INSERT INTO fingerprint_components VALUES ('different_fp', 'cargo_lock', 'h');
                ",
            )?;
        }

        let db = Db::open(dir.path())?;
        assert!(!db.has_any_coverage()?);
        Ok(())
    }

    /// `tests_covering_ranges` returns one [`TestHit`] per (row, hunk)
    /// match for the LineOverlap path; the hit's reason names the file,
    /// the matched hunk, and the stored range.
    #[test]
    fn hits_classify_line_overlap() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(tid(BIN_A, "test_a"), BTreeSet::from([rng("src/lib.rs", 10, 20)]))],
        )?;

        let hits = db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(15, 18)])?;
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].test_id, tid(BIN_A, "test_a"));
        assert_eq!(hits[0].reason.kind, HitKind::LineOverlap);
        assert_eq!(hits[0].reason.file, "src/lib.rs");
        assert_eq!(hits[0].reason.collect_sha, SHA_A);
        assert_eq!(hits[0].reason.matched_hunk, (15, 18));
        assert_eq!(hits[0].reason.stored_range, Some((10, 20)));
        Ok(())
    }

    /// A row matching the canonical `(1, CRATE_ROOT_SENTINEL_END)` shape
    /// must classify as `CrateRootSentinel`, not `LineOverlap`.
    #[test]
    fn hits_classify_crate_root_sentinel() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[(
                tid(BIN_A, "test_a"),
                BTreeSet::from([HitRange::sentinel(Utf8PathBuf::from("src/lib.rs"))]),
            )],
        )?;

        let hits = db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(7, 7)])?;
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].reason.kind, HitKind::CrateRootSentinel);
        assert_eq!(hits[0].reason.stored_range, Some((1, CRATE_ROOT_SENTINEL_END)));
        Ok(())
    }

    /// When no row overlaps the hunk, the structural-edit backstop fires:
    /// emit one hit per unique test for the file (NOT once per row), with
    /// `kind = StructuralBackstop` and `stored_range = None`.
    #[test]
    fn hits_classify_structural_backstop_dedupes_per_test() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let mut db = Db::open(dir.path())?;

        // test_a has TWO rows in lib.rs (10-15 and 30-35); test_b has one
        // row (50-55). A hunk at line 25 overlaps NONE of them, so the
        // backstop fires. test_a must appear exactly once despite having
        // multiple rows for the file.
        db.store_coverage(
            FP_A,
            &comps_for(FP_A),
            SHA_A,
            &[
                (
                    tid(BIN_A, "test_a"),
                    BTreeSet::from([
                        rng("src/lib.rs", 10, 15),
                        rng("src/lib.rs", 30, 35),
                    ]),
                ),
                (tid(BIN_A, "test_b"), BTreeSet::from([rng("src/lib.rs", 50, 55)])),
            ],
        )?;

        let hits = db.tests_covering_ranges(FP_A, SHA_A, "src/lib.rs", &[hunk(25, 25)])?;
        assert_eq!(hits.len(), 2, "one hit per unique test, not per row");
        for hit in &hits {
            assert_eq!(hit.reason.kind, HitKind::StructuralBackstop);
            assert_eq!(hit.reason.stored_range, None);
            assert_eq!(hit.reason.matched_hunk, (25, 25));
        }
        let unique: BTreeSet<TestId> = hits.iter().map(|h| h.test_id.clone()).collect();
        assert_eq!(
            unique,
            BTreeSet::from([tid(BIN_A, "test_a"), tid(BIN_A, "test_b")])
        );
        Ok(())
    }
}