kache 0.25.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more, with S3 and shared-filesystem remotes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
//! Walking an `extern:` cascade back to the crate that actually changed
//! (kunobi-ninja/kache#609).
//!
//! When one crate's artifact content moves, `extern:<name>=<hash>` re-keys
//! every crate above it. `why-miss` then reports the same thing for all of
//! them: "same config -- likely source code, dependency, or rustc version
//! change". True for the crate that changed, useless for the forty that are
//! only downstream of it, and the reporter in #580 had to work down the chain
//! by hand to find that `aws_lc_sys` was the root.
//!
//! The per-dependency digests recorded on each event (`key_externs`) make the
//! walk mechanical: diff a crate's compile against the previous recorded state
//! of the same crate to see WHICH dependencies moved, then repeat for each of
//! them until reaching crates whose divergence is not itself dependency-driven.
//!
//! # Why every branch is walked
//!
//! In a real cascade the crate being asked about usually has SEVERAL changed
//! dependencies — in #580, `rig_core` sits above `aws_lc_rs`, `aws_sdk_*`,
//! `async_nats` and more, all re-keyed by the same leaf. Following one of them
//! and calling it "the root" would be an arbitrary choice dressed up as a
//! diagnosis. Bailing out whenever more than one moved would instead give up
//! exactly in the case this exists to explain. So every branch is walked, and
//! the roots are ranked by how many branches converge on them: the crate that
//! shows up under most of the changed dependencies is the one to look at.
//!
//! # Event selection
//!
//! The walk is driven by POSITION in the oldest-first event slice, never by
//! timestamp. Each hop searches strictly before the parent's event, so the
//! selected events are causally ordered and the walk cannot pick a later,
//! unrelated compile of a dependency. Timestamps are unfit for this: two events
//! can share one, and a dependency can be recompiled between the moment a
//! parent hashes its artifact and the moment the parent's own event is logged.
//!
//! # Unit identity
//!
//! `crate_name` is not a compilation-unit identity: two versions of a package,
//! a host and a target build of the same crate, and two feature sets of it all
//! collapse onto one name, and Cargo's `package = "..."` renaming makes the
//! consumer's name for a dependency differ from the producer's own
//! (kunobi-ninja/kache#627). Pairing by name therefore risks comparing
//! unrelated units, or dead-ending on an alias no event carries.
//!
//! So the walk pairs by unit id wherever the events have one: cargo's
//! `-C extra-filename` hash, recorded on the producing event (`unit_id`) and
//! recovered by the consumer from its `--extern` artifact filename
//! (`extern_units`). That is the disambiguator cargo itself uses to keep those
//! units' artifacts apart in one `deps/` directory, and it is visible from both
//! sides, so the join holds regardless of the name the consumer used.
//!
//! Name matching stays as the fallback for events carrying no unit id — a
//! non-cargo rustc invocation, a sysroot crate, a pre-#627 wrapper. There the
//! old ambiguity remains, and the walk still prefers an unresolved endpoint
//! over a confident wrong one wherever the history does not support a
//! conclusion.
//!
//! # Another checkout as the baseline
//!
//! The first build in a second clone or worktree has no earlier build in its
//! own tree, so a same-tree walk has nothing to diff. That is the cross-clone
//! case, where one checkout filled the cache and the next still misses some
//! crates. When the tree has no baseline for the crate being explained, the
//! walk uses the most recent build of the same unit in another checkout, and
//! takes every baseline from that one checkout. Unit ids make that pairing
//! safe: cargo hashes a workspace member relative to its workspace root, so two
//! checkouts of one project agree on them. Without a unit id nothing crosses
//! checkouts.
//!
//! Key group digests hash path-normalized inputs, so a group that differs
//! between checkouts is a real input difference, or a path normalization
//! missed. A unit with the same key in both checkouts whose artifact still
//! differs ends the walk as `PathOnly`: nothing it is keyed on differs, and its
//! output is not reproducible across checkouts.
//!
//! Everything here is a pure function over already-read events: no store, no
//! filesystem, no clock. `cli` renders the result.

use crate::events::{BuildEvent, EventResult};
use std::collections::{BTreeMap, HashSet};

/// Hops to follow down one branch before giving up.
const MAX_DEPTH: usize = 12;

/// Total crates examined across all branches, so a wide graph cannot turn a
/// diagnostic into a long walk.
const MAX_NODES: usize = 64;

/// A dependency whose artifact digest differs between a crate's compile and the
/// previous recorded state of that crate.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct ChangedDep {
    /// The name the CONSUMER used, which Cargo's `package = "..."` renaming can
    /// make different from the producing crate's own name.
    pub name: String,
    /// Digest in the baseline event. `None` when the dependency is new.
    pub from: Option<String>,
    /// Digest at the compile being explained. `None` when it went away.
    pub to: Option<String>,
    /// The producing unit's id, when the consumer's event recorded one
    /// (kunobi-ninja/kache#627). This, not `name`, is what selects the
    /// dependency's own events.
    pub unit: Option<String>,
}

/// One step down a branch: `crate_name` diverged because `via` moved.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Hop {
    pub crate_name: String,
    /// Unit id of the crate at this hop, when its event recorded one. Carried
    /// so cycle detection can compare units rather than names; renderers use
    /// `crate_name`.
    pub unit: Option<String>,
    pub via: ChangedDep,
}

/// Identity a branch is tracked by: the unit id when known, else the name.
///
/// Prefixed so a unit id can never collide with a crate that happens to be
/// named the same as some hash.
fn node_key(name: &str, unit: Option<&str>) -> String {
    match unit {
        Some(unit) => format!("unit:{unit}"),
        None => format!("name:{name}"),
    }
}

/// Why the crate at the end of a branch diverged.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "kind", content = "groups", rename_all = "snake_case")]
pub enum RootKind {
    /// Key input groups that moved, `externs` excluded. The only variant that
    /// asserts a cause; everything else is an explicit dead end.
    Groups(Vec<String>),
    /// Dependencies compared clean and no traced group moved: the difference
    /// sits in a post-hoc fold (key salt, extra inputs).
    NothingRecorded,
    /// The dependency moved but has no compile recorded in this event window.
    NoMissRecorded,
    /// Nothing earlier to diff this crate against.
    NoBaseline,
    /// Reached, but its own dependency history is not comparable, so it cannot
    /// be shown to be the end of the cascade. Distinct from "dependencies were
    /// compared and were stable" — conflating the two invents a root.
    NoDiffableHistory,
    /// The branch was still descending when a limit was hit.
    LimitReached,
    /// Only against another checkout: this unit computed the same cache key
    /// there, so nothing it is keyed on differs beyond the checkout path, yet
    /// its artifact moved. The compile's output is not reproducible across
    /// checkouts.
    PathOnly,
}

impl RootKind {
    /// Whether this endpoint actually explains anything. Renderers must not
    /// present an unresolved endpoint as the cause.
    pub fn is_resolved(&self) -> bool {
        matches!(
            self,
            RootKind::Groups(_) | RootKind::NothingRecorded | RootKind::PathOnly
        )
    }
}

/// Passthrough (uncached) compiles attributed to a root crate, grouped by
/// reason. This is the actionable half: a passthrough there means the crate's
/// artifact varies per checkout, and the reason names the flag to model.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct PassthroughGroup {
    pub reason: String,
    pub count: usize,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Root {
    pub crate_name: String,
    /// Unit id of the event this endpoint resolved to, when that event recorded
    /// one.
    ///
    /// Taken from the SELECTED producer rather than from what the consumer
    /// asked for, so `crate_name` and `unit` always describe the same event and
    /// convergence counting keys on the node actually analyzed. Renderers show
    /// `crate_name`.
    pub unit: Option<String>,
    pub kind: RootKind,
    pub passthroughs: Vec<PassthroughGroup>,
    /// Distinct branches from the starting crate that ended here. A root many
    /// branches converge on is the likely cause of the whole cascade.
    pub branches: usize,
    /// Shortest path of hops that reached this root.
    pub path: Vec<Hop>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Chain {
    /// Endpoints, most-converged first, then shallowest.
    pub roots: Vec<Root>,
    /// Dependencies that moved directly under the crate being explained.
    pub direct: Vec<ChangedDep>,
    /// Set when exploration stopped early rather than exhausting the graph.
    pub truncated: Option<&'static str>,
    /// The other checkout every baseline came from, when the build tree being
    /// explained had no earlier build of the crate. `None` means the usual
    /// same-tree comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub baseline_root: Option<String>,
}

impl Chain {
    /// Whether any endpoint actually explains the cascade.
    pub fn has_resolved_root(&self) -> bool {
        self.roots.iter().any(|r| r.kind.is_resolved())
    }
}

/// What a compile differs in from the same unit built in another checkout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutVerdict {
    /// Same cache key in both checkouts: only the checkout path differs.
    PathOnly,
    /// At least one of the unit's own key input groups differs.
    OwnInputs,
    /// Its own inputs match; only dependency artifacts moved.
    Dependencies,
    /// No traced group or dependency differs, but the keys do: the difference
    /// sits in a post-hoc fold (key salt, extra inputs).
    Untraced,
}

/// A compile compared with the same unit built in another checkout of the
/// project, for a build tree that has no earlier build of its own to diff.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct CheckoutComparison {
    /// Build tree of the compile being explained.
    pub root: String,
    /// The other checkout whose build is the baseline.
    pub baseline_root: String,
    /// Own key input groups that differ, `externs` excluded. Each group is
    /// hashed over path-normalized inputs, so a checkout path alone does not
    /// move one; the exception is `remap` with path remapping turned off, which
    /// keys the raw checkout path on purpose.
    pub groups: Vec<String>,
    /// Dependencies whose artifact digests differ.
    pub dependencies: Vec<ChangedDep>,
    /// Whether both checkouts computed the same final cache key.
    pub same_key: bool,
    pub verdict: CheckoutVerdict,
}

/// Compare the compile at `miss_index` with the same unit in another
/// checkout.
///
/// `None` when the compile's own build tree has an earlier build to diff
/// against (the same-tree comparison stays authoritative), or when no other
/// checkout built this unit.
pub fn compare_checkout(events: &[BuildEvent], miss_index: usize) -> Option<CheckoutComparison> {
    let compiled = events.get(miss_index)?;
    let (baseline, cross_checkout) = top_baseline(events, miss_index)?;
    if !cross_checkout {
        return None;
    }
    let baseline = &events[baseline];
    let groups = own_groups(&baseline.key_fields, &compiled.key_fields);
    let dependencies = diff_externs(
        &baseline.key_externs,
        &compiled.key_externs,
        &compiled.extern_units,
    );
    let same_key = same_key(baseline, compiled);
    let verdict = if !groups.is_empty() {
        CheckoutVerdict::OwnInputs
    } else if !dependencies.is_empty() {
        CheckoutVerdict::Dependencies
    } else if same_key {
        CheckoutVerdict::PathOnly
    } else {
        CheckoutVerdict::Untraced
    };
    Some(CheckoutComparison {
        root: compiled.root.clone(),
        baseline_root: baseline.root.clone(),
        groups,
        dependencies,
        same_key,
        verdict,
    })
}

/// Baseline of the compile a walk starts from, and whether it is in another
/// checkout.
///
/// The compile's own tree whenever it has an earlier build of the crate there,
/// exactly as before. Otherwise the most recent build of the same unit in
/// another checkout. Unit ids qualify for that because cargo hashes a
/// workspace member's package id relative to the workspace root, so two
/// checkouts of one project produce the same id while an unrelated workspace
/// with a crate of the same name does not. Without a unit id there is only the
/// name, which is the wrong pairing `same_root` exists to refuse.
///
/// That checkout supplies every baseline of the walk: diffing one crate
/// against one checkout and its dependency against another would mix two
/// unrelated comparisons. See [`dependency_baseline`] for which of its builds.
fn top_baseline(events: &[BuildEvent], index: usize) -> Option<(usize, bool)> {
    let compiled = events.get(index)?;
    if compiled.root.is_empty() {
        return None;
    }
    if let Some(same_tree) = last_baseline_index(events, compiled, &compiled.root, index) {
        return Some((same_tree, false));
    }
    let unit = unit_of(compiled)?;
    events[..index]
        .iter()
        .rposition(|e| {
            !e.root.is_empty() && e.root != compiled.root && unit_of(e) == Some(unit) && is_keyed(e)
        })
        .map(|other| (other, true))
}

/// Baseline of the dependency compiled at `dep_index`, reached from a consumer
/// whose own baseline is `consumer_baseline`.
///
/// In one tree, the dependency's previous state before its compile: builds
/// there run one after another. Across checkouts, this tree's positions say
/// nothing about the other checkout's timeline. Two worktrees building at once
/// interleave, and a tree that built part of the project early compiled some
/// dependencies long before the other checkout's latest build. So the baseline
/// is the other checkout's build of the dependency before the consumer's
/// baseline: the one that consumer was keyed on.
fn dependency_baseline(
    events: &[BuildEvent],
    dep_index: usize,
    baseline_root: &str,
    cross_checkout: bool,
    consumer_baseline: usize,
) -> Option<usize> {
    let bound = if cross_checkout {
        consumer_baseline
    } else {
        dep_index
    };
    last_baseline_index(events, &events[dep_index], baseline_root, bound)
}

/// Both compiles computed the same, non-empty final key.
fn same_key(baseline: &BuildEvent, compiled: &BuildEvent) -> bool {
    !compiled.cache_key.is_empty() && compiled.cache_key == baseline.cache_key
}

/// Walk the cascade below the compile at `miss_index`.
///
/// `miss_index` indexes `events` — an oldest-first slice. `None` means there is
/// nothing to report: no per-dependency digests were recorded (the wrapper
/// writes them only under `[cache] explain_miss`, or the events predate #609),
/// or this crate's dependencies did not move, in which case the existing
/// diagnosis already says everything known.
pub fn analyze(events: &[BuildEvent], miss_index: usize) -> Option<Chain> {
    let miss = events.get(miss_index)?;
    if !miss.key_externs_recorded || miss.root.is_empty() {
        return None;
    }
    let (top, cross_checkout) = top_baseline(events, miss_index)?;
    let baseline_root = events[top].root.as_str();
    let direct = changed_deps_at(events, miss_index, Some(top))?;
    if direct.is_empty() {
        return None;
    }

    // Breadth-first over (crate, event position), so the first path reaching a
    // crate is the shortest one. `seen` and `reached` are keyed by unit where
    // the events carry one, so two same-named units count as two nodes rather
    // than silently folding into one (#627); revisiting a node on another
    // branch adds no information beyond the convergence count, tracked
    // separately.
    // Each node carries its baseline, which a dependency's own lookup is
    // bounded by across checkouts.
    let mut queue: Vec<(usize, usize, Vec<Hop>)> = vec![(miss_index, top, Vec::new())];
    let mut seen: HashSet<String> = HashSet::from([node_key(&miss.crate_name, unit_of(miss))]);
    // Branches that reached each node, counted independently of `roots`: a node
    // can be reached again while it is still queued, long before it becomes an
    // endpoint.
    let mut reached: BTreeMap<String, usize> = BTreeMap::new();
    let mut roots: Vec<Root> = Vec::new();
    let mut nodes = 0usize;
    let mut truncated = None;

    while let Some((index, baseline, path)) = queue.pop() {
        let changed = match changed_deps_at(events, index, Some(baseline)) {
            Some(changed) => changed,
            // Guarded by the caller for the first node; deeper nodes are
            // checked before being enqueued.
            None => continue,
        };

        for dep in changed {
            if nodes >= MAX_NODES {
                truncated = Some("too many changed dependencies to follow");
                break;
            }
            nodes += 1;

            let mut next_path = path.clone();
            next_path.push(Hop {
                crate_name: events[index].crate_name.clone(),
                unit: unit_of(&events[index]).map(str::to_string),
                via: dep.clone(),
            });

            // A dependency that points back at a crate already on this path is
            // a loop, whether or not it has an event of its own to resolve to.
            // Checking the REQUESTED identity here catches the case where it
            // has none — the walk would otherwise report the crate being
            // explained as an unresolved endpoint of its own cascade.
            if loops_back(&path, miss, &node_key(&dep.name, dep.unit.as_deref())) {
                truncated = Some("cycle in recorded dependency digests");
                continue;
            }

            // Resolve the producer, then track the branch by the identity of the
            // event actually selected — not by the identity the consumer asked
            // for. The two differ whenever a dep carrying a unit id resolves to
            // a legacy event that has none, and every downstream structure
            // (`reached`, `seen`, the cycle check, each root) has to agree on
            // one key, or the walk reports a converged root as reached by a
            // single branch, explores one event twice, and misses loops. Hops
            // carry their own event's identity, so comparing against the
            // selected producer's keeps that check apples-to-apples.
            let Some(dep_index) = producer_index(events, &dep, &events[index].root, index) else {
                // Nothing was selected, so the requested identity is all there
                // is to count this dead end under.
                *reached
                    .entry(node_key(&dep.name, dep.unit.as_deref()))
                    .or_default() += 1;
                roots.push(unresolved(
                    dep.name,
                    dep.unit,
                    RootKind::NoMissRecorded,
                    next_path,
                ));
                continue;
            };
            let producer = &events[dep_index];
            // Report the producing crate's OWN name from here down. Under
            // Cargo's `package = "..."` renaming the consumer's alias names no
            // crate the user can go look at (#627).
            let dep_name = producer.crate_name.clone();
            let dep_unit = unit_of(producer).map(str::to_string);
            let dep_key = node_key(&dep_name, dep_unit.as_deref());
            *reached.entry(dep_key.clone()).or_default() += 1;

            // And again on the resolved identity: name matching in a mixed
            // window can land on an event already visited under a unit id.
            if loops_back(&path, miss, &dep_key) {
                truncated = Some("cycle in recorded dependency digests");
                continue;
            }

            if !seen.insert(dep_key) {
                // Reached by another branch already; the convergence is
                // recorded above and there is nothing new to explore.
                continue;
            }

            let diffed =
                dependency_baseline(events, dep_index, baseline_root, cross_checkout, baseline)
                    .and_then(|dep_baseline| {
                        changed_deps_at(events, dep_index, Some(dep_baseline))
                            .map(|next| (dep_baseline, next))
                    });
            match diffed {
                // Its own dependencies moved: keep descending, unless this
                // branch has run out of depth.
                Some((dep_baseline, next)) if !next.is_empty() => {
                    if next_path.len() >= MAX_DEPTH {
                        truncated = Some("chain longer than the walk limit");
                        roots.push(unresolved(
                            dep_name,
                            dep_unit,
                            RootKind::LimitReached,
                            next_path,
                        ));
                        continue;
                    }
                    queue.push((dep_index, dep_baseline, next_path));
                }
                // Compared cleanly and stable: this is a genuine endpoint.
                // `classify_at` derives the same identity from the same event.
                Some((dep_baseline, _)) => roots.push(classify_at(
                    events,
                    dep_index,
                    Some(dep_baseline),
                    cross_checkout,
                    next_path,
                )),
                // Not comparable. NOT the same as stable — saying so would
                // invent a root out of missing data.
                None => {
                    let mut root =
                        unresolved(dep_name, dep_unit, RootKind::NoDiffableHistory, next_path);
                    root.passthroughs = passthroughs_for(events, &root.crate_name, dep_index);
                    roots.push(root);
                }
            }
        }
        if truncated == Some("too many changed dependencies to follow") {
            break;
        }
    }

    for root in &mut roots {
        root.branches = reached
            .get(&node_key(&root.crate_name, root.unit.as_deref()))
            .copied()
            .unwrap_or(1);
    }
    // Most-converged first, then shallowest, then by name so output is stable.
    roots.sort_by(|a, b| {
        b.branches
            .cmp(&a.branches)
            .then_with(|| a.path.len().cmp(&b.path.len()))
            .then_with(|| a.crate_name.cmp(&b.crate_name))
    });

    Some(Chain {
        roots,
        direct,
        truncated,
        baseline_root: cross_checkout.then(|| baseline_root.to_string()),
    })
}

/// Whether `key` names a node already on this path, or the crate being
/// explained.
///
/// Cargo forbids real dependency cycles, so a loop here means the recorded
/// digests are inconsistent: with unit ids present, two compiles disagreeing
/// about what produced what; without them, the older failure of two units
/// sharing a crate name being paired as one. Either way the branch stops.
fn loops_back(path: &[Hop], miss: &BuildEvent, key: &str) -> bool {
    path.iter()
        .any(|hop| node_key(&hop.crate_name, hop.unit.as_deref()) == key)
        || key == node_key(&miss.crate_name, unit_of(miss))
}

fn unresolved(crate_name: String, unit: Option<String>, kind: RootKind, path: Vec<Hop>) -> Root {
    Root {
        crate_name,
        unit,
        kind,
        passthroughs: Vec::new(),
        branches: 1,
        path,
    }
}

/// Dependencies whose digests differ between the compile at `index` and its
/// `baseline` event: the previous recorded state of the same crate, in the
/// compile's own tree or in the other checkout the walk compares against.
///
/// `None` means the history is not diffable (no baseline, or either side
/// recorded no digests). That is deliberately distinct from `Some(vec![])`,
/// which means the comparison succeeded and the dependencies are identical —
/// only the latter supports concluding that a crate ends the cascade.
fn changed_deps_at(
    events: &[BuildEvent],
    index: usize,
    baseline: Option<usize>,
) -> Option<Vec<ChangedDep>> {
    let compiled = events.get(index)?;
    if !compiled.key_externs_recorded {
        return None;
    }
    let baseline = baseline?;
    Some(diff_externs(
        &events[baseline].key_externs,
        &compiled.key_externs,
        &compiled.extern_units,
    ))
}

/// Symmetric diff of two dependency-digest maps, sorted by name.
///
/// `units` comes from the LATER of the two events: it describes the dependency
/// set as of the compile being explained, which is the one the walk descends
/// into. A dependency that only exists in the baseline has no unit recorded and
/// falls back to name matching, which is all that state supports anyway.
fn diff_externs(
    before: &BTreeMap<String, String>,
    after: &BTreeMap<String, String>,
    units: &BTreeMap<String, String>,
) -> Vec<ChangedDep> {
    let mut out = Vec::new();
    for (name, to) in after {
        match before.get(name) {
            Some(from) if from == to => {}
            from => out.push(ChangedDep {
                name: name.clone(),
                from: from.cloned(),
                to: Some(to.clone()),
                unit: units.get(name).cloned(),
            }),
        }
    }
    // Dependencies that disappeared also moved the key.
    for (name, from) in before {
        if !after.contains_key(name) {
            out.push(ChangedDep {
                name: name.clone(),
                from: Some(from.clone()),
                to: None,
                unit: units.get(name).cloned(),
            });
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// Explain a crate's own divergence, dependencies aside.
fn classify_at(
    events: &[BuildEvent],
    index: usize,
    baseline: Option<usize>,
    cross_checkout: bool,
    path: Vec<Hop>,
) -> Root {
    let compiled = &events[index];
    let passthroughs = passthroughs_for(events, &compiled.crate_name, index);
    let Some(baseline) = baseline else {
        return Root {
            crate_name: compiled.crate_name.clone(),
            unit: unit_of(compiled).map(str::to_string),
            kind: RootKind::NoBaseline,
            passthroughs,
            branches: 1,
            path,
        };
    };

    // Diff against the SAME baseline the dependency comparison used. The
    // wrapper's own `key_diff` is computed against that crate's last hit, which
    // can be an older event than this baseline, so preferring it here would mix
    // two different comparisons.
    let mut groups = own_groups(&events[baseline].key_fields, &compiled.key_fields);
    if groups.is_empty() && !cross_checkout && !compiled.key_diff.is_empty() {
        // No group digests recorded to diff (pre-#131 events): fall back to
        // whatever the wrapper concluded at the time. Never across checkouts:
        // the wrapper diffed against this tree, not the other one.
        groups = compiled.key_diff.clone();
        groups.retain(|g| g != "externs");
        groups.sort();
        groups.dedup();
    }

    let kind = if !groups.is_empty() {
        RootKind::Groups(groups)
    } else if cross_checkout && same_key(&events[baseline], compiled) {
        RootKind::PathOnly
    } else {
        RootKind::NothingRecorded
    };
    Root {
        crate_name: compiled.crate_name.clone(),
        unit: unit_of(compiled).map(str::to_string),
        kind,
        passthroughs,
        branches: 1,
        path,
    }
}

/// Key input groups that differ, `externs` excluded: dependency movement is
/// the walk's business, not the crate's own.
fn own_groups(before: &BTreeMap<String, String>, after: &BTreeMap<String, String>) -> Vec<String> {
    let mut out: Vec<String> = after
        .iter()
        .filter(|(group, digest)| before.get(*group) != Some(digest))
        .map(|(group, _)| group.clone())
        .collect();
    out.extend(before.keys().filter(|g| !after.contains_key(*g)).cloned());
    out.retain(|g| g != "externs");
    out.sort();
    out.dedup();
    out
}

/// Passthrough compiles plausibly belonging to `crate_name`, grouped by reason.
///
/// Attribution is a heuristic and deliberately a loose one. A cc invocation
/// driven by a build script logs the source file as its `crate_name`
/// (`bcm.c`), so it cannot be joined to the Rust crate by name; what it does
/// carry is a `root` derived from the build-script cwd, which for a registry
/// dependency contains the package directory (`.../aws-lc-sys-0.43.0`).
/// Matching on that names the right crate for the case this exists to
/// diagnose, and when it is wrong it over-reports rather than pointing
/// somewhere else. `cli` labels the line as inferred.
///
/// Bounded to events before the compile being explained, so an unrelated later
/// build cannot be folded in.
fn passthroughs_for(
    events: &[BuildEvent],
    crate_name: &str,
    before: usize,
) -> Vec<PassthroughGroup> {
    let needle = crate_name.replace('_', "-");
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    for event in &events[..before.min(events.len())] {
        if event.result != EventResult::Passthrough || event.root.is_empty() {
            continue;
        }
        if !package_dir_matches(&event.root, &needle) {
            continue;
        }
        let reason = if event.passthrough_reason.is_empty() {
            "(no reason recorded)".to_string()
        } else {
            event.passthrough_reason.clone()
        };
        *counts.entry(reason).or_default() += 1;
    }
    let mut out: Vec<PassthroughGroup> = counts
        .into_iter()
        .map(|(reason, count)| PassthroughGroup { reason, count })
        .collect();
    out.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.reason.cmp(&b.reason)));
    out.truncate(4);
    out
}

/// Whether any path component of `root` is the package directory for `needle` —
/// exactly `needle`, or `needle-<semver>`.
///
/// Split on both separators rather than using `Path::components`, so a Windows
/// path analyzed on Unix (or the reverse) still resolves. Component-wise and
/// version-shaped on purpose: a plain `contains` would let `aws-lc` match
/// `aws-lc-sys-0.43.0`, and a bare "starts with a digit" test would let
/// `foo-2-helper-0.1.0` match `foo`.
fn package_dir_matches(root: &str, needle: &str) -> bool {
    root.split(['/', '\\']).any(|component| {
        component == needle
            || component
                .strip_prefix(needle)
                .and_then(|rest| rest.strip_prefix('-'))
                .is_some_and(looks_like_semver)
    })
}

/// `MAJOR.MINOR.PATCH`, with an optional `-pre` / `+build` tail — the shape
/// Cargo puts in a registry package directory.
fn looks_like_semver(value: &str) -> bool {
    let core = value.split(['-', '+']).next().unwrap_or_default();
    let parts: Vec<&str> = core.split('.').collect();
    parts.len() == 3
        && parts
            .iter()
            .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
}

/// This compile's unit id, or `None` when it recorded none.
fn unit_of(event: &BuildEvent) -> Option<&str> {
    (!event.unit_id.is_empty()).then_some(event.unit_id.as_str())
}

/// Whether `event` is the unit `dep` names.
///
/// Exact when both sides carry a unit id. When the dependency has one and the
/// candidate does not, the candidate predates #627, so fall back to the name —
/// otherwise the walk would go blind across the upgrade. An event with a
/// DIFFERENT unit id is never accepted on the name: that is precisely the
/// wrong-pairing this exists to stop.
fn is_producer(event: &BuildEvent, dep: &ChangedDep) -> bool {
    match (dep.unit.as_deref(), unit_of(event)) {
        (Some(want), Some(have)) => want == have,
        (Some(_), None) => event.crate_name == dep.name,
        (None, _) => event.crate_name == dep.name,
    }
}

/// Last compile (`Miss`/`Dup`) of the unit `dep` names, strictly before
/// `before`.
///
/// Selection prefers an exact unit match anywhere in the window over a
/// name-only match, so one legacy event cannot shadow the right unit's own
/// history just by being closer.
fn producer_index(
    events: &[BuildEvent],
    dep: &ChangedDep,
    root: &str,
    before: usize,
) -> Option<usize> {
    let window = &events[..before.min(events.len())];
    let compiled = |e: &BuildEvent| matches!(e.result, EventResult::Miss | EventResult::Dup);

    if let Some(want) = dep.unit.as_deref() {
        let exact = window
            .iter()
            .rposition(|e| unit_of(e) == Some(want) && same_root(e, root) && compiled(e));
        if exact.is_some() {
            return exact;
        }
    }
    window
        .iter()
        .rposition(|e| is_producer(e, dep) && same_root(e, root) && compiled(e))
}

/// The previous event that recorded dependency digests for this crate.
///
/// Any keyed outcome counts, not just a hit: after two consecutive misses,
/// diffing the second against the last HIT reports everything that changed
/// across both, which over-reports the dependencies responsible for the second
/// one. A dependency can equally reach its new artifact through a remote or
/// prefetch hit, so those count too.
/// Matched by unit id when the compile has one, so the previous state of THIS
/// unit is compared rather than that of a same-named sibling — a duplicate
/// package version, or the host build of a crate also built for the target
/// (#627). Events with no unit id (pre-#627, non-cargo) still match by name, so
/// a mixed window keeps working.
fn last_baseline_index(
    events: &[BuildEvent],
    compiled: &BuildEvent,
    root: &str,
    before: usize,
) -> Option<usize> {
    let keyed = |e: &BuildEvent| same_root(e, root) && is_keyed(e);
    let window = &events[..before.min(events.len())];

    if let Some(unit) = unit_of(compiled) {
        if let Some(exact) = window
            .iter()
            .rposition(|e| unit_of(e) == Some(unit) && keyed(e))
        {
            return Some(exact);
        }
        // No event for this unit carries an id: only legacy events are left to
        // compare against, and those can only be matched by name.
        return window.iter().rposition(|e| {
            e.unit_id.is_empty() && e.crate_name == compiled.crate_name && keyed(e)
        });
    }
    window
        .iter()
        .rposition(|e| e.crate_name == compiled.crate_name && keyed(e))
}

/// A keyed outcome that recorded dependency digests.
fn is_keyed(e: &BuildEvent) -> bool {
    e.key_externs_recorded
        && matches!(
            e.result,
            EventResult::LocalHit
                | EventResult::PrefetchHit
                | EventResult::RemoteHit
                | EventResult::Miss
                | EventResult::Dup
        )
}

/// Exact build-tree match.
///
/// A missing root is NOT a wildcard. Treating it as one lets a legacy or
/// foreign event stand in as the baseline for a crate of the same name in a
/// different workspace, which produces a confident and wrong cascade.
fn same_root(event: &BuildEvent, root: &str) -> bool {
    !root.is_empty() && event.root == root
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{DateTime, TimeZone, Utc};

    fn ts(secs: i64) -> DateTime<Utc> {
        Utc.timestamp_opt(1_700_000_000 + secs, 0).unwrap()
    }

    fn event(
        crate_name: &str,
        result: EventResult,
        at: i64,
        externs: &[(&str, &str)],
    ) -> BuildEvent {
        let mut e = BuildEvent::new_for_test(crate_name, result);
        e.ts = ts(at);
        e.root = "/w".to_string();
        e.key_externs = externs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        e.key_externs_recorded = true;
        e
    }

    /// An event from a build where the digests were not recorded at all —
    /// `explain_miss` off, or a pre-#609 wrapper.
    fn unrecorded(crate_name: &str, result: EventResult, at: i64) -> BuildEvent {
        let mut e = event(crate_name, result, at, &[]);
        e.key_externs_recorded = false;
        e
    }

    fn with_fields(mut e: BuildEvent, fields: &[(&str, &str)]) -> BuildEvent {
        e.key_fields = fields
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        e
    }

    fn analyze_last(events: &[BuildEvent]) -> Option<Chain> {
        analyze(events, events.len() - 1)
    }

    /// Same-tree dependency diff of the compile at `index`.
    fn deps_at(events: &[BuildEvent], index: usize) -> Option<Vec<ChangedDep>> {
        let baseline = last_baseline_index(events, &events[index], "/w", index);
        changed_deps_at(events, index, baseline)
    }

    /// This event's own compilation unit (cargo's `-C extra-filename`).
    fn with_unit(mut e: BuildEvent, unit: &str) -> BuildEvent {
        e.unit_id = unit.to_string();
        e
    }

    /// The producing unit behind each of this event's externs, as the consumer
    /// recovered it from the `--extern` artifact path.
    fn with_extern_units(mut e: BuildEvent, units: &[(&str, &str)]) -> BuildEvent {
        e.extern_units = units
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        e
    }

    /// Cargo's `package = "..."` renaming: the consumer's key records the alias
    /// (`foo_old`), the producer's events record its real name (`foo`). Matching
    /// by name dead-ends on the alias; matching by unit reaches the producer and
    /// reports the name the user can actually go look at (#627).
    #[test]
    fn follows_a_renamed_dependency_to_the_crate_that_produced_it() {
        let events = vec![
            with_extern_units(
                event("app", EventResult::LocalHit, 0, &[("foo_old", "aaaa")]),
                &[("foo_old", "ufoo")],
            ),
            with_unit(
                with_fields(
                    event("foo", EventResult::LocalHit, 1, &[]),
                    &[("sources", "1111")],
                ),
                "ufoo",
            ),
            with_unit(
                with_fields(
                    event("foo", EventResult::Miss, 10, &[]),
                    &[("sources", "2222")],
                ),
                "ufoo",
            ),
            with_extern_units(
                event("app", EventResult::Miss, 11, &[("foo_old", "bbbb")]),
                &[("foo_old", "ufoo")],
            ),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        assert_eq!(chain.roots.len(), 1);
        let root = &chain.roots[0];
        assert_eq!(
            root.crate_name, "foo",
            "the producing crate's own name, not the consumer's alias"
        );
        assert_eq!(root.kind, RootKind::Groups(vec!["sources".to_string()]));
        // The alias still names the edge, since that is what the consumer's
        // manifest says.
        assert_eq!(chain.direct[0].name, "foo_old");

        // Strip the unit ids and the same events reproduce the pre-#627
        // behaviour: no crate is named `foo_old`, so the walk dead-ends on the
        // alias. This is what the fix buys.
        let by_name: Vec<BuildEvent> = events
            .iter()
            .cloned()
            .map(|mut e| {
                e.unit_id.clear();
                e.extern_units.clear();
                e
            })
            .collect();
        let chain = analyze_last(&by_name).expect("cascade should still be reported");
        assert_eq!(chain.roots[0].crate_name, "foo_old");
        assert_eq!(chain.roots[0].kind, RootKind::NoMissRecorded);
    }

    /// Two versions of one package in the same graph. The consumer depends on
    /// the second, so the walk must diff THAT unit's history — matching by name
    /// would pick whichever `foo` event came last and report a change that
    /// belongs to the other version (#627).
    #[test]
    fn picks_the_right_unit_when_two_versions_share_a_crate_name() {
        let events = vec![
            with_extern_units(
                event("app", EventResult::LocalHit, 0, &[("foo", "aaaa")]),
                &[("foo", "foo_v2")],
            ),
            // v2: stable dependencies, its own sources moved.
            with_unit(
                with_fields(
                    event("foo", EventResult::LocalHit, 1, &[("libc", "cccc")]),
                    &[("sources", "1111")],
                ),
                "foo_v2",
            ),
            with_unit(
                with_fields(
                    event("foo", EventResult::Miss, 10, &[("libc", "cccc")]),
                    &[("sources", "2222")],
                ),
                "foo_v2",
            ),
            // v1 compiles later and is the nearest `foo` event by name, with a
            // completely different dependency set. A name-keyed walk would diff
            // against this one.
            with_unit(
                with_fields(
                    event("foo", EventResult::Miss, 11, &[("bitflags", "zzzz")]),
                    &[("args", "9999")],
                ),
                "foo_v1",
            ),
            with_extern_units(
                event("app", EventResult::Miss, 12, &[("foo", "bbbb")]),
                &[("foo", "foo_v2")],
            ),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        assert_eq!(chain.roots.len(), 1);
        let root = &chain.roots[0];
        assert_eq!(root.crate_name, "foo");
        assert_eq!(root.unit.as_deref(), Some("foo_v2"));
        assert_eq!(
            root.kind,
            RootKind::Groups(vec!["sources".to_string()]),
            "v2's own inputs moved; v1's `args` change belongs to a different unit"
        );

        // Without unit ids the walk picks v1 — the nearest `foo` by name — then
        // diffs it against v2's event, so v1's unrelated dependency set reads as
        // "everything changed" and the walk descends into crates the miss has
        // nothing to do with. The pre-#627 failure, pinned.
        let by_name: Vec<BuildEvent> = events
            .iter()
            .cloned()
            .map(|mut e| {
                e.unit_id.clear();
                e.extern_units.clear();
                e
            })
            .collect();
        let chain = analyze_last(&by_name).expect("cascade should still be reported");
        let mut names: Vec<&str> = chain.roots.iter().map(|r| r.crate_name.as_str()).collect();
        names.sort_unstable();
        assert_eq!(
            names,
            vec!["bitflags", "libc"],
            "name matching walks into v1's dependencies: {:?}",
            chain.roots
        );
        assert!(
            !chain.has_resolved_root(),
            "and explains nothing, having compared two different units"
        );
    }

    /// A host build and a target build of one crate, interleaved. Each unit's
    /// baseline must be its own previous compile: pairing across the two makes
    /// stable dependencies look like they were added and removed.
    #[test]
    fn baselines_a_unit_against_itself_not_a_same_named_sibling() {
        let events = vec![
            with_unit(
                event("shared", EventResult::LocalHit, 0, &[("libc", "aaaa")]),
                "host",
            ),
            with_unit(
                event("shared", EventResult::LocalHit, 1, &[("libc", "aaaa")]),
                "target",
            ),
            // The host unit recompiles with everything unchanged. Diffed against
            // the target unit's event it would look identical here, so give the
            // target unit a different dependency set to make a wrong pairing
            // visible.
            with_unit(
                event("shared", EventResult::Miss, 2, &[("libc", "aaaa")]),
                "host",
            ),
        ];

        // Same unit, same digests: comparison succeeded and nothing moved.
        assert_eq!(deps_at(&events, 2), Some(vec![]));

        let mut cross = events.clone();
        cross[1].key_externs = [("winapi".to_string(), "bbbb".to_string())]
            .into_iter()
            .collect();
        assert_eq!(
            deps_at(&cross, 2),
            Some(vec![]),
            "the target unit's different dependency set must not leak into the host unit's diff"
        );
    }

    /// Convergence counting has to use the identity the BRANCH was tracked by.
    /// Here two branches reach one dependency that the consumers identify by
    /// unit, but whose own events are legacy and carry no id: keying the root
    /// off the producing event instead would report 1 branch for a root that 2
    /// converge on, which is the ranking signal `why-miss` sorts by (#627).
    #[test]
    fn counts_converging_branches_when_the_producer_is_a_legacy_event() {
        let via_foo = |name: &str, unit: &str, at: i64, digest: &str, result| {
            with_extern_units(
                with_unit(event(name, result, at, &[("foo", digest)]), unit),
                &[("foo", "ufoo")],
            )
        };
        let events = vec![
            with_extern_units(
                event(
                    "app",
                    EventResult::LocalHit,
                    0,
                    &[("b1", "aa"), ("b2", "aa")],
                ),
                &[("b1", "ub1"), ("b2", "ub2")],
            ),
            via_foo("b1", "ub1", 1, "x1", EventResult::LocalHit),
            via_foo("b2", "ub2", 2, "x1", EventResult::LocalHit),
            // The shared dependency predates #627: no unit id of its own.
            with_fields(
                event("foo", EventResult::LocalHit, 3, &[]),
                &[("sources", "1111")],
            ),
            with_fields(
                event("foo", EventResult::Miss, 4, &[]),
                &[("sources", "2222")],
            ),
            via_foo("b1", "ub1", 5, "x2", EventResult::Miss),
            via_foo("b2", "ub2", 6, "x2", EventResult::Miss),
            with_extern_units(
                event("app", EventResult::Miss, 7, &[("b1", "bb"), ("b2", "bb")]),
                &[("b1", "ub1"), ("b2", "ub2")],
            ),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        let foo = chain
            .roots
            .iter()
            .find(|r| r.crate_name == "foo")
            .expect("the shared dependency should be a root");
        assert_eq!(foo.kind, RootKind::Groups(vec!["sources".to_string()]));
        assert_eq!(
            foo.branches, 2,
            "both b1 and b2 converge on it: {:?}",
            chain.roots
        );
    }

    /// Two consumers ask for two DIFFERENT units that both fall back, by name,
    /// to the same legacy producer. Tracking the branch by what was asked for
    /// would explore that one event twice and report two roots for it; tracking
    /// it by the event actually selected collapses them into one node, which is
    /// what the walk analyzed (#627).
    #[test]
    fn two_requested_units_resolving_to_one_legacy_event_are_one_node() {
        let events = vec![
            with_extern_units(
                event(
                    "app",
                    EventResult::LocalHit,
                    0,
                    &[("b1", "aa"), ("b2", "aa")],
                ),
                &[("b1", "ub1"), ("b2", "ub2")],
            ),
            with_extern_units(
                with_unit(
                    event("b1", EventResult::LocalHit, 1, &[("foo", "x1")]),
                    "ub1",
                ),
                // b1 and b2 disagree about which unit of `foo` they used, and
                // neither id exists in the window.
                &[("foo", "ufoo_a")],
            ),
            with_extern_units(
                with_unit(
                    event("b2", EventResult::LocalHit, 2, &[("foo", "x1")]),
                    "ub2",
                ),
                &[("foo", "ufoo_b")],
            ),
            with_fields(
                event("foo", EventResult::LocalHit, 3, &[]),
                &[("sources", "1111")],
            ),
            with_fields(
                event("foo", EventResult::Miss, 4, &[]),
                &[("sources", "2222")],
            ),
            with_extern_units(
                with_unit(event("b1", EventResult::Miss, 5, &[("foo", "x2")]), "ub1"),
                &[("foo", "ufoo_a")],
            ),
            with_extern_units(
                with_unit(event("b2", EventResult::Miss, 6, &[("foo", "x2")]), "ub2"),
                &[("foo", "ufoo_b")],
            ),
            with_extern_units(
                event("app", EventResult::Miss, 7, &[("b1", "bb"), ("b2", "bb")]),
                &[("b1", "ub1"), ("b2", "ub2")],
            ),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        let foo: Vec<&Root> = chain
            .roots
            .iter()
            .filter(|r| r.crate_name == "foo")
            .collect();
        assert_eq!(foo.len(), 1, "one event, one node: {:?}", chain.roots);
        assert_eq!(foo[0].branches, 2, "both consumers converge on it");
    }

    /// A loop back onto a crate that is NOT the one being explained. Only the
    /// path half of the cycle test fires here, so it pins that the two halves
    /// are alternatives rather than joint conditions.
    #[test]
    fn terminates_on_a_cycle_that_does_not_include_the_starting_crate() {
        let events = vec![
            event("b", EventResult::LocalHit, 0, &[("c", "1111")]),
            event("c", EventResult::LocalHit, 1, &[("b", "3333")]),
            event("a", EventResult::LocalHit, 2, &[("b", "5555")]),
            // c's digests point back at b, which is already on the path.
            event("c", EventResult::Miss, 10, &[("b", "4444")]),
            event("b", EventResult::Miss, 11, &[("c", "2222")]),
            event("a", EventResult::Miss, 12, &[("b", "6666")]),
        ];
        let chain = analyze_last(&events).unwrap();
        assert_eq!(
            chain.truncated,
            Some("cycle in recorded dependency digests")
        );
    }

    /// The node cap stops a pathologically wide graph from turning a diagnostic
    /// into a long walk.
    #[test]
    fn stops_after_too_many_changed_dependencies() {
        let deps: Vec<(String, &str)> = (0..MAX_NODES + 8)
            .map(|i| (format!("d{i}"), "2222"))
            .collect();
        let before: Vec<(&str, &str)> = deps.iter().map(|(n, _)| (n.as_str(), "1111")).collect();
        let after: Vec<(&str, &str)> = deps.iter().map(|(n, _)| (n.as_str(), "2222")).collect();
        let events = vec![
            event("app", EventResult::LocalHit, 0, &before),
            event("app", EventResult::Miss, 10, &after),
        ];

        let chain = analyze_last(&events).unwrap();
        assert_eq!(
            chain.truncated,
            Some("too many changed dependencies to follow")
        );
        assert!(
            chain.roots.len() <= MAX_NODES,
            "the cap must bound the work actually done: {}",
            chain.roots.len()
        );
    }

    /// Convergence is counted for unresolved endpoints too: "three branches all
    /// end at a dependency with no compile recorded" is exactly the signal that
    /// says where to look next.
    #[test]
    fn counts_converging_branches_on_an_unresolved_endpoint() {
        let events = vec![
            event(
                "app",
                EventResult::LocalHit,
                0,
                &[("b1", "aa"), ("b2", "aa")],
            ),
            event("b1", EventResult::LocalHit, 1, &[("ghost", "x1")]),
            event("b2", EventResult::LocalHit, 2, &[("ghost", "x1")]),
            event("b1", EventResult::Miss, 3, &[("ghost", "x2")]),
            event("b2", EventResult::Miss, 4, &[("ghost", "x2")]),
            event("app", EventResult::Miss, 5, &[("b1", "bb"), ("b2", "bb")]),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        let ghost = chain
            .roots
            .iter()
            .find(|r| r.crate_name == "ghost")
            .expect("the never-compiled dependency should be an endpoint");
        assert_eq!(ghost.kind, RootKind::NoMissRecorded);
        assert_eq!(ghost.branches, 2, "both b1 and b2 end here");
    }

    /// The legacy fallback in `last_baseline_index` has to satisfy all three of
    /// its conditions at once. Here a nearer legacy event of a DIFFERENT crate
    /// would be accepted if any one of them were optional, and the diff it
    /// produces is visibly wrong.
    #[test]
    fn the_legacy_baseline_fallback_requires_name_and_keying_together() {
        let events = vec![
            event("foo", EventResult::LocalHit, 0, &[("libc", "aaaa")]),
            // Same build tree, keyed, no unit id — but a different crate.
            event("bar", EventResult::LocalHit, 1, &[("other", "zzzz")]),
            with_unit(
                event("foo", EventResult::Miss, 2, &[("libc", "bbbb")]),
                "ufoo",
            ),
        ];

        assert_eq!(
            deps_at(&events, 2),
            Some(vec![ChangedDep {
                name: "libc".to_string(),
                from: Some("aaaa".to_string()),
                to: Some("bbbb".to_string()),
                unit: None,
            }]),
            "must diff against foo's own legacy event, not bar's"
        );
    }

    /// Mixed windows happen across an upgrade: the compile carries a unit id,
    /// the only earlier event for it does not. Falling back to the name keeps
    /// the walk working rather than going blind.
    #[test]
    fn falls_back_to_the_name_when_only_legacy_events_are_available() {
        let events = vec![
            event("foo", EventResult::LocalHit, 0, &[("libc", "aaaa")]),
            with_unit(
                event("foo", EventResult::Miss, 10, &[("libc", "bbbb")]),
                "ufoo",
            ),
        ];

        assert_eq!(
            deps_at(&events, 1),
            Some(vec![ChangedDep {
                name: "libc".to_string(),
                from: Some("aaaa".to_string()),
                to: Some("bbbb".to_string()),
                unit: None,
            }])
        );
    }

    /// The #580 shape: a leaf `-sys` crate's artifact moves and re-keys two
    /// crates above it. The walk must name the leaf, not the crate asked about.
    #[test]
    fn walks_a_cascade_to_the_leaf_that_changed() {
        let events = vec![
            event(
                "rig_core",
                EventResult::LocalHit,
                0,
                &[("aws_lc_rs", "aaaa")],
            ),
            event(
                "aws_lc_rs",
                EventResult::LocalHit,
                1,
                &[("aws_lc_sys", "bbbb")],
            ),
            with_fields(
                event("aws_lc_sys", EventResult::LocalHit, 2, &[("libc", "cccc")]),
                &[("sources", "1111")],
            ),
            with_fields(
                event("aws_lc_sys", EventResult::Miss, 10, &[("libc", "cccc")]),
                &[("sources", "2222")],
            ),
            event(
                "aws_lc_rs",
                EventResult::Miss,
                11,
                &[("aws_lc_sys", "dddd")],
            ),
            event("rig_core", EventResult::Miss, 12, &[("aws_lc_rs", "eeee")]),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        assert_eq!(chain.roots.len(), 1);
        let root = &chain.roots[0];
        assert_eq!(root.crate_name, "aws_lc_sys");
        assert_eq!(root.kind, RootKind::Groups(vec!["sources".to_string()]));
        assert_eq!(
            root.path
                .iter()
                .map(|h| (h.crate_name.as_str(), h.via.name.as_str()))
                .collect::<Vec<_>>(),
            vec![("rig_core", "aws_lc_rs"), ("aws_lc_rs", "aws_lc_sys")]
        );
        assert!(chain.truncated.is_none());
        assert!(chain.has_resolved_root());
    }

    /// Several dependencies moving is the NORMAL case in a cascade (#580's
    /// `rig_core` sits above a whole re-keyed subtree). Every branch must be
    /// walked, and the root they converge on ranked first — following one
    /// branch and calling it "the root" would be an arbitrary choice.
    #[test]
    fn ranks_the_root_that_most_branches_converge_on() {
        let events = vec![
            event(
                "top",
                EventResult::LocalHit,
                0,
                &[("a", "1111"), ("b", "2222")],
            ),
            event("a", EventResult::LocalHit, 1, &[("leaf", "5555")]),
            event("b", EventResult::LocalHit, 2, &[("leaf", "5555")]),
            with_fields(
                event("leaf", EventResult::LocalHit, 3, &[("libc", "9999")]),
                &[("sources", "1111")],
            ),
            with_fields(
                event("leaf", EventResult::Miss, 10, &[("libc", "9999")]),
                &[("sources", "2222")],
            ),
            event("a", EventResult::Miss, 11, &[("leaf", "6666")]),
            event("b", EventResult::Miss, 12, &[("leaf", "6666")]),
            event(
                "top",
                EventResult::Miss,
                13,
                &[("a", "3333"), ("b", "4444")],
            ),
        ];

        let chain = analyze_last(&events).unwrap();
        assert_eq!(chain.direct.len(), 2, "both direct dependencies moved");
        let leaf = &chain.roots[0];
        assert_eq!(leaf.crate_name, "leaf");
        assert_eq!(leaf.branches, 2, "reached via both a and b");
        assert_eq!(leaf.kind, RootKind::Groups(vec!["sources".to_string()]));
    }

    /// A dependency whose own history is not comparable must NOT be reported as
    /// a root: missing data is not evidence that its dependencies were stable.
    #[test]
    fn undiffable_history_is_not_reported_as_a_root() {
        let events = vec![
            // b's baseline recorded no digests (explain_miss was off then).
            unrecorded("b", EventResult::LocalHit, 0),
            with_fields(
                event("b", EventResult::Miss, 1, &[("c", "1111")]),
                &[("sources", "2222")],
            ),
            event("a", EventResult::LocalHit, 2, &[("b", "aaaa")]),
            event("a", EventResult::Miss, 3, &[("b", "bbbb")]),
        ];
        let chain = analyze_last(&events).unwrap();
        assert_eq!(chain.roots.len(), 1);
        assert_eq!(chain.roots[0].crate_name, "b");
        assert_eq!(chain.roots[0].kind, RootKind::NoDiffableHistory);
        assert!(
            !chain.has_resolved_root(),
            "an undiffable endpoint must not read as an explanation"
        );
    }

    /// After two consecutive misses the baseline is the previous MISS, not the
    /// older hit — otherwise the diff reports everything that moved across
    /// both compiles and can follow the wrong branch.
    #[test]
    fn baseline_is_the_previous_recorded_state_not_the_last_hit() {
        let events = vec![
            event(
                "b",
                EventResult::LocalHit,
                0,
                &[("c", "1111"), ("d", "2222")],
            ),
            // c moved here.
            event("b", EventResult::Miss, 1, &[("c", "9999"), ("d", "2222")]),
            // only d moved here; c is unchanged since the previous miss.
            event("b", EventResult::Miss, 2, &[("c", "9999"), ("d", "8888")]),
        ];
        let chain = analyze_last(&events).unwrap();
        assert_eq!(
            chain
                .direct
                .iter()
                .map(|d| d.name.as_str())
                .collect::<Vec<_>>(),
            vec!["d"],
            "diffing against the last hit would wrongly also report c"
        );
    }

    /// Walking must descend strictly backwards through the log, so a later,
    /// causally unrelated compile of a dependency is never selected.
    #[test]
    fn dependency_lookup_cannot_select_a_later_compile() {
        let events = vec![
            with_fields(
                event("c", EventResult::LocalHit, 0, &[("d", "1111")]),
                &[("sources", "aaaa")],
            ),
            event("b", EventResult::LocalHit, 1, &[("c", "5555")]),
            event("a", EventResult::LocalHit, 2, &[("b", "7777")]),
            // The compile of c that b actually consumed: driven by d.
            with_fields(
                event("c", EventResult::Miss, 10, &[("d", "2222")]),
                &[("sources", "aaaa")],
            ),
            event("b", EventResult::Miss, 11, &[("c", "6666")]),
            // A LATER, independent change to c, after b was already built.
            with_fields(
                event("c", EventResult::Miss, 12, &[("d", "2222")]),
                &[("sources", "bbbb")],
            ),
            event("a", EventResult::Miss, 13, &[("b", "8888")]),
        ];
        let chain = analyze_last(&events).unwrap();
        // c's dependencies moved at the event b consumed, so the walk descends
        // past c to d rather than stopping at c's later source change.
        assert_eq!(chain.roots[0].crate_name, "d");
        assert_eq!(chain.roots[0].kind, RootKind::NoMissRecorded);
    }

    /// A crate with no dependency movement is not part of a cascade.
    #[test]
    fn reports_nothing_when_dependencies_are_stable() {
        let events = vec![
            event("foo", EventResult::LocalHit, 0, &[("bar", "aaaa")]),
            event("foo", EventResult::Miss, 1, &[("bar", "aaaa")]),
        ];
        assert!(analyze_last(&events).is_none());
    }

    /// Without recorded digests there is nothing to walk, and the caller must
    /// fall back to the existing diagnosis rather than print an empty chain.
    #[test]
    fn reports_nothing_without_recorded_digests() {
        let events = vec![
            unrecorded("foo", EventResult::LocalHit, 0),
            unrecorded("foo", EventResult::Miss, 1),
        ];
        assert!(analyze_last(&events).is_none());
    }

    /// A rootless legacy event must not stand in as a baseline for a crate of
    /// the same name in a real build tree.
    #[test]
    fn rootless_events_are_not_wildcards() {
        let mut legacy = event("app", EventResult::LocalHit, 0, &[("dep", "1111")]);
        legacy.root = String::new();
        let events = vec![
            legacy,
            event("app", EventResult::Miss, 1, &[("dep", "2222")]),
        ];
        assert!(
            analyze_last(&events).is_none(),
            "an unrelated rootless event must not seed a cascade"
        );
    }

    /// Digests that point in a loop must terminate the walk and be reported as
    /// unexplained. Cargo forbids real dependency cycles, so a loop here means
    /// two compilation units were paired by a shared crate name — which is
    /// exactly when a confident answer would be wrong.
    #[test]
    fn terminates_on_a_cycle_in_recorded_digests() {
        let events = vec![
            event("a", EventResult::LocalHit, 0, &[("b", "1111")]),
            event("b", EventResult::LocalHit, 1, &[("a", "3333")]),
            event("b", EventResult::Miss, 10, &[("a", "4444")]),
            event("a", EventResult::Miss, 11, &[("b", "2222")]),
        ];
        let chain = analyze_last(&events).unwrap();
        assert_eq!(
            chain.truncated,
            Some("cycle in recorded dependency digests")
        );
        assert!(
            !chain.has_resolved_root(),
            "a cycle must not yield a confident root: {:?}",
            chain.roots
        );
        assert!(chain.roots.iter().all(|r| r.path.len() <= MAX_DEPTH));
    }

    /// A chain exactly MAX_DEPTH long ends in a real root, not a truncation.
    #[test]
    fn a_chain_at_the_depth_limit_still_resolves() {
        let mut events = Vec::new();
        let names: Vec<String> = (0..=MAX_DEPTH).map(|i| format!("c{i}")).collect();
        let last = names.len() - 1;
        // Every crate keeps one dependency, including the deepest: an empty
        // digest map cannot be told apart from an unrecorded one, so a
        // dependency-free crate would end the branch unresolved for reasons
        // unrelated to the depth limit under test.
        let deps_of = |i: usize, digest: &'static str| -> Vec<(String, &'static str)> {
            match names.get(i + 1) {
                Some(next) => vec![(next.clone(), digest)],
                None => vec![("libc".to_string(), "stable")],
            }
        };
        // Baselines, shallowest first.
        for (i, name) in names.iter().enumerate() {
            let deps = deps_of(i, "old");
            let deps: Vec<(&str, &str)> = deps.iter().map(|(n, d)| (n.as_str(), *d)).collect();
            events.push(with_fields(
                event(name, EventResult::LocalHit, i as i64, &deps),
                &[("sources", "1111")],
            ));
        }
        // Misses, deepest first, so each parent's dependency compile precedes it.
        for (i, name) in names.iter().enumerate().rev() {
            let deps = deps_of(i, "new");
            let deps: Vec<(&str, &str)> = deps.iter().map(|(n, d)| (n.as_str(), *d)).collect();
            events.push(with_fields(
                event(
                    name,
                    EventResult::Miss,
                    100 + (names.len() - i) as i64,
                    &deps,
                ),
                &[("sources", if i == last { "2222" } else { "1111" })],
            ));
        }
        let start = events
            .iter()
            .rposition(|e| e.crate_name == "c0" && e.result == EventResult::Miss)
            .unwrap();

        let chain = analyze(&events, start).unwrap();
        assert_eq!(chain.roots[0].crate_name, format!("c{MAX_DEPTH}"));
        assert!(
            chain.roots[0].kind.is_resolved(),
            "a root exactly at the limit must still resolve: {:?}",
            chain.roots[0].kind
        );
        assert!(chain.truncated.is_none());
    }

    #[test]
    fn diff_externs_reports_added_and_removed() {
        let before: BTreeMap<String, String> = [
            ("keep".to_string(), "1".to_string()),
            ("gone".to_string(), "2".to_string()),
        ]
        .into_iter()
        .collect();
        let after: BTreeMap<String, String> = [
            ("keep".to_string(), "1".to_string()),
            ("new".to_string(), "3".to_string()),
        ]
        .into_iter()
        .collect();
        // The unit map covers only the current dependency set, so the removed
        // one carries no unit and the added one does.
        let units: BTreeMap<String, String> = [("new".to_string(), "unit3".to_string())]
            .into_iter()
            .collect();
        assert_eq!(
            diff_externs(&before, &after, &units),
            vec![
                ChangedDep {
                    name: "gone".to_string(),
                    from: Some("2".to_string()),
                    to: None,
                    unit: None,
                },
                ChangedDep {
                    name: "new".to_string(),
                    from: None,
                    to: Some("3".to_string()),
                    unit: Some("unit3".to_string()),
                },
            ]
        );
    }

    /// The passthrough join is by package directory, so a shorter crate name
    /// must not absorb a longer one's uncached compiles, and a directory that
    /// merely starts with the name must not read as a version.
    #[test]
    fn package_dir_match_is_component_and_version_aware() {
        assert!(package_dir_matches(
            "/home/u/.cargo/registry/src/idx/aws-lc-sys-0.43.0",
            "aws-lc-sys"
        ));
        assert!(package_dir_matches("/src/aws-lc-sys", "aws-lc-sys"));
        assert!(package_dir_matches(
            "/registry/src/idx/serde-1.0.0-alpha.1",
            "serde"
        ));
        // `aws-lc` must not swallow `aws-lc-sys`.
        assert!(!package_dir_matches(
            "/home/u/.cargo/registry/src/idx/aws-lc-sys-0.43.0",
            "aws-lc"
        ));
        // A substring that isn't a whole component doesn't count.
        assert!(!package_dir_matches(
            "/src/my-aws-lc-sys-fork",
            "aws-lc-sys"
        ));
        // "starts with a digit" is not enough to be a version.
        assert!(!package_dir_matches("/src/foo-2-helper-0.1.0", "foo"));
        // Windows separators resolve even when parsed on Unix.
        assert!(package_dir_matches(
            r"C:\Users\u\.cargo\registry\src\idx\aws-lc-sys-0.43.0",
            "aws-lc-sys"
        ));
    }

    /// The root crate's uncached cc TUs are the actionable half of the answer.
    #[test]
    fn attributes_passthroughs_to_the_root_package_dir() {
        let mut pt = BuildEvent::new_for_test("bcm.c", EventResult::Passthrough);
        pt.ts = ts(5);
        pt.root = "/home/u/.cargo/registry/src/idx/aws-lc-sys-0.43.0".to_string();
        pt.passthrough_reason = "cc unsupported flag(s): --include=... not yet".to_string();

        let mut unrelated = pt.clone();
        unrelated.root = "/home/u/.cargo/registry/src/idx/ring-0.17.8".to_string();

        let events = vec![
            with_fields(
                event("aws_lc_sys", EventResult::LocalHit, 0, &[("libc", "cccc")]),
                &[("sources", "1111")],
            ),
            pt.clone(),
            pt,
            unrelated,
            with_fields(
                event("aws_lc_sys", EventResult::Miss, 10, &[("libc", "cccc")]),
                &[("sources", "2222")],
            ),
        ];
        let last = events.len() - 1;
        let baseline = last_baseline_index(&events, &events[last], "/w", last);
        let root = classify_at(&events, last, baseline, false, Vec::new());
        assert_eq!(root.passthroughs.len(), 1);
        assert_eq!(root.passthroughs[0].count, 2);
        assert!(root.passthroughs[0].reason.contains("--include="));
    }

    /// Passthroughs logged after the compile being explained belong to a later
    /// build and must not be folded in.
    #[test]
    fn passthrough_attribution_is_bounded_to_earlier_events() {
        let mut pt = BuildEvent::new_for_test("bcm.c", EventResult::Passthrough);
        pt.root = "/registry/src/idx/aws-lc-sys-0.43.0".to_string();
        pt.passthrough_reason = "later build".to_string();
        let events = vec![
            event("aws_lc_sys", EventResult::Miss, 0, &[("libc", "cccc")]),
            pt,
        ];
        assert!(passthroughs_for(&events, "aws_lc_sys", 1).is_empty());
    }

    /// One build of `app -> mid -> leaf` in checkout `root`, oldest first, as
    /// `explain_miss` records it. Keys follow the inputs: `leaf` is keyed on
    /// `leaf_env`, each dependent on the artifact digest of the crate below
    /// it, and `leaf_out` is the artifact `leaf` produced. Unit ids are the
    /// same in every checkout, as cargo computes them relative to the
    /// workspace.
    fn project_build(
        root: &str,
        at: i64,
        leaf_env: &str,
        leaf_out: &str,
        results: [EventResult; 3],
    ) -> Vec<BuildEvent> {
        let [leaf_result, mid_result, app_result] = results;
        let mid_out = format!("m-{leaf_out}");
        let mut leaf = with_unit(
            with_fields(
                event("leaf", leaf_result, at, &[("libc", "cccc")]),
                &[("env_deps", leaf_env), ("sources", "1111")],
            ),
            "uleaf",
        );
        leaf.cache_key = format!("leaf-{leaf_env}");
        let mut mid = with_extern_units(
            with_unit(
                with_fields(
                    event("mid", mid_result, at + 1, &[("leaf", leaf_out)]),
                    &[("env_deps", "e"), ("sources", "2222")],
                ),
                "umid",
            ),
            &[("leaf", "uleaf")],
        );
        mid.cache_key = format!("mid-{leaf_out}");
        let mut app = with_extern_units(
            with_unit(
                with_fields(
                    event("app", app_result, at + 2, &[("mid", &mid_out)]),
                    &[("env_deps", "e"), ("sources", "3333")],
                ),
                "uapp",
            ),
            &[("mid", "umid")],
        );
        app.cache_key = format!("app-{mid_out}");
        let mut build = vec![leaf, mid, app];
        for e in &mut build {
            e.root = root.to_string();
        }
        build
    }

    fn builds(builds: Vec<Vec<BuildEvent>>) -> Vec<BuildEvent> {
        builds.into_iter().flatten().collect()
    }

    const MISSES: [EventResult; 3] = [EventResult::Miss, EventResult::Miss, EventResult::Miss];

    fn position_of(events: &[BuildEvent], root: &str, crate_name: &str) -> usize {
        events
            .iter()
            .rposition(|e| e.root == root && e.crate_name == crate_name)
            .unwrap()
    }

    /// The cross-clone warm case with nothing actually different: a second
    /// checkout of the project computes the same keys, and `app` still missed
    /// (its entry was gone). Without a baseline in its own tree the miss used to
    /// have no comparison at all; against the first checkout it reads as what
    /// it is, a difference of checkout path only.
    #[test]
    fn a_second_checkout_with_the_same_keys_differs_only_in_its_path() {
        let events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build(
                "/b",
                10,
                "e1",
                "L1",
                [
                    EventResult::LocalHit,
                    EventResult::LocalHit,
                    EventResult::Miss,
                ],
            ),
        ]);
        let app = position_of(&events, "/b", "app");

        assert_eq!(
            compare_checkout(&events, app),
            Some(CheckoutComparison {
                root: "/b".to_string(),
                baseline_root: "/a".to_string(),
                groups: vec![],
                dependencies: vec![],
                same_key: true,
                verdict: CheckoutVerdict::PathOnly,
            })
        );
        assert!(
            analyze(&events, app).is_none(),
            "no dependency moved, so there is no cascade to walk"
        );
    }

    /// The common cross-checkout cascade: `leaf` computes the same key in both
    /// checkouts but produces a different artifact, which re-keys everything
    /// above it. `leaf` is the root, and it is reported as reproducibility
    /// rather than as an input change nobody can find.
    #[test]
    fn a_leaf_whose_output_varies_by_checkout_is_a_path_only_root() {
        let mut events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e1", "L2", MISSES),
        ]);
        // The wrapper's own same-tree diff never applies across checkouts; it
        // must not be taken for this comparison's result.
        let leaf = position_of(&events, "/b", "leaf");
        events[leaf].key_diff = vec!["sources".to_string()];
        let app = position_of(&events, "/b", "app");

        let chain = analyze(&events, app).expect("cascade should be reported");
        assert_eq!(chain.baseline_root.as_deref(), Some("/a"));
        assert_eq!(chain.roots.len(), 1, "{:?}", chain.roots);
        let root = &chain.roots[0];
        assert_eq!(root.crate_name, "leaf");
        assert_eq!(root.kind, RootKind::PathOnly);
        assert!(chain.has_resolved_root());

        let compared = compare_checkout(&events, app).unwrap();
        assert_eq!(compared.verdict, CheckoutVerdict::Dependencies);
        assert!(compared.groups.is_empty());
        assert!(!compared.same_key);
        assert_eq!(compared.dependencies[0].name, "mid");

        let compared = compare_checkout(&events, leaf).unwrap();
        assert_eq!(compared.verdict, CheckoutVerdict::PathOnly);
        assert!(compared.same_key);
    }

    /// A real input difference in the second checkout: `leaf` sees another
    /// value for an environment dependency. The walk names `leaf` and the group
    /// that moved, and both crates above it are attributed to it through the
    /// path rather than reported as changed themselves.
    #[test]
    fn an_input_change_in_another_checkout_names_the_leaf_and_attributes_dependents() {
        let events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e2", "L2", MISSES),
        ]);
        let app = position_of(&events, "/b", "app");
        let mid = position_of(&events, "/b", "mid");
        let leaf = position_of(&events, "/b", "leaf");

        let chain = analyze(&events, app).expect("cascade should be reported");
        assert_eq!(chain.baseline_root.as_deref(), Some("/a"));
        assert_eq!(chain.roots.len(), 1, "{:?}", chain.roots);
        let root = &chain.roots[0];
        assert_eq!(root.crate_name, "leaf");
        assert_eq!(root.kind, RootKind::Groups(vec!["env_deps".to_string()]));
        assert_eq!(
            root.path
                .iter()
                .map(|h| (h.crate_name.as_str(), h.via.name.as_str()))
                .collect::<Vec<_>>(),
            vec![("app", "mid"), ("mid", "leaf")]
        );

        let chain = analyze(&events, mid).unwrap();
        assert_eq!(chain.roots[0].crate_name, "leaf");

        let compared = compare_checkout(&events, leaf).unwrap();
        assert_eq!(compared.verdict, CheckoutVerdict::OwnInputs);
        assert_eq!(compared.groups, vec!["env_deps".to_string()]);
        assert!(compared.dependencies.is_empty());
        assert_eq!(
            compare_checkout(&events, mid).unwrap().verdict,
            CheckoutVerdict::Dependencies
        );
    }

    /// Keys differ, yet no traced group and no dependency does: the difference
    /// is in a post-hoc fold, not in the checkout path.
    #[test]
    fn a_key_difference_outside_every_group_is_untraced() {
        let mut events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e1", "L1", MISSES),
        ]);
        let leaf = position_of(&events, "/b", "leaf");
        events[leaf].cache_key = "salted".to_string();
        assert_eq!(
            compare_checkout(&events, leaf).unwrap().verdict,
            CheckoutVerdict::Untraced
        );
        // An empty key is no evidence of a same key.
        events[leaf].cache_key.clear();
        let baseline = position_of(&events, "/a", "leaf");
        events[baseline].cache_key.clear();
        assert_eq!(
            compare_checkout(&events, leaf).unwrap().verdict,
            CheckoutVerdict::Untraced
        );
    }

    /// Another checkout is a fallback. When this tree built the crate before,
    /// that build stays the baseline, even though the other checkout would
    /// report something else.
    #[test]
    fn an_earlier_build_in_the_same_checkout_is_preferred() {
        let events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e2", "L2", MISSES),
            project_build("/b", 20, "e1", "L1", MISSES),
        ]);
        let app = events.len() - 1;

        assert!(compare_checkout(&events, app).is_none());
        let chain = analyze(&events, app).expect("same-tree cascade");
        assert_eq!(chain.baseline_root, None);
        assert_eq!(chain.roots[0].crate_name, "leaf");
        assert_eq!(
            chain.roots[0].kind,
            RootKind::Groups(vec!["env_deps".to_string()]),
            "diffed against the earlier /b build, not the identical /a one"
        );
    }

    /// Two worktrees building at once. `/b`'s leaf compiles before `/a`'s new
    /// one, but `/b`'s app is compared with `/a`'s app, which was keyed on the
    /// NEW leaf. Every dependency has to be compared with the build the other
    /// checkout's consumer actually used; bounding it by this tree's compile
    /// instead picks `/a`'s older leaf, whose key matches, and invents a
    /// reproducibility problem.
    #[test]
    fn concurrent_checkouts_compare_each_dependency_with_what_the_baseline_used() {
        let old_a = project_build("/a", 0, "e1", "L1", MISSES);
        let new_a = project_build("/a", 20, "e3", "L3", MISSES);
        let b = project_build("/b", 20, "e1", "Lb", MISSES);
        let interleaved = |old: Vec<BuildEvent>| -> Vec<BuildEvent> {
            let mut events = old;
            events.extend([
                b[0].clone(),
                new_a[0].clone(),
                new_a[1].clone(),
                b[1].clone(),
                new_a[2].clone(),
                b[2].clone(),
            ]);
            events
        };

        let events = interleaved(old_a);
        let chain = analyze(&events, events.len() - 1).expect("cascade should be reported");
        assert_eq!(chain.baseline_root.as_deref(), Some("/a"));
        assert_eq!(chain.roots.len(), 1, "{:?}", chain.roots);
        assert_eq!(chain.roots[0].crate_name, "leaf");
        assert_eq!(
            chain.roots[0].kind,
            RootKind::Groups(vec!["env_deps".to_string()]),
            "the leaf /a's app was built on differs in env_deps"
        );

        // Without the older /a build the stale lookup finds nothing at all and
        // loses the cause instead of misreporting it.
        let events = interleaved(Vec::new());
        let chain = analyze(&events, events.len() - 1).unwrap();
        assert_eq!(
            chain.roots[0].kind,
            RootKind::Groups(vec!["env_deps".to_string()])
        );
    }

    /// The new tree built part of the project early (`cargo build -p leaf`),
    /// then the first checkout rebuilt with another input, then the new tree
    /// built the rest with `leaf` served as a hit. `leaf`'s compile is the old
    /// one, but the baseline is what the first checkout's latest build used.
    #[test]
    fn a_partial_early_build_is_compared_with_the_latest_baseline_build() {
        let mut events = project_build("/a", 0, "e1", "L1", MISSES);
        events.push(project_build("/b", 10, "e1", "L1b", MISSES)[0].clone());
        events.extend(project_build("/a", 20, "e2", "L2", MISSES));
        events.extend(project_build(
            "/b",
            30,
            "e1",
            "L1b",
            [EventResult::LocalHit, EventResult::Miss, EventResult::Miss],
        ));

        let chain = analyze(&events, events.len() - 1).expect("cascade should be reported");
        assert_eq!(chain.baseline_root.as_deref(), Some("/a"));
        assert_eq!(chain.roots.len(), 1, "{:?}", chain.roots);
        assert_eq!(chain.roots[0].crate_name, "leaf");
        assert_eq!(
            chain.roots[0].kind,
            RootKind::Groups(vec!["env_deps".to_string()])
        );
    }

    /// The wrapper's own `key_diff` stands in for group digests an older event
    /// did not record. It names groups relative to the same tree, so it is
    /// cleaned like a digest diff: no `externs`, sorted, once each.
    #[test]
    fn a_same_tree_root_without_group_digests_uses_the_recorded_key_diff() {
        let mut leaf_miss = event("leaf", EventResult::Miss, 10, &[("libc", "cccc")]);
        leaf_miss.key_diff = ["sources", "externs", "args", "sources"]
            .map(str::to_string)
            .to_vec();
        let events = vec![
            event("leaf", EventResult::LocalHit, 0, &[("libc", "cccc")]),
            event("app", EventResult::LocalHit, 1, &[("leaf", "aaaa")]),
            leaf_miss,
            event("app", EventResult::Miss, 11, &[("leaf", "bbbb")]),
        ];

        let chain = analyze_last(&events).expect("cascade should be reported");
        assert_eq!(
            chain.roots[0].kind,
            RootKind::Groups(vec!["args".to_string(), "sources".to_string()])
        );
    }

    /// With several other checkouts, the latest build is the baseline.
    #[test]
    fn the_most_recent_other_checkout_is_the_baseline() {
        let events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/c", 10, "e2", "L2", MISSES),
            project_build("/b", 20, "e2", "L2", MISSES),
        ]);
        let compared = compare_checkout(&events, events.len() - 1).unwrap();
        assert_eq!(compared.baseline_root, "/c");
        assert_eq!(compared.verdict, CheckoutVerdict::PathOnly);
    }

    /// Crossing checkouts is only safe on unit identity: a crate name alone
    /// matches unrelated workspaces. Events without unit ids, a different unit,
    /// a rootless event, and an event with no recorded key material are never
    /// taken as another checkout's build.
    #[test]
    fn another_checkout_is_matched_by_recorded_unit_only() {
        let base = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e2", "L2", MISSES),
        ]);
        let app = base.len() - 1;

        let by_name: Vec<BuildEvent> = base
            .iter()
            .cloned()
            .map(|mut e| {
                e.unit_id.clear();
                e.extern_units.clear();
                e
            })
            .collect();
        assert!(compare_checkout(&by_name, app).is_none());
        assert!(analyze(&by_name, app).is_none());

        let mut other_unit = base.clone();
        let a_app = position_of(&other_unit, "/a", "app");
        other_unit[a_app].unit_id = "uapp_v2".to_string();
        assert!(compare_checkout(&other_unit, app).is_none());
        assert!(analyze(&other_unit, app).is_none());

        // Newer candidates that must not shadow the valid /a build.
        let mut shadowed = base.clone();
        let mut rootless = shadowed[a_app].clone();
        rootless.root.clear();
        rootless.cache_key = "rootless".to_string();
        let mut unrecorded = shadowed[a_app].clone();
        unrecorded.root = "/c".to_string();
        unrecorded.key_externs_recorded = false;
        let insert_at = position_of(&shadowed, "/b", "leaf");
        shadowed.insert(insert_at, rootless);
        shadowed.insert(insert_at, unrecorded);
        let app = shadowed.len() - 1;
        assert_eq!(
            compare_checkout(&shadowed, app).unwrap().baseline_root,
            "/a"
        );
        assert_eq!(
            analyze(&shadowed, app).unwrap().baseline_root.as_deref(),
            Some("/a")
        );
    }

    /// `PathOnly` is a claim about two checkouts agreeing on a key. In one tree
    /// the same evidence keeps its old reading, and across checkouts a key
    /// that differs with no group to show for it is not path-only either.
    #[test]
    fn path_only_needs_another_checkout_and_the_same_key() {
        let same_tree = builds(vec![
            project_build("/b", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e1", "L2", MISSES),
        ]);
        let chain = analyze(&same_tree, same_tree.len() - 1).unwrap();
        assert_eq!(chain.roots[0].crate_name, "leaf");
        assert_eq!(chain.roots[0].kind, RootKind::NothingRecorded);

        let mut other_key = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e1", "L2", MISSES),
        ]);
        let leaf = position_of(&other_key, "/b", "leaf");
        other_key[leaf].cache_key = "salted".to_string();
        let chain = analyze(&other_key, other_key.len() - 1).unwrap();
        assert_eq!(chain.roots[0].crate_name, "leaf");
        assert_eq!(chain.roots[0].kind, RootKind::NothingRecorded);
    }

    /// A compile with no build tree of its own has no checkout to compare.
    #[test]
    fn a_rootless_compile_has_no_checkout_comparison() {
        let mut events = builds(vec![
            project_build("/a", 0, "e1", "L1", MISSES),
            project_build("/b", 10, "e2", "L2", MISSES),
        ]);
        let app = events.len() - 1;
        events[app].root.clear();
        assert!(compare_checkout(&events, app).is_none());
    }
}