kache 0.23.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
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
use crate::args::RustcArgs;
use crate::path_normalizer::{PathNormalizer, check_for_path_leak};
use anyhow::{Context, Result};
pub(crate) use kache_format::{is_valid_cache_key, is_valid_crate_name};
pub(crate) use kache_store::file_hash::*;
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};

/// Bump this when cache key logic changes in a way that could have produced
/// incorrect entries. All entries from previous versions become unreachable.
///
/// v3: PathNormalizer replaces the ad-hoc `normalize_flags` (CWD-only,
/// fooled by macOS `/tmp` ↔ `/private/tmp` symlinks). Strips $HOME,
/// $CARGO_HOME, $CARGO_TARGET_DIR and the workspace root with stable
/// sentinels.
///
/// v4: `--remap-path-prefix` injection switched from a single
/// CWD-based mapping to multi-prefix using PathNormalizer's full rule
/// set. Output binaries now embed sentinel paths in DWARF / PDB
/// instead of machine-local prefixes — bytes are byte-incompatible
/// with v3 single-prefix outputs, so the bump invalidates v3 entries.
///
/// v5: `--emit` is now hashed. `cargo check` emits `metadata`
/// (`.rmeta`); `cargo build` emits `link` (`.rlib`). Same crate with
/// everything else the key hashed identical → same key, so a check's
/// metadata-only entry could be served to a build needing the
/// `.rlib`. The composition changed, so v4 entries are invalidated.
///
/// v6: `PathNormalizer` gained a rule for the rustc working directory
/// → `<WORKSPACE>`, so `--remap-path-prefix` now also rewrites DWARF
/// `DW_AT_comp_dir` (rustc records the raw CWD there). Debug builds
/// previously leaked the build path through `comp_dir`; the remapped
/// output is byte-incompatible with v5, so the bump invalidates it.
///
/// v7: `-Clinker=<path>` is no longer part of the key. mozbuild (and any
/// build that points rustc at a bootstrapped toolchain) sets
/// `-Clinker=/abs/path/to/clang++`, which previously baked the
/// machine-local path into the key — every clone produced a distinct
/// key for the same crate (Firefox bench measured 0.2% cross-clone key
/// stability). The linker's *identity* is still hashed via
/// `linker:<--version output>` (see `get_linker_identity`), which is
/// path-independent. Existing v6 entries become unreachable.
///
/// v8: `RUSTFLAGS` is whitespace-normalized before hashing. Cargo / mach
/// assemble the env value with cosmetically-varying whitespace across
/// compile profiles (extra spaces between flags, trailing spaces); the
/// raw string previously produced different cache keys for
/// semantically-identical flag sets. Observed on the Firefox bench as
/// the dominant source of "leaf" cache-key divergence — fixing it
/// stabilizes ~18 leaf crates and their non-mozbuild dependents.
///
/// v9: dep-info blobs use an explicit kache sentinel instead of `./`
/// for stored project-root paths. The old marker was ambiguous with
/// ordinary make depfile paths such as `../foo.h`, whose second dot
/// contains a `./` substring and could be expanded incorrectly on
/// restore.
///
/// v10: source files are hashed in content-hash order instead of
/// absolute-path order (a build-script-generated file under `OUT_DIR`
/// sorted differently once the build tree moved, leaking path-order into
/// the key and breaking relocated cache hits — #201). The update order
/// changes on EVERY platform, not just Windows, so the same crate hashes
/// to a different key; bump to invalidate v9 entries cleanly rather than
/// leave a silent partial invalidation. (Env-dep values are also now
/// un-escaped, which can change Windows OUT_DIR keys.)
///
/// v11: previously-unkeyed codegen-affecting inputs are now folded in —
/// `--sysroot`, native link flags (`-L`/`-l`), `-Z` flags, and the
/// CONTENTS of a custom `--target` JSON spec. Also unifies the cc recipe
/// onto this same constant (was a separate `CC_CACHE_KEY_VERSION`).
///
/// v12: cc resolved `-###` tokens are path-normalized through the same
/// prefix maps as the preprocessor stdout before hashing (were hashed
/// raw). Absolute build paths in those tokens — `-I` dirs, `-D` defines
/// like `FIREFOX_ICO="/abs/.../firefox.ico"`, input/`-o` paths — made the
/// cc key path-dependent, so two builds of the same TU at different paths
/// missed cross-machine / cross-clone (Firefox bench: `resolved_token`
/// was a top cross-clone divergence).
///
/// v13: cc prefix-map roots now also derive from the `-I` include dirs,
/// not just (cwd, source-dir). Objdir-generated TUs (`Unified_cpp_*`)
/// compile a source that lives IN the build dir, so the old derivation
/// collapsed to a narrow objdir subdir and leaked `__FILE__` paths into
/// `dist/include` + the source tree (Firefox bench: `preprocessed` was the
/// top cross-clone divergence, ~1000 TUs). The include dirs span the repo,
/// so their common ancestor with cwd reaches the repo root, making
/// cross-checkout cc caching work automatically. (`KACHE_BASE_DIR` is an
/// explicit override; `KACHE_CC_PATH_NORMALIZE=0` disables it all.)
///
/// v14: the per-checkout `from` side of `--remap-path-prefix` (and the clang
/// `-f*-prefix-map` family) is collapsed to a `<REMAP_FROM>` sentinel in the
/// RUSTFLAGS / CARGO_ENCODED_RUSTFLAGS key inputs. A build system's own path
/// remapping (Firefox `--enable-path-remapping`) emits
/// `--remap-path-prefix=/abs/clone-a/=/topsrcdir/` — the flag that makes the
/// *artifact* path-portable was itself making the *key* path-dependent, since
/// FROM is the checkout path. Keying on the stable TO target (and scrubbing
/// FROM) lets the build's declared remap and kache's key agree (Firefox bench:
/// `RUSTFLAGS` was the top cross-clone divergence, 392 crates, after remapping
/// fixed the source/include! leak).
///
/// Single source of truth for both the rustc recipe (this module) and
/// the cc recipe ([`crate::compiler::cc`]). The two hash distinct labels
/// (`key_version:` vs `cc_key_version:`) and disjoint field layouts, so
/// their entries never collide regardless of this number — the version
/// only controls *invalidation*. One constant, one bump.
// v16 (kunobi-ninja/kache#324): length-prefix the free-text key fields (cfg,
// env-dep, codegen flag args) so a value containing the old `\n`/`=` delimiter
// can't be confused with an adjacent field's boundary.
//
// v17 (kunobi-ninja/kache#399): the `--remap-path-prefix` SENTINEL SET is no
// longer folded into the key — only the remap on/off choice (multi-prefix vs
// none) is. The set's membership depended on which machine-local dirs existed
// relative to the build, so it varied across machines and across relocations
// when the build tree lived inside one of those dirs (an out-of-tree build
// under the system tempdir dropped the <TMPDIR> rule by de-dupe, diverging the
// key). It was also redundant with the already-keyed normalized path fields.
// Dropping it fixes out-of-tree relocate misses on Windows and improves
// cross-machine key stability. Removing the per-sentinel fold changes the key
// bytes for every crate, so bump to invalidate v16 entries cleanly.
//
// v18 (kunobi-ninja/kache#431): a build-script `cargo:rustc-env=VAR=<path under
// OUT_DIR>` used purely as an `include!(env!("VAR"))` locator (e.g. typenum's
// TYPENUM_BUILD_CONSTS → `$OUT_DIR/consts.rs`) is now path-normalized in the
// key, like OUT_DIR itself. Previously only the literal var `OUT_DIR` (or a
// user-allowlisted name) qualified, so typenum — a foundational dep of the
// whole substrate/crypto stack — kept an absolute build path in its key and
// re-keyed per checkout, missing cross-clone. Normalizing it changes typenum's
// (and any such crate's) key bytes, so bump to invalidate v17 entries cleanly.
//
// v19 (kunobi-ninja/kache#471): a `-l static=` GNU archive is now folded via a
// build-path-PORTABLE member-content hash ([`crate::native_archive`]) instead of
// a whole-file hash. The `cc` crate names archive members by a hash of the
// absolute build path (`cafca65b…-quickjs.o` vs `4af22b2a…`) while the object
// bytes are identical, so the whole-file hash re-keyed per checkout and missed
// cross-clone (rquickjs-sys, wasm-opt-cc, …). The portable hash ignores those
// names; at v19, non-GNU/unparseable archives fell back to the whole-file hash.
// v24 revises that identity definition and adds bounded BSD parsing. Either way
// the static-lib key bytes changed here, so v19 invalidated v18 entries cleanly.
//
// v20 (kunobi-ninja/kache#480 follow-up): coverage builds now fold the raw local
// path identity into the key, like the `KACHE_RUSTC_PATH_NORMALIZE=0` opt-out
// already did. Coverage skips `--remap-path-prefix` (llvm-cov / tarpaulin need
// real paths in the profraw), so it bakes machine-local paths into DWARF while
// the rest of the key normalized its path inputs — two checkouts computed the
// same `remap:none` key and a shared cache could serve one checkout's real-path
// coverage artifact to another. Folding [`fold_unremapped_path_identity`] for
// coverage (not just the opt-out) changes coverage key bytes, so bump to
// invalidate v19 coverage entries cleanly.
//
// v21 (kunobi-ninja/kache#485): remap-path-prefix TARGETS changed from
// angle-bracket sentinels (`<WORKSPACE>`, `<CARGO_HOME>`, `<CC_ROOT>`, …) to
// resolvable absolute paths (`/proc/self/cwd` on Linux, `/rustc/<hash>`,
// `/kache/*`) so samply / the Firefox Profiler and debuggers can resolve cached
// sources without configuration. The targets are baked into DWARF/PDB and into
// functional bytes (rustc `file!()` / `#[track_caller]` / panic locations; the
// clang/gcc `__FILE__` via `-ffile-prefix-map`), so the produced artifacts
// differ even though the cache-key `normalize()` sentinels are unchanged. The
// rustc sentinel set is not folded into the key (v17/#399) and the cc target
// strings ARE hashed, so a single bump covers both and prevents new builds from
// being served old-sentinel artifacts. Bump to invalidate v20 entries cleanly.
//
// v22 (kunobi-ninja/kache#521): target_dir and workspace_root derivation for
// cross-compilation. Stripping the target triple from target_dir() when cross-compiling
// alters the path remapping prefix and dep-info rewriting anchor. Bumping the key version
// invalidates v21 cross-compiled cache entries cleanly.
//
// #647 deliberately needs no bump: rustc response files were refused under
// every existing version, while their expanded effective arguments key exactly
// like the equivalent inline argv and leave ordinary invocation keys unchanged.
//
// v23 (kunobi-ninja/kache#330): env-dep values under the build's own OUT_DIR
// (the literal OUT_DIR and typenum-style locator vars) now normalize to an
// `<OUT_DIR:{unit-dir}>`-relative sentinel instead of running through the
// generic prefix rules. The generic rules kept per-location components inside
// the value when `CARGO_TARGET_DIR` sits outside the workspace (the derived
// workspace root is the target dir's parent, so `<WORKSPACE>` swallowed the
// target path), diverging keys across build locations for content-identical
// compiles. Cargo's per-unit directory component stays in the sentinel — a
// generated file can observe its own remapped path via `file!()`, so units
// differing only by unit hash must not collide. Bump so v22 entries with the
// old spelling invalidate cleanly.
//
// v24 (kunobi-ninja/kache#691): BSD / Darwin archives gain a bounded structural
// parser, while both GNU and BSD digests now retain exact effective member
// names and timestamps. rustc preserves member names when bundling archives
// into rlibs, and linkers can observe `archive-path(member)`, so ignoring `cc`'s
// path-derived prefixes was not safe across producer/consumer invocations.
// Unsupported non-thin archives use a lexical-path-bound digest; thin archives
// make the invocation uncacheable because their external bytes are absent from
// the container. This intentionally gives up #471/#691 cross-clone reuse when
// member names differ, preferring false misses over false hits.
//
// v25 (kunobi-ninja/kache#730): the Windows dep-info rewrite (#733) is escape-
// aware per line, but the entries the OLD rewrite already stored under v24 stay
// reachable, and they are not merely stale — they are build-breakers. The old
// whole-content `Relativize` could split an escaped `\\` pair while anchoring,
// so the CORRUPTION IS BAKED INTO THE STORED BYTES: the fixed `Expand` cannot
// repair an orphan escape, and cargo hard-rejects the restored `.d` with
// "unknown escape character", failing the compile on every hit (the nightly
// Firefox/Windows bench reproduced exactly this). The mixed fleet is exposed
// both ways too — a pre-#733 client restoring a correctly stored entry runs the
// old unescaped `Expand` and re-corrupts it. Both directions share key v24, so
// only a bump makes them unreachable. Cost is one cold rebuild, which v0.13.0
// users (key v22) already pay crossing to this release regardless.
//
// v26 (kunobi-ninja/kache#760): source identity now folds each normalized path
// together with its content hash. v25 retained only the sorted multiset of
// contents, so swapping two module bodies (or renaming an include_dir asset)
// could preserve the key while changing the compiled program. The same bump
// also makes old dep-info blobs that retain donor-worktree absolute paths
// unreachable; v26 stores separate target/cwd sentinels and re-roots both.
//
// v27 (kunobi-ninja/kache#808): generated dep-info sources beneath an
// in-workspace Cargo target now belong to the effective target before the
// higher-ranked workspace source root. v26 could store
// `__kache_workspace__/target_1/.../OUT_DIR/private.rs`; another concurrent
// Cargo process using target_2 expanded that donor suffix, failed
// validate-on-hit, evicted the entry, and recompiled. The stored dep-info bytes
// change, so the bump makes every incorrectly owned v26 blob unreachable.
//
// v28: every rustc lint-setting flag and `--check-cfg` now participates in
// the outcome key. v27 ignored `-W`/`-A` and check-cfg expectation sets, so a
// successful compile could be replayed after an allow was removed, a warning
// was enabled beneath a deny group, or accepted cfg values were tightened.
// v0.16.0 shipped v27, so the bump also protects mixed fleets from consuming
// already-persisted false-success entries.
//
// v29: native host-loaded links now pin the objects the driver actually
// places (Linux CRT/startup + libc hashes) and the macOS SDK identity
// (version + build), failing closed to passthrough when those essentials
// cannot be resolved. macOS debug links also inject ld64 `-oso_prefix` so
// `N_OSO` paths are relative to `--out-dir` rather than checkout-local.
// WASM admission is explicit for rustc-bundled self-contained targets.
// Shared with the cc recipe, so local and remote Rust/C entries from v28
// are unreachable; `kache gc --stale-schema` reclaims them.
//
// v30: native Windows MSVC links now pin the validated link.exe/lld-link and
// cl banners, selected architecture, MSVC/SDK/UCRT versions, and hashes of
// the selected CRT/UCRT libraries and of every `-l` library resolved through
// `-L`/`/LIBPATH`/LIB. Explicit `-C link-arg` input files (`.lib`, `.a`,
// `.obj`, `.o`, `.res`, `.def`, `.exp`, `.manifest`) and file-carrying LINK
// options (`/DEF`, `/DEFAULTLIB`, `/MANIFESTINPUT`, `/MANIFESTFILE`,
// `/PDBSTRIPPED`, ...) are keyed only as text, so they fail closed to
// passthrough. Windows GNU, cross-target, and metadata invocations remain
// unprobed. Existing Windows linked-output keys did not contain this
// identity, so invalidate them rather than mix schemas.
pub(crate) use kache_format::CACHE_KEY_VERSION;

/// Collapse runs of ASCII whitespace into single spaces and trim
/// leading / trailing whitespace.
///
/// `RUSTFLAGS` is whitespace-tokenized by rustc when it interprets the
/// env var, so `"-C a    -C b"` and `"-C a -C b"` produce the same
/// compile result. But cargo / mach assemble the value with
/// cosmetically-varying whitespace across compile profiles, and the
/// raw string would otherwise hash to different cache keys for
/// semantically-identical flag sets — observed on the Firefox bench
/// as the dominant source of "leaf" cache-key divergence (~18 crates
/// missing in warm despite cold having cached them).
///
/// Order is preserved: `-Cfoo=a -Cfoo=b` and `-Cfoo=b -Cfoo=a` produce
/// distinct strings because later flags override earlier ones in
/// rustc's parser, so they MUST keep distinct keys.
fn normalize_rustflags(rustflags: &str) -> String {
    rustflags.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Sentinel that replaces the volatile "from" path of a compiler path-remap
/// flag in the cache key.
const REMAP_FROM_SENTINEL: &str = "<REMAP_FROM>";

/// Collapse the per-checkout "from" side of compiler path-remap flags to a
/// fixed sentinel so two builds at different checkout paths hash identically.
///
/// `--remap-path-prefix=FROM=TO` (and the clang `-f*-prefix-map` family, which
/// can ride in RUSTFLAGS via `-Clink-arg`) carry a FROM that is the per-checkout
/// build path — e.g. Firefox's `--enable-path-remapping` emits
/// `--remap-path-prefix=/abs/clone-a/=/topsrcdir/`. FROM is *exactly* the path
/// the remap erases from the compiler's output, so it must not make the key
/// path-dependent; otherwise the very flag that makes the artifact portable
/// makes the key un-portable (Firefox bench: `--remap-path-prefix` left a
/// `clone-a`/`clone-b` residual that diverged 392 crates). We keep the flag and
/// the stable TO target and replace only FROM with [`REMAP_FROM_SENTINEL`], so
/// adding/removing a remap or changing TO still diverges the key. This mirrors
/// the cc recipe, which keys on the prefix-map `to` sentinel and scrubs the
/// `from` build path ([`crate::compiler::cc`]).
fn scrub_remap_from_prefixes<'a, I>(tokens: I) -> Vec<String>
where
    I: IntoIterator<Item = &'a str>,
{
    // Equals-form flags whose value is `FROM=TO`.
    const EQ_FLAGS: [&str; 4] = [
        "--remap-path-prefix=",
        "-ffile-prefix-map=",
        "-fdebug-prefix-map=",
        "-fmacro-prefix-map=",
    ];
    let mut out = Vec::new();
    let mut iter = tokens.into_iter();
    while let Some(tok) = iter.next() {
        if let Some(flag) = EQ_FLAGS.iter().find(|f| tok.starts_with(**f)) {
            out.push(format!("{flag}{}", scrub_remap_value(&tok[flag.len()..])));
        } else if tok == "--remap-path-prefix" {
            // Space-separated form: the value is the next token.
            out.push(tok.to_string());
            if let Some(value) = iter.next() {
                out.push(scrub_remap_value(value));
            }
        } else {
            out.push(tok.to_string());
        }
    }
    out
}

/// Replace the FROM half of a `FROM=TO` remap value with [`REMAP_FROM_SENTINEL`],
/// keeping TO. Splits on the LAST `=` to match rustc/clang (both let FROM
/// contain `=`). A value with no `=` is malformed and left untouched.
fn scrub_remap_value(value: &str) -> String {
    match value.rsplit_once('=') {
        Some((_from, to)) => format!("{REMAP_FROM_SENTINEL}={to}"),
        None => value.to_string(),
    }
}

/// Normalize only machine-local prefixes known to [`PathNormalizer`] on the
/// FROM side of a direct rustc remap. Unlike environment-provided build-system
/// remaps, an arbitrary direct FROM may not match this invocation at all, so
/// erasing it unconditionally would collide with a mapping that does match.
fn normalize_direct_remap_value(value: &str, path_normalizer: &PathNormalizer) -> String {
    match value.rsplit_once('=') {
        Some((from, to)) => format!("{}={to}", path_normalizer.normalize(from)),
        None => value.to_string(),
    }
}

/// Fold a user-declared salt into an already-computed cache key.
///
/// The salt captures toolchain divergence kache cannot observe from the
/// invocation itself — a glibc/mold/linker bump, a Nix store rebuild,
/// anything that changes compiled output without changing a tool's
/// `--version` banner (which is all the linker identity the key sees,
/// see [`get_linker_identity`]). Hashing the base key together with the
/// salt yields a distinct key per salt value while leaving the unsalted
/// case **byte-identical** to today: `None`/empty returns `base`
/// untouched, so no `CACHE_KEY_VERSION` bump is needed and a project
/// that never sets it is unaffected.
///
/// Shared by every compiler family (rustc and cc) so the salt applies
/// uniformly regardless of which adapter produced `base`.
///
/// `label` is the crate/source name used in the `[key:…]` trace line so a
/// salt-induced miss is visible under `KACHE_LOG=trace` alongside the other key
/// components — previously the salt was the one key part that folded silently,
/// so a miss caused by a (stray or rotated) salt was invisible to the
/// `why-miss` grep recipe.
pub(crate) fn apply_key_salt(base: String, salt: Option<&str>, label: &str) -> String {
    match salt {
        Some(salt) if !salt.is_empty() => {
            let keyed = fold_labeled(base, "key_salt", salt);
            tracing::trace!(
                "[key:{label}] key_salt={salt:?} -> {}",
                &keyed[..keyed.len().min(16)]
            );
            keyed
        }
        _ => base,
    }
}

/// Fold user-declared environment variables into an already-computed key
/// (kunobi-ninja/kache#635).
///
/// rustc records an env var in dep-info only when the crate reads it through
/// `env!`/`option_env!`. A **proc macro** that branches on `std::env::var`
/// while expanding is invisible to every input kache observes: the rustc
/// command line, the source hashes, and the `--extern` set are byte-identical
/// whether or not the var is set, yet the emitted artifact differs. Both
/// compiles then key the same and the second one restores the first one's
/// expansion. `proc_macro::tracked_env` would surface this properly, but it is
/// still unstable, so the var has to be declared.
///
/// Matching is by exact name, or by prefix when the pattern ends in `*`
/// (`BOLTFFI_*`), ASCII case-insensitive so a Windows environment — where the
/// OS itself treats names case-insensitively — behaves the same as a Unix one.
/// A `*` anywhere but the end is a literal character (a Unix process *can*
/// carry a variable named `A*B`), so `A*B` matches only that exact name.
///
/// Two things are folded, and both are load-bearing:
/// - the declared patterns, so *turning the feature on re-keys the crate*.
///   Without this, the build that leaves the vars unset would fold nothing,
///   land on its old key, and restore the very entry the declaration was meant
///   to escape — the poisoned entry is already in the cache by the time anyone
///   notices they need this setting. `Config::load` upper-cases and sorts the
///   patterns first, so two spellings that select the same variables cannot
///   split the cache.
/// - the matched `NAME=VALUE` pairs, which is what separates the two modes from
///   each other going forward.
///
/// Values are folded **exactly**, as their raw OS bytes — deliberately *not*
/// through the [`PathNormalizer`], and not via a lossy UTF-8 conversion. A
/// declared variable is an opaque semantic input: a macro is free to paste its
/// value straight into the code it emits, so two checkout paths that normalize
/// to the same sentinel can still produce different artifacts, and two distinct
/// non-UTF-8 values that both lossy-convert to `U+FFFD` can too. Either
/// shortcut trades the exact miscompile this function exists to prevent for hit
/// rate. The cost is real and is the right way round: a declared variable
/// holding a machine-local path makes that crate's key machine-specific. Declare
/// the switch a macro actually branches on, not a glob that sweeps in path
/// variables. This matches the policy [`env_dep_is_safe_to_normalize`] already
/// applies to reported `env!` deps — normalize only where a value is *proven*
/// to be nothing but a locator.
///
/// Empty pattern list = feature off, key byte-identical to the undeclared case.
/// The fold is union-only: a misdeclared pattern can cost a cache miss, never
/// restore a wrong artifact.
pub(crate) fn apply_key_env_vars(base: String, patterns: &[String], label: &str) -> String {
    if patterns.is_empty() {
        return base;
    }

    let (matched, matched_names) = matching_key_env_vars(patterns);
    let keyed = fold_labeled(base, "key_env_vars", &key_env_digest(patterns, matched));
    // Names only, never values: a declared var may legitimately hold a token or
    // another secret, and the trace log is what users paste into bug reports.
    tracing::trace!(
        "[key:{label}] key_env_vars patterns={patterns:?} matched={matched_names:?} -> {}",
        &keyed[..keyed.len().min(16)]
    );
    keyed
}

/// Digest the configured `key_env_vars` patterns and their current raw values
/// for an adaptive-incremental unit identity. A changed value must select a new
/// rustc state directory before the full artifact key is computed.
pub(crate) fn key_env_guard(patterns: &[String]) -> Option<String> {
    (!patterns.is_empty()).then(|| {
        let (matched, _) = matching_key_env_vars(patterns);
        key_env_digest(patterns, matched)
    })
}

type RawEnvPair = (Vec<u8>, Vec<u8>);

fn matching_key_env_vars(patterns: &[String]) -> (Vec<RawEnvPair>, Vec<String>) {
    // Matching runs on the lossy name because patterns are UTF-8; folding runs
    // on the raw bytes below, so a lossy collision here can only mis-select a
    // variable (a miss), never merge two variables into one key component.
    let mut matched: Vec<RawEnvPair> = Vec::new();
    let mut matched_names: Vec<String> = Vec::new();
    for (name, value) in std::env::vars_os() {
        let lossy = name.to_string_lossy();
        if !key_env_var_matches(patterns, &lossy) {
            continue;
        }
        matched_names.push(lossy.into_owned());
        matched.push((env_name_key_bytes(&name), env_os_key_bytes(&value)));
    }
    (matched, matched_names)
}

/// Digest the declared patterns plus the matched `(name, value)` byte pairs.
///
/// Split out from [`apply_key_env_vars`] because the ordering rules here decide
/// whether two environments key the same, and they are only testable if they
/// don't require rewriting the process environment to exercise.
fn key_env_digest(patterns: &[String], mut matched: Vec<RawEnvPair>) -> String {
    // `vars_os` iteration order is platform-defined, so sort for a digest that
    // is stable across processes and hosts. The exception is a process whose
    // environment carries the same name twice — only constructible by handing
    // execve a hand-built envp, since the `set_var` APIs replace. `getenv` then
    // returns the *first* occurrence, which makes the order semantically
    // observable, and sorting would erase it. Keep environ order in that case.
    let mut names_seen = std::collections::HashSet::new();
    let has_duplicate_names = matched
        .iter()
        .any(|(name, _)| !names_seen.insert(name.clone()));
    if !has_duplicate_names {
        matched.sort();
    }

    let mut hasher = blake3::Hasher::new();
    for pattern in patterns {
        fold_field(&mut hasher, b"key_env_pattern:", pattern.as_bytes());
    }
    for (name, value) in &matched {
        fold_field(&mut hasher, b"key_env_name:", name);
        fold_field(&mut hasher, b"key_env_val:", value);
    }
    hasher.finalize().to_hex().to_string()
}

/// An env var *value* as key bytes: the OS's own representation, losslessly.
///
/// `to_string_lossy` would map every distinct invalid sequence onto `U+FFFD`,
/// merging values a macro reading `var_os` can still tell apart.
fn env_os_key_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        value.as_bytes().to_vec()
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        value.encode_wide().flat_map(u16::to_le_bytes).collect()
    }
    #[cfg(not(any(unix, windows)))]
    {
        value.to_string_lossy().into_owned().into_bytes()
    }
}

/// An env var *name* as key bytes.
///
/// Same lossless rule as [`env_os_key_bytes`], plus case folding on Windows:
/// there `PATH` and `Path` are one variable, so folding whichever casing the OS
/// happened to report would split the cache between two machines describing the
/// same environment. On Unix the two are genuinely different variables and the
/// case is preserved.
///
/// Windows compares names by an *uppercase* mapping, and that mapping is not
/// ASCII-only, so fold through `str::to_uppercase` (full Unicode) whenever the
/// name is representable — which is every name the OS actually produces. The
/// fallback for an unpaired surrogate keeps the raw units; it can only cost a
/// miss, and getting there at all means the name is not a real Windows name.
/// Both arms emit UTF-16LE so the two encodings can never be confused.
fn env_name_key_bytes(name: &std::ffi::OsStr) -> Vec<u8> {
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        // Tail expression, not `return`: on Windows the `cfg(not(windows))` arm
        // below is compiled out, so this block IS the function body and clippy
        // rejects the `return` under `-D warnings`.
        match name.to_str() {
            Some(name) => name
                .to_uppercase()
                .encode_utf16()
                .flat_map(u16::to_le_bytes)
                .collect(),
            None => name.encode_wide().flat_map(u16::to_le_bytes).collect(),
        }
    }
    #[cfg(not(windows))]
    env_os_key_bytes(name)
}

/// Env text as key bytes: the exact UTF-8 bytes when the text is valid
/// UTF-8, or `0xFF`-tagged lossless OS bytes when it isn't.
///
/// The valid arm is byte-identical to hashing the `String` that
/// `std::env::vars()` used to yield, so keys for all-UTF-8 environments
/// (every one cargo itself constructs) are unchanged. The tag byte never
/// occurs in valid UTF-8, so the two arms cannot collide — and unlike
/// `to_string_lossy`, distinct invalid sequences stay distinct instead
/// of merging under U+FFFD (see [`env_os_key_bytes`]).
fn env_text_key_bytes(text: &std::ffi::OsStr) -> Vec<u8> {
    match text.to_str() {
        Some(utf8) => utf8.as_bytes().to_vec(),
        None => {
            let mut bytes = vec![0xff];
            bytes.extend(env_os_key_bytes(text));
            bytes
        }
    }
}

/// The `CARGO_CFG_*` pairs of an environment, sorted by name.
///
/// Takes `vars_os` pairs rather than `vars()`, which panics if *any*
/// environment variable holds non-UTF-8 — even one this filter would
/// discard. Pairs stay `OsString` so the hasher can fold them
/// losslessly via [`env_text_key_bytes`].
///
/// The primary sort key is the lossy name — the same order the old
/// `String` sort produced for every valid-UTF-8 environment. The
/// lossless tiebreak pins two names that collide under U+FFFD to a
/// deterministic order instead of platform iteration order.
fn cargo_cfg_pairs(
    vars: impl Iterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
    let mut pairs: Vec<(std::ffi::OsString, std::ffi::OsString)> = vars
        .filter(|(name, _)| name.to_string_lossy().starts_with("CARGO_CFG_"))
        .collect();
    pairs.sort_by_cached_key(|(name, _)| {
        (name.to_string_lossy().into_owned(), env_os_key_bytes(name))
    });
    pairs
}

/// Does any `key_env_vars` pattern select the env var `name`?
///
/// Exact match, or prefix match when the pattern ends in `*`. ASCII
/// case-insensitive (see [`apply_key_env_vars`]).
fn key_env_var_matches(patterns: &[String], name: &str) -> bool {
    // Byte slicing, not `&name[..n]`: a lossy `vars_os` conversion can leave a
    // multi-byte replacement char in the name, and a prefix length landing
    // mid-character would panic on a str slice.
    let name = name.as_bytes();
    patterns
        .iter()
        .any(|pattern| match pattern.strip_suffix('*') {
            Some(prefix) => {
                let prefix = prefix.as_bytes();
                name.len() >= prefix.len() && name[..prefix.len()].eq_ignore_ascii_case(prefix)
            }
            None => name.eq_ignore_ascii_case(pattern.as_bytes()),
        })
}

/// Fold a labeled `value` into an already-computed key by re-hashing
/// `label:value\x1f base`. Used by post-hoc key components (the salt,
/// user-declared extra inputs) folded after [`compute_cache_key`] at the
/// per-compiler seam rather than inside it. Distinct labels can never
/// collide, and a component that produces no value simply isn't folded —
/// leaving the key byte-identical to the unaugmented case.
pub(crate) fn fold_labeled(base: String, label: &str, value: &str) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(label.as_bytes());
    hasher.update(b":");
    hasher.update(value.as_bytes());
    hasher.update(b"\x1f");
    hasher.update(base.as_bytes());
    hasher.finalize().to_hex().to_string()
}

/// Fold `label` followed by a length-prefixed `value` into the cache-key hasher.
/// The length prefix removes field-boundary ambiguity: a free-text value that
/// contains the old `\n`/`=` delimiter (build-script cfgs, env-dep values,
/// codegen flag arguments) can no longer be confused with an adjacent field
/// (kunobi-ninja/kache#324).
fn fold_field<H: KeyFold>(hasher: &mut H, label: &[u8], value: &[u8]) {
    hasher.update(label);
    hasher.update(&(value.len() as u64).to_le_bytes());
    hasher.update(value);
}

/// The byte-fold surface shared by [`blake3::Hasher`] and [`GroupedHasher`],
/// so the key-fold helpers (and their tests, which drive a plain hasher) stay
/// agnostic to whether per-group tee-hashing is active.
trait KeyFold {
    fn update(&mut self, bytes: &[u8]);
}

impl KeyFold for blake3::Hasher {
    fn update(&mut self, bytes: &[u8]) {
        blake3::Hasher::update(self, bytes);
    }
}

impl KeyFold for GroupedHasher {
    fn update(&mut self, bytes: &[u8]) {
        GroupedHasher::update(self, bytes);
    }
}

/// Hex-prefix length persisted per key-field group — enough to make an
/// accidental collision between "changed" and "unchanged" implausible while
/// keeping the per-event cost ~a couple hundred bytes.
const KEY_FIELD_HEX: usize = 16;

/// A blake3 hasher that TEES every update into the current key-field group's
/// sub-hasher alongside the main key hasher (kunobi-ninja/kache#131). The
/// main digest is byte-for-byte what a plain `blake3::Hasher` fed the same
/// update sequence produces — grouping cannot change the cache key by
/// construction (`grouped_hasher_main_digest_matches_plain_blake3` pins it).
///
/// The per-group digests power the `explain_miss` diagnostics: persisted on
/// each event, then diffed on a miss to name WHICH input group changed.
/// `set_group` may name the same group across non-contiguous segments; the
/// sub-hasher just keeps accumulating.
struct GroupedHasher {
    main: blake3::Hasher,
    groups: std::collections::BTreeMap<&'static str, blake3::Hasher>,
    current: &'static str,
}

impl GroupedHasher {
    fn new(initial_group: &'static str) -> Self {
        GroupedHasher {
            main: blake3::Hasher::new(),
            groups: std::collections::BTreeMap::new(),
            current: initial_group,
        }
    }

    fn set_group(&mut self, group: &'static str) {
        self.current = group;
    }

    fn update(&mut self, bytes: &[u8]) {
        self.main.update(bytes);
        self.groups.entry(self.current).or_default().update(bytes);
    }

    /// Final key digest + the per-group hex prefixes for event persistence.
    fn finalize_with_fields(self) -> (blake3::Hash, std::collections::BTreeMap<String, String>) {
        let fields = self
            .groups
            .into_iter()
            .map(|(group, hasher)| {
                (
                    group.to_string(),
                    hasher.finalize().to_hex()[..KEY_FIELD_HEX].to_string(),
                )
            })
            .collect();
        (self.main.finalize(), fields)
    }
}

thread_local! {
    /// Per-group digests of the most recent [`compute_cache_key`] run on this
    /// thread, for the wrapper's event logging (one compile per wrapper
    /// process, same stash pattern as `link.rs`'s toggles). `None` until a key
    /// is computed (cc compiles, passthroughs).
    ///
    /// Thread-local rather than process-global (kunobi-ninja/kache#777): the
    /// write and every read are one wrapper invocation on one thread, so
    /// per-thread storage costs the production path nothing and makes the
    /// take-once contract hold under `cargo test`, where libtest runs each test
    /// on its own thread and a concurrent key computation would otherwise
    /// consume or overwrite another test's stash.
    static LAST_KEY_FIELDS: std::cell::RefCell<Option<std::collections::BTreeMap<String, String>>> =
        const { std::cell::RefCell::new(None) };
}

/// Clone the per-group key digests without consuming them.
///
/// Adaptive incremental policy needs the same input-group evidence as miss
/// diagnostics before event logging takes the thread-local stash.
pub fn peek_last_key_fields() -> Option<std::collections::BTreeMap<String, String>> {
    LAST_KEY_FIELDS
        .try_with(|stash| stash.borrow().clone())
        .ok()
        .flatten()
}

/// Take (consume) the per-group key digests of the last computed rustc key.
pub fn take_last_key_fields() -> Option<std::collections::BTreeMap<String, String>> {
    LAST_KEY_FIELDS
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

thread_local! {
    /// Per-EXTERN artifact digests of the most recent [`compute_cache_key`] run
    /// (kunobi-ninja/kache#609), stashed like [`LAST_KEY_FIELDS`].
    ///
    /// The `externs` group digest says only THAT some dependency's artifact
    /// changed. In an `extern:` cascade — one native `-sys` crate's `.a`
    /// diverging and re-keying everything above it — every downstream crate
    /// reports the same undifferentiated "externs changed", which is exactly
    /// the case that has to be diagnosed by hand today. Keeping the
    /// per-dependency hashes lets `why-miss` name WHICH dependency moved, then
    /// follow that dependency's own events to the root of the chain.
    ///
    /// The value is the dependency artifact's own content hash (the same bytes
    /// folded into the key), truncated to [`KEY_FIELD_HEX`] — not a digest of
    /// the folded segment. Same discriminating power, and it can be compared
    /// against hashes recorded elsewhere.
    static LAST_KEY_EXTERNS: std::cell::RefCell<Option<std::collections::BTreeMap<String, String>>> =
        const { std::cell::RefCell::new(None) };
}

/// Marker recorded for an extern whose artifact could not be hashed — a
/// sysroot crate (`std`, `core`), whose identity rides on rustc version + name
/// instead. Distinct from any real hash, so it never reads as a content match.
pub const EXTERN_UNREADABLE: &str = "(sysroot)";

/// Take (consume) the per-extern artifact digests of the last computed rustc
/// key. `None` for cc compiles and passthroughs, which compute no rustc key.
pub fn take_last_key_externs() -> Option<std::collections::BTreeMap<String, String>> {
    LAST_KEY_EXTERNS
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

thread_local! {
    /// Producing-unit identity per extern, teed off the same loop that computes
    /// [`LAST_KEY_EXTERNS`] (kunobi-ninja/kache#627).
    ///
    /// Keyed by the name the CONSUMER used, which under Cargo's
    /// `package = "..."` renaming is an alias (`foo_old` for a crate whose own
    /// events say `foo`). The value is the producer's `-C extra-filename`,
    /// recovered from the artifact path — the one identity visible from both
    /// sides, so `why-miss` can join a changed dependency to the exact unit
    /// that produced it instead of guessing by name.
    ///
    /// Absent for an extern whose path carries no such suffix (sysroot crates,
    /// non-cargo invocations); the walk then falls back to matching by name.
    static LAST_KEY_EXTERN_UNITS: std::cell::RefCell<
        Option<std::collections::BTreeMap<String, String>>,
    > = const { std::cell::RefCell::new(None) };
}

/// Take (consume) the per-extern producing-unit ids of the last computed rustc
/// key. Always taken alongside [`take_last_key_externs`] so a stale map cannot
/// outlive its digests.
pub fn take_last_key_extern_units() -> Option<std::collections::BTreeMap<String, String>> {
    LAST_KEY_EXTERN_UNITS
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

thread_local! {
    /// The compiling unit's own identity, stashed at key computation so the
    /// event writer needs no extra plumbing — the same pattern the per-group
    /// digests use (kunobi-ninja/kache#131). Set unconditionally at the top of
    /// [`compute_cache_key`], including to `None` when cargo passed no
    /// `-C extra-filename`, so it can never carry over from a previous compile.
    static LAST_KEY_UNIT_ID: std::cell::RefCell<Option<String>> =
        const { std::cell::RefCell::new(None) };
}

/// Take (consume) the unit id of the last computed rustc key.
pub fn take_last_key_unit_id() -> Option<String> {
    LAST_KEY_UNIT_ID
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

thread_local! {
    /// The input closure the last [`compute_cache_key`] on this thread
    /// discovered, stashed like the per-group digests above.
    ///
    /// The wrapper needs it to record a prediction, but only once the compile
    /// or restore it belongs to has actually succeeded — which happens far
    /// below the key computation, past the store, the scheduler and the
    /// compiler. Threading a `DepInfo` through all of that would touch every
    /// caller of `compute_cache_key`; the stash is the pattern the other
    /// key by-products already use.
    static LAST_KEY_DEP_INFO: std::cell::RefCell<Option<DepInfo>> =
        const { std::cell::RefCell::new(None) };
}

/// Put a closure in the stash as a key computation would, so the wrapper's
/// recording gate can be tested without spawning a compiler.
#[cfg(test)]
pub(crate) fn stash_last_dep_info_for_test(dep_info: DepInfo) {
    let _ = LAST_KEY_DEP_INFO.try_with(|stash| *stash.borrow_mut() = Some(dep_info));
}

thread_local! {
    /// The crate tree digest the last guarded key computation on this thread
    /// used, so the record made from it carries the same digest.
    static LAST_KEY_TREE_DIGEST: std::cell::RefCell<Option<String>> =
        const { std::cell::RefCell::new(None) };
}

/// Take (consume) the crate tree digest of the last computed rustc key, if it
/// was a proc-macro-dependent unit.
pub(crate) fn take_last_tree_digest() -> Option<String> {
    LAST_KEY_TREE_DIGEST
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

/// Cap on entries digested for the tree guard. A crate directory past this is
/// a build tree or a monorepo root, and the pre-pass stays cheaper than
/// digesting it.
const CRATE_TREE_MAX_ENTRIES: usize = 20_000;

/// A content digest of everything under the crate directory and its
/// `OUT_DIR`, the two places a proc macro reads from by convention
/// (`CARGO_MANIFEST_DIR`-relative paths and generated files).
///
/// Content rather than metadata, so a fresh checkout matches a record made
/// from another one. Every file hashes through the persistent content cache,
/// so an unchanged tree costs stats, not reads. `None` when the crate
/// directory is unknown, unreadable, or too large to digest, which leaves the
/// unit on the pre-pass.
pub(crate) fn crate_tree_digest(file_hasher: &FileHasher<'_>) -> Option<String> {
    let manifest_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR")?);
    // Only for published crates, whose package directory is immutable and
    // self-contained: a macro in one can only read files under the package or
    // its OUT_DIR. A workspace crate can point a macro at `../assets`, which
    // no digest of its own directory would notice, so it keeps the pre-pass.
    if !is_registry_package(&manifest_dir) {
        return None;
    }
    let mut roots = vec![(manifest_dir, &b"manifest_dir"[..])];
    if let Some(out_dir) = std::env::var_os("OUT_DIR").map(PathBuf::from) {
        roots.push((out_dir, &b"out_dir"[..]));
    }
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache-crate-tree-v1\n");
    let mut budget = CRATE_TREE_MAX_ENTRIES;
    // Roots are named by role, not by path: the identity the record is filed
    // under already knows the path, and the guard is about content.
    for (root, role) in roots {
        fold_field(&mut hasher, b"root:", role);
        // A build directory or a git checkout under the crate is not what a
        // macro reads, and `target` in particular is rewritten by the build
        // this key belongs to.
        let excluded = [root.join("target"), root.join(".git")];
        crate_tree_fold(
            &root,
            &root,
            &excluded,
            file_hasher,
            &mut hasher,
            &mut budget,
        )?;
    }
    Some(hasher.finalize().to_hex().to_string())
}

/// Is `manifest_dir` an extracted registry package (`<CARGO_HOME>/registry/src/<index>/<pkg>`)?
fn is_registry_package(manifest_dir: &Path) -> bool {
    let mut components = manifest_dir.components().rev();
    let _package = components.next();
    let _index = components.next();
    let src = components.next();
    let registry = components.next();
    matches!(
        (src, registry),
        (Some(std::path::Component::Normal(src)), Some(std::path::Component::Normal(registry)))
            if src == "src" && registry == "registry"
    )
}

fn crate_tree_fold(
    root: &Path,
    directory: &Path,
    excluded: &[PathBuf],
    file_hasher: &FileHasher<'_>,
    hasher: &mut blake3::Hasher,
    budget: &mut usize,
) -> Option<()> {
    let mut entries: Vec<_> = std::fs::read_dir(directory)
        .ok()?
        .collect::<std::io::Result<_>>()
        .ok()?;
    entries.sort_by_key(std::fs::DirEntry::file_name);
    for entry in entries {
        let path = entry.path();
        if excluded.contains(&path) {
            continue;
        }
        *budget = budget.checked_sub(1)?;
        let relative = path.strip_prefix(root).ok()?;
        fold_field(hasher, b"path:", relative.as_os_str().as_encoded_bytes());
        let metadata = std::fs::symlink_metadata(&path).ok()?;
        if metadata.file_type().is_symlink() {
            let target = std::fs::read_link(&path).ok()?;
            fold_field(hasher, b"symlink:", target.as_os_str().as_encoded_bytes());
        } else if metadata.is_dir() {
            fold_field(hasher, b"dir:", b"");
            crate_tree_fold(root, &path, excluded, file_hasher, hasher, budget)?;
        } else if metadata.is_file() {
            fold_field(hasher, b"file:", file_hasher.hash(&path).ok()?.as_bytes());
        } else {
            fold_field(hasher, b"other:", b"");
        }
    }
    Some(())
}

thread_local! {
    /// Did the last key computed on this thread derive its input set from a
    /// record rather than from the pre-pass?
    ///
    /// The wrapper needs it for the one rule that keeps stores sound: a
    /// derived key that misses locally must be recomputed the slow way before
    /// anything reaches the remote, the scheduler or the store.
    static LAST_KEY_USED_PREDICTION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// May the key refuse to discover a closure it has no record of, so the
    /// wrapper compiles first and keys from the dep-info rustc emits?
    static DEFER_DISCOVERY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// A closure handed in by the wrapper after such a compile: the next key
    /// computation uses it instead of a record or a pre-pass.
    static PROVIDED_DEP_INFO: std::cell::RefCell<Option<DepInfo>> = const { std::cell::RefCell::new(None) };
}

/// The key stopped before discovering the closure: no record, and the wrapper
/// allowed compiling first (see [`set_defer_discovery`]).
#[derive(Debug)]
pub struct DeferredDiscovery;

impl std::fmt::Display for DeferredDiscovery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("closure discovery deferred until after the compile")
    }
}

impl std::error::Error for DeferredDiscovery {}

/// Allow (or forbid) deferring closure discovery for keys computed on this
/// thread. With no record and no remote to consult, a miss is certain, so
/// the dep-info pre-pass would only repeat what the compile is about to
/// emit; the wrapper compiles, hands the emitted closure to
/// [`provide_dep_info`] and keys again.
pub fn set_defer_discovery(allowed: bool) {
    DEFER_DISCOVERY.with(|cell| cell.set(allowed));
}

/// Use `dep_info` for the next key computed on this thread.
pub fn provide_dep_info(dep_info: DepInfo) {
    PROVIDED_DEP_INFO.with(|cell| *cell.borrow_mut() = Some(dep_info));
}

/// The closure rustc wrote to `path` during the compile whose crate root is
/// `source_file`: the same content the pre-pass reads from its own output.
pub fn dep_info_from_emitted(path: &Path, source_file: &Path) -> Result<DepInfo> {
    let content = read_dep_info_file(path)?;
    let mut source_files = parse_dep_info(&content);
    if source_files.is_empty() {
        source_files.push(source_file.to_path_buf());
    }
    let env_deps = parse_env_dep_info(&content);
    Ok(DepInfo {
        source_files,
        env_deps,
    })
}

/// Take (consume) whether the last computed rustc key came from a prediction.
pub(crate) fn take_last_key_used_prediction() -> bool {
    LAST_KEY_USED_PREDICTION
        .try_with(|stash| stash.replace(false))
        .unwrap_or(false)
}

/// Take (consume) the input closure of the last computed rustc key.
///
/// `None` for cc compiles, passthroughs, and any invocation with no source
/// file — none of which discovered a closure to remember.
pub(crate) fn take_last_dep_info() -> Option<DepInfo> {
    LAST_KEY_DEP_INFO
        .try_with(|stash| stash.borrow_mut().take())
        .ok()
        .flatten()
}

/// Stable identity for one dep-info source path.
///
/// Cargo/worktree-local roots use the same rule rustc receives through
/// `--remap-path-prefix`. Keep the dep-info spelling intact: canonicalizing a
/// symlink would merge two spellings even though rustc may embed them
/// differently through `file!()` or debug info. An unmodeled spelling stays
/// deliberately path-local through an opaque, lossless-OS-byte digest.
fn source_path_identity(file: &Path, path_normalizer: &PathNormalizer) -> Result<Vec<u8>> {
    if let Some(identity) = path_normalizer.source_path_identity(file) {
        return Ok(identity);
    }

    // Preserve the exact dep-info OS representation before hashing. Lossy
    // UTF-8, NFC normalization, or canonicalization can merge distinct source
    // spellings and recreate #760.
    let mut opaque = blake3::Hasher::new();
    opaque.update(b"kache-source-path-v1\0");
    opaque.update(&env_os_key_bytes(file.as_os_str()));
    Ok(format!("<OPAQUE_PATH>/{}", opaque.finalize().to_hex()).into_bytes())
}

/// The prediction identity of one rustc invocation, or `None` when there is
/// nothing to predict.
///
/// `None` when the invocation names no source file (no closure to discover),
/// or when the compiler's own version cannot be read — without it two
/// toolchains would share one record, and their closures need not match.
pub(crate) fn rustc_prediction_identity(args: &RustcArgs) -> Option<String> {
    rustc_prediction_identity_in_env(args, std::env::vars_os().collect())
}

fn rustc_prediction_identity_in_env(
    args: &RustcArgs,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
) -> Option<String> {
    rustc_prediction_identity_with_args(args, vars, None)
}

fn rustc_prediction_identity_with_args(
    args: &RustcArgs,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
    closure_args: Option<Vec<String>>,
) -> Option<String> {
    let source_file = args.source_file.as_ref()?;
    let rustc_version = get_rustc_version(&args.rustc).ok()?;
    Some(prediction_identity_in_env(
        &PredictionIdentityParts {
            rustc_version: &rustc_version,
            inner_rustc: args.inner_rustc.as_deref(),
            current_dir: std::env::current_dir().ok().as_deref(),
            source_file,
            closure_args: &closure_args
                .unwrap_or_else(|| closure_shaping_args(source_file, &args.all_args)),
            skip_path_remap: args.skip_path_remap(),
        },
        vars,
    ))
}

/// Share a prediction across Cargo target directories without relocating any
/// source. Only dependency-search and extern paths are virtualized; cwd,
/// source paths, cfg values and environment retain their original identity.
/// A record containing a source under target is never published here.
pub(crate) fn rustc_shared_prediction_identity(args: &RustcArgs) -> Option<String> {
    let target = args.target_dir()?;
    if !target.is_absolute() || !prediction_applies(&args.externs) {
        return None;
    }
    let source = args.source_file.as_ref()?;
    let closure_args =
        shared_prediction_args(&closure_shaping_args(source, &args.all_args), &target);
    let identity = rustc_prediction_identity_with_args(
        args,
        std::env::vars_os().collect(),
        Some(closure_args),
    )?;
    Some(format!("shared-target-v1:{identity}"))
}

fn shared_prediction_args(args: &[String], target: &Path) -> Vec<String> {
    let mut kind = None;
    args.iter()
        .map(|arg| {
            let path_arg = match kind.take() {
                Some(flag) => Some((flag, arg.as_str())),
                None => {
                    if arg == "--extern" || arg == "-L" {
                        kind = Some(arg.as_str());
                    }
                    arg.strip_prefix("--extern=")
                        .map(|value| ("--extern=", value))
                        .or_else(|| {
                            arg.strip_prefix("-L")
                                .filter(|s| !s.is_empty())
                                .map(|value| ("-L", value))
                        })
                }
            };
            let mapped = path_arg.and_then(|(flag, value)| {
                let (name, path) = value.split_once('=').unwrap_or(("", value));
                let relative = Path::new(path).strip_prefix(target).ok()?;
                if relative
                    .components()
                    .any(|c| !matches!(c, std::path::Component::Normal(_)))
                {
                    return None;
                }
                Some(("target", flag, name, relative.to_str()?))
            });
            // Tag every argument, including literals, so a user-supplied path
            // or cfg string cannot impersonate an encoded target-relative one.
            serde_json::to_string(&mapped.unwrap_or(("literal", "", "", arg))).unwrap()
        })
        .collect()
}

pub(crate) fn shared_prediction_can_record(args: &RustcArgs, dep_info: &DepInfo) -> bool {
    args.target_dir().is_some_and(|target| {
        !dep_info
            .source_files
            .iter()
            .any(|source| source.starts_with(&target))
    })
}

/// How often to check a prediction against the pre-pass it replaced.
///
/// The rules in [`validate_prediction`] are an argument, and this is the
/// measurement of that argument on real code. `sampled` pays one pre-pass per
/// [`VERIFY_PREDICTION_RATE`] units to keep the argument honest; `always` is
/// for a nightly, where the point is to count disagreements rather than to be
/// fast. Any disagreement means the prediction is used nowhere: the pre-pass
/// result wins.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VerifyPredictions {
    Off,
    Sampled,
    Always,
}

/// One in this many predictions is checked under `sampled`.
const VERIFY_PREDICTION_RATE: usize = 64;

fn parse_verify_predictions(value: Option<&str>) -> VerifyPredictions {
    match value {
        Some(v) if v.eq_ignore_ascii_case("sampled") => VerifyPredictions::Sampled,
        Some(v)
            if v.eq_ignore_ascii_case("always") || v == "1" || v.eq_ignore_ascii_case("true") =>
        {
            VerifyPredictions::Always
        }
        _ => VerifyPredictions::Off,
    }
}

/// Does THIS prediction get checked against the pre-pass it replaced?
///
/// Sampling is decided from the unit's own identity, not from a counter. A
/// rolling counter is what the restore verifier uses, and it works there
/// because the daemon is one long-lived process. The wrapper is not: it is a
/// fresh process per compile, so a process-global counter starts at zero every
/// time and `0 % rate == 0` makes every unit verify. That turned `sampled`
/// into `always`, and a nightly measured the cost of both paths at once
/// instead of the saving.
///
/// Hashing the identity also makes the sample stable: the same units are
/// checked on every build, so a disagreement is reproducible rather than a
/// one-off nobody can chase. Different units are covered across a graph
/// because the identities differ, not because a counter advanced.
fn should_verify_this_prediction(mode: VerifyPredictions, identity: &str) -> bool {
    match mode {
        VerifyPredictions::Off => false,
        VerifyPredictions::Always => true,
        VerifyPredictions::Sampled => sampled_by_identity(identity, VERIFY_PREDICTION_RATE),
    }
}

/// One identity in `rate` selects, decided by its own bytes so that no shared
/// state and no ordering is involved.
fn sampled_by_identity(identity: &str, rate: usize) -> bool {
    if rate <= 1 {
        return true;
    }
    let digest = blake3::hash(identity.as_bytes());
    let bucket = u64::from_le_bytes(digest.as_bytes()[..8].try_into().unwrap_or([0; 8]));
    bucket % (rate as u64) == 0
}

/// Do the two closures agree on what rustc reads?
///
/// Source order is not compared: the key sorts sources before folding them,
/// so two orderings of the same set produce the same key. Env deps are
/// compared as a set for the same reason.
fn closures_agree(predicted: &DepInfo, discovered: &DepInfo) -> bool {
    let mut a = predicted.source_files.clone();
    let mut b = discovered.source_files.clone();
    a.sort();
    b.sort();
    let mut ea = predicted.env_deps.clone();
    let mut eb = discovered.env_deps.clone();
    ea.sort();
    eb.sort();
    a == b && ea == eb
}

/// The closure a prior build recorded for this unit, if every rule still
/// holds against the tree as it is now.
///
/// Nothing here is trusted on its word: the record supplies candidate paths
/// and env values, and each one is re-checked. Any doubt is a `Rejection`,
/// and every `Rejection` means the same thing to the caller — spawn the
/// pre-pass and discover the closure for real.
fn predicted_key_inputs(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
) -> std::result::Result<(DepInfo, String), Rejection> {
    let _trace = crate::phase_trace::phase("prediction_validate");
    if !file_hasher.uses_input_predictions() {
        return Err(Rejection::Disabled);
    }
    // A unit with a proc-macro dependency is only predictable under the tree
    // guard: the record must carry the crate tree digest and it must still
    // match. Computed once here and stashed, because the same digest is what
    // a record made from this invocation has to carry.
    let tree = if prediction_applies(&args.externs) {
        None
    } else {
        let _trace = crate::phase_trace::phase("crate_tree");
        let digest = crate_tree_digest(file_hasher).ok_or(Rejection::NotEligible)?;
        let _ = LAST_KEY_TREE_DIGEST.try_with(|stash| *stash.borrow_mut() = Some(digest.clone()));
        Some(digest)
    };
    let mut identity = rustc_prediction_identity(args).ok_or(Rejection::Disabled)?;
    let record = file_hasher
        .input_prediction(&identity)
        .or_else(|| {
            identity = rustc_shared_prediction_identity(args)?;
            file_hasher.input_prediction(&identity)
        })
        .ok_or(Rejection::NoRecord)?;
    if let Some(tree) = &tree {
        match &record.tree {
            Some(recorded) if recorded == tree => {}
            Some(_) => return Err(Rejection::TreeChanged),
            None => return Err(Rejection::NoRecord),
        }
    }
    let dep_info = validate_prediction(
        &record,
        |path| std::fs::metadata(path).ok(),
        |path| path.exists(),
        |var| std::env::var(var).ok(),
    )?;
    // The identity travels with the closure: the sampled cross-check selects
    // by it, so it must be the one this record actually came from.
    Ok((dep_info, identity))
}

/// Join only when an eligible unit needs discovery. A peer holds the lock
/// until it has published a successful prediction and artifacts; this caller
/// then validates the record and computes its own complete key as usual.
fn prediction_discovery_identity(args: &RustcArgs, file_hasher: &FileHasher<'_>) -> Option<String> {
    if !file_hasher.uses_input_predictions() || !prediction_applies(&args.externs) {
        return None;
    }
    rustc_shared_prediction_identity(args).or_else(|| rustc_prediction_identity(args))
}

/// Discover the source closure that feeds the key.
///
/// The dep-info pre-pass enumerates the real closure. If it fails we must NOT
/// fabricate a crate-root-only `DepInfo` and key off it: that under-specifies
/// the inputs, so a later build whose transitive sources (`#[path]`,
/// `include_str!`, generated files) changed would produce the same key and
/// restore a stale artifact (kunobi-ninja/kache#323). Propagate the error so
/// the wrapper passes through to the real compiler and never stores under an
/// incomplete input set.
///
/// `None` when the invocation names no source file: there is no closure to
/// discover, and the key simply folds no source or env-dep group.
fn resolve_key_inputs(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    crate_name: &str,
) -> Result<Option<DepInfo>> {
    if let Some(provided) = PROVIDED_DEP_INFO.with(|cell| cell.borrow_mut().take()) {
        crate::phase_trace::decision("prediction", "emitted");
        tracing::trace!("[key:{}] inputs=emitted-dep-info", crate_name);
        return Ok(Some(provided));
    }
    if args.source_file.is_some() {
        let mut prediction = predicted_key_inputs(args, file_hasher);
        // Whether "no record" means nobody built this unit here. A unit whose
        // record is shared across target directories and whose discovery
        // flight this process owns (or needs no flight) can be sure; a peer
        // that waited for an owner and still finds nothing, or a unit whose
        // record is target-directory-local (a proc-macro dependent, or a
        // unit with an OUT_DIR, which the record identity keeps verbatim),
        // may well find the entry under the key the pre-pass yields.
        let mut certain_miss = rustc_shared_prediction_identity(args).is_some()
            && std::env::var_os("OUT_DIR").is_none();
        if prediction.is_err()
            && let Some(cache_dir) = &file_hasher.prediction_flight_dir
            && let Some(identity) = prediction_discovery_identity(args, file_hasher)
        {
            let flight = crate::scheduler::join_discovery(cache_dir, &identity);
            certain_miss = certain_miss && flight.is_some();
            *file_hasher.discovery_flight.borrow_mut() = flight;
            // The previous owner may have published while this process waited.
            prediction = predicted_key_inputs(args, file_hasher);
        }
        match prediction {
            Ok((dep_info, identity)) => {
                crate::phase_trace::decision("prediction", "validated");
                let mode = parse_verify_predictions(
                    std::env::var("KACHE_VERIFY_INPUT_PREDICTIONS")
                        .ok()
                        .as_deref(),
                );
                // Verification is the exceptional path: it runs the pre-pass
                // anyway and uses ITS answer, so a disagreement is reported
                // rather than acted on.
                if should_verify_this_prediction(mode, &identity) {
                    crate::phase_trace::decision("prediction", "verify-sampled");
                    let discovered = dep_info_pre_pass(args)?;
                    if discovered
                        .as_ref()
                        .is_some_and(|discovered| closures_agree(&dep_info, discovered))
                    {
                        tracing::trace!("[key:{}] inputs=predicted(verified)", crate_name);
                    } else {
                        tracing::warn!(
                            "[key:{}] input prediction disagreed with the dep-info pass; \
                             using the pass. Please report this with the crate and its \
                             dependencies (kunobi-ninja/kache).",
                            crate_name
                        );
                        crate::opcounts::record_prediction_mismatch();
                    }
                    return Ok(discovered);
                }
                tracing::trace!("[key:{}] inputs=predicted", crate_name);
                let _ = LAST_KEY_USED_PREDICTION.try_with(|stash| stash.set(true));
                return Ok(Some(dep_info));
            }
            Err(Rejection::NoRecord)
                if certain_miss && DEFER_DISCOVERY.with(std::cell::Cell::get) =>
            {
                crate::phase_trace::decision("prediction", "deferred");
                tracing::trace!("[key:{}] inputs=deferred", crate_name);
                return Err(anyhow::Error::new(DeferredDiscovery));
            }
            Err(reason) => {
                crate::phase_trace::decision("prediction", reason.as_str());
                tracing::trace!("[key:{}] inputs=dep-info({})", crate_name, reason.as_str())
            }
        }
    }
    dep_info_pre_pass(args)
}

/// Spawn rustc to enumerate the closure. The slow, authoritative answer.
fn dep_info_pre_pass(args: &RustcArgs) -> Result<Option<DepInfo>> {
    let _trace = crate::phase_trace::phase("dep-info");
    args.source_file
        .as_ref()
        .map(|source| {
            run_dep_info_pass(
                &args.rustc,
                args.inner_rustc.as_deref(),
                source,
                &args.all_args,
                args.has_expanded_argfiles(),
            )
            .with_context(|| {
                format!(
                    "dep-info pre-pass failed for {} — refusing to cache from an \
                     incomplete input set",
                    source.display()
                )
            })
        })
        .transpose()
}

/// Compute the blake3 cache key for a rustc invocation.
///
/// The key captures everything that affects compilation output:
/// - rustc version (full verbose string)
/// - target triple
/// - crate name and type
/// - emit kinds (metadata vs link — distinguishes check from build)
/// - codegen options (opt-level, lto, codegen-units, panic, etc.)
/// - feature flags (sorted)
/// - source file hash
/// - dependency artifact hashes
/// - RUSTFLAGS and relevant env vars
/// - linker identity (for bin/dylib caching)
pub fn compute_cache_key(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
) -> Result<String> {
    let _trace = crate::phase_trace::phase("key");
    // Grouped: the main digest is identical to a plain hasher's; the group
    // tee powers `explain_miss` (kunobi-ninja/kache#131).
    let mut hasher = GroupedHasher::new("compiler");
    let crate_name = args.crate_name.as_deref().unwrap_or("unknown");

    // Clear the extern stash up front (#609). It is written near the end of
    // this function, so a computation that bails before the externs group —
    // or one that never reaches the event writer — would otherwise leave a
    // previous invocation's dependency digests to be picked up as if they
    // belonged to this compile.
    let _ = LAST_KEY_EXTERNS.try_with(|stash| *stash.borrow_mut() = None);
    // Same reasoning for the unit ids (#627); both are cleared and written
    // together so the walk can never pair one compile's digests with another's
    // identities.
    let _ = LAST_KEY_EXTERN_UNITS.try_with(|stash| *stash.borrow_mut() = None);
    let _ = LAST_KEY_UNIT_ID.try_with(|stash| *stash.borrow_mut() = args.unit_id());
    // And the discovered closure, for the same reason: a computation that
    // bails before the pre-pass would otherwise leave the previous compile's
    // closure to be recorded against this one's identity.
    let _ = LAST_KEY_DEP_INFO.try_with(|stash| *stash.borrow_mut() = None);
    let _ = LAST_KEY_TREE_DIGEST.try_with(|stash| *stash.borrow_mut() = None);
    let _ = LAST_KEY_USED_PREDICTION.try_with(|stash| stash.set(false));

    // key version — bump CACHE_KEY_VERSION to invalidate all prior entries
    hasher.update(b"key_version:");
    hasher.update(CACHE_KEY_VERSION.to_string().as_bytes());
    hasher.update(b"\n");
    tracing::trace!("[key:{}] key_version={}", crate_name, CACHE_KEY_VERSION);

    // Distinguish configured from unconfigured clients of this same release.
    // Only the stable sentinel/target SET (represented by its deterministic
    // count) is folded — never the machine-local prefix spellings — so two
    // hosts that relocate corresponding configured roots still share keys.
    let configured_base_dirs = path_normalizer.configured_base_dir_count();
    if configured_base_dirs != 0 {
        fold_field(
            &mut hasher,
            b"configured_base_dirs.v1:",
            configured_base_dirs.to_string().as_bytes(),
        );
        tracing::trace!(
            "[key:{}] configured_base_dirs={}",
            crate_name,
            configured_base_dirs
        );
    }

    // rustc version
    let rustc_version = get_rustc_version(&args.rustc)?;
    hasher.update(b"rustc_version:");
    hasher.update(rustc_version.as_bytes());
    hasher.update(b"\n");
    tracing::trace!(
        "[key:{}] rustc_version={}",
        crate_name,
        rustc_version.lines().next().unwrap_or("?")
    );

    // Clippy: the driver's own version, its configuration file and the lint
    // arguments Cargo hands it through the environment all change what a
    // successful compile prints, and hits replay diagnostics.
    if args.is_clippy_chain() {
        let identity = clippy_identity(&args.rustc)?;
        fold_field(&mut hasher, b"clippy.v1:", identity.as_bytes());
        tracing::trace!(
            "[key:{}] clippy={}",
            crate_name,
            identity.lines().next().unwrap_or("?")
        );
    }

    // target triple
    let target = args
        .target
        .as_deref()
        .unwrap_or_else(|| host_target_triple());
    // `--target=` can be a path to a custom target JSON spec (Firefox /
    // embedded toolchains do this) — flag any absolute machine-local path
    // that lands here unsentinelized.
    check_for_path_leak(target, "target");
    hasher.update(b"target:");
    hasher.update(target.as_bytes());
    hasher.update(b"\n");
    tracing::trace!("[key:{}] target={}", crate_name, target);

    // A `--target` value can be a path to a custom target JSON spec
    // (Firefox / embedded toolchains). That spec encodes data-layout,
    // target-cpu/features, linker, panic strategy, code-model — all
    // codegen-affecting — yet the dep-info pass never lists it, so only
    // the path string above would distinguish two builds. Hash the file
    // CONTENTS too, so editing the spec in place (or a different spec at
    // the same path on another machine) diverges the key. Built-in
    // triples aren't files, so they're unaffected.
    let target_path = Path::new(target);
    if target_path.is_file() {
        match hash_file(target_path) {
            Ok(spec_hash) => {
                hasher.update(b"target_spec:");
                hasher.update(spec_hash.as_bytes());
                hasher.update(b"\n");
                tracing::trace!("[key:{}] target_spec={}", crate_name, &spec_hash[..16]);
            }
            Err(e) => {
                tracing::warn!(
                    "[key:{}] failed to hash target spec {}: {}",
                    crate_name,
                    target,
                    e
                );
            }
        }
    }

    // crate identity
    hasher.set_group("crate");
    if let Some(name) = &args.crate_name {
        hasher.update(b"crate_name:");
        hasher.update(name.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] crate_name={}", crate_name, name);
    }

    // crate types
    for ct in &args.crate_types {
        hasher.update(b"crate_type:");
        hasher.update(ct.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] crate_type={}", crate_name, ct);
    }

    // edition
    if let Some(edition) = &args.edition {
        hasher.update(b"edition:");
        hasher.update(edition.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] edition={}", crate_name, edition);
    }

    hasher.set_group("args");
    // emit kinds (sorted for determinism)
    //
    // `cargo check` runs `rustc --emit=metadata` (produces `.rmeta`);
    // `cargo build` runs `--emit=link` (produces `.rlib`). With every
    // other hashed input identical the two invocations would collide,
    // letting a check's metadata-only entry be served to a build that
    // needs the `.rlib` — a miscache. Hashing `emit` keeps the two
    // keyed apart by design rather than by cargo's incidental per-unit
    // `-C metadata` differing between the two.
    let mut emit: Vec<&String> = args.emit.iter().collect();
    emit.sort();
    for kind in &emit {
        hasher.update(b"emit:");
        hasher.update(kind.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] emit:{}", crate_name, kind);
    }

    // Codegen options grouped by name for determinism. This is a stable sort,
    // so repeated last-wins options retain argv order. Rustc's `-O` and `-g`
    // shorthands are normalized into this same list during parsing.
    let mut codegen_opts: Vec<_> = args
        .codegen_opts
        .iter()
        .filter(|(k, _)| {
            // Skip incremental as it's path-dependent.
            // Skip linker because its value is a machine-local absolute
            // path on toolchain-bootstrapping builds (Firefox/mozbuild
            // sets `-Clinker=/abs/path/to/clang++`). The linker's
            // semantic identity is captured separately via
            // `get_linker_identity` (its `--version` output) which is
            // path-independent.
            k != "incremental" && k != "linker"
        })
        .collect();
    codegen_opts.sort_by_key(|(k, _)| k.as_str());
    for (key, value) in &codegen_opts {
        fold_field(&mut hasher, b"codegen_key:", key.as_bytes());
        if let Some(v) = value {
            // `-Clink-arg=`, `-Clink-args=…`, `-Cprofile-use=…`, etc. can
            // carry absolute paths. None of these go through
            // PathNormalizer (they're rustc-controlled flags, not env);
            // flag any leaked path so the field is identifiable.
            check_for_path_leak(v, &format!("codegen:{key}"));
            fold_field(&mut hasher, b"codegen_val:", v.as_bytes());
            tracing::trace!("[key:{}] codegen:{}={}", crate_name, key, v);
        } else {
            tracing::trace!("[key:{}] codegen:{}", crate_name, key);
        }
    }

    // feature flags (already sorted in args parsing)
    for feat in &args.features {
        hasher.update(b"feature:");
        hasher.update(feat.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] feature:{}", crate_name, feat);
    }

    // cfg flags (non-feature, sorted)
    let mut cfgs: Vec<_> = args
        .cfgs
        .iter()
        .filter(|c| !c.starts_with("feature="))
        .collect();
    cfgs.sort();
    for cfg in &cfgs {
        // Build-script `cargo:rustc-cfg=…` lines reach us as raw strings;
        // mozbuild / embedded crates sometimes emit cfgs that embed
        // generated paths. None go through PathNormalizer — flag leaks.
        check_for_path_leak(cfg, "cfg");
        fold_field(&mut hasher, b"cfg:", cfg.as_bytes());
        tracing::trace!("[key:{}] cfg:{}", crate_name, cfg);
    }

    let dep_info = resolve_key_inputs(args, file_hasher, crate_name)?;
    // Keep the closure available to the wrapper, which records it as a
    // prediction only once the invocation it belongs to has succeeded. The
    // clone is one allocation per closure file against a whole rustc spawn.
    let _ = LAST_KEY_DEP_INFO.try_with(|stash| *stash.borrow_mut() = dep_info.clone());

    let mut externs: Vec<_> = args.externs.iter().filter(|e| e.path.is_some()).collect();
    externs.sort_by_key(|e| &e.name);

    let mut hash_paths = Vec::new();
    if let Some(dep_info) = &dep_info {
        hash_paths.extend(dep_info.source_files.iter().map(|p| p.as_path()));
    }
    hash_paths.extend(externs.iter().filter_map(|ext| ext.path.as_deref()));
    file_hasher.prefetch(&hash_paths);

    // ── Group A: source files + env deps (from dep-info pre-pass) ──
    hasher.set_group("sources");
    if let Some(dep_info) = &dep_info {
        // A source is identified by its stable normalized path and bytes.
        // Hashing only a sorted content multiset lets swapping modules/assets
        // preserve the key while changing semantics (#760). Matched paths use
        // stable sentinels for relocation (#201); unmatched paths stay local
        // rather than risk a false hit.
        let mut hashed: Vec<(Vec<u8>, String)> = Vec::with_capacity(dep_info.source_files.len());
        for file in &dep_info.source_files {
            let file_hash = file_hasher
                .hash(file)
                .with_context(|| format!("hashing source identity {}", file.display()))?;
            let normalized_path = source_path_identity(file, path_normalizer)?;
            hashed.push((normalized_path, file_hash));
        }
        hashed.sort();
        for (normalized_path, file_hash) in &hashed {
            fold_field(&mut hasher, b"source_path:", normalized_path);
            fold_field(&mut hasher, b"source_hash:", file_hash.as_bytes());
            tracing::trace!(
                "[key:{}] source:{}={}",
                crate_name,
                String::from_utf8_lossy(normalized_path),
                &file_hash[..16]
            );
        }

        hasher.set_group("env_deps");
        for (var, val) in &dep_info.env_deps {
            let normalized_env_dep = normalize_env_dep_value_with_hasher(
                crate_name,
                var,
                val,
                &dep_info.source_files,
                file_hasher,
                path_normalizer,
            );
            fold_field(&mut hasher, b"env_dep_var:", var.as_bytes());
            fold_field(
                &mut hasher,
                b"env_dep_val:",
                normalized_env_dep.value.as_bytes(),
            );
            tracing::trace!(
                "[key:{}] env_dep:{}={} ({})",
                crate_name,
                var,
                normalized_env_dep.value,
                normalized_env_dep.decision.as_str()
            );
        }
    }

    // ── Group B: extern crate artifacts ──
    hasher.set_group("externs");
    // Per-dependency digests teed off the same hashes folded below, for
    // `why-miss`'s extern-chain walk (#609). Recording happens unconditionally
    // — it is one map insert per extern, no extra I/O, since the hash is
    // already in hand — while the decision to PERSIST it stays with the
    // wrapper's `explain_miss` gate.
    let mut extern_digests = std::collections::BTreeMap::new();
    // Producing-unit ids, from the artifact filename rather than the extern
    // name, so a renamed or duplicated dependency still joins to its producer
    // (kunobi-ninja/kache#627).
    let mut extern_units = std::collections::BTreeMap::new();
    for ext in &externs {
        if let Some(path) = &ext.path {
            if let Some(unit) = crate::args::unit_id_from_artifact_path(path) {
                extern_units.insert(ext.name.clone(), unit);
            }
            match file_hasher.hash(path) {
                Ok(dep_hash) => {
                    hasher.update(b"extern:");
                    hasher.update(ext.name.as_bytes());
                    hasher.update(b"=");
                    hasher.update(dep_hash.as_bytes());
                    hasher.update(b"\n");
                    extern_digests.insert(
                        ext.name.clone(),
                        dep_hash
                            .get(..KEY_FIELD_HEX)
                            .unwrap_or(dep_hash.as_str())
                            .to_string(),
                    );
                    tracing::trace!(
                        "[key:{}] extern:{}={}",
                        crate_name,
                        ext.name,
                        &dep_hash[..16]
                    );
                }
                Err(_) => {
                    // Sysroot crate (std, core, etc.) — identity is determined by
                    // rustc version + name, both already in the hash. Use a sentinel
                    // instead of the absolute path to enable cross-machine sharing.
                    hasher.update(b"extern_unreadable:");
                    hasher.update(ext.name.as_bytes());
                    hasher.update(b"\n");
                    extern_digests.insert(ext.name.clone(), EXTERN_UNREADABLE.to_string());
                    tracing::trace!("[key:{}] extern_unreadable:{}", crate_name, ext.name);
                }
            }
        }
    }
    let _ = LAST_KEY_EXTERNS.try_with(|stash| *stash.borrow_mut() = Some(extern_digests));
    let _ = LAST_KEY_EXTERN_UNITS.try_with(|stash| *stash.borrow_mut() = Some(extern_units));

    // RUSTFLAGS — normalize via PathNormalizer (canonical-prefix
    // sentinel substitution; supersedes the older CWD-only
    // `normalize_flags` for cache-key purposes), then collapse runs of
    // whitespace into single spaces. Cargo / mach assemble the env
    // value with cosmetically-varying whitespace (multiple spaces
    // between flags, trailing spaces) across compile profiles, which
    // produced different hash inputs for semantically-identical flag
    // sets. Order is preserved — `-Cfoo=a -Cfoo=b` differs from
    // `-Cfoo=b -Cfoo=a` because later flags override earlier ones in
    // rustc's parser.
    hasher.set_group("args");
    if let Ok(rustflags) = std::env::var("RUSTFLAGS") {
        // Scrub the per-checkout `from` of any `--remap-path-prefix` BEFORE
        // sentinel normalization, so a checkout path the PathNormalizer would
        // only partially rewrite collapses to a single sentinel and clones
        // converge.
        let scrubbed = scrub_remap_from_prefixes(rustflags.split_whitespace()).join(" ");
        let normalized = normalize_rustflags(&path_normalizer.normalize(&scrubbed));
        hasher.update(b"RUSTFLAGS:");
        hasher.update(normalized.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] RUSTFLAGS={}", crate_name, normalized);
    }

    // CARGO_ENCODED_RUSTFLAGS (cargo's way of passing flags)
    if let Ok(flags) = std::env::var("CARGO_ENCODED_RUSTFLAGS") {
        // Same scrub as RUSTFLAGS; the encoded form is `\x1f`-separated, so
        // tokenize on that (a space-form `--remap-path-prefix` is its own unit
        // with the value in the next unit).
        let scrubbed = scrub_remap_from_prefixes(flags.split('\x1f')).join("\x1f");
        let normalized = path_normalizer.normalize(&scrubbed);
        hasher.update(b"CARGO_ENCODED_RUSTFLAGS:");
        hasher.update(normalized.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            "[key:{}] CARGO_ENCODED_RUSTFLAGS={}",
            crate_name,
            normalized
        );
    }

    // Direct argv remaps are codegen inputs too: they alter `file!()`, panic
    // locations, and debug paths. Normalize known machine-local prefixes on
    // FROM, but retain unrelated FROM values because matching vs non-matching
    // mappings are semantically different. Keep TO verbatim because it is
    // embedded in the artifact, and preserve order because overlapping remaps
    // are order-sensitive.
    for value in &args.remap_path_prefixes {
        let normalized = normalize_direct_remap_value(value, path_normalizer);
        fold_field(
            &mut hasher,
            b"argv_remap_path_prefix.v1:",
            normalized.as_bytes(),
        );
        tracing::trace!(
            "[key:{}] argv --remap-path-prefix={}",
            crate_name,
            normalized
        );
    }

    // RUSTC_BOOTSTRAP changes what rustc accepts — nightly-only
    // `#![feature(...)]` and unstable `-Z` flags on a stable/beta toolchain —
    // so byte-identical source can compile differently (or succeed vs fail)
    // purely because this var is set. It's consumed by the driver and never
    // surfaces as a source env-dep, so the `-Z`/`#![feature]` bytes are keyed
    // but the var's presence was not. Fold it in only when set, so the key is
    // byte-identical for the common case (var unset): no CACHE_KEY_VERSION bump
    // and no cache invalidation for existing users.
    if let Ok(bootstrap) = std::env::var("RUSTC_BOOTSTRAP")
        && !bootstrap.is_empty()
    {
        hasher.update(b"RUSTC_BOOTSTRAP:");
        hasher.update(bootstrap.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] RUSTC_BOOTSTRAP={}", crate_name, bootstrap);
    }

    // Sysroot override (`--sysroot`). Selects which std/core/proc-macro
    // libs rustc links against, so two builds of the same rustc binary
    // with different sysroots (custom-built std, `-Zbuild-std`) must not
    // collide. Normalized so a standard rustup layout still shares
    // across machines while a genuinely different path diverges.
    hasher.set_group("link");
    if let Some(sysroot) = &args.sysroot {
        let normalized = path_normalizer.normalize(sysroot.to_string_lossy());
        hasher.update(b"sysroot:");
        hasher.update(normalized.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] sysroot={}", crate_name, normalized);
    }

    // Native link search paths (`-L [KIND=]PATH`). cargo's own
    // `dependency=`/`crate=` entries are redundant with the
    // content-hashed `--extern` rlibs and are machine-local, so they're
    // skipped; build-script-supplied `native=`/`framework=`/bare paths
    // DO change a linked artifact and are kept (path-normalized for
    // cross-machine stability). Order is preserved — link order is
    // significant, and a stable argv from cargo keeps the key stable.
    const KNOWN_L_KINDS: [&str; 5] = ["dependency", "crate", "native", "framework", "all"];
    // Real (un-normalized) build-script search dirs, kept for resolving `-l`
    // static libs to a content hash below (#421). `native=`/bare entries are the
    // OUT_DIR dirs a `cc`/`cmake` build script emits; `dependency=`/`crate=` are
    // cargo's own rlib dirs (redundant with content-hashed externs).
    let mut native_search_dirs: Vec<PathBuf> = Vec::new();
    for spec in &args.link_search {
        // Only split on a *recognized* kind so a path containing '='
        // isn't mis-parsed (matches rustc's own `-L` parsing).
        let (kind, path) = match spec.split_once('=') {
            Some((k, p)) if KNOWN_L_KINDS.contains(&k) => (Some(k), p),
            _ => (None, spec.as_str()),
        };
        if matches!(kind, Some("dependency") | Some("crate")) {
            continue;
        }
        // `all=` and bare/`native=` dirs all search native libs (rustc's `-L`
        // default kind is `all`); a `static=` lib can resolve in any of them.
        if matches!(kind, None | Some("native") | Some("all")) {
            native_search_dirs.push(PathBuf::from(path));
        }
        let normalized = path_normalizer.normalize(path);
        hasher.update(b"link_search:");
        if let Some(k) = kind {
            hasher.update(k.as_bytes());
            hasher.update(b"=");
        }
        hasher.update(normalized.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] link_search:{}", crate_name, normalized);
    }

    // Native libraries to link (`-l`). The name alone (machine-independent;
    // a build script repointing `-l` to a different lib is caught here) is
    // hashed raw, order preserved (static link order is significant).
    //
    // The name does NOT capture a `static=` lib whose *content* changed in
    // place — same `-l` name, same `-L` path, different bytes. rustc bundles a
    // `static=` archive INTO the produced rlib/binary, so its bytes are part of
    // the output: an unchanged key there is a stale-artifact false hit (#421).
    // Resolve each `static=` lib against the kept build-script search dirs and
    // fold its content hash. Phase 1 is deliberately narrow — only `static=`
    // (the bundled, output-affecting case) and only build-script `native=`/bare
    // dirs (the OUT_DIR false-hit trigger). `dylib=` is normally referenced
    // rather than bundled and is left name-only here. Direct command-line
    // native Windows MSVC libraries are handled separately below: their
    // import-library bytes affect the executable and are hashed as part of the
    // host link identity. Files handed to LINK through `-C link-arg` (`.res`,
    // `.def`, `.obj`, `/DEF:`, `/MANIFESTINPUT:`, ...) are folded only as
    // text by the generic codegen fold, so that identity refuses them rather
    // than let a rebuilt file under the same name restore a stale executable.
    // Libraries inherited only through rlib metadata are not exposed in this
    // argv and are outside that direct-input identity. An invocation that
    // links a `static=` archive itself keeps a DWARF-bearing Mach-O archive
    // path-bound; see [`StaticLibUse`].
    // Linker order/section-order/map files and opaque response files require
    // side-input/output handling beyond the archive key. Fail closed instead
    // of caching an invocation whose auxiliary behavior cannot be reproduced.
    if native_linker_side_files_are_unmodeled(args) {
        anyhow::bail!("native linker order/map/response side files are not cacheable");
    }
    for lib in &args.link_libs {
        hasher.update(b"link_lib:");
        hasher.update(lib.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] link_lib:{}", crate_name, lib);

        if let Some((path, content_hash)) =
            resolve_native_static_lib(lib, &native_search_dirs, file_hasher, static_lib_use(args))?
        {
            hasher.update(b"link_lib_content:");
            hasher.update(content_hash.as_bytes());
            hasher.update(b"\n");
            tracing::trace!(
                "[key:{}] link_lib_content:{}={} ({})",
                crate_name,
                lib,
                &content_hash[..content_hash.len().min(16)],
                path.display()
            );
        }
    }

    // Unstable `-Z` flags arriving on argv outside RUSTFLAGS. Can change
    // codegen (`-Zsanitizer`, `-Zshare-generics`, …); hashed raw.
    hasher.set_group("args");
    for z in &args.unstable_flags {
        hasher.update(b"unstable:");
        hasher.update(z.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] unstable:{}", crate_name, z);
    }

    // Parallel frontend compilation changes the compiler execution mode and
    // can affect emitted artifacts. Preserve occurrence order because rustc
    // applies repeated values last-wins.
    for jobs in &args.frontend_jobs {
        fold_field(&mut hasher, b"frontend_jobs.v1:", jobs.as_bytes());
        tracing::trace!("[key:{}] frontend_jobs:{}", crate_name, jobs);
    }

    // Residual argv tokens (kunobi-ninja/kache#324): flags kache does not model
    // explicitly still reach rustc and can affect codegen (for example a
    // future flag), yet were previously invisible to the key — the `_ => {}`
    // catch-all in `args.rs` dropped them. Fold the NORMALIZED, sorted residual
    // under a versioned tag so an unmodeled codegen-affecting flag changes the
    // key. Diagnostics / lint / query / already-keyed path flags are stripped
    // during arg parsing, so they never reach here. Normalize via PathNormalizer
    // (a residual token can embed a machine-local path) and sort so argv order /
    // host paths don't perturb the key. Folded only when non-empty, so the
    // common case (no residual) is byte-identical and needs no
    // CACHE_KEY_VERSION bump (same precedent as RUSTC_BOOTSTRAP above).
    if !args.residual_args.is_empty() {
        let mut residual: Vec<String> = args
            .residual_args
            .iter()
            .map(|tok| path_normalizer.normalize(tok))
            .collect();
        residual.sort();
        for tok in &residual {
            check_for_path_leak(tok, "residual_arg");
            fold_field(&mut hasher, b"residual_args.v1:", tok.as_bytes());
            tracing::trace!("[key:{}] residual_arg:{}", crate_name, tok);
        }
        // Surface unmodeled ("exotic") rustc flags so it is visible which ones
        // appear in real builds (kunobi-ninja/kache#183). They are already folded
        // into the key above, so they cannot cause a false hit; this is a prompt
        // to model them explicitly for precise keying (or to report them). Raw
        // tokens (not the path-normalized form) so they match what was passed.
        // Fires per cacheable invocation, which is rare: direct-argv unmodeled
        // flags only, since -C/-Z and RUSTFLAGS are already modeled.
        let mut raw: Vec<&str> = args.residual_args.iter().map(String::as_str).collect();
        raw.sort_unstable();
        raw.dedup();
        tracing::warn!(
            "[key:{}] {} unmodeled rustc flag(s) folded into the cache key \
             (kache does not model these; keyed defensively so they cannot cause \
             a false hit, but model them for precise keying): {}",
            crate_name,
            raw.len(),
            raw.join(" "),
        );
    }

    // Outcome-affecting lint configuration (-A/-W/-D/-F, their long forms,
    // --force-warn, --cap-lints, and --check-cfg): two invocations differing
    // only here can disagree about whether compilation succeeded while
    // producing identical object bytes on success. In particular, allow/warn
    // levels interact with deny groups, and --check-cfg feeds unexpected_cfgs.
    // A hit replays success, which would flip a build that `-D warnings`
    // should have failed to green. The flags are captured during parsing
    // (see `OUTCOME_AFFECTING_VALUE_FLAGS` in args.rs) and folded here. v28
    // invalidates prior entries because v27 was released with these inputs
    // missing and old clients can still populate that shared schema.
    //
    // Folded in ARGV ORDER, deliberately unsorted. The captured vector is a
    // flat token stream (`-D`, `warnings`, `--force-warn`, `deprecated`), so
    // sorting would both break the flag↔value pairing — `-D unsafe_code -F
    // warnings` and `-F unsafe_code -D warnings` share a sorted multiset but
    // not an outcome — and erase order, which rustc itself treats as
    // meaningful (the last level named for a lint wins). A stable argv order
    // for a given build config means keeping it costs no hits.
    if !args.outcome_lint_flags.is_empty() {
        hasher.set_group("outcome_lints");
        for tok in &args.outcome_lint_flags {
            // Fold raw: check-cfg accepts arbitrary string values, including
            // path-looking text. Path normalization could collapse two
            // distinct accepted-value sets and reopen a false hit.
            // The leak check is observability-only; it never rewrites the key.
            check_for_path_leak(tok, "outcome_lint");
            fold_field(&mut hasher, b"outcome_lint.v1:", tok.as_bytes());
            tracing::trace!("[key:{}] outcome_lint:{}", crate_name, tok);
        }
    }

    // Relevant CARGO_CFG_* env vars (sorted for determinism —
    // environment iteration order is platform-defined and not stable)
    hasher.set_group("env_cfg");
    let cargo_cfgs = cargo_cfg_pairs(std::env::vars_os());
    tracing::trace!("[key:{}] cargo_cfg_count={}", crate_name, cargo_cfgs.len());
    for (key, value) in &cargo_cfgs {
        // Cargo derives CARGO_CFG_* from `--cfg` flags. Build scripts (and
        // mozbuild specifically) emit cfgs that can embed absolute paths;
        // those land here uncensored. Flag leaks so the offending var
        // name is visible in the warn. The lossy forms are diagnostic
        // only; the hash folds the lossless bytes.
        let key_lossy = key.to_string_lossy();
        check_for_path_leak(&value.to_string_lossy(), &format!("cargo_cfg:{key_lossy}"));
        hasher.update(&env_text_key_bytes(key));
        hasher.update(b"=");
        hasher.update(&env_text_key_bytes(value));
        hasher.update(b"\n");
    }

    // Linker identity for bin/dylib targets
    hasher.set_group("link");
    let native_windows_msvc = is_native_windows_msvc_link(
        args,
        &rustc_version,
        cfg!(target_os = "windows"),
        get_rustc_version,
    )?;
    fold_generic_linker_identity(&mut hasher, args, native_windows_msvc, get_linker_identity);

    // A native Linux linked artifact also depends on the host libc ABI. The
    // rustc host triple does not include the libc version, so two machines with
    // the same rustc/linker versions could otherwise share an incompatible
    // bin/dylib through a remote cache (kunobi-ninja/kache#127). Cross targets
    // deliberately skip this HOST signal: their libc comes from the target
    // sysroot/toolchain, and poisoning those keys with the build host would
    // only destroy valid cross-machine hits without identifying that sysroot.
    // Probe failure is an error, making the wrapper pass through instead of
    // risking a shared-cache false hit.
    fold_native_host_libc_signature(
        &mut hasher,
        args,
        &rustc_version,
        cfg!(target_os = "linux"),
        probe_linux_libc_signature,
    )?;

    // Stronger than the version string above: hash the CRT/startup objects and
    // libc the driver actually places (Linux), and the SDK identity (macOS).
    // Two hosts with the same `cc --version` / libc version banner and
    // different object bytes then miss instead of sharing. If none of the
    // essentials resolve, fail closed — passthrough rather than a key that
    // claims to have pinned a runtime neither host identified. v29.
    fold_native_link_runtime_identity(
        &mut hasher,
        args,
        &rustc_version,
        cfg!(target_os = "linux"),
        cfg!(target_os = "macos"),
        |driver| {
            // Placements come from the memo while the searched directories
            // are unchanged; content hashes are still reused only with an
            // unchanged file fingerprint, through the same guards as other
            // key inputs.
            crate::native_link_key::probe_linux_crt_objects_memoized(
                &crate::config::probe_memo_dir(),
                driver,
                |path| file_hasher.hash(path),
            )
        },
        |sdkroot| match crate::native_link_key::sdk_identity_for(sdkroot)? {
            Some(identity) => Ok(identity),
            None => anyhow::bail!("the macOS SDK could not be identified"),
        },
        std::env::var("MACOSX_DEPLOYMENT_TARGET").ok(),
    )?;

    // Native Windows MSVC links depend on the selected COFF linker/compiler,
    // the architecture-specific MSVC/SDK/UCRT environment, and the runtime
    // import/static libraries. The probe is strictly host-native: metadata,
    // cross-target links, and windows-gnu links must remain portable and must
    // not execute or inspect host tools. A failed probe bubbles out so the
    // wrapper passes through rather than sharing an unidentified executable;
    // so does any `-C link-arg` that names an input file the identity does
    // not hash (see `windows_native_link_search_dirs`).
    fold_native_windows_msvc_identity(
        &mut hasher,
        args,
        &rustc_version,
        cfg!(target_os = "windows"),
        |linker, architecture| {
            let search_dirs = windows_native_link_search_dirs(args)?;
            crate::native_link_key::probe_windows_msvc_identity_with_library_dirs(
                linker,
                architecture,
                &search_dirs.rustc,
                &search_dirs.linker,
                &args.link_libs,
                |path| file_hasher.hash_static_lib(path),
            )
            .map(|identity| identity.encode())
        },
    )?;

    // Path remapping status: kache injects multi-prefix
    // `--remap-path-prefix` flags (one per PathNormalizer rule) for
    // reproducible builds across machines — but skips them under
    // coverage instrumentation (tarpaulin / llvm-cov need original
    // paths in profraw to map coverage back to source) or when the user
    // opts out via `KACHE_RUSTC_PATH_NORMALIZE=0` (local profiler /
    // debugger source lookup needs real paths, kunobi-ninja/kache#480).
    // Since this produces different binaries, the key must reflect the
    // choice — the opt-out namespace hashes `remap:none`, so a build with
    // remapping disabled never collides with a default remapped artifact.
    // This uses the SAME `args.skip_path_remap()` decision (a parse-time
    // snapshot) that `RustcCompiler::execute` uses to gate injection, so the
    // key can never claim one remap state while the binary was built with the
    // other, breaking the byte-for-byte cache invariant.
    //
    // We hash the SENTINEL set (not the prefix paths) so the key
    // stays portable across machines — different hosts have
    // different `$HOME` / `$CARGO_HOME` prefixes but the same
    // sentinel categories, so the key is identical.
    hasher.set_group("remap");
    let remap = if args.skip_path_remap() {
        hasher.update(b"remap:none\n");
        // Whenever remap injection is skipped — the `KACHE_RUSTC_PATH_NORMALIZE=0`
        // opt-out OR a coverage build (llvm-cov / tarpaulin need real paths in
        // the profraw) — rustc bakes real machine-local paths into DWARF instead
        // of sentinels. Those paths are NOT otherwise in the key (path-bearing
        // inputs are still normalized and source is hashed by content), so
        // without this fold two different checkouts compute the same `remap:none`
        // key and a shared cache would serve one checkout's real-path artifact to
        // another (kunobi-ninja/kache#480 for the opt-out; the same hazard for
        // coverage). Fold the raw local prefixes that would have been remapped so
        // the key is path-local, matching the cc `KACHE_CC_PATH_NORMALIZE=0`
        // "keys become path-literal" contract.
        fold_unremapped_path_identity(&mut hasher, args, path_normalizer);
        "none".to_string()
    } else {
        hasher.update(b"remap:multi-prefix\n");
        // Only the remap on/off choice is keyed (above) — it is the
        // binary-affecting bit: coverage builds skip remapping because
        // tarpaulin / llvm-cov need original paths in the profraw. The
        // SPECIFIC sentinel set is deliberately NOT folded into the key.
        // Its membership depends on which machine-local dirs exist relative
        // to the build ($TMPDIR, %PROGRAMFILES%, $CARGO_HOME, …), so it
        // varied across machines and — when the build tree sat INSIDE one of
        // those dirs — across relocations: an out-of-tree build under the
        // system tempdir dropped the <TMPDIR> rule via the prefix de-dupe,
        // diverging the key and missing on relocate (kunobi-ninja/kache#399).
        // The set is also redundant: any path that actually reaches the
        // compile is already keyed through its normalized env-dep / source /
        // link field (rewritten to these same sentinels), and
        // `--remap-path-prefix` only neutralizes rustc-emitted file paths,
        // never `env!` runtime values (those are keyed separately). Rendered
        // here for the diagnostic trace only.
        let remap_args = path_normalizer.remap_args();
        let mut targets: Vec<String> = remap_args
            .iter()
            .filter_map(|a| a.split('=').next_back().map(str::to_string))
            .collect();
        targets.sort();
        targets.dedup();
        format!("multi-prefix({})", targets.join(","))
    };
    tracing::trace!("[key:{}] remap={}", crate_name, remap);

    let (hash, fields) = hasher.finalize_with_fields();
    let _ = LAST_KEY_FIELDS.try_with(|stash| *stash.borrow_mut() = Some(fields));
    let key = hash.to_hex().to_string();
    tracing::trace!("[key:{}] final={}", crate_name, &key[..16]);
    Ok(key)
}

/// Fold the raw, un-normalized machine-local path prefixes into the key so any
/// unremapped (`remap:none`) build's key is path-local — both the
/// `KACHE_RUSTC_PATH_NORMALIZE=0` opt-out and coverage builds.
///
/// With remapping disabled rustc bakes real paths into DWARF (`comp_dir` = the
/// working directory; `decl_file`s under the workspace / `$CARGO_TARGET_DIR` /
/// `$CARGO_HOME` / `$RUSTUP_HOME` / `$HOME` / the tempdir / a build-script
/// `OUT_DIR`). Without this fold the rest of `compute_cache_key` normalizes
/// those path inputs to sentinels and hashes source by normalized path/content,
/// `remap:none` key path-independent and letting a shared cache hand one
/// checkout's real-path artifact to another (kunobi-ninja/kache#480 for the
/// opt-out; the same hazard for coverage).
///
/// The discriminator set is the normalizer's OWN [`PathNormalizer::raw_prefixes`]
/// — precisely the prefixes it would have remapped, so the key diverges whenever
/// the baked paths would, and the fold stays complete as normalizer rules evolve
/// (`<TARGET>`, `<BASE_DIR>`, the Windows roots, path-only env vars, …) rather
/// than tracking a hand-maintained env subset. cwd and the crate source path are
/// folded explicitly too: cargo passes a *relative* crate source, so `comp_dir`
/// (the cwd) is the load-bearing per-checkout discriminator, and this keeps the
/// fold meaningful even under a normalizer with no rules (tests / degraded env).
/// A path baked into DWARF that lies OUTSIDE every prefix is not normalized in
/// the key either, so it already reaches the key raw via its dep-info field — no
/// separate handling needed here.
fn fold_unremapped_path_identity<H: KeyFold>(
    hasher: &mut H,
    args: &RustcArgs,
    path_normalizer: &PathNormalizer,
) {
    hasher.update(b"unremapped_path_identity:v1\n");

    if let Ok(cwd) = std::env::current_dir() {
        fold_field(
            hasher,
            b"unremapped:cwd:",
            cwd.as_os_str().as_encoded_bytes(),
        );
    }
    if let Some(source) = &args.source_file {
        fold_field(
            hasher,
            b"unremapped:source:",
            source.as_os_str().as_encoded_bytes(),
        );
    }
    // Sort so the fold is order-stable regardless of rule-construction order.
    let mut prefixes: Vec<&str> = path_normalizer.raw_prefixes().collect();
    prefixes.sort_unstable();
    prefixes.dedup();
    for prefix in prefixes {
        fold_field(hasher, b"unremapped:prefix:", prefix.as_bytes());
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EnvDepNormalizationDecision {
    Unchanged,
    NormalizedPathOnly,
    KeptAbsoluteRuntimePath,
    /// Normalized because the var (optionally crate-scoped) is in the
    /// user-asserted force list, bypassing the source scans.
    ForcedPathOnly,
}

impl EnvDepNormalizationDecision {
    fn as_str(self) -> &'static str {
        match self {
            Self::Unchanged => "unchanged",
            Self::NormalizedPathOnly => "normalized path-only",
            Self::KeptAbsoluteRuntimePath => "kept absolute runtime path",
            Self::ForcedPathOnly => "forced path-only (user-asserted)",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct NormalizedEnvDep {
    value: String,
    decision: EnvDepNormalizationDecision,
}

/// Lexically collapse `.` / `..` components and unify path separators, without
/// touching the filesystem. Splits on BOTH `/` and `\` so it handles
/// Windows-style paths on any host, preserves a leading root / drive / UNC
/// anchor that `..` cannot escape, and rejoins with the platform separator so
/// the result lines up with the host-canonical rule prefixes the cache key
/// matches against.
///
/// Why: Windows cargo joins a relative `CARGO_TARGET_DIR` (`../oot-target`) onto
/// the package dir literally, so `OUT_DIR` arrives as
/// `C:\proj\pkg\..\oot-target\...` with mixed separators and an unresolved
/// `..`. The workspace-root prefix then only matches up to `C:\proj\pkg`,
/// leaving a `\..`-bearing residual that differs by build location and breaks
/// out-of-tree cross-location convergence (kunobi-ninja/kache#399). Resolving
/// the `..` first yields `C:\proj\oot-target\...`, which normalizes
/// consistently. On Linux cargo already resolves the target dir, so this is a
/// no-op there.
fn lexically_resolve_path(input: &str) -> String {
    let is_sep = |c: char| c == '/' || c == '\\';
    let sep = std::path::MAIN_SEPARATOR;
    let chars: Vec<char> = input.chars().collect();
    let n = chars.len();

    // Split off the un-poppable anchor (root / drive / UNC) and the index where
    // the resolvable component list starts.
    let (anchor, start) = if n >= 2 && is_sep(chars[0]) && is_sep(chars[1]) {
        // UNC: \\server\share — keep `\\` plus the next two components as root.
        let mut root = String::from(r"\\");
        let mut i = 2;
        let mut taken = 0;
        while i < n && taken < 2 {
            while i < n && is_sep(chars[i]) {
                i += 1;
            }
            let comp_start = i;
            while i < n && !is_sep(chars[i]) {
                i += 1;
            }
            if comp_start == i {
                break;
            }
            if taken == 1 {
                root.push(sep);
            }
            root.extend(&chars[comp_start..i]);
            taken += 1;
        }
        root.push(sep);
        (root, i)
    } else if n >= 2 && chars[1] == ':' && chars[0].is_ascii_alphabetic() {
        // Windows drive: `C:` optionally followed by a separator (absolute).
        let mut root: String = chars[..2].iter().collect();
        let mut i = 2;
        if i < n && is_sep(chars[i]) {
            root.push(sep);
            i += 1;
        }
        (root, i)
    } else if n >= 1 && is_sep(chars[0]) {
        (String::from(sep), 1) // Unix absolute
    } else {
        (String::new(), 0) // relative
    };

    let absolute = anchor.ends_with(sep);
    let tail: String = chars[start..].iter().collect();
    let mut stack: Vec<&str> = Vec::new();
    for comp in tail.split(is_sep).filter(|c| !c.is_empty()) {
        match comp {
            "." => {}
            ".." => match stack.last() {
                Some(&top) if top != ".." => {
                    stack.pop();
                }
                _ if absolute => {} // cannot escape the root
                _ => stack.push(".."),
            },
            other => stack.push(other),
        }
    }

    let joined = stack.join(&sep.to_string());
    match (anchor.is_empty(), joined.is_empty()) {
        (true, true) => ".".to_string(),
        (true, false) => joined,
        (false, true) => anchor,
        (false, false) => format!("{anchor}{joined}"),
    }
}

/// Resolve a `-l` spec to a plain `static=` archive in one of the build-script
/// search dirs and return `(path, content_hash)`, or `None` when it is not a
/// clean `static=NAME` or no candidate is found. Ambiguous/read/identity
/// failures return an error so the invocation passes through uncached.
/// Used to fold a native static lib's content into the cache key so an in-place
/// rebuild of `lib<name>.a` (same name, same path, changed bytes) no longer
/// produces a stale hit (#421). Phase 1 is intentionally narrow — see the `-l`
/// loop in [`compute_cache_key`].
fn resolve_native_static_lib(
    spec: &str,
    search_dirs: &[PathBuf],
    file_hasher: &FileHasher<'_>,
    usage: StaticLibUse,
) -> Result<Option<(PathBuf, String)>> {
    let Some(name) = clean_static_lib_name(spec) else {
        return Ok(None);
    };
    // Probe the common platform conventions by existence (host-agnostic; the
    // file only exists where the build produced it). Build scripts can emit the
    // same search directory more than once (for example, one `cc::Build::compile`
    // call per archive), so repeated sightings of the same candidate are not
    // ambiguous. If more than one distinct candidate matches — `lib<name>.a`
    // and `<name>.lib`, or hits in two dirs — the choice is target-specific, so
    // fail the cache key rather than risk hashing the wrong file.
    let mut found: Option<PathBuf> = None;
    for dir in search_dirs {
        for filename in [format!("lib{name}.a"), format!("{name}.lib")] {
            let candidate = dir.join(&filename);
            if candidate.is_file() {
                if found.as_ref().is_some_and(|path| path == &candidate) {
                    continue;
                }
                if found.is_some() {
                    anyhow::bail!("ambiguous native static library {name:?}");
                }
                found = Some(candidate);
            }
        }
    }
    let Some(path) = found else {
        return Ok(None);
    };
    // Every parse/read failure is uncacheable, never name-only: this archive is
    // bundled into the output, so omitting an existing file would be a false hit.
    let hash = file_hasher.hash_static_lib_for(&path, usage)?;
    Ok(Some((path, hash)))
}

/// How an invocation uses a `static=` archive. It decides whether an archive
/// with DWARF-bearing Mach-O members may share its structural digest across
/// checkouts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaticLibUse {
    /// The invocation does not link the archive: rustc bundles it into its
    /// rlib (or staticlib) output. A later cached debug link names rlib
    /// members `<rlib>(member)` under `--out-dir`, which the `-oso_prefix`
    /// kache injects there makes relative.
    Bundled,
    /// The invocation links the archive itself (bin, test, dylib, cdylib,
    /// proc-macro). ld64 writes the archive's absolute path into the `N_OSO`
    /// entry of every DWARF-bearing member.
    Linked,
}

impl StaticLibUse {
    /// Memo namespace. The two uses can hash one file differently, so they
    /// never share a row.
    fn memo_namespace(self) -> &'static str {
        match self {
            Self::Bundled => "static-ar-v6-bundled",
            Self::Linked => "static-ar-v6",
        }
    }
}

fn static_lib_use(args: &RustcArgs) -> StaticLibUse {
    if args.is_executable_output() {
        StaticLibUse::Linked
    } else {
        StaticLibUse::Bundled
    }
}

/// Auxiliary linker files are not yet captured/restored as cache artifacts.
/// Refuse the native-static-lib invocation rather than guess at their content.
fn native_linker_side_files_are_unmodeled(args: &RustcArgs) -> bool {
    let apple_target = match args.target.as_deref() {
        Some(target) => is_builtin_apple_target(target),
        None => cfg!(target_vendor = "apple"),
    };
    args.codegen_opts.iter().any(|(key, value)| {
        matches!(key.as_str(), "link-arg" | "link-args")
            && value
                .as_deref()
                .is_some_and(|value| linker_value_has_unmodeled_file(value, apple_target))
    })
}

fn is_builtin_apple_target(target: &str) -> bool {
    // Rust 1.95's built-in Apple targets. Unknown names can resolve arbitrary
    // JSON through RUST_TARGET_PATH, so additions must fail closed until
    // reviewed rather than inheriting ld64 token semantics from their spelling.
    matches!(
        target,
        "aarch64-apple-darwin"
            | "aarch64-apple-ios"
            | "aarch64-apple-ios-macabi"
            | "aarch64-apple-ios-sim"
            | "aarch64-apple-tvos"
            | "aarch64-apple-tvos-sim"
            | "aarch64-apple-visionos"
            | "aarch64-apple-visionos-sim"
            | "aarch64-apple-watchos"
            | "aarch64-apple-watchos-sim"
            | "arm64_32-apple-watchos"
            | "arm64e-apple-darwin"
            | "arm64e-apple-ios"
            | "arm64e-apple-tvos"
            | "armv7k-apple-watchos"
            | "armv7s-apple-ios"
            | "i386-apple-ios"
            | "i686-apple-darwin"
            | "x86_64-apple-darwin"
            | "x86_64-apple-ios"
            | "x86_64-apple-ios-macabi"
            | "x86_64-apple-tvos"
            | "x86_64-apple-watchos-sim"
            | "x86_64h-apple-darwin"
    )
}

fn linker_value_has_unmodeled_file(value: &str, apple_target: bool) -> bool {
    value.split([',', '=', ' ', '\t', '\n', '\r']).any(|token| {
        matches!(
            token,
            "-map"
                | "-Map"
                | "--Map"
                | "-order_file"
                | "-sectorder"
                | "--symbol-ordering-file"
                | "--call-graph-ordering-file"
                | "--section-ordering-file"
        ) || token.eq_ignore_ascii_case("/map")
            || ascii_prefix_eq_ignore_case(token, "/map:")
            || ascii_prefix_eq_ignore_case(token, "/mapinfo:")
            || ascii_prefix_eq_ignore_case(token, "/order:")
            || ascii_prefix_eq_ignore_case(token, "/call-graph-ordering-file:")
            || (token.starts_with('@')
                && !(apple_target
                    && (token == "@loader_path"
                        || token.starts_with("@loader_path/")
                        || token == "@rpath"
                        || token.starts_with("@rpath/")
                        || token == "@executable_path"
                        || token.starts_with("@executable_path/"))))
    })
}

fn ascii_prefix_eq_ignore_case(value: &str, prefix: &str) -> bool {
    value
        .get(..prefix.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
}

/// `Some(name)` only for a plain `static=NAME` with no kind modifiers and no
/// `:RENAME`. Anything fancier is returned as `None` so the caller falls back to
/// name-only rather than mis-resolve or over-key:
/// - `static:+verbatim=` / `static:-bundle=` etc. — modifiers change whether the
///   archive is bundled into the output and how the name maps to a file;
/// - `static=foo:bar` — a `:RENAME` form whose linked file is not simply `foo`;
/// - `dylib=` / bare `-l name` — referenced, not bundled, so content must not
///   key the consumer.
fn clean_static_lib_name(spec: &str) -> Option<&str> {
    let (kind, name) = spec.split_once('=')?;
    // Exactly `static`: a modifier suffix (`static:+bundle`) makes `kind != "static"`.
    if kind != "static" {
        return None;
    }
    if name.is_empty() || name.contains(':') {
        return None;
    }
    Some(name)
}

/// The normalized key value for a path-only env dep: the `<OUT_DIR:unit>`
/// sentinel form when the value lives under the build's own OUT_DIR
/// (kunobi-ninja/kache#330 — the unit-hash component stays observable), else
/// the generic prefix-rule normalization.
fn sentinelized_env_dep_value(resolved: &str, normalized: &str) -> String {
    if let Some(rel) = out_dir_relative_suffix(resolved) {
        let unit = std::env::var_os("OUT_DIR")
            .map(std::path::PathBuf::from)
            .as_deref()
            .and_then(|p| p.parent().and_then(|d| d.file_name().map(|n| n.to_owned())))
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        if rel.is_empty() {
            format!("<OUT_DIR:{unit}>")
        } else {
            format!("<OUT_DIR:{unit}>/{}", rel.trim_start_matches('/'))
        }
    } else {
        normalized.to_string()
    }
}

fn normalize_env_dep_value_with_hasher(
    crate_name: &str,
    var: &str,
    val: &str,
    source_files: &[std::path::PathBuf],
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
) -> NormalizedEnvDep {
    // Resolve the value to the SAME canonical form the rule prefixes use
    // (kunobi-ninja/kache#399). Windows cargo joins a relative CARGO_TARGET_DIR
    // literally, so an out-of-tree `OUT_DIR` arrives as `...\pkg\..\oot-target\...`
    // with mixed separators and an unresolved `..`. The PathNormalizer rules are
    // `canonicalize()`d (symlinks + `..` resolved, `\\?\` stripped, OS-native
    // separators, NFC), and `normalize` is a byte-literal substring replace — so
    // the raw value matches no rule and the build location stays in the key,
    // missing on relocate. Running the value through the rules' own
    // `canonical_string` puts it in matchable shape (an out-of-tree OUT_DIR
    // under the workspace / `$CARGO_TARGET_DIR` collapses to its
    // `<WORKSPACE>`/`<TARGET>` sentinel, converging across build locations). The
    // dir exists at key time (the build script already
    // wrote into it). Fall back to a lexical `.`/`..` collapse when the path is
    // absent. A no-op on Linux/macOS with a relative target dir, which cargo
    // canonicalizes before invoking rustc.
    let resolved = crate::path_normalizer::canonical_string(std::path::Path::new(val))
        .unwrap_or_else(|| lexically_resolve_path(val));
    let normalized = path_normalizer.normalize(&resolved);

    // Unchanged: resolution was a no-op AND no rule prefix matched. The value is
    // not a path kache models, so it enters the key verbatim.
    if resolved == val && normalized == val {
        return NormalizedEnvDep {
            value: val.to_string(),
            decision: EnvDepNormalizationDecision::Unchanged,
        };
    }

    // A `crate_name:VAR` entry in the path-only allowlist is the user-asserted
    // FORCE form: it bypasses the include-proof and runtime-value scans for
    // exactly that (crate, var) pair. Plain entries keep the scan-gated
    // semantics below. rustc crate-name form (underscores).
    // CARGO_MANIFEST_DIR is never forceable: rustc can embed it in crate
    // metadata and generated code, so erasing it from the key can restore an
    // rlib containing another checkout's path (#167).
    let forced = var != "CARGO_MANIFEST_DIR"
        && path_normalizer.path_only_env_vars().iter().any(|entry| {
            matches!(entry.split_once(':'), Some((krate, v)) if krate == crate_name && v == var)
        });
    if forced {
        return NormalizedEnvDep {
            value: sentinelized_env_dep_value(&resolved, &normalized),
            decision: EnvDepNormalizationDecision::ForcedPathOnly,
        };
    }

    if env_dep_is_safe_to_normalize(
        var,
        &resolved,
        source_files,
        path_normalizer.path_only_env_vars(),
        file_hasher,
    ) {
        // A value under the build's own OUT_DIR normalizes relative to
        // OUT_DIR itself (kunobi-ninja/kache#330): the generic prefix rules
        // keep per-LOCATION path components inside the sentinel'd value
        // (see `out_dir_relative_suffix`), diverging keys across build
        // locations, while the include'd CONTENT the locator points at is
        // already content-hashed through the source list. Cargo's per-unit
        // directory (`<pkg>-<unit hash>`) stays IN the sentinel: a
        // generated file can observe its own path (`file!()`, panic
        // locations), and rustc's remap keeps the unit component in that
        // observable value, so two units whose OUT_DIRs differ only by
        // unit hash are not interchangeable (cross-model review finding).
        return NormalizedEnvDep {
            value: sentinelized_env_dep_value(&resolved, &normalized),
            decision: EnvDepNormalizationDecision::NormalizedPathOnly,
        };
    }

    // Keep-absolute branch: by design the raw path stays in the key
    // because the compiled artifact may embed it via `env!`. Do not
    // warn here: this is an intentional key discriminator, and Cargo
    // fingerprints RUSTC_WRAPPER stderr for build freshness.
    NormalizedEnvDep {
        value: val.to_string(),
        decision: EnvDepNormalizationDecision::KeptAbsoluteRuntimePath,
    }
}

#[cfg(test)]
fn normalize_env_dep_value(
    crate_name: &str,
    var: &str,
    val: &str,
    source_files: &[std::path::PathBuf],
    path_normalizer: &PathNormalizer,
) -> NormalizedEnvDep {
    normalize_env_dep_value_with_hasher(
        crate_name,
        var,
        val,
        source_files,
        &FileHasher::new(),
        path_normalizer,
    )
}

/// Whether `var`'s value may be path-normalized in the cache key. `allowlist`
/// is the user-configured opt-in set (`KACHE_PATH_ONLY_ENV_VARS` /
/// `[cache] path_only_env_vars`); OUT_DIR is always included.
fn env_dep_is_safe_to_normalize(
    var: &str,
    val: &str,
    source_files: &[std::path::PathBuf],
    allowlist: &[String],
    file_hasher: &FileHasher<'_>,
) -> bool {
    // OUT_DIR is the built-in path-only exception:
    //
    //   include!(concat!(env!("OUT_DIR"), "/foo"))
    //
    // splices file content into the AST and dep-info lists the generated
    // file under OUT_DIR. That dep-info shape is necessary but not sufficient:
    // a crate can also use `env!("OUT_DIR")` as a runtime value. Normalize only
    // when source inspection proves the env macro use is inside `include*!(...)`
    // path-locator contexts. Other vars with the same property — e.g. a
    // generated build-config path, or an objdir base used by an `include!`
    // macro — can be opted into `allowlist` by the build.
    //
    // It must stay an explicit allowlist: for CARGO_MANIFEST_DIR and arbitrary
    // user vars the path-only test alone is not valid (normal crate sources
    // already live under the manifest dir, so normalizing it would recreate
    // #167). The `path_is_only_used_for_includes` gate is then applied on top,
    // so an allowlisted var is still kept absolute when it is baked as a value
    // rather than used to locate a source file.
    //
    // Third built-in case (kunobi-ninja/kache#431): a build script can set
    // `cargo:rustc-env=VAR=<absolute path under OUT_DIR>` and the crate then does
    // `include!(env!("VAR"))` — e.g. typenum's TYPENUM_BUILD_CONSTS points at
    // `$OUT_DIR/consts.rs`. Such a var is functionally identical to OUT_DIR: its
    // value is build-generated, ephemeral, and only locates a generated include,
    // so it is exactly as safe to normalize. Keeping it absolute makes the crate
    // (typenum, a foundational substrate/crypto dep) re-key per checkout path,
    // missing cross-clone. We gate it on the value living UNDER the build's
    // OUT_DIR — the precise property that makes OUT_DIR safe and that
    // CARGO_MANIFEST_DIR (the #167 hazard) does NOT have — so it widens
    // eligibility without re-opening #167. The same include-only proof below
    // still applies, so a VAR pointing under OUT_DIR but baked as a runtime
    // value is still kept absolute.
    (var == "OUT_DIR" || allowlist.iter().any(|v| v == var) || value_is_under_out_dir(val))
        && path_is_only_used_for_includes(val, source_files)
        && !env_dep_has_runtime_value_use(var, source_files, file_hasher)
}

/// True when `val` is an absolute path located under the current build's
/// `OUT_DIR`. A build-script `cargo:rustc-env` var whose value points here
/// (typenum's `TYPENUM_BUILD_CONSTS` → `$OUT_DIR/consts.rs`) is build-generated
/// and ephemeral, so it shares OUT_DIR's safety for key path-normalization
/// (kunobi-ninja/kache#431).
///
/// Canonical comparison so the macOS `/tmp` ↔ `/private/tmp` symlink doesn't
/// spuriously miss; falls back to the raw paths when either side can't be
/// canonicalized. Returns false when `OUT_DIR` is unset (the crate has no build
/// script, so no such var exists) or the value is not under it — in particular
/// `CARGO_MANIFEST_DIR`, which lives above OUT_DIR, never qualifies here.
fn value_is_under_out_dir(val: &str) -> bool {
    out_dir_relative_suffix(val).is_some()
}

/// The value's path relative to the build's own `OUT_DIR`, when it lives
/// under it (`Some("")` for `OUT_DIR` itself). This is the anchor for the
/// `<OUT_DIR>` sentinel (kunobi-ninja/kache#330): an OUT_DIR-locator value
/// must normalize relative to OUT_DIR, not through the generic prefix rules
/// — an out-of-workspace `CARGO_TARGET_DIR` makes the derived workspace
/// root the target dir's PARENT, so the generic `<WORKSPACE>` rule matches
/// first and keeps the per-location target-dir component inside the
/// sentinel'd value, diverging the key across build locations. Anchoring on
/// OUT_DIR itself also drops cargo's per-unit hash from the value, which
/// the generic rules preserve.
fn out_dir_relative_suffix(val: &str) -> Option<String> {
    let out_dir = std::env::var_os("OUT_DIR")?;
    let out_dir = Path::new(&out_dir);
    let out_canonical = std::fs::canonicalize(out_dir).ok();
    let out_probe = out_canonical.as_deref().unwrap_or(out_dir);
    // An empty/relative OUT_DIR can't anchor a meaningful "under" test.
    if !out_probe.is_absolute() {
        return None;
    }
    let val_path = Path::new(val);
    let val_canonical = std::fs::canonicalize(val_path).ok();
    let val_probe = val_canonical.as_deref().unwrap_or(val_path);
    val_probe
        .strip_prefix(out_probe)
        .ok()
        .map(|rel| rel.to_string_lossy().replace('\\', "/"))
}

/// Decide whether dep-info shows the env_dep value acting as the parent dir
/// of one or more `include!()`'d source files. This is only the path-shape
/// half of the proof; [`env_dep_has_runtime_value_use`] rejects dual-pattern
/// crates that also bake the env value into the compiled artifact.
///
/// Background and contract: see the OUT_DIR comment in
/// [`compute_cache_key`] and issue kunobi-ninja/kache#75.
///
/// Compares canonical paths so the macOS `/tmp` ↔ `/private/tmp`
/// symlink case doesn't produce a spurious false. If either side
/// can't be canonicalized (file moved, etc.), falls back to the
/// raw path components — `Path::starts_with` handles partial
/// component prefixes correctly without requiring lexical matching.
fn path_is_only_used_for_includes(
    out_dir_value: &str,
    source_files: &[std::path::PathBuf],
) -> bool {
    let raw = Path::new(out_dir_value);
    let canonical = std::fs::canonicalize(raw).ok();
    let probe = canonical.as_deref().unwrap_or(raw);
    source_files.iter().any(|f| {
        let f_canonical = std::fs::canonicalize(f).ok();
        let f_probe = f_canonical.as_deref().unwrap_or(f.as_path());
        f_probe.starts_with(probe)
    })
}

/// True when source text shows `env!(var)` / `option_env!(var)` outside an
/// `include*!(...)` path-locator context. Missing files fail closed: if we
/// cannot prove the env dep is path-only, keep the absolute value in the key.
fn env_dep_has_runtime_value_use(
    var: &str,
    source_files: &[std::path::PathBuf],
    file_hasher: &FileHasher<'_>,
) -> bool {
    for file in source_files {
        match file_hasher.runtime_env_use(file, var) {
            Ok(false) => {}
            Ok(true) => return true,
            Err(e) => {
                tracing::debug!(
                    "keeping env dep {var} absolute: failed to inspect source {}: {}",
                    file.display(),
                    e
                );
                return true;
            }
        }
    }
    false
}

fn source_has_runtime_env_dep_use(source: &str, var: &str) -> bool {
    let bytes = source.as_bytes();
    let mut i = 0usize;
    let mut macro_stack: Vec<String> = Vec::new();

    while i < bytes.len() {
        match bytes[i] {
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                i += 2;
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i += 2;
                while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                    i += 1;
                }
                i = (i + 2).min(bytes.len());
            }
            b'"' => i = skip_quoted_string(bytes, i + 1),
            b'\'' => i = skip_char_literal(bytes, i + 1),
            b'r' | b'b' if raw_string_starts_at(bytes, i).is_some() => {
                i = skip_raw_string(bytes, i);
            }
            b')' => {
                let _ = macro_stack.pop();
                i += 1;
            }
            b if is_ident_start(b) => {
                let ident_start = i;
                i += 1;
                while i < bytes.len() && is_ident_continue(bytes[i]) {
                    i += 1;
                }
                let ident = &source[ident_start..i];

                if matches!(ident, "env" | "option_env")
                    && let Some((env_var, next)) = parse_env_macro_string(source, i)
                    && env_var == var
                {
                    if !macro_stack.iter().any(|name| is_include_macro(name)) {
                        return true;
                    }
                    i = next;
                    continue;
                }

                if let Some(next) = parse_macro_open(source, i) {
                    macro_stack.push(ident.to_string());
                    i = next;
                }
            }
            _ => i += 1,
        }
    }

    false
}

fn is_include_macro(name: &str) -> bool {
    matches!(name, "include" | "include_str" | "include_bytes")
}

fn parse_env_macro_string(source: &str, after_ident: usize) -> Option<(&str, usize)> {
    let bytes = source.as_bytes();
    let mut i = skip_ascii_ws(bytes, after_ident);
    if bytes.get(i) != Some(&b'!') {
        return None;
    }
    i = skip_ascii_ws(bytes, i + 1);
    if bytes.get(i) != Some(&b'(') {
        return None;
    }
    i = skip_ascii_ws(bytes, i + 1);
    if bytes.get(i) != Some(&b'"') {
        return None;
    }
    let value_start = i + 1;
    i = value_start;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'"' => return Some((&source[value_start..i], i + 1)),
            _ => i += 1,
        }
    }
    None
}

fn parse_macro_open(source: &str, after_ident: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let mut i = skip_ascii_ws(bytes, after_ident);
    if bytes.get(i) != Some(&b'!') {
        return None;
    }
    i = skip_ascii_ws(bytes, i + 1);
    if bytes.get(i) == Some(&b'(') {
        Some(i + 1)
    } else {
        None
    }
}

fn skip_ascii_ws(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

fn skip_quoted_string(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'"' => return i + 1,
            _ => i += 1,
        }
    }
    bytes.len()
}

fn skip_char_literal(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'\'' => return i + 1,
            _ => i += 1,
        }
    }
    bytes.len()
}

fn raw_string_starts_at(bytes: &[u8], i: usize) -> Option<usize> {
    let mut cursor = i;
    if bytes.get(cursor) == Some(&b'b') {
        cursor += 1;
    }
    if bytes.get(cursor) != Some(&b'r') {
        return None;
    }
    cursor += 1;
    while bytes.get(cursor) == Some(&b'#') {
        cursor += 1;
    }
    if bytes.get(cursor) == Some(&b'"') {
        Some(cursor)
    } else {
        None
    }
}

fn skip_raw_string(bytes: &[u8], i: usize) -> usize {
    let Some(open_quote) = raw_string_starts_at(bytes, i) else {
        return i + 1;
    };
    let hashes = open_quote - i - usize::from(bytes[i] == b'b') - 1;
    let mut cursor = open_quote + 1;
    while cursor < bytes.len() {
        if bytes[cursor] == b'"'
            && cursor + hashes < bytes.len()
            && bytes[cursor + 1..cursor + 1 + hashes]
                .iter()
                .all(|b| *b == b'#')
        {
            return cursor + hashes + 1;
        }
        cursor += 1;
    }
    bytes.len()
}

fn is_ident_start(byte: u8) -> bool {
    byte == b'_' || byte.is_ascii_alphabetic()
}

fn is_ident_continue(byte: u8) -> bool {
    is_ident_start(byte) || byte.is_ascii_digit()
}

// `normalize_flags` (CWD-only literal-replace) used to live here.
// Replaced by `PathNormalizer` (canonical-prefix sentinel
// substitution). The ad-hoc helper had two failure modes — see
// the `path_normalizer` module docs for the full story.

/// Compute a linked `static=` archive's cache-key digest. A proven GNU/BSD
/// archive gets the structural member-identity hash, unless the invocation
/// links an archive with DWARF-bearing Mach-O members itself. Every other
/// non-thin archive gets a digest of both its bytes and lexical absolute path
/// because linkers can expose `archive-path(member)`. Thin archives are
/// uncacheable: rustc reads external members whose bytes are absent from the
/// container.
fn compute_static_lib_hash(path: &Path, usage: StaticLibUse) -> Result<String> {
    let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;
    if bytes.starts_with(b"!<thin>\n") {
        anyhow::bail!(
            "thin static archive {} has external members that are not modeled",
            path.display()
        );
    }
    if let Some(identity) = crate::native_archive::portable_static_archive_identity(&bytes)
        && !(usage == StaticLibUse::Linked && identity.macho_dwarf_members)
    {
        return Ok(identity.digest);
    }

    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
    let encoded_path = absolute.as_os_str().as_encoded_bytes();
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache.native-ar.path-bound-fallback.v1\0");
    hasher.update(&(encoded_path.len() as u64).to_le_bytes());
    hasher.update(encoded_path);
    hasher.update(&(bytes.len() as u64).to_le_bytes());
    hasher.update(&bytes);
    Ok(format!("path-ar-v1:{}", hasher.finalize().to_hex()))
}

/// Result of a dep-info pre-pass. Contains all information discovered by
/// running `rustc --emit=dep-info`.
///
/// This is a struct (not a tuple) so we can add fields later without
/// breaking call sites. Future candidates: `target_json_hash`, timing metrics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DepInfo {
    /// All source files the crate depends on (sorted, absolute paths).
    /// Includes the crate root, module files, `include!()` targets, etc.
    pub source_files: Vec<std::path::PathBuf>,
    /// Environment variables tracked by rustc (`env!()` / `option_env!()`).
    /// Values are RAW — `compute_cache_key` decides whether to
    /// path-normalize each one based on per-var safety (see
    /// `env_dep_is_safe_to_normalize`). Storing raw values keeps that
    /// decision available to the consumer; pre-normalizing here
    /// would erase the absolute-path information the discriminator
    /// needs to read.
    pub env_deps: Vec<(String, String)>,
}

/// Version of the prediction record's own logic and encoding.
///
/// Folded into the identity AND stored in the row, so changing how a closure
/// is recorded or validated orphans the old rows without touching
/// [`CACHE_KEY_VERSION`] and therefore without invalidating a single cache
/// entry. Precedent: `STATE_SCHEMA` / `POLICY_VERSION` in
/// `incremental_policy.rs`.
pub(crate) const PREDICTION_SCHEMA: u32 = 1;

/// The input closure a previous build of one unit discovered, remembered so a
/// later build of the same unit can skip re-discovering it.
///
/// This is a *prediction*, never an authority. It records what the dep-info
/// pre-pass found, and every field has to be re-validated against the current
/// tree before a key may be derived from it. Recording is all this commit
/// does; nothing reads a record back yet.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct InputPrediction {
    /// The [`PREDICTION_SCHEMA`] that wrote the row. A reader that does not
    /// recognise it must treat the record as absent.
    pub(crate) schema: u32,
    /// Exactly the spellings [`DepInfo::source_files`] carried, so a
    /// prediction reproduces the key's `sources` group byte for byte.
    pub(crate) sources: Vec<PathBuf>,
    /// `# env-dep:` pairs as raw values. The key normalises some of them
    /// (OUT_DIR-like values collapse to a sentinel), so the raw value is the
    /// only signal that an included file moved.
    pub(crate) env_deps: Vec<(String, String)>,
    /// Digest of the crate's own tree ([`crate_tree_digest`]) when the unit
    /// depends on a proc macro. Such a macro can read any file under the crate
    /// without it entering the closure, so the closure alone cannot say
    /// whether the record still applies; the tree can. Absent on records made
    /// for units that need no such guard, and on rows written before it
    /// existed, which the guard then treats as unusable.
    #[serde(default)]
    pub(crate) tree: Option<String>,
}

impl InputPrediction {
    fn from_dep_info(dep_info: &DepInfo, tree: Option<String>) -> Self {
        Self {
            schema: PREDICTION_SCHEMA,
            sources: dep_info.source_files.clone(),
            env_deps: dep_info.env_deps.clone(),
            tree,
        }
    }
}

/// Why a recorded closure could not be used for this invocation.
///
/// Every variant means the same thing operationally — run the pre-pass — but
/// they are distinguished so the trace says which rule fired, and so the
/// tests can name the case they are pinning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Rejection {
    /// Predictions are off, or there is no table to read one from. Also the
    /// deliberate case: the re-derivation after a predicted key misses turns
    /// them off so it discovers the closure for real.
    Disabled,
    /// The invocation is not the shape a prediction is sound for.
    NotEligible,
    /// No record, or one this build cannot read.
    NoRecord,
    /// A recorded file is gone. The pre-pass will fail too and the build will
    /// pass through to rustc's own error, which is today's behaviour.
    Missing,
    /// A recorded path is no longer a regular file.
    NotRegular,
    /// A recorded `# env-dep:` value is not what it was.
    EnvChanged,
    /// `mod foo;` now resolves ambiguously: both `foo.rs` and `foo/mod.rs`
    /// exist. rustc rejects that (E0761), and replaying a recorded success
    /// would restore an artifact for a build that should fail.
    Sibling,
    /// The unit depends on a proc macro and the crate tree is not the one the
    /// record was made against, so a file the macro reads may have changed.
    TreeChanged,
}

impl Rejection {
    fn as_str(self) -> &'static str {
        match self {
            Rejection::Disabled => "disabled",
            Rejection::NotEligible => "not-eligible",
            Rejection::NoRecord => "no-record",
            Rejection::Missing => "missing",
            Rejection::NotRegular => "not-regular",
            Rejection::EnvChanged => "env-changed",
            Rejection::Sibling => "sibling",
            Rejection::TreeChanged => "tree-changed",
        }
    }
}

/// Is this invocation the shape a prediction is sound for?
///
/// A proc macro can scan the filesystem and emit `include_str!` per entry, so
/// a file can enter the closure with nothing already in the closure changing.
/// The pre-pass sees the new file; a prediction would not, and would derive
/// the stored key: a false hit. Cargo does not make this assumption either —
/// it recompiles when a build script's `rerun-if-changed` directory fires
/// even if the bytes are identical.
///
/// The test is how cargo hands rustc a proc macro: as a dynamic library.
/// `dylib` crate-type dependencies get swept in too, which is
/// over-conservative and safe. This was the scoping rule of the closed
/// kunobi-ninja/kache#334, where it left 84% of units eligible.
pub(crate) fn prediction_applies(externs: &[crate::args::ExternDep]) -> bool {
    !externs.iter().any(|ext| {
        ext.path.as_deref().is_some_and(|path| {
            path.file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| {
                    matches!(
                        crate::compiler::classify_by_filename(name),
                        crate::compiler::ArtifactKind::DynamicLibrary
                    )
                })
        })
    })
}

/// The other spelling of the same module, if this file is one half of a
/// `mod foo;` pair.
///
/// `src/foo.rs` and `src/foo/mod.rs` both answer `mod foo;`, and rustc
/// refuses to choose (E0761). A record made when only one existed must not
/// replay success after the other appears.
fn mod_sibling_candidate(file: &Path) -> Option<PathBuf> {
    let stem = file.file_stem()?.to_str()?;
    let parent = file.parent()?;
    if file.extension().and_then(|e| e.to_str()) != Some("rs") {
        return None;
    }
    match stem {
        // `foo/mod.rs`: the other spelling is `foo.rs` beside the directory.
        "mod" => Some(
            parent
                .parent()?
                .join(parent.file_name()?)
                .with_extension("rs"),
        ),
        // A crate root is named by argv, not by a `mod` item, so it has no
        // sibling spelling to be ambiguous with.
        "lib" | "main" => None,
        // `foo.rs`: the other spelling is `foo/mod.rs`.
        stem => Some(parent.join(stem).join("mod.rs")),
    }
}

/// Turn a recorded closure back into a `DepInfo` this invocation may key off,
/// or say why it cannot.
///
/// Everything is re-checked against the tree as it is now. The claim being
/// tested is narrow: *any edit that adds a file to the closure also changes a
/// file already in it*. Where that does not hold, one of the rules above
/// catches it, and where none of them does, the derived key misses and the
/// caller falls back before anything is stored.
pub(crate) fn validate_prediction(
    record: &InputPrediction,
    stat: impl Fn(&Path) -> Option<std::fs::Metadata>,
    exists: impl Fn(&Path) -> bool,
    env_value: impl Fn(&str) -> Option<String>,
) -> std::result::Result<DepInfo, Rejection> {
    for file in &record.sources {
        let Some(metadata) = stat(file) else {
            return Err(Rejection::Missing);
        };
        if !metadata.is_file() {
            return Err(Rejection::NotRegular);
        }
        if mod_sibling_candidate(file).is_some_and(|sibling| exists(&sibling)) {
            return Err(Rejection::Sibling);
        }
    }
    for (var, recorded) in &record.env_deps {
        // Raw values, because the key normalises OUT_DIR-like ones to a
        // sentinel: the raw value is the only signal that an included file
        // moved. A value that is no longer valid UTF-8 reads as changed,
        // which is the safe direction.
        //
        // The parser conflates an unset variable with an empty one (both
        // arrive as `""`), so validation must too: otherwise any crate
        // reading an unset `option_env!` would reject every record and pay
        // a pre-pass on every warm build.
        let matches = match env_value(var) {
            Some(value) => value == *recorded,
            None => recorded.is_empty(),
        };
        if !matches {
            return Err(Rejection::EnvChanged);
        }
    }
    Ok(DepInfo {
        source_files: record.sources.clone(),
        env_deps: record.env_deps.clone(),
    })
}

/// The parts of an invocation that decide which closure it will discover.
///
/// Everything here shapes what rustc reads: the compiler, the argv, the
/// directory paths resolve against, and the environment the key already
/// folds. Two invocations agreeing on all of it discover the same files, so
/// they may share a record. Anything that disagrees gets its own row rather
/// than a wrong answer.
///
/// Deliberately absent: extern *content* hashes. A changed dependency changes
/// the derived key on its own, and re-deriving is what refreshes the record.
/// Present but acknowledged: extern *paths*, which make a row target-dir
/// local. A fresh worktree therefore pays one pre-pass per unit until the
/// identity is path-normalised.
pub(crate) struct PredictionIdentityParts<'a> {
    pub(crate) rustc_version: &'a str,
    pub(crate) inner_rustc: Option<&'a Path>,
    pub(crate) current_dir: Option<&'a Path>,
    pub(crate) source_file: &'a Path,
    pub(crate) closure_args: &'a [String],
    pub(crate) skip_path_remap: bool,
}

/// Environment folded into a prediction identity, by name.
///
/// Named rather than wholesale, because the cc preprocessor memo spent a year
/// never hitting once for exactly this mistake: it folded the whole
/// environment, so `_`, `PWD` and the jobserver fds made every key unique
/// (kunobi-ninja/kache#927). Only variables that change what rustc reads
/// belong here.
const PREDICTION_ENV: &[&str] = &[
    "RUSTFLAGS",
    "CARGO_ENCODED_RUSTFLAGS",
    "RUSTC_BOOTSTRAP",
    "OUT_DIR",
    "CARGO_MANIFEST_DIR",
];

/// Identity of the unit whose closure a record describes.
///
/// Length-prefixed like the cache key's own fields, so no combination of
/// values can be re-read as a different combination.
///
/// Takes the environment rather than reading it, so the folding can be tested
/// against a fixed one. `vars_os` would otherwise be read twice in a test
/// binary whose other tests set and unset variables concurrently.
fn prediction_identity_in_env(
    parts: &PredictionIdentityParts<'_>,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache-input-prediction-v1\n");
    fold_field(
        &mut hasher,
        b"prediction_schema:",
        PREDICTION_SCHEMA.to_string().as_bytes(),
    );
    fold_field(
        &mut hasher,
        b"key_version:",
        CACHE_KEY_VERSION.to_string().as_bytes(),
    );
    fold_field(
        &mut hasher,
        b"rustc_version:",
        parts.rustc_version.as_bytes(),
    );
    fold_field(
        &mut hasher,
        b"inner_rustc:",
        &parts
            .inner_rustc
            .map(|path| env_os_key_bytes(path.as_os_str()))
            .unwrap_or_default(),
    );
    // Relative paths in the argv resolve against the working directory, so two
    // directories are two closures even with identical arguments.
    fold_field(
        &mut hasher,
        b"current_dir:",
        &parts
            .current_dir
            .map(|path| env_os_key_bytes(path.as_os_str()))
            .unwrap_or_default(),
    );
    fold_field(
        &mut hasher,
        b"source_file:",
        &env_os_key_bytes(parts.source_file.as_os_str()),
    );
    fold_field(
        &mut hasher,
        b"closure_args_len:",
        parts.closure_args.len().to_string().as_bytes(),
    );
    for arg in parts.closure_args {
        fold_field(&mut hasher, b"closure_arg:", arg.as_bytes());
    }
    let by_name: std::collections::BTreeMap<Vec<u8>, &std::ffi::OsString> = vars
        .iter()
        .map(|(name, value)| (env_text_key_bytes(name), value))
        .collect();
    for name in PREDICTION_ENV {
        fold_field(&mut hasher, b"env_var:", name.as_bytes());
        match by_name.get(name.as_bytes()) {
            Some(value) => {
                fold_field(&mut hasher, b"env_set:", b"1");
                fold_field(&mut hasher, b"env_val:", &env_os_key_bytes(value));
            }
            // An unset variable is not an empty one: `env!` distinguishes them.
            None => fold_field(&mut hasher, b"env_set:", b"0"),
        }
    }
    for (name, value) in cargo_cfg_pairs(vars.iter().cloned()) {
        fold_field(&mut hasher, b"cargo_cfg_name:", &env_text_key_bytes(&name));
        fold_field(&mut hasher, b"cargo_cfg_val:", &env_os_key_bytes(&value));
    }
    fold_field(
        &mut hasher,
        b"skip_path_remap:",
        if parts.skip_path_remap { b"1" } else { b"0" },
    );
    hasher.finalize().to_hex().to_string()
}

/// Thin abstraction over file hashing.
///
/// When backed by the persistent index DB, hashes are memoized by
/// `(absolute path, mtime, ctime, size)` across wrapper processes. In a workspace
/// with 30 crates that all depend on `serde`, the serde rlib gets hashed once
/// instead of 30 times.
pub struct FileHasher<'db> {
    cache: Option<FileHashCache<'db>>,
    daemon_socket: Option<PathBuf>,
    use_input_predictions: bool,
    prediction_flight_dir: Option<PathBuf>,
    discovery_flight: RefCell<Option<crate::store::StoreLock>>,
    prefetched: RefCell<HashMap<FileFingerprint, PrefetchedHash>>,
    recent_hashes: RefCell<HashMap<PathBuf, RecentHash>>,
    runtime_env_uses: RefCell<HashMap<(String, String), bool>>,
    stats: FileHashStatsCells,
    too_new: TooNewGuard,
    /// Fingerprints of every file hashed while the too-new guard was armed.
    /// Drained after the compile so the wrapper can prove clock-independently
    /// that none of them changed mid-build (see
    /// [`FileHasher::guarded_inputs_unchanged_since_hash`]).
    guard_inputs: RefCell<Vec<FileFingerprint>>,
    /// Memo rows for files hashed in this process, written in one transaction
    /// by [`FileHasher::flush_memo`] (and on drop). One autocommit write per
    /// file made every hit in a six-job cold cell wait for the index's write
    /// lock behind the misses' store transactions: 6 ms of hashing became
    /// 380 ms.
    pending_memo: RefCell<Vec<(FileFingerprint, String)>>,
}

impl Drop for FileHasher<'_> {
    fn drop(&mut self) {
        self.flush_memo();
    }
}

/// Optional "too-new input" guard (kunobi-ninja/kache#324). When armed, any
/// hashed input whose mtime/ctime falls within `margin_ns` of the build's start
/// is flagged: its content at hash time may differ from what the compiler reads,
/// so the wrapper treats the invocation as non-cacheable (it still looks up, but
/// refuses to store). Disabled when `invocation_start_ns == 0` (the default).
#[derive(Default)]
struct TooNewGuard {
    invocation_start_ns: i64,
    margin_ns: i64,
    saw_too_new: Cell<bool>,
}

#[derive(Debug, Default, Clone, Copy)]
pub struct FileHashStats {
    pub cache_hits: u64,
    pub cache_misses: u64,
    pub bytes_hashed: u64,
}

#[derive(Default)]
struct FileHashStatsCells {
    cache_hits: Cell<u64>,
    cache_misses: Cell<u64>,
    bytes_hashed: Cell<u64>,
}

#[derive(Debug, Clone)]
struct PrefetchedHash {
    hash: String,
    cache_hit: bool,
    bytes_hashed: u64,
}

#[derive(Clone)]
struct RecentHash {
    hash: String,
    fingerprint: Option<FileFingerprint>,
}

impl FileHasher<'static> {
    pub fn new() -> Self {
        FileHasher {
            cache: None,
            daemon_socket: None,
            use_input_predictions: false,
            prediction_flight_dir: None,
            discovery_flight: RefCell::new(None),
            prefetched: RefCell::new(HashMap::new()),
            recent_hashes: RefCell::new(HashMap::new()),
            runtime_env_uses: RefCell::new(HashMap::new()),
            stats: FileHashStatsCells::default(),
            too_new: TooNewGuard::default(),
            guard_inputs: RefCell::new(Vec::new()),
            pending_memo: RefCell::new(Vec::new()),
        }
    }

    #[cfg(test)]
    pub fn persistent(index_db_path: &Path) -> Self {
        match FileHashCache::open(index_db_path) {
            Ok(cache) => FileHasher {
                cache: Some(cache),
                daemon_socket: None,
                use_input_predictions: false,
                prediction_flight_dir: None,
                discovery_flight: RefCell::new(None),
                prefetched: RefCell::new(HashMap::new()),
                recent_hashes: RefCell::new(HashMap::new()),
                runtime_env_uses: RefCell::new(HashMap::new()),
                stats: FileHashStatsCells::default(),
                too_new: TooNewGuard::default(),
                guard_inputs: RefCell::new(Vec::new()),
                pending_memo: RefCell::new(Vec::new()),
            },
            Err(e) => {
                tracing::debug!(
                    "file hash cache disabled for {}: {e}",
                    index_db_path.display()
                );
                FileHasher::new()
            }
        }
    }
}

impl<'db> FileHasher<'db> {
    /// Write every memo row hashed so far in one transaction. The rows are an
    /// optimisation, so a busy index (another process holds the write lock
    /// for longer than the short wait here) drops them rather than stalling
    /// a hit; the next process hashes those files again.
    pub fn flush_memo(&self) {
        let pending = std::mem::take(&mut *self.pending_memo.borrow_mut());
        if pending.is_empty() {
            return;
        }
        let _trace = crate::phase_trace::phase("memo_flush");
        let Some(cache) = &self.cache else {
            return;
        };
        let db = cache.db();
        let _ = db.busy_timeout(std::time::Duration::from_millis(100));
        let written = (|| -> rusqlite::Result<()> {
            db.execute_batch("BEGIN IMMEDIATE")?;
            for (fingerprint, hash) in &pending {
                if let Err(error) = cache.put(fingerprint, hash) {
                    let _ = db.execute_batch("ROLLBACK");
                    return Err(error);
                }
            }
            db.execute_batch("COMMIT")
        })();
        let _ = db.busy_timeout(std::time::Duration::from_millis(5000));
        if let Err(error) = written {
            tracing::debug!(
                rows = pending.len(),
                "file hash memo not written (index busy): {error}"
            );
        }
    }

    pub(crate) fn from_cache(cache: FileHashCache<'db>) -> Self {
        FileHasher {
            cache: Some(cache),
            daemon_socket: None,
            use_input_predictions: false,
            prediction_flight_dir: None,
            discovery_flight: RefCell::new(None),
            prefetched: RefCell::new(HashMap::new()),
            recent_hashes: RefCell::new(HashMap::new()),
            runtime_env_uses: RefCell::new(HashMap::new()),
            stats: FileHashStatsCells::default(),
            too_new: TooNewGuard::default(),
            guard_inputs: RefCell::new(Vec::new()),
            pending_memo: RefCell::new(Vec::new()),
        }
    }

    pub(crate) fn with_daemon(mut self, socket_path: PathBuf) -> Self {
        self.daemon_socket = Some(socket_path);
        self
    }

    /// Let key computation derive its input set from a recorded closure
    /// instead of spawning the dep-info pre-pass.
    ///
    /// A property of the hasher because the hasher is what reaches the
    /// prediction table: without an index DB there is nothing to read, and
    /// asking is always allowed to answer "run the pre-pass".
    pub(crate) fn with_input_predictions(mut self, enabled: bool) -> Self {
        self.use_input_predictions = enabled;
        self
    }

    pub(crate) fn with_prediction_flights(mut self, cache_dir: Option<PathBuf>) -> Self {
        self.prediction_flight_dir = cache_dir;
        self
    }

    pub(crate) fn take_discovery_flight(&self) -> Option<crate::store::StoreLock> {
        self.discovery_flight.borrow_mut().take()
    }

    /// May key computation derive its inputs from a record? Only when it was
    /// asked to AND there is a table to read.
    fn uses_input_predictions(&self) -> bool {
        self.use_input_predictions && self.cache.is_some()
    }

    /// Arm the too-new-input guard (kunobi-ninja/kache#324): flag any subsequently
    /// hashed input whose mtime/ctime is within `margin_ns` of `invocation_start_ns`
    /// (the build's wall-clock start). A `start` of 0 leaves the guard disabled.
    pub fn arm_too_new_guard(&mut self, invocation_start_ns: i64, margin_ns: i64) {
        self.too_new.invocation_start_ns = invocation_start_ns;
        self.too_new.margin_ns = margin_ns;
    }

    /// Whether any hashed input was "too new" since the guard was armed.
    pub fn too_new(&self) -> bool {
        self.too_new.saw_too_new.get()
    }

    /// Drain the fingerprints hashed while the guard was armed. The wrapper
    /// carries them past the compile and hands them to
    /// [`FileHasher::guarded_inputs_unchanged_since_hash`].
    pub fn take_guarded_inputs(&self) -> Vec<FileFingerprint> {
        std::mem::take(&mut *self.guard_inputs.borrow_mut())
    }

    /// Clock-independent proof that guarded inputs did not change since they
    /// were hashed: every recorded fingerprint still matches a fresh stat and
    /// carries a strong identity. Comparing a file's metadata against itself
    /// never orders either side against the host clock, so this stays valid
    /// when the filesystem lives in another clock domain (NFS skew, a fresh
    /// checkout with future mtimes) where the wall-clock guard misfires.
    ///
    /// Fails closed: an empty set, a missing or changed file, or an input
    /// without an inode (non-Unix, where replace-by-rename is invisible)
    /// never excuses a tripped guard.
    pub fn guarded_inputs_unchanged_since_hash(inputs: &[FileFingerprint]) -> bool {
        if inputs.is_empty() {
            return false;
        }
        inputs.iter().all(|expected| {
            expected.inode != 0
                && FileFingerprint::from_path(Path::new(&expected.path))
                    .is_ok_and(|current| current == *expected)
        })
    }

    fn note_too_new(&self, fingerprint: &FileFingerprint) {
        if self.too_new.invocation_start_ns > 0 {
            let threshold = self.too_new.invocation_start_ns - self.too_new.margin_ns;
            if fingerprint.mtime_ns >= threshold || fingerprint.ctime_ns >= threshold {
                self.too_new.saw_too_new.set(true);
            }
        }
    }

    pub fn stats(&self) -> FileHashStats {
        FileHashStats {
            cache_hits: self.stats.cache_hits.get(),
            cache_misses: self.stats.cache_misses.get(),
            bytes_hashed: self.stats.bytes_hashed.get(),
        }
    }

    /// Whether this hasher can persist C/C++ preprocessor memo records.
    pub(crate) fn supports_cc_preprocess_memo(&self) -> bool {
        self.cache.is_some()
    }

    /// Is there anywhere to keep a prediction record? Without the index DB
    /// (the daemon's store-free hasher) there is not, and the caller keeps
    /// running the pre-pass.
    pub(crate) fn supports_input_predictions(&self) -> bool {
        self.cache.is_some()
    }

    /// Remember the closure this build discovered for `identity`.
    ///
    /// Best-effort: a record is an optimisation, so a database that will not
    /// take it costs a future pre-pass and nothing else. Never called with a
    /// closure the pre-pass failed to produce — that is the one input set
    /// that must not be remembered (kunobi-ninja/kache#323).
    pub(crate) fn record_input_prediction(
        &self,
        identity: &str,
        crate_name: Option<&str>,
        dep_info: &DepInfo,
        tree: Option<String>,
    ) {
        let Some(cache) = self.cache.as_ref() else {
            return;
        };
        let record = InputPrediction::from_dep_info(dep_info, tree);
        let json = match serde_json::to_string(&record) {
            Ok(json) => json,
            Err(error) => {
                tracing::debug!("input prediction encode failed: {error}");
                return;
            }
        };
        if let Err(error) = cache.put_input_prediction(identity, record.schema, crate_name, &json) {
            tracing::debug!("input prediction record failed: {error}");
        }
    }

    /// The closure recorded for `identity`, if this build can still read it.
    ///
    /// The Rust prediction path validates this closure before deriving a key.
    /// Missing rows, unknown schemas, and undecodable records return `None`,
    /// so the caller runs the pre-pass.
    ///
    pub(crate) fn input_prediction(&self, identity: &str) -> Option<InputPrediction> {
        let _trace = crate::phase_trace::phase("prediction_read");
        let cache = self.cache.as_ref()?;
        let (schema, json) = match cache.get_input_prediction(identity) {
            Ok(row) => row?,
            Err(error) => {
                tracing::debug!("input prediction lookup failed: {error}");
                return None;
            }
        };
        if schema != PREDICTION_SCHEMA {
            return None;
        }
        match serde_json::from_str::<InputPrediction>(&json) {
            Ok(record) if record.schema == PREDICTION_SCHEMA => Some(record),
            Ok(_) => None,
            Err(error) => {
                tracing::debug!("input prediction decode failed: {error}");
                None
            }
        }
    }

    /// Reuse a preprocessor-output hash only when every source and header the
    /// probe read still holds the same bytes.
    ///
    /// Metadata first, because identical metadata needs no read. When it
    /// differs the file is hashed and compared, so bytes that merely moved
    /// (another worktree, a fresh checkout) or were rewritten unchanged (a
    /// build script regenerating a header) still hit.
    ///
    /// The too-new guard deliberately does not apply. It exists because
    /// metadata cannot tell a file written a moment ago from one still being
    /// written; a content hash can, because a file that changes afterwards
    /// simply fails the next comparison. Any database, decoding, or metadata
    /// uncertainty is still a miss.
    /// Whether any memo is recorded under `memo_key`, whatever its inputs
    /// say now. Decides between compiling first (nothing recorded) and
    /// rediscovering the read set with the preprocessor (a stale record).
    pub(crate) fn cc_preprocess_memo_recorded(&self, memo_key: &str) -> bool {
        self.cache
            .as_ref()
            .is_some_and(|cache| matches!(cache.get_cc_preprocess_memo(memo_key), Ok(Some(_))))
    }

    pub(crate) fn cc_preprocess_memo_lookup(
        &self,
        memo_key: &str,
        resolve: impl Fn(&str) -> Vec<PathBuf>,
        mapped_content: &impl Fn(&Path) -> Option<String>,
    ) -> Option<(String, Vec<PathBuf>)> {
        let cache = self.cache.as_ref()?;
        let record = match cache.get_cc_preprocess_memo(memo_key) {
            Ok(record) => record?,
            Err(error) => {
                tracing::debug!("cc preprocess memo lookup failed: {error}");
                return None;
            }
        };
        // A `pb:` prefix marks a path-bound read set; the digest follows.
        let digest = record
            .preprocessed_hash
            .strip_prefix("pb:")
            .unwrap_or(&record.preprocessed_hash);
        if digest.len() != 64
            || !digest
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        {
            tracing::debug!("cc preprocess memo hash is invalid");
            return None;
        }
        let inputs = record.inputs;
        if inputs.is_empty() {
            return None;
        }
        // The paths that satisfied the memo are the inputs this invocation
        // would have discovered by preprocessing, and the caller needs them to
        // resolve include shadowing without a fresh dependency capture.
        let mut satisfied = Vec::with_capacity(inputs.len());
        for expected in &inputs {
            satisfied.push(self.memo_input_is_unchanged(expected, &resolve, mapped_content)?);
        }
        if record.needs_touch
            && let Err(error) = cache.touch_cc_preprocess_memo(memo_key)
        {
            tracing::debug!("cc preprocess memo touch failed: {error}");
        }
        Some((record.preprocessed_hash, satisfied))
    }

    /// Does this input still hold the bytes the memo was recorded against?
    ///
    /// Identical metadata answers yes without a read. Otherwise the file is
    /// hashed through the ordinary content cache, so a header shared by many
    /// translation units is read once per build rather than once per unit.
    fn memo_input_is_unchanged(
        &self,
        expected: &CcPreprocessMemoInput,
        resolve: &impl Fn(&str) -> Vec<PathBuf>,
        mapped_content: &impl Fn(&Path) -> Option<String>,
    ) -> Option<PathBuf> {
        // Only where THIS invocation resolves the recorded name. The path the
        // recording checkout used is not a candidate on its own merit: it may
        // still exist, unmodified, while the tree being compiled now has an
        // edited copy at the same mapped name. Trusting it let a modified
        // source hit, which the relocate-modified e2e phase exists to catch.
        // When the two trees are the same, the resolver returns that path
        // anyway and the metadata comparison below still avoids the read.
        let candidates = resolve(&expected.name);

        for path in &candidates {
            let Ok(current) = FileFingerprint::from_path(path) else {
                continue;
            };
            self.note_too_new(&current);
            // Cheapest first: identical metadata needs no read, identical raw
            // bytes come from the content cache, and only a file differing in
            // both is read through the maps.
            if current == expected.fingerprint {
                return Some(path.clone());
            }
            if self
                .hash(path)
                .is_ok_and(|content| content == expected.content)
            {
                return Some(path.clone());
            }
            if !expected.mapped.is_empty()
                && mapped_content(path).is_some_and(|mapped| mapped == expected.mapped)
            {
                return Some(path.clone());
            }
        }
        tracing::debug!(
            "cc preprocess memo input {} matched none of {} candidate paths",
            expected.name,
            candidates.len()
        );
        None
    }

    /// Capture the source/header metadata and contents observed immediately
    /// after a full preprocess probe. The caller revalidates this snapshot
    /// after a successful compile or restore before committing it.
    ///
    /// Hashing here is what the memo is validated against later. It is not
    /// free on a cold build, but every hash goes through the content cache,
    /// so a header included by many translation units is read once.
    pub(crate) fn cc_preprocess_fingerprints(
        &self,
        paths: &[(String, PathBuf)],
        mapped_content: &impl Fn(&Path) -> Option<String>,
    ) -> Option<Vec<CcPreprocessMemoInput>> {
        if paths.is_empty() {
            return None;
        }
        let mut inputs = Vec::with_capacity(paths.len());
        for (name, path) in paths {
            let fingerprint = match FileFingerprint::from_path(path) {
                Ok(fingerprint) => fingerprint,
                Err(error) => {
                    tracing::debug!(
                        "cc preprocess memo input {} could not be fingerprinted: {error}",
                        path.display()
                    );
                    return None;
                }
            };
            self.note_too_new(&fingerprint);
            let content = match self.hash(path) {
                Ok(content) => content,
                Err(error) => {
                    tracing::debug!(
                        "cc preprocess memo input {} could not be hashed: {error}",
                        path.display()
                    );
                    return None;
                }
            };
            let mapped = mapped_content(path)?;
            inputs.push(CcPreprocessMemoInput {
                name: name.clone(),
                fingerprint,
                content,
                mapped,
            });
        }
        inputs.sort_by(|a, b| a.name.cmp(&b.name));
        inputs.dedup_by(|a, b| a.name == b.name);
        Some(inputs)
    }

    /// Commit a pending preprocessor memo after proving its inputs held the
    /// same bytes through the successful compiler/restore boundary.
    ///
    /// An input written during this build no longer blocks the record. What
    /// it was blocking is a torn read, and a torn read is caught where it
    /// matters: the recorded hash is of whatever bytes were there, so the
    /// finished file simply fails the next comparison and the expansion is
    /// recomputed. Refusing to record instead meant a fresh checkout — every
    /// CI runner, every new worktree — could never memoise anything at all.
    pub(crate) fn cc_preprocess_memo_record_if_unchanged(
        &self,
        memo_key: &str,
        preprocessed_hash: &str,
        inputs: &[CcPreprocessMemoInput],
        mapped_content: &impl Fn(&Path) -> Option<String>,
    ) {
        let Some(cache) = &self.cache else {
            return;
        };
        if inputs.is_empty() {
            return;
        }
        for expected in inputs {
            // Recording happens in the checkout that just ran the preprocess,
            // so each name resolves to the path it was captured from.
            let recorded_path = PathBuf::from(&expected.fingerprint.path);
            if self
                .memo_input_is_unchanged(
                    expected,
                    &|_: &str| vec![recorded_path.clone()],
                    mapped_content,
                )
                .is_none()
            {
                return;
            }
        }
        if let Err(error) = cache.put_cc_preprocess_memo_inputs(memo_key, preprocessed_hash, inputs)
        {
            tracing::debug!("cc preprocess memo update failed: {error}");
        }
    }

    pub fn prefetch(&self, paths: &[&Path]) {
        let _trace = crate::phase_trace::phase("input_hash_prefetch");
        let Some(socket_path) = &self.daemon_socket else {
            return;
        };

        let mut requests = Vec::new();
        for path in paths {
            let Ok(fingerprint) = FileFingerprint::from_path(path) else {
                continue;
            };
            if fingerprint.size < MIN_PERSISTED_HASH_BYTES
                || self.prefetched.borrow().contains_key(&fingerprint)
            {
                continue;
            }
            requests.push(crate::daemon::HashFileRequest {
                path: fingerprint.path,
                size: fingerprint.size,
                mtime_ns: fingerprint.mtime_ns,
                ctime_ns: fingerprint.ctime_ns,
                inode: fingerprint.inode,
            });
        }

        if requests.is_empty() {
            return;
        }

        match crate::daemon::send_hash_files_request(socket_path, requests) {
            Ok(results) => {
                let mut prefetched = self.prefetched.borrow_mut();
                for result in results {
                    let Some(hash) = result.hash else {
                        continue;
                    };
                    prefetched.insert(
                        FileFingerprint {
                            path: result.path,
                            size: result.size,
                            mtime_ns: result.mtime_ns,
                            ctime_ns: result.ctime_ns,
                            inode: result.inode,
                        },
                        PrefetchedHash {
                            hash,
                            cache_hit: result.cache_hit,
                            bytes_hashed: result.bytes_hashed,
                        },
                    );
                }
            }
            Err(e) => tracing::debug!("daemon file hash prefetch failed: {e}"),
        }
    }

    /// Hash a file's contents, using the persistent cache when available.
    pub fn hash(&self, path: &Path) -> Result<String> {
        let _trace = crate::phase_trace::phase("input_hash");
        let (hash, fingerprint) = self.hash_inner(path)?;
        if self.too_new.invocation_start_ns > 0
            && let Some(fingerprint) = &fingerprint
        {
            self.guard_inputs.borrow_mut().push(fingerprint.clone());
        }
        self.recent_hashes.borrow_mut().insert(
            absolute_path(path),
            RecentHash {
                hash: hash.clone(),
                fingerprint,
            },
        );
        Ok(hash)
    }

    fn hash_inner(&self, path: &Path) -> Result<(String, Option<FileFingerprint>)> {
        let Some(cache) = &self.cache else {
            if self.too_new.invocation_start_ns == 0 {
                let hash = hash_file(path)?;
                return Ok((hash, FileFingerprint::from_path(path).ok()));
            }
            let before = FileFingerprint::from_path(path).ok();
            if let Some(fingerprint) = &before {
                self.note_too_new(fingerprint);
            }
            let hash = hash_file(path)?;
            let after = FileFingerprint::from_path(path).ok();
            if let Some(fingerprint) = &after {
                self.note_too_new(fingerprint);
            }
            if before != after {
                self.too_new.saw_too_new.set(true);
            }
            return Ok((hash, after));
        };

        let fingerprint = match FileFingerprint::from_path(path) {
            Ok(fingerprint) => fingerprint,
            Err(e) => {
                tracing::debug!(
                    "file hash cache metadata lookup failed for {}: {e}",
                    path.display()
                );
                return hash_file(path).map(|hash| (hash, None));
            }
        };

        self.note_too_new(&fingerprint);

        if fingerprint.size < MIN_PERSISTED_HASH_BYTES {
            let hash = hash_file(path)?;
            self.record_miss(fingerprint.size);
            return Ok((hash, Some(fingerprint)));
        }

        if let Some(prefetched) = self.prefetched.borrow().get(&fingerprint) {
            if prefetched.cache_hit {
                self.record_hit();
            } else {
                self.record_miss_count();
                self.record_miss_bytes(prefetched.bytes_hashed);
            }
            return Ok((prefetched.hash.clone(), Some(fingerprint)));
        }

        match cache.get(&fingerprint) {
            Ok(Some(hash)) => {
                self.record_hit();
                return Ok((hash, Some(fingerprint)));
            }
            Ok(None) => {}
            Err(e) => {
                tracing::debug!("file hash cache lookup failed for {}: {e}", path.display());
            }
        }

        let hash = hash_file(path)?;
        self.record_miss(fingerprint.size);
        self.pending_memo
            .borrow_mut()
            .push((fingerprint.clone(), hash.clone()));
        Ok((hash, Some(fingerprint)))
    }

    /// Return whether `var` is used by this source outside an `include*` path.
    /// Decisions are keyed by the already-computed content hash, so warm key
    /// construction can reuse them without opening the source again (#557).
    fn runtime_env_use(&self, path: &Path, var: &str) -> Result<bool> {
        let absolute = absolute_path(path);
        let recent = self.recent_hashes.borrow().get(&absolute).cloned();
        let recent = match recent {
            Some(recent) => recent,
            None => {
                self.hash(path)?;
                self.recent_hashes
                    .borrow()
                    .get(&absolute)
                    .cloned()
                    .expect("a successful hash records its fingerprint")
            }
        };
        if let Some(expected) = recent.fingerprint {
            let current = FileFingerprint::from_path(path)
                .with_context(|| format!("revalidating {} before env-use scan", path.display()))?;
            if current != expected {
                anyhow::bail!(
                    "source {} changed between content hashing and env-use scan",
                    path.display()
                );
            }
            return self.runtime_env_use_for_hash(path, var, &recent.hash);
        }

        // Without a trustworthy fingerprint, bypass memo lookup. The scan
        // still verifies the content hash before recording a reusable result.
        self.scan_runtime_env_use(path, var, &recent.hash)
    }

    fn runtime_env_use_for_hash(&self, path: &Path, var: &str, content_hash: &str) -> Result<bool> {
        let key = (content_hash.to_string(), var.to_string());
        if let Some(result) = self.runtime_env_uses.borrow().get(&key) {
            return Ok(*result);
        }

        if let Some(cache) = &self.cache {
            match cache.get_runtime_env_use(content_hash, var) {
                Ok(Some(result)) => {
                    self.runtime_env_uses.borrow_mut().insert(key, result);
                    return Ok(result);
                }
                Ok(None) => {}
                Err(error) => {
                    tracing::debug!("runtime env-use cache lookup failed: {error}");
                }
            }
        }

        self.scan_runtime_env_use(path, var, content_hash)
    }

    fn scan_runtime_env_use(&self, path: &Path, var: &str, content_hash: &str) -> Result<bool> {
        let key = (content_hash.to_string(), var.to_string());
        let bytes = std::fs::read(path)
            .with_context(|| format!("reading {} for env-use scan", path.display()))?;
        let observed_hash = blake3::hash(&bytes).to_hex().to_string();
        if observed_hash != content_hash {
            anyhow::bail!(
                "source {} changed between content hashing and env-use scan",
                path.display()
            );
        }

        let source = String::from_utf8_lossy(&bytes);
        let result = source_has_runtime_env_dep_use(&source, var);
        if let Some(cache) = &self.cache
            && let Err(error) = cache.put_runtime_env_use(content_hash, var, result)
        {
            tracing::debug!("runtime env-use cache update failed: {error}");
        }
        self.runtime_env_uses.borrow_mut().insert(key, result);
        Ok(result)
    }

    /// Hash a linked `-l static=` archive for the cache key. Clean GNU/BSD
    /// archives use a structural digest that retains exact member identity.
    /// Other non-thin inputs use a path-bound fallback; thin archives error so
    /// the wrapper passes through without caching. The too-new guard (#324) is
    /// applied either way, and every scheme is domain-tagged.
    /// Scoped to `static=` (this method) on purpose — `.rlib`s are also `ar`
    /// archives but are hashed whole via [`Self::hash`].
    /// This is the strict [`StaticLibUse::Linked`] reading; rlib bundling
    /// goes through [`Self::hash_static_lib_for`].
    pub fn hash_static_lib(&self, path: &Path) -> Result<String> {
        self.hash_static_lib_for(path, StaticLibUse::Linked)
    }

    /// [`Self::hash_static_lib`] for a known [`StaticLibUse`].
    pub fn hash_static_lib_for(&self, path: &Path, usage: StaticLibUse) -> Result<String> {
        // Without a persistent cache (daemonless / tests), compute directly —
        // still honoring the too-new guard.
        let Some(cache) = &self.cache else {
            if let Ok(fingerprint) = FileFingerprint::from_path(path) {
                self.note_too_new(&fingerprint);
            }
            return compute_static_lib_hash(path, usage);
        };
        let fingerprint = match FileFingerprint::from_path(path) {
            Ok(fp) => fp,
            Err(e) => {
                tracing::debug!(
                    "static-lib hash metadata lookup failed for {}: {e}",
                    path.display()
                );
                return compute_static_lib_hash(path, usage);
            }
        };
        self.note_too_new(&fingerprint);

        // Small libs skip the persistent cache (same policy as `hash`); the
        // archive read is cheap and not worth a row.
        let size = fingerprint.size;
        if size < MIN_PERSISTED_HASH_BYTES {
            let hash = compute_static_lib_hash(path, usage)?;
            self.record_miss(size);
            return Ok(hash);
        }

        // Cache under a SCHEME-NAMESPACED key so a static-lib digest never shares
        // a row with a whole-file hash of the same path (they mean different
        // things — `hash` stores plain blake3, this stores a structural or
        // path-bound archive digest). This restores the warm-build fast path the whole-file
        // hasher had: an unchanged large `static=` archive (e.g. rocksdb) is not
        // re-read on every incremental build. `v6`: v1/v2 rows used older
        // identity definitions, v3 predates the fail-closed ELF gate, v4
        // predates the GCC Mach-O LTO gate, and v5 predates admitting
        // DWARF-bearing Mach-O members (a v5 row would keep serving the
        // path-bound digest of an unchanged archive). None may be served
        // after the final archive hardening. Bundled and linked uses get
        // separate rows because a DWARF archive hashes differently for each.
        let key = FileFingerprint {
            path: format!("{}\0{}", usage.memo_namespace(), fingerprint.path),
            size: fingerprint.size,
            mtime_ns: fingerprint.mtime_ns,
            ctime_ns: fingerprint.ctime_ns,
            inode: fingerprint.inode,
        };
        match cache.get(&key) {
            Ok(Some(hash)) => {
                self.record_hit();
                return Ok(hash);
            }
            Ok(None) => {}
            Err(e) => tracing::debug!("static-lib hash cache lookup failed: {e}"),
        }
        let hash = compute_static_lib_hash(path, usage)?;
        self.record_miss(size);
        self.pending_memo.borrow_mut().push((key, hash.clone()));
        Ok(hash)
    }

    fn record_hit(&self) {
        self.stats.cache_hits.set(self.stats.cache_hits.get() + 1);
    }

    fn record_miss(&self, size: i64) {
        self.record_miss_count();
        if let Ok(size) = u64::try_from(size) {
            self.record_miss_bytes(size);
        }
    }

    fn record_miss_count(&self) {
        self.stats
            .cache_misses
            .set(self.stats.cache_misses.get() + 1);
    }

    fn record_miss_bytes(&self, bytes: u64) {
        self.stats
            .bytes_hashed
            .set(self.stats.bytes_hashed.get().saturating_add(bytes));
    }
}

/// `-C extra-filename=` in either spelling. rustc normalises `-` and `_` in
/// codegen option names at parse time, so `-C extra_filename=` is the same
/// option and must be dropped from the pre-pass just the same.
fn is_extra_filename_option(value: &str) -> bool {
    value.starts_with("extra-filename=") || value.starts_with("extra_filename=")
}

/// Build the argv for the dep-info pre-pass from the original rustc argv.
///
/// The pre-pass reuses everything that shapes the source closure (features,
/// cfgs, edition, target, `--extern`, codegen opts) and replaces only the
/// output configuration: `--emit dep-info -o <dep_file>`. Dropped on the way:
///
/// - `--emit` / `--out-dir` / `-o`, superseded by the pre-pass's own pair.
///   The joined spellings go too: `-oFILE` (which rustc accepts), a joined
///   `--out-dir=DIR`, and single-dash `-out-dir`, which rustc parses as `-o`
///   plus junk ("option `-o` has no space between flag name and value"). A
///   leftover joins the pre-pass's own `-o` and rustc rejects the pair with
///   "Option 'o' given more than once", exit 1 — a permanent passthrough for
///   every invocation using that spelling (kunobi-ninja/kache#896). The value
///   is inline, so unlike bare `-o` no following argument is consumed, and
///   the match is case-sensitive: `-O` (opt-level) is kept.
/// - `-C extra-filename`, which names output artifacts the pre-pass never
///   produces. rustc warns "ignoring -C extra-filename flag due to -o flag"
///   whenever both are present, and because that warning is emitted while the
///   session is built it lands *first* on stderr — ahead of any real
///   diagnostic. That made a failing pre-pass look like the flag combination
///   was the cause (kunobi-ninja/kache#896). `--out-dir` is the only other flag
///   rustc reports as ignored due to `-o`, and it is already dropped here.
/// - the source file, re-added as the leading positional argument.
/// - `-C incremental`, via the same canonical filter the real compilation path
///   uses.
fn dep_info_pass_args(source_file: &Path, rustc_args: &[String], dep_file: &Path) -> Vec<String> {
    let mut dep_args = closure_shaping_args(source_file, rustc_args);
    dep_args.push("--emit".to_string());
    dep_args.push("dep-info".to_string());
    dep_args.push("-o".to_string());
    dep_args.push(dep_file.to_string_lossy().into_owned());
    dep_args
}

/// The arguments that decide WHICH files rustc reads, with everything that
/// only decides where its output goes removed.
///
/// Shared by the pre-pass argv and the prediction identity, so the two can
/// never disagree about what shapes a closure. Two invocations of one crate
/// that differ only in `-C extra-filename` read the same files, and dropping
/// it is what lets them share a record.
fn closure_shaping_args(source_file: &Path, rustc_args: &[String]) -> Vec<String> {
    let source_str = source_file.to_string_lossy();
    let rustc_args = crate::compile::strip_incremental_flags(rustc_args);
    let mut dep_args = vec![source_str.to_string()];

    let mut remaining = rustc_args.iter().peekable();
    while let Some(arg) = remaining.next() {
        match arg.as_str() {
            "--emit" | "--out-dir" | "-o" => {
                remaining.next(); // drop the flag's value too
            }
            // Two-arg codegen form: `-C extra-filename=<hash>`.
            "-C" | "--codegen"
                if remaining
                    .peek()
                    .is_some_and(|value| is_extra_filename_option(value)) =>
            {
                remaining.next();
            }
            _ if arg.starts_with("--emit=") || arg.starts_with("--out-dir=") => {}
            // Joined output form: `-oFILE`. Value is inline — consume nothing
            // further. (Exact `-o` is handled above, with its value.)
            _ if arg.starts_with("-o") => {}
            // Joined codegen forms: `-Cextra-filename=…`, `--codegen=extra-filename=…`.
            _ if arg
                .strip_prefix("-C")
                .or_else(|| arg.strip_prefix("--codegen="))
                .is_some_and(is_extra_filename_option) => {}
            // Skip the source file — already added as the first positional arg.
            _ if arg.as_str() == source_str.as_ref() => {}
            _ => dep_args.push((*arg).clone()),
        }
    }

    dep_args
}

/// Pick the stderr line that explains why the dep-info pre-pass failed.
///
/// rustc writes diagnostics in the order it produces them, so session-level
/// warnings precede the error that actually aborted the run. Reporting
/// `stderr.lines().next()` therefore blames whichever warning happened to come
/// first: in kunobi-ninja/kache#896 the stated reason a pre-pass exited 1 was
/// "ignoring -C extra-filename flag due to -o flag", a warning that on every
/// rustc from 1.97 to 1.98 leaves the exit status at 0. The real error was
/// never printed, and the crate stayed a passthrough with no way to diagnose
/// it.
///
/// Prefer the first error-level line in either `--error-format=json` or human
/// form, and fall back to the first non-empty line when nothing looks like an
/// error (`rustc` can die on a signal, or a wrapper can fail before rustc runs).
pub(crate) fn first_rustc_error_line(stderr: &str) -> Option<&str> {
    let mut fallback = None;
    for line in stderr.lines() {
        if line.trim().is_empty() {
            continue;
        }
        // JSON: `{"$message_type":"diagnostic",…,"level":"error",…}`.
        // Human: `error: …` or `error[E0433]: …` at column 0 — indented lines
        // are snippet/note continuations, never the diagnostic header.
        if line.contains(r#""level":"error""#)
            || line.starts_with("error:")
            || line.starts_with("error[")
        {
            return Some(line);
        }
        fallback.get_or_insert(line);
    }
    fallback
}

/// Run `rustc --emit=dep-info` as a pre-pass to discover source files and env deps.
///
/// This is the I/O layer — it invokes rustc and reads the output file. Building
/// the pre-pass argv is delegated to `dep_info_pass_args()`, and parsing to
/// `parse_dep_info()` / `parse_env_dep_info()` (all pure functions).
///
/// Returns `Err` on any failure (rustc non-zero exit, missing/unreadable dep
/// file, etc.). The caller MUST treat that as non-cacheable: `compute_cache_key`
/// propagates the error so the wrapper passes through to the real compiler and
/// never stores an entry keyed off an incomplete input set (kunobi-ninja/kache#323).
pub fn run_dep_info_pass(
    rustc: &Path,
    inner_rustc: Option<&Path>,
    source_file: &Path,
    rustc_args: &[String],
    use_response_file: bool,
) -> Result<DepInfo> {
    let temp_dir = tempfile::Builder::new()
        .prefix("kache-depinfo")
        .tempdir()
        .context("creating temp dir for dep-info")?;
    let dep_file = temp_dir.path().join("deps.d");

    let mut cmd = std::process::Command::new(rustc);
    if let Some(inner_rustc) = inner_rustc {
        cmd.arg(inner_rustc);
    }

    let dep_args = dep_info_pass_args(source_file, rustc_args, &dep_file);

    let response_file = if use_response_file {
        let response = crate::compile::RustcResponseFile::new(
            dep_args.iter().map(std::string::String::as_str),
        )?;
        cmd.arg(response.argument());
        Some(response)
    } else {
        cmd.args(&dep_args);
        None
    };

    tracing::trace!("dep-info pre-pass: {:?}", cmd);

    let spawned = std::time::Instant::now();
    let output = cmd
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .output()
        .context("running rustc --emit=dep-info")?;
    // One extra rustc start per invocation, hit or miss. Counted and timed so
    // the event log can show what removing it would buy (`dep_info_runs`,
    // `dep_info_ms`); it stays inside `key_ms` too.
    crate::opcounts::record_dep_info_run(spawned.elapsed());
    drop(response_file);

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Do NOT fall back to a crate-root-only DepInfo: that under-specifies the
        // input set, so a later build whose transitive sources changed would hit
        // this key and restore a stale artifact (kunobi-ninja/kache#323). Fail
        // instead — the caller treats the invocation as non-cacheable and passes
        // through to the real compiler (which, for a genuinely broken crate, also
        // fails, so no real hit was being served anyway).
        anyhow::bail!(
            "dep-info pre-pass failed (exit {}): {}",
            output.status.code().unwrap_or(-1),
            first_rustc_error_line(&stderr).unwrap_or("(no output)")
        );
    }

    let dep_content = read_dep_info_file(&dep_file)?;

    let mut source_files = parse_dep_info(&dep_content);
    if source_files.is_empty() {
        source_files.push(source_file.to_path_buf());
    }
    let env_deps = parse_env_dep_info(&dep_content);

    tracing::trace!(
        "dep-info found {} source files, {} env deps for {}",
        source_files.len(),
        env_deps.len(),
        source_file.display()
    );

    Ok(DepInfo {
        source_files,
        env_deps,
    })
}

/// Read a dep-info file rustc just wrote.
///
/// Split out of [`run_dep_info_pass`] so the encoding failure gets its own
/// diagnosis: a non-UTF8 filename or env value in the source closure lands
/// verbatim in this file, and `read_to_string` would refuse it with only
/// "stream did not contain valid UTF-8" — no hint which input set stayed
/// uncached. Fail closed with the cause named, never lossy: a lossy path
/// would hash a filename that exists nowhere on disk.
fn read_dep_info_file(dep_file: &Path) -> Result<String> {
    let bytes = std::fs::read(dep_file).context("reading dep-info output")?;
    String::from_utf8(bytes).context("dep-info output is not valid UTF-8")
}

/// Parse a Makefile-style dep-info file to extract source file paths.
///
/// Format: `target: dep1 dep2 dep3`
/// Handles `\ ` escaped spaces in paths. Returns sorted paths.
pub(crate) fn parse_dep_info(dep_info: &str) -> Vec<std::path::PathBuf> {
    let line = match dep_info.lines().next() {
        Some(l) => l,
        None => return vec![],
    };

    let pos = match line.find(": ") {
        Some(p) => p,
        None => return vec![],
    };

    let mut deps = Vec::new();
    let mut current = String::new();
    let mut chars = line[pos + 2..].chars().peekable();

    loop {
        match chars.next() {
            Some('\\') if chars.peek() == Some(&' ') => {
                current.push(' ');
                chars.next();
            }
            Some('\\') => current.push('\\'),
            Some(' ') => {
                if !current.is_empty() {
                    deps.push(std::path::PathBuf::from(&current));
                    current.clear();
                }
            }
            Some(c) => current.push(c),
            None => {
                if !current.is_empty() {
                    deps.push(std::path::PathBuf::from(&current));
                }
                break;
            }
        }
    }

    deps.sort();
    deps
}

/// Parse `# env-dep:VAR=VALUE` lines from rustc's dep-info output.
///
/// Returns RAW values — does NOT path-normalize them. Normalization
/// is the consumer's call: `compute_cache_key` runs each value through
/// either `PathNormalizer::normalize` (safe-to-share crates, e.g.
/// serde-style `include!()` use of OUT_DIR) or keeps it absolute
/// (env!()-as-value pattern; see `path_is_only_used_for_includes`). Doing the
/// substitution here would erase the information `compute_cache_key`
/// needs to make that distinction.
fn parse_env_dep_info(dep_info: &str) -> Vec<(String, String)> {
    let mut env_deps = Vec::new();
    for line in dep_info.lines() {
        if let Some(env_dep) = line.strip_prefix("# env-dep:") {
            if let Some((var, val)) = env_dep.split_once('=') {
                env_deps.push((var.to_string(), unescape_env_dep_value(val)));
            } else {
                env_deps.push((env_dep.to_string(), String::new()));
            }
        }
    }
    env_deps.sort_by(|(a, _), (b, _)| a.cmp(b));
    env_deps
}

/// Reverse rustc's `# env-dep:` value escaping.
///
/// rustc writes env-dep values through `escape_dep_env`, which emits
/// `\` as `\\`, newline as `\n`, and carriage return as `\r` so the
/// value stays on one line. Without undoing it, a Windows path arrives
/// doubled (`C:\\foo\\bar`); the cache-key path normalizer's rules use
/// single backslashes, so the value never matched and `OUT_DIR` leaked
/// its absolute path into the key — defeating cross-path cache hits on
/// Windows (kunobi-ninja/kache#201). On Unix, paths rarely contain
/// backslashes, so this was latent.
fn unescape_env_dep_value(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('\\') => out.push('\\'),
            // Unknown escape: keep both bytes so the value round-trips
            // rather than silently dropping the backslash.
            Some(other) => {
                out.push('\\');
                out.push(other);
            }
            None => out.push('\\'),
        }
    }
    out
}

/// Get rustc version string, cached to a file keyed by binary mtime.
///
/// Every wrapper invocation needs this, but the output only changes when rustc
/// itself is updated.  A file cache avoids spawning `rustc --version --verbose`
/// 300+ times per parallel build — the first invocation writes the file and the
/// rest read it back in <1 ms.
fn get_rustc_version(rustc: &Path) -> Result<String> {
    let _trace = crate::phase_trace::phase("compiler_identity");
    if let Some(cached) = read_tool_version_cache(rustc, "rustc-ver") {
        return Ok(cached);
    }

    let output = std::process::Command::new(rustc)
        .arg("--version")
        .arg("--verbose")
        .output()
        .context("running rustc --version --verbose")?;

    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
    write_tool_version_cache(rustc, "rustc-ver", &version);
    Ok(version)
}

/// `clippy-driver --version` (`clippy 0.1.98 (hash date)`), file-cached like
/// the rustc version. `-vV` only reports the underlying rustc.
fn get_clippy_version(driver: &Path) -> Result<String> {
    if let Some(cached) = read_tool_version_cache(driver, "clippy-ver") {
        return Ok(cached);
    }
    let output = std::process::Command::new(driver)
        .arg("--version")
        .output()
        .context("running clippy-driver --version")?;
    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
    anyhow::ensure!(
        !version.is_empty(),
        "clippy-driver --version printed nothing"
    );
    write_tool_version_cache(driver, "clippy-ver", &version);
    Ok(version)
}

/// Everything about a Clippy invocation that its argv does not carry: the
/// driver version, the configuration file Clippy would load (`.clippy.toml`
/// or `clippy.toml`, searched from `CLIPPY_CONF_DIR`, else the manifest
/// directory, upwards) and the lint arguments `cargo clippy` passes through
/// the environment. Content, not location, so two checkouts share keys.
pub(crate) fn clippy_identity(driver: &Path) -> Result<String> {
    clippy_identity_in(
        driver,
        |name| std::env::var_os(name),
        std::env::current_dir().ok(),
    )
}

fn clippy_identity_in(
    driver: &Path,
    env: impl Fn(&str) -> Option<std::ffi::OsString>,
    current_dir: Option<PathBuf>,
) -> Result<String> {
    let mut identity = get_clippy_version(driver)?;
    identity.push('\n');
    // The `cargo` lint group reads the package manifest, which rustc's
    // dep-info never lists.
    if let Some(manifest_dir) = env("CARGO_MANIFEST_DIR") {
        let manifest = PathBuf::from(manifest_dir).join("Cargo.toml");
        match std::fs::read(&manifest) {
            Ok(content) => {
                identity.push_str(&format!("manifest:{}\n", blake3::hash(&content).to_hex()))
            }
            Err(_) => identity.push_str("manifest:none\n"),
        }
    }
    let start = env("CLIPPY_CONF_DIR")
        .or_else(|| env("CARGO_MANIFEST_DIR"))
        .map(PathBuf::from)
        .or(current_dir);
    match start.and_then(|start| selected_clippy_config(&start)) {
        Some(path) => {
            let content = std::fs::read(&path)
                .with_context(|| format!("reading Clippy configuration {}", path.display()))?;
            identity.push_str(&format!(
                "config:{}:{}\n",
                path.file_name()
                    .map(|n| n.to_string_lossy())
                    .unwrap_or_default(),
                blake3::hash(&content).to_hex()
            ));
        }
        None => identity.push_str("config:none\n"),
    }
    for name in ["CLIPPY_ARGS", "CLIPPY_DISABLE_DOCS_LINKS"] {
        match env(name) {
            Some(value) => identity.push_str(&format!("{name}={}\n", value.to_string_lossy())),
            None => identity.push_str(&format!("{name} unset\n")),
        }
    }
    Ok(identity)
}

/// The configuration file Clippy loads: the first `.clippy.toml` or
/// `clippy.toml` from `start` up to the filesystem root.
fn selected_clippy_config(start: &Path) -> Option<PathBuf> {
    let mut directory = std::fs::canonicalize(start).ok()?;
    loop {
        for name in [".clippy.toml", "clippy.toml"] {
            let candidate = directory.join(name);
            if candidate.is_file() {
                return Some(candidate);
            }
        }
        if !directory.pop() {
            return None;
        }
    }
}

/// The toolchain commit hash from `rustc -vV`'s `commit-hash:` line, for the
/// `<RUST_SRC>` remap target (`/rustc/<hash>`).
///
/// Reuses the file-cached `-vV` output ([`get_rustc_version`]) — no extra
/// process spawn. Returns `None` for a locally-built rustc whose `commit-hash`
/// is absent or `unknown`; the `<RUST_SRC>` rule is then skipped and std paths
/// stay virtual (see [`crate::path_normalizer::PathNormalizer::with_rust_src_rule`]).
pub(crate) fn get_rustc_commit_hash(rustc: &Path) -> Option<String> {
    let vv = get_rustc_version(rustc).ok()?;
    vv.lines()
        .find_map(|l| l.strip_prefix("commit-hash:"))
        .map(|h| h.trim().to_string())
        .filter(|h| !h.is_empty() && h != "unknown")
}

/// The toolchain sysroot, used to locate `{sysroot}/lib/rustlib/src/rust` for
/// the `<RUST_SRC>` remap rule.
///
/// Prefers an explicit `--sysroot` (already parsed into [`RustcArgs::sysroot`]);
/// otherwise runs `rustc --print sysroot` once and file-caches it like the
/// version probe. The cache key folds the binary path + mtime plus the rustup
/// toolchain-selection state, so a shim redirected to another toolchain
/// re-probes instead of serving a stale sysroot (see
/// [`toolchain_selector_fingerprint`]).
pub(crate) fn get_rustc_sysroot(args: &RustcArgs) -> Option<PathBuf> {
    if let Some(sysroot) = &args.sysroot {
        return Some(sysroot.clone());
    }
    let rustc = &args.rustc;
    if let Some(cached) = read_tool_version_cache(rustc, "rustc-sysroot") {
        return Some(PathBuf::from(cached));
    }
    let output = std::process::Command::new(rustc)
        .arg("--print")
        .arg("sysroot")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let sysroot = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if sysroot.is_empty() {
        return None;
    }
    write_tool_version_cache(rustc, "rustc-sysroot", &sysroot);
    Some(PathBuf::from(sysroot))
}

/// Read a cached tool-version string.  Returns `None` on any failure (missing
/// file, stale mtime, I/O error) so the caller falls back to running the tool.
fn read_tool_version_cache(binary: &Path, prefix: &str) -> Option<String> {
    let cache_file = tool_version_cache_path(binary, prefix)?;
    std::fs::read_to_string(cache_file)
        .ok()
        .filter(|s| !s.is_empty())
}

/// Persist a tool-version string for later reads.  Best-effort — errors are
/// silently ignored because the fallback (running the tool) is always available.
fn write_tool_version_cache(binary: &Path, prefix: &str, version: &str) {
    if let Some(cache_file) = tool_version_cache_path(binary, prefix) {
        // The cache directory may not exist yet (a fresh machine, or a CI
        // runner whose store lives elsewhere); without it nothing was ever
        // persisted and every process re-ran the probe.
        crate::probe_memo::write_atomic(&cache_file, version);
    }
}

/// Build the cache-file path: `<cache_dir>/<prefix>-<hash>.txt` where the hash
/// is derived from the binary's canonical path + mtime so it auto-invalidates
/// when the toolchain is updated, plus the rustup toolchain-selection state
/// (see [`toolchain_selector_fingerprint`]).
fn tool_version_cache_path(binary: &Path, prefix: &str) -> Option<std::path::PathBuf> {
    let canon = std::fs::canonicalize(binary).ok()?;
    let mtime = std::fs::metadata(&canon)
        .ok()?
        .modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs();
    let key = format!(
        "{}:{}:{}",
        canon.display(),
        mtime,
        toolchain_selector_fingerprint(
            std::env::var_os("RUSTUP_TOOLCHAIN").as_deref(),
            std::env::current_dir().ok().as_deref(),
            rustup_settings_path().as_deref(),
        )
    );
    let hash = blake3::hash(key.as_bytes()).to_hex();
    Some(crate::config::default_cache_dir().join(format!("{}-{}.txt", prefix, &hash[..16])))
}

/// The rustup toolchain-selection state that can redirect an unchanged shim
/// binary (`~/.cargo/bin/rustc` is rustup itself) to a different toolchain:
/// path + mtime alone then serve a stale version, sysroot, or linker string
/// across a `RUSTUP_TOOLCHAIN` change, an edited `rust-toolchain{,.toml}`,
/// or a `rustup default` switch (which rewrites `settings.toml`).
///
/// Selector files fold by content digest, not mtime: these are tiny files,
/// and a digest catches an edit within one mtime second or under a
/// preserved timestamp. The nearest directory with either toolchain-file
/// spelling contributes BOTH spellings, sidestepping rustup's precedence
/// rules entirely — whichever file actually wins, changing it changes the
/// fingerprint. For a non-shim binary all this costs is a cheap re-probe
/// on the rare occasions the selection state changes.
fn toolchain_selector_fingerprint(
    rustup_toolchain: Option<&std::ffi::OsStr>,
    cwd: Option<&Path>,
    rustup_settings: Option<&Path>,
) -> String {
    let mut fp = String::new();
    if let Some(toolchain) = rustup_toolchain {
        fp.push_str("env:");
        fp.push_str(&toolchain.to_string_lossy());
    }
    // Rustup resolves toolchain files from the cwd upward; the nearest
    // directory holding one ends the search.
    if let Some(cwd) = cwd {
        'search: for dir in cwd.ancestors() {
            let mut found = false;
            for name in ["rust-toolchain", "rust-toolchain.toml"] {
                let candidate = dir.join(name);
                if let Some(digest) = file_digest(&candidate) {
                    fp.push_str(";file:");
                    fp.push_str(&candidate.to_string_lossy());
                    fp.push(':');
                    fp.push_str(&digest);
                    found = true;
                }
            }
            if found {
                break 'search;
            }
        }
    }
    if let Some(settings) = rustup_settings
        && let Some(digest) = file_digest(settings)
    {
        fp.push_str(";default:");
        fp.push_str(&digest);
    }
    fp
}

/// `$RUSTUP_HOME/settings.toml` (or its `~/.rustup` default), which records
/// the `rustup default` toolchain.
fn rustup_settings_path() -> Option<std::path::PathBuf> {
    let home = std::env::var_os("RUSTUP_HOME")
        .map(std::path::PathBuf::from)
        .or_else(|| dirs::home_dir().map(|home| home.join(".rustup")))?;
    Some(home.join("settings.toml"))
}

/// Content digest of a small selector file, or `None` if unreadable.
fn file_digest(path: &Path) -> Option<String> {
    let bytes = std::fs::read(path).ok()?;
    Some(blake3::hash(&bytes).to_hex()[..16].to_string())
}

/// Get the host target triple.
fn host_target_triple() -> &'static str {
    option_env!("TARGET").unwrap_or("unknown")
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LinuxLibcFamily {
    Gnu,
    Musl,
}

impl LinuxLibcFamily {
    fn key_name(self) -> &'static str {
        match self {
            Self::Gnu => "gnu-libc",
            Self::Musl => "musl",
        }
    }
}

/// Extract the wrapped rustc's native host triple from `rustc -vV`.
///
/// This must not use [`host_target_triple`]: release kache binaries are built
/// for musl, but commonly wrap a GNU rustc on a glibc host.
fn rustc_host_triple(rustc_version: &str) -> Option<&str> {
    rustc_version.lines().find_map(|line| {
        line.strip_prefix("host:")
            .map(str::trim)
            .filter(|host| !host.is_empty())
    })
}

fn linux_libc_family(target: &str) -> Option<LinuxLibcFamily> {
    let mut components = target.split('-');
    if !components.clone().any(|component| component == "linux") {
        return None;
    }
    components.find_map(|component| {
        if component.starts_with("gnu") {
            Some(LinuxLibcFamily::Gnu)
        } else if component.starts_with("musl") {
            Some(LinuxLibcFamily::Musl)
        } else {
            None
        }
    })
}

/// Return the native Linux libc family only when this invocation emits an
/// OS-loaded artifact for the wrapped rustc's own host target.
fn native_linux_libc_family(
    args: &RustcArgs,
    rustc_version: &str,
    running_on_linux: bool,
) -> Result<Option<LinuxLibcFamily>> {
    // An executable-shaped crate under `cargo check` emits metadata only; no
    // OS-loaded file exists and probing libc here would both fragment its key
    // and make a missing host utility disable otherwise-portable caching.
    let emits_link = args.emit.is_empty() || args.emit.iter().any(|kind| kind == "link");
    if !running_on_linux || !args.is_executable_output() || !emits_link {
        return Ok(None);
    }
    let host = rustc_host_triple(rustc_version)
        .context("wrapped rustc -vV output has no host triple; cannot key native Linux libc")?;
    let effective_target = args.target.as_deref().unwrap_or(host);
    if effective_target != host {
        return Ok(None);
    }
    if !host.split('-').any(|component| component == "linux") {
        return Ok(None);
    }
    linux_libc_family(host)
        .map(Some)
        .with_context(|| format!("unsupported native Linux libc in rustc host triple {host}"))
}

fn rustc_version_for_native_link<'a, F>(
    args: &RustcArgs,
    outer_rustc_version: &'a str,
    load_version: F,
) -> Result<Cow<'a, str>>
where
    F: FnOnce(&Path) -> Result<String>,
{
    match args.inner_rustc.as_deref() {
        Some(inner) => load_version(inner)
            .map(Cow::Owned)
            .context("reading inner rustc version for native host link key"),
        None => Ok(Cow::Borrowed(outer_rustc_version)),
    }
}

/// Fold the native host's libc signature into linked-output keys.
///
/// The injected probe keeps the gating independently testable without running
/// host tools or depending on the test runner's libc.
fn fold_native_host_libc_signature<H: KeyFold, F>(
    hasher: &mut H,
    args: &RustcArgs,
    rustc_version: &str,
    running_on_linux: bool,
    probe: F,
) -> Result<()>
where
    F: FnOnce(LinuxLibcFamily) -> Result<String>,
{
    // In a double-wrapper invocation (`clippy-driver rustc ...`), the outer
    // wrapper's version banner may not contain rustc's `host:` line. Read the
    // already-file-cached verbose version of the actual inner rustc, but only
    // for a Linux linked output where the host triple is needed.
    let emits_link = args.emit.is_empty() || args.emit.iter().any(|kind| kind == "link");
    if !running_on_linux || !args.is_executable_output() || !emits_link {
        return Ok(());
    }
    let rustc_version = rustc_version_for_native_link(args, rustc_version, get_rustc_version)?;

    let Some(family) = native_linux_libc_family(args, &rustc_version, running_on_linux)? else {
        return Ok(());
    };
    let signature = probe(family).with_context(|| {
        format!(
            "determining native Linux {} signature for cache key",
            family.key_name()
        )
    })?;
    fold_field(
        hasher,
        b"host_libc.v1:",
        format!("{}:{signature}", family.key_name()).as_bytes(),
    );
    tracing::trace!(
        "[key:{}] host_libc={}:{signature}",
        args.crate_name.as_deref().unwrap_or("unknown"),
        family.key_name()
    );
    Ok(())
}

/// Fold hashed CRT/startup/libc objects (Linux) and SDK identity (macOS)
/// into linked-output keys. Injected probes keep the gating testable without
/// running host tools.
fn fold_native_link_runtime_identity<H, Crt, Sdk>(
    hasher: &mut H,
    args: &RustcArgs,
    rustc_version: &str,
    running_on_linux: bool,
    running_on_macos: bool,
    crt_probe: Crt,
    sdk_probe: Sdk,
    deployment_target: Option<String>,
) -> Result<()>
where
    H: KeyFold,
    Crt: FnOnce(&Path) -> Result<BTreeMap<String, String>>,
    Sdk: FnOnce(Option<String>) -> Result<String>,
{
    let emits_link = args.emit.is_empty() || args.emit.iter().any(|kind| kind == "link");
    if !args.is_executable_output() || !emits_link {
        return Ok(());
    }
    if !running_on_linux && !running_on_macos {
        return Ok(());
    }
    let rustc_version = rustc_version_for_native_link(args, rustc_version, get_rustc_version)?;
    let host = rustc_host_triple(&rustc_version)
        .context("wrapped rustc -vV output has no host triple; cannot key native link runtime")?;
    let effective_target = args.target.as_deref().unwrap_or(host);
    if effective_target != host {
        return Ok(());
    }

    if running_on_linux && host.split('-').any(|component| component == "linux") {
        let driver = resolve_link_driver(args)
            .context("native Linux link has no cc/linker driver; cannot key CRT objects")?;
        let objects = crt_probe(&driver).context("determining native Linux CRT/libc identity")?;
        let encoded = crate::native_link_key::encode_crt_objects(&objects);
        fold_field(hasher, b"host_crt.v1:", encoded.as_bytes());
        tracing::trace!(
            "[key:{}] host_crt={}",
            args.crate_name.as_deref().unwrap_or("unknown"),
            encoded.replace('\n', ",")
        );
    }

    if running_on_macos && host.split('-').any(|component| component == "darwin") {
        let identity = sdk_probe(std::env::var("SDKROOT").ok())
            .context("determining macOS SDK identity for cache key")?;
        fold_field(hasher, b"host_sdk.v1:", identity.as_bytes());
        tracing::trace!(
            "[key:{}] host_sdk={}",
            args.crate_name.as_deref().unwrap_or("unknown"),
            identity
        );
        if let Some(target) = deployment_target.filter(|value| !value.is_empty()) {
            fold_field(hasher, b"host_deployment_target.v1:", target.as_bytes());
            tracing::trace!(
                "[key:{}] host_deployment_target={}",
                args.crate_name.as_deref().unwrap_or("unknown"),
                target
            );
        }
    }
    Ok(())
}

/// Extract the effective native library search directories that can shadow
/// the MSVC/SDK defaults. `-L native/all` entries are already parsed by rustc;
/// `/LIBPATH` is accepted only in an unambiguous single-argument form.
#[derive(Debug, PartialEq, Eq)]
struct WindowsNativeLinkSearchDirs {
    /// Directories rustc searches before passing a library name to LINK.
    rustc: Vec<PathBuf>,
    /// Directories emitted to LINK before the LIB environment paths.
    linker: Vec<PathBuf>,
}

fn windows_native_link_search_dirs(args: &RustcArgs) -> Result<WindowsNativeLinkSearchDirs> {
    const KNOWN_L_KINDS: [&str; 5] = ["dependency", "crate", "native", "framework", "all"];
    let mut rustc = Vec::new();
    for spec in &args.link_search {
        let (kind, path) = match spec.split_once('=') {
            Some((kind, path)) if KNOWN_L_KINDS.contains(&kind) => (Some(kind), path),
            _ => (None, spec.as_str()),
        };
        if matches!(kind, Some("dependency") | Some("crate")) {
            continue;
        }
        if matches!(kind, None | Some("native") | Some("all")) {
            rustc.push(PathBuf::from(path));
        }
    }
    let mut linker = rustc.clone();
    for (key, value) in &args.codegen_opts {
        if !matches!(key.as_str(), "link-arg" | "link-args") {
            continue;
        }
        let Some(value) = value.as_deref() else {
            continue;
        };
        if crate::native_link_key::windows_link_argument_has_unmodeled_input(value) {
            anyhow::bail!(
                "explicit Windows linker input files (.lib/.a/.obj/.o/.res/.def/.exp/.manifest) \
                 and file-carrying LINK options (/DEF, /DEFAULTLIB, /MANIFESTINPUT, \
                 /MANIFESTFILE, /PDBSTRIPPED, ...) are not hashed and are not cacheable"
            );
        }
        if let Some(path) = windows_libpath_argument(value)? {
            linker.push(PathBuf::from(path));
        }
    }
    Ok(WindowsNativeLinkSearchDirs { rustc, linker })
}

fn windows_libpath_argument(value: &str) -> Result<Option<String>> {
    let value = value.trim();
    let value = value.strip_prefix("-Wl,").unwrap_or(value);
    let upper = value.to_ascii_uppercase();
    let marker = ["/LIBPATH:", "/LIBPATH=", "-LIBPATH:", "-LIBPATH="]
        .into_iter()
        .find(|marker| upper.starts_with(*marker));
    let Some(marker) = marker else {
        if upper.contains("/LIBPATH") || upper.contains("-LIBPATH") {
            anyhow::bail!("ambiguous Windows /LIBPATH linker argument");
        }
        return Ok(None);
    };
    let path = value[marker.len()..].trim();
    let path = if let Some(quoted) = path.strip_prefix('"') {
        let closing = quoted
            .find('"')
            .context("unterminated quoted Windows /LIBPATH linker argument")?;
        if !quoted[closing + 1..].trim().is_empty() {
            anyhow::bail!("ambiguous Windows /LIBPATH linker argument");
        }
        quoted[..closing].trim()
    } else {
        if path.contains('"') || path.chars().any(char::is_whitespace) {
            anyhow::bail!("ambiguous Windows /LIBPATH linker argument");
        }
        path
    };
    if path.is_empty() {
        anyhow::bail!("empty Windows /LIBPATH linker argument");
    }
    Ok(Some(path.to_string()))
}

fn fold_generic_linker_identity<H, Get>(
    hasher: &mut H,
    args: &RustcArgs,
    native_windows_msvc: bool,
    get_identity: Get,
) where
    H: KeyFold,
    Get: FnOnce(&RustcArgs) -> Option<String>,
{
    if args.is_executable_output()
        && args.emits_link()
        && !native_windows_msvc
        && let Some(linker_id) = get_identity(args)
    {
        hasher.update(b"linker:");
        hasher.update(linker_id.as_bytes());
        hasher.update(b"\n");
    }
}

/// Native Windows MSVC links use the complete toolchain/runtime identity below
/// as their sole linker signal. Folding the generic `cc --version` probe too
/// would make the key depend on an unrelated Unix-style driver that happens to
/// be on PATH.
fn is_native_windows_msvc_link<Load>(
    args: &RustcArgs,
    rustc_version: &str,
    running_on_windows: bool,
    load_version: Load,
) -> Result<bool>
where
    Load: FnOnce(&Path) -> Result<String>,
{
    if !running_on_windows || !args.is_executable_output() || !args.emits_link() {
        return Ok(false);
    }
    let rustc_version = rustc_version_for_native_link(args, rustc_version, load_version)?;
    let host = rustc_host_triple(&rustc_version)
        .context("wrapped rustc -vV output has no host triple; cannot key native Windows link")?;
    let effective_target = args.target.as_deref().unwrap_or(host);
    Ok(effective_target == host && crate::native_link_key::is_windows_msvc_target(host))
}

/// Fold the selected native Windows MSVC link identity into a linked-output
/// key. The probe is injected so the admission gate can be tested without a
/// Windows toolchain; production supplies the real tool/library discovery.
fn fold_native_windows_msvc_identity<H, Probe>(
    hasher: &mut H,
    args: &RustcArgs,
    rustc_version: &str,
    running_on_windows: bool,
    probe: Probe,
) -> Result<()>
where
    H: KeyFold,
    Probe: FnOnce(Option<&Path>, &str) -> Result<String>,
{
    if !running_on_windows || !args.is_executable_output() || !args.emits_link() {
        return Ok(());
    }
    let rustc_version = rustc_version_for_native_link(args, rustc_version, get_rustc_version)?;
    let host = rustc_host_triple(&rustc_version)
        .context("wrapped rustc -vV output has no host triple; cannot key native Windows link")?;
    let effective_target = args.target.as_deref().unwrap_or(host);
    if effective_target != host {
        if crate::native_link_key::is_windows_msvc_target(effective_target) {
            anyhow::bail!(
                "cross-target Windows MSVC link identity is not modeled; passing through"
            );
        }
        return Ok(());
    }
    if !crate::native_link_key::is_windows_msvc_target(host) {
        return Ok(());
    }
    let architecture = crate::native_link_key::windows_msvc_architecture(host)
        .context("native Windows MSVC host has an unsupported architecture")?;
    let linker = args.get_codegen_opt("linker").map(Path::new);
    let identity =
        probe(linker, architecture).context("determining native Windows MSVC link identity")?;
    fold_field(&mut *hasher, b"host_windows_msvc.v1:", identity.as_bytes());
    tracing::trace!(
        "[key:{}] host_windows_msvc={}",
        args.crate_name.as_deref().unwrap_or("unknown"),
        identity.replace('\n', ",")
    );
    Ok(())
}

fn resolve_link_driver(args: &RustcArgs) -> Option<PathBuf> {
    let linker = args.get_codegen_opt("linker").unwrap_or("cc");
    let linker_path = Path::new(linker);
    if linker_path.is_absolute() {
        Some(linker_path.to_path_buf())
    } else {
        resolve_in_path(linker)
    }
}

fn is_libc_version(version: &str) -> bool {
    let mut parts = version.split('.');
    let Some(major) = parts.next() else {
        return false;
    };
    let Some(minor) = parts.next() else {
        return false;
    };
    !major.is_empty()
        && !minor.is_empty()
        && major.bytes().all(|b| b.is_ascii_digit())
        && minor.bytes().all(|b| b.is_ascii_digit())
        && parts.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
}

fn parse_getconf_gnu_libc(stdout: &str) -> Option<String> {
    let mut fields = stdout.split_whitespace();
    let family = fields.next()?;
    let version = fields.next()?;
    if family == "glibc" && is_libc_version(version) && fields.next().is_none() {
        Some(version.to_string())
    } else {
        None
    }
}

fn parse_ldd_libc(text: &str) -> Option<(LinuxLibcFamily, String)> {
    let lower = text.to_ascii_lowercase();
    if lower.contains("musl") {
        let version = text.lines().find_map(|line| {
            let mut fields = line.split_whitespace();
            if !fields.next()?.eq_ignore_ascii_case("version") {
                return None;
            }
            let version = fields.next()?;
            is_libc_version(version).then(|| version.to_string())
        })?;
        return Some((LinuxLibcFamily::Musl, version));
    }

    if lower.contains("glibc") || lower.contains("gnu libc") || lower.contains("gnu c library") {
        let first_line = text.lines().find(|line| !line.trim().is_empty())?;
        let version = first_line
            .split_whitespace()
            .rev()
            .find(|field| is_libc_version(field))?;
        return Some((LinuxLibcFamily::Gnu, version.to_string()));
    }
    None
}

/// Probe the runtime libc selected by a native Linux toolchain.
///
/// GNU's `getconf` provides the stable, distro-independent version signal
/// requested by #127. `ldd --version` is a fallback for minimal GNU systems and
/// the primary musl signal. A family mismatch or unparseable result fails
/// closed; the caller then treats the compile as uncacheable.
fn probe_linux_libc_signature(expected: LinuxLibcFamily) -> Result<String> {
    let _trace = crate::phase_trace::phase("native_libc_signature");
    if expected == LinuxLibcFamily::Gnu
        && let Ok(output) = std::process::Command::new("getconf")
            .arg("GNU_LIBC_VERSION")
            .env("LC_ALL", "C")
            .env("LANG", "C")
            .output()
        && output.status.success()
        && let Some(version) = parse_getconf_gnu_libc(&String::from_utf8_lossy(&output.stdout))
    {
        return Ok(version);
    }

    if let Ok(output) = std::process::Command::new("ldd")
        .arg("--version")
        .env("LC_ALL", "C")
        .env("LANG", "C")
        .output()
    {
        // musl commonly writes its banner to stderr (and may return non-zero),
        // so parse both streams before considering the exit status.
        let text = format!(
            "{}\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        if let Some((family, version)) = parse_ldd_libc(&text)
            && family == expected
        {
            return Ok(version);
        }
    }

    anyhow::bail!(
        "unable to identify native Linux {} (tried getconf/ldd)",
        expected.key_name()
    )
}

/// Get linker identity string for cache key, with file-based caching.
fn get_linker_identity(args: &RustcArgs) -> Option<String> {
    let _trace = crate::phase_trace::phase("linker_identity");
    let linker = args.get_codegen_opt("linker").unwrap_or("cc");
    let linker_path = Path::new(linker);

    // If it's already an absolute path, use it directly; otherwise try to
    // resolve via PATH so we can key the cache on the binary's mtime.
    let resolved = if linker_path.is_absolute() {
        linker_path.to_path_buf()
    } else {
        resolve_in_path(linker)?
    };

    if let Some(cached) = read_tool_version_cache(&resolved, "linker-ver") {
        return Some(cached);
    }

    let output = std::process::Command::new(linker)
        .arg("--version")
        .output()
        .ok()?;

    let version = String::from_utf8_lossy(&output.stdout);
    let first_line = version.lines().next()?.to_string();
    write_tool_version_cache(&resolved, "linker-ver", &first_line);
    Some(first_line)
}

/// Resolve a bare command name to a full path by searching PATH.
fn resolve_in_path(name: &str) -> Option<std::path::PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    std::env::split_paths(&path_var)
        .map(|dir| dir.join(name))
        .find(|p| p.is_file())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::args::RustcArgs;
    use crate::test_support::process_state_test_lock;

    const GNU_RUSTC_VERSION: &str =
        "rustc 1.90.0\nhost: x86_64-unknown-linux-gnu\nrelease: 1.90.0\n";
    const DARWIN_RUSTC_VERSION: &str =
        "rustc 1.90.0\nhost: aarch64-apple-darwin\nrelease: 1.90.0\n";

    #[test]
    fn source_identity_uses_a_stable_configured_root() {
        let dir = tempfile::tempdir().unwrap();
        let checkout = dir.path().join("checkout");
        let source = checkout.join("src/lib.rs");
        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
        std::fs::write(&source, "pub fn value() {}\n").unwrap();
        let normalizer =
            PathNormalizer::empty().with_base_dirs(&[checkout.to_string_lossy().into_owned()]);

        let mut expected = b"<BASE_DIR_0>/".to_vec();
        expected.extend_from_slice(
            source
                .strip_prefix(&checkout)
                .unwrap()
                .to_string_lossy()
                .as_bytes(),
        );
        assert_eq!(
            source_path_identity(&source, &normalizer).unwrap(),
            expected
        );
    }

    #[test]
    fn source_identity_uses_a_configured_external_root_losslessly() {
        let dir = tempfile::tempdir().unwrap();
        let external = dir.path().join("external");
        let source = external.join("generated/value.rs");
        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
        std::fs::write(&source, "pub const VALUE: u8 = 1;\n").unwrap();
        let normalizer =
            PathNormalizer::empty().with_base_dirs(&[external.to_string_lossy().into_owned()]);

        let mut expected = b"<BASE_DIR_0>/".to_vec();
        expected.extend_from_slice(
            source
                .strip_prefix(&external)
                .unwrap()
                .to_string_lossy()
                .as_bytes(),
        );
        assert_eq!(
            source_path_identity(&source, &normalizer).unwrap(),
            expected
        );
    }

    #[cfg(unix)]
    #[test]
    fn source_identity_keeps_distinct_symlink_spellings_of_one_inode() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.rs");
        let alias = dir.path().join("alias.rs");
        std::fs::write(&real, "pub const VALUE: u8 = 1;\n").unwrap();
        std::os::unix::fs::symlink(&real, &alias).unwrap();

        let real_identity = source_path_identity(&real, &PathNormalizer::empty()).unwrap();
        let alias_identity = source_path_identity(&alias, &PathNormalizer::empty()).unwrap();
        assert_ne!(real_identity, alias_identity);
        assert!(real_identity.starts_with(b"<OPAQUE_PATH>/"));
        assert!(alias_identity.starts_with(b"<OPAQUE_PATH>/"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn source_identity_opaque_fallback_preserves_non_utf8_bytes() {
        use std::os::unix::ffi::OsStringExt;

        let dir = tempfile::tempdir().unwrap();
        let external = dir.path().join("external");
        std::fs::create_dir_all(&external).unwrap();
        let path_a = external.join(std::ffi::OsString::from_vec(vec![b'a', 0x80]));
        let path_b = external.join(std::ffi::OsString::from_vec(vec![b'a', 0x81]));
        std::fs::write(&path_a, b"same").unwrap();
        std::fs::write(&path_b, b"same").unwrap();
        let identity_a = source_path_identity(&path_a, &PathNormalizer::empty()).unwrap();
        let identity_b = source_path_identity(&path_b, &PathNormalizer::empty()).unwrap();
        assert_ne!(identity_a, identity_b);
        assert!(identity_a.starts_with(b"<OPAQUE_PATH>/"));
        assert!(identity_b.starts_with(b"<OPAQUE_PATH>/"));
    }

    /// #131 load-bearing invariant: the grouped tee must produce EXACTLY the
    /// digest a plain blake3 hasher produces over the same update sequence —
    /// per-field tracing can never change a cache key.
    #[test]
    fn grouped_hasher_main_digest_matches_plain_blake3() {
        let mut plain = blake3::Hasher::new();
        let mut grouped = GroupedHasher::new("compiler");
        for (group, chunk) in [
            ("compiler", b"rustc_version:1.90".as_slice()),
            ("args", b"emit:link\n"),
            ("sources", b"source:abc\n"),
            ("args", b"RUSTFLAGS:-Copt-level=3\n"),
            ("link", b"linker:ld64\n"),
        ] {
            plain.update(chunk);
            grouped.set_group(group);
            grouped.update(chunk);
        }
        let (hash, fields) = grouped.finalize_with_fields();
        assert_eq!(hash, plain.finalize(), "grouping must not perturb the key");
        assert_eq!(
            fields.keys().collect::<Vec<_>>(),
            ["args", "compiler", "link", "sources"],
            "only groups that received bytes appear",
        );
        assert!(fields.values().all(|v| v.len() == KEY_FIELD_HEX));
    }

    /// #131: bytes route to the CURRENT group, non-contiguous segments of the
    /// same group accumulate, and only the touched group's digest changes.
    #[test]
    fn grouped_hasher_isolates_changes_to_their_group() {
        let build = |rustflags: &[u8]| {
            let mut h = GroupedHasher::new("compiler");
            h.update(b"rustc_version:1.90\n");
            h.set_group("sources");
            h.update(b"source:abc\n");
            h.set_group("args");
            h.update(b"emit:link\n");
            h.update(rustflags);
            h.finalize_with_fields()
        };
        let (key_a, fields_a) = build(b"RUSTFLAGS:-Copt-level=3\n");
        let (key_b, fields_b) = build(b"RUSTFLAGS:-Copt-level=2\n");
        assert_ne!(key_a, key_b);
        assert_ne!(fields_a["args"], fields_b["args"], "args group must differ");
        assert_eq!(fields_a["compiler"], fields_b["compiler"]);
        assert_eq!(fields_a["sources"], fields_b["sources"]);
    }

    fn parsed_crate_type(crate_type: &str, target: Option<&str>) -> RustcArgs {
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "probe".to_string(),
            "--crate-type".to_string(),
            crate_type.to_string(),
            "src/lib.rs".to_string(),
        ];
        if let Some(target) = target {
            argv.push("--target".to_string());
            argv.push(target.to_string());
        }
        RustcArgs::parse(&argv).unwrap()
    }

    fn libc_fold_key(
        args: &RustcArgs,
        rustc_version: &str,
        running_on_linux: bool,
        signature: &str,
    ) -> Result<String> {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"base-key");
        fold_native_host_libc_signature(
            &mut hasher,
            args,
            rustc_version,
            running_on_linux,
            |_| Ok(signature.to_string()),
        )?;
        Ok(hasher.finalize().to_hex().to_string())
    }

    #[test]
    fn native_linux_linked_outputs_key_host_libc_version() {
        for crate_type in ["bin", "dylib", "cdylib", "proc-macro"] {
            let args = parsed_crate_type(crate_type, None);
            let old = libc_fold_key(&args, GNU_RUSTC_VERSION, true, "2.36").unwrap();
            let new = libc_fold_key(&args, GNU_RUSTC_VERSION, true, "2.39").unwrap();
            assert_ne!(old, new, "{crate_type} must re-key across libc versions");
        }
    }

    #[test]
    fn rlibs_and_cross_targets_do_not_key_host_libc() {
        let rlib = parsed_crate_type("rlib", None);
        assert_eq!(
            libc_fold_key(&rlib, GNU_RUSTC_VERSION, true, "2.36").unwrap(),
            libc_fold_key(&rlib, GNU_RUSTC_VERSION, true, "2.39").unwrap(),
            "portable rlibs must not be tied to the host libc"
        );

        let cross = parsed_crate_type("bin", Some("aarch64-unknown-linux-gnu"));
        assert_eq!(
            libc_fold_key(&cross, GNU_RUSTC_VERSION, true, "2.36").unwrap(),
            libc_fold_key(&cross, GNU_RUSTC_VERSION, true, "2.39").unwrap(),
            "cross-target output must not be tied to the build host libc"
        );

        let explicit_native = parsed_crate_type("bin", Some("x86_64-unknown-linux-gnu"));
        assert_ne!(
            libc_fold_key(&explicit_native, GNU_RUSTC_VERSION, true, "2.36").unwrap(),
            libc_fold_key(&explicit_native, GNU_RUSTC_VERSION, true, "2.39").unwrap(),
            "an explicit rustc-host target is still a native output"
        );
    }

    #[test]
    fn host_libc_probe_is_linux_only_and_fails_closed() {
        let bin = parsed_crate_type("bin", None);
        assert_eq!(
            libc_fold_key(&bin, GNU_RUSTC_VERSION, false, "2.36").unwrap(),
            libc_fold_key(&bin, GNU_RUSTC_VERSION, false, "2.39").unwrap(),
            "non-Linux hosts must not gain a Linux libc component"
        );

        let mut hasher = blake3::Hasher::new();
        let err =
            fold_native_host_libc_signature(&mut hasher, &bin, GNU_RUSTC_VERSION, true, |_| {
                anyhow::bail!("probe failed")
            })
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("determining native Linux gnu-libc")
        );

        let missing_host = "rustc 1.90.0\nrelease: 1.90.0\n";
        let err = libc_fold_key(&bin, missing_host, true, "2.39").unwrap_err();
        assert!(err.to_string().contains("no host triple"));
    }

    #[test]
    fn metadata_only_outputs_do_not_probe_or_key_host_libc() {
        let mut metadata = parsed_crate_type("bin", None);
        metadata.emit = vec!["metadata".to_string()];
        let mut hasher = blake3::Hasher::new();
        fold_native_host_libc_signature(&mut hasher, &metadata, GNU_RUSTC_VERSION, true, |_| {
            panic!("metadata-only output must not probe libc")
        })
        .unwrap();

        let baseline = blake3::Hasher::new().finalize().to_hex().to_string();
        assert_eq!(hasher.finalize().to_hex().to_string(), baseline);
    }

    #[test]
    fn double_wrapper_uses_inner_rustc_host_banner() {
        let mut bin = parsed_crate_type("bin", None);
        bin.inner_rustc = Some(PathBuf::from("/toolchain/bin/rustc"));
        let version = rustc_version_for_native_link(&bin, "clippy 0.1.90\n", |path| {
            assert_eq!(path, Path::new("/toolchain/bin/rustc"));
            Ok(GNU_RUSTC_VERSION.to_string())
        })
        .unwrap();

        assert_eq!(
            rustc_host_triple(&version),
            Some("x86_64-unknown-linux-gnu")
        );
    }

    fn dummy_absolute_linker() -> String {
        std::env::temp_dir()
            .join("kache-dummy-cc")
            .to_string_lossy()
            .into_owned()
    }

    fn parsed_linked_bin(target: Option<&str>) -> RustcArgs {
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "probe".to_string(),
            "--crate-type".to_string(),
            "bin".to_string(),
            "src/lib.rs".to_string(),
            format!("-Clinker={}", dummy_absolute_linker()),
        ];
        if let Some(target) = target {
            argv.push("--target".to_string());
            argv.push(target.to_string());
        }
        RustcArgs::parse(&argv).unwrap()
    }

    fn crt_fold_key(
        args: &RustcArgs,
        rustc_version: &str,
        linux: bool,
        macos: bool,
        crt: &str,
        sdk: &str,
        deployment_target: Option<&str>,
    ) -> Result<String> {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"base-key");
        fold_native_link_runtime_identity(
            &mut hasher,
            args,
            rustc_version,
            linux,
            macos,
            |_| {
                let mut objects = BTreeMap::new();
                for pair in crt.split(';').filter(|pair| !pair.is_empty()) {
                    let (name, digest) = pair.split_once('=').unwrap();
                    objects.insert(name.to_string(), digest.to_string());
                }
                Ok(objects)
            },
            |_| Ok(sdk.to_string()),
            deployment_target.map(str::to_string),
        )?;
        Ok(hasher.finalize().to_hex().to_string())
    }

    #[test]
    fn native_linux_linked_outputs_key_crt_object_hashes() {
        let args = parsed_linked_bin(None);
        let old = crt_fold_key(
            &args,
            GNU_RUSTC_VERSION,
            true,
            false,
            "crt1.o=aaa;libc.so.6=bbb",
            "",
            None,
        )
        .unwrap();
        let new = crt_fold_key(
            &args,
            GNU_RUSTC_VERSION,
            true,
            false,
            "crt1.o=aaa;libc.so.6=ccc",
            "",
            None,
        )
        .unwrap();
        assert_ne!(old, new, "libc object bytes must re-key the native link");
    }

    #[test]
    fn rlibs_and_cross_targets_do_not_key_crt_or_sdk() {
        let rlib = parsed_crate_type("rlib", None);
        assert_eq!(
            crt_fold_key(
                &rlib,
                GNU_RUSTC_VERSION,
                true,
                true,
                "crt1.o=aaa;libc.so.6=bbb",
                "14.0 (a)",
                Some("11.0"),
            )
            .unwrap(),
            crt_fold_key(
                &rlib,
                GNU_RUSTC_VERSION,
                true,
                true,
                "crt1.o=zzz;libc.so.6=yyy",
                "15.0 (b)",
                Some("12.0"),
            )
            .unwrap(),
            "portable rlibs must not be tied to CRT/SDK identity"
        );

        let cross = parsed_linked_bin(Some("aarch64-unknown-linux-gnu"));
        assert_eq!(
            crt_fold_key(
                &cross,
                GNU_RUSTC_VERSION,
                true,
                false,
                "crt1.o=aaa;libc.so.6=bbb",
                "",
                None,
            )
            .unwrap(),
            crt_fold_key(
                &cross,
                GNU_RUSTC_VERSION,
                true,
                false,
                "crt1.o=zzz;libc.so.6=yyy",
                "",
                None,
            )
            .unwrap(),
            "cross-target output must not be tied to the build host CRT"
        );
    }

    #[test]
    fn native_linux_crt_probe_fails_closed() {
        let bin = parsed_linked_bin(None);
        let mut hasher = blake3::Hasher::new();
        let err = fold_native_link_runtime_identity(
            &mut hasher,
            &bin,
            GNU_RUSTC_VERSION,
            true,
            false,
            |_| anyhow::bail!("no startup object"),
            |_| unreachable!("linux fold must not probe the macOS SDK"),
            None,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("determining native Linux CRT/libc identity")
        );
    }

    #[test]
    fn native_macos_linked_outputs_key_sdk_identity() {
        let args = parsed_linked_bin(None);
        let old = crt_fold_key(
            &args,
            DARWIN_RUSTC_VERSION,
            false,
            true,
            "",
            "14.0 (23A344)",
            None,
        )
        .unwrap();
        let new = crt_fold_key(
            &args,
            DARWIN_RUSTC_VERSION,
            false,
            true,
            "",
            "15.0 (24A348)",
            None,
        )
        .unwrap();
        assert_ne!(old, new, "SDK identity must re-key the native macOS link");

        let with_dt = crt_fold_key(
            &args,
            DARWIN_RUSTC_VERSION,
            false,
            true,
            "",
            "14.0 (23A344)",
            Some("11.0"),
        )
        .unwrap();
        assert_ne!(
            old, with_dt,
            "MACOSX_DEPLOYMENT_TARGET must re-key when set"
        );
    }

    const WINDOWS_RUSTC_VERSION: &str =
        "rustc 1.90.0\nhost: x86_64-pc-windows-msvc\nrelease: 1.90.0\n";
    const WINDOWS_GNU_RUSTC_VERSION: &str =
        "rustc 1.90.0\nhost: x86_64-pc-windows-gnu\nrelease: 1.90.0\n";

    fn windows_fold_key_on_host(
        args: &RustcArgs,
        version: &str,
        identity: &str,
        running_on_windows: bool,
    ) -> Result<String> {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"base-key");
        fold_native_windows_msvc_identity(
            &mut hasher,
            args,
            version,
            running_on_windows,
            |_, _| Ok(identity.to_string()),
        )?;
        Ok(hasher.finalize().to_hex().to_string())
    }

    fn windows_fold_key(args: &RustcArgs, version: &str, identity: &str) -> Result<String> {
        windows_fold_key_on_host(args, version, identity, true)
    }

    #[test]
    fn native_windows_msvc_identity_keys_only_native_link_outputs() {
        let bin = parsed_crate_type("bin", None);
        let old = windows_fold_key(&bin, WINDOWS_RUSTC_VERSION, "toolset=14.4").unwrap();
        let new = windows_fold_key(&bin, WINDOWS_RUSTC_VERSION, "toolset=14.5").unwrap();
        assert_ne!(old, new);

        let mut metadata = bin.clone();
        metadata.emit = vec!["metadata".into()];
        assert_eq!(
            windows_fold_key(&metadata, WINDOWS_RUSTC_VERSION, "probe must not run").unwrap(),
            windows_fold_key(&metadata, WINDOWS_RUSTC_VERSION, "anything").unwrap()
        );

        let cross = parsed_crate_type("bin", Some("aarch64-pc-windows-msvc"));
        assert!(
            windows_fold_key(&cross, WINDOWS_RUSTC_VERSION, "probe must not run").is_err(),
            "cross-target Windows MSVC links must pass through until target identity is modeled"
        );

        let gnu = parsed_crate_type("bin", Some("x86_64-pc-windows-gnu"));
        assert_eq!(
            windows_fold_key(&gnu, WINDOWS_RUSTC_VERSION, "probe must not run").unwrap(),
            windows_fold_key(&gnu, WINDOWS_RUSTC_VERSION, "anything").unwrap()
        );

        let rlib = parsed_crate_type("rlib", None);
        assert_eq!(
            windows_fold_key(&rlib, WINDOWS_RUSTC_VERSION, "probe must not run").unwrap(),
            windows_fold_key(&rlib, WINDOWS_RUSTC_VERSION, "anything").unwrap()
        );

        assert_eq!(
            windows_fold_key_on_host(&bin, WINDOWS_RUSTC_VERSION, "probe must not run", false)
                .unwrap(),
            windows_fold_key_on_host(&bin, WINDOWS_RUSTC_VERSION, "anything", false).unwrap(),
            "a non-Windows host must not probe native MSVC inputs"
        );
    }

    #[test]
    fn native_windows_msvc_detection_requires_a_windows_linked_executable() {
        let bin = parsed_crate_type("bin", None);
        let mut metadata = bin.clone();
        metadata.emit = vec!["metadata".into()];
        let rlib = parsed_crate_type("rlib", None);

        for (args, running_on_windows) in [(&bin, false), (&metadata, true), (&rlib, true)] {
            assert!(
                !is_native_windows_msvc_link(
                    args,
                    WINDOWS_RUSTC_VERSION,
                    running_on_windows,
                    |_| unreachable!("the supplied rustc version must be reused"),
                )
                .unwrap()
            );
        }

        // Both halves of the admission must hold: the target must be the host
        // and the host must be MSVC. A cross target on an MSVC host and a
        // native build on a GNU host each fail one half.
        let cross = parsed_crate_type("bin", Some("x86_64-unknown-linux-gnu"));
        for (args, version) in [
            (&cross, WINDOWS_RUSTC_VERSION),
            (&bin, WINDOWS_GNU_RUSTC_VERSION),
        ] {
            assert!(
                !is_native_windows_msvc_link(args, version, true, |_| unreachable!(
                    "the supplied rustc version must be reused"
                ))
                .unwrap(),
                "{version:?} must not admit {:?}",
                args.target
            );
        }
    }

    #[test]
    fn native_windows_msvc_ignores_unrelated_generic_cc_identity() {
        let bin = parsed_crate_type("bin", None);
        assert!(
            is_native_windows_msvc_link(&bin, WINDOWS_RUSTC_VERSION, true, |_| unreachable!(
                "non-nested rustc must use the supplied version"
            ),)
            .unwrap()
        );

        let fold = |identity: &str| {
            let mut hasher = blake3::Hasher::new();
            hasher.update(b"base-key");
            fold_generic_linker_identity(&mut hasher, &bin, true, |_| Some(identity.to_string()));
            hasher.finalize()
        };
        assert_eq!(
            fold("unrelated MinGW cc"),
            fold("no cc installed"),
            "native MSVC keys must not depend on an unrelated generic cc probe"
        );

        let mut generic = blake3::Hasher::new();
        generic.update(b"base-key");
        fold_generic_linker_identity(&mut generic, &bin, false, |_| {
            Some("actual generic linker".into())
        });
        assert_ne!(generic.finalize(), fold("anything"));
    }

    #[test]
    fn native_windows_msvc_identity_probe_failure_is_cache_failure() {
        let bin = parsed_crate_type("bin", None);
        let mut hasher = blake3::Hasher::new();
        let error = fold_native_windows_msvc_identity(
            &mut hasher,
            &bin,
            WINDOWS_RUSTC_VERSION,
            true,
            |_, _| anyhow::bail!("ambiguous toolchain"),
        )
        .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("native Windows MSVC link identity")
        );
    }

    #[test]
    fn windows_native_link_search_dirs_include_l_and_libpath_and_reject_ambiguity() {
        let dir = tempfile::tempdir().unwrap();
        let native = dir.path().join("native");
        let libpath = dir.path().join("libpath");
        std::fs::create_dir_all(&native).unwrap();
        std::fs::create_dir_all(&libpath).unwrap();
        // `-l static=foo` resolves to `foo.lib` through the modeled search
        // dirs and is hashed by the identity; only `-C link-arg` inputs are
        // classified.
        let args = RustcArgs::parse(&[
            "rustc".into(),
            "--crate-type=bin".into(),
            "-l".into(),
            "static=foo".into(),
            "-L".into(),
            format!("native={}", native.display()),
            format!("-Clink-arg=/LIBPATH:{}", libpath.display()),
        ])
        .unwrap();
        assert_eq!(args.link_libs, vec!["static=foo".to_string()]);
        assert_eq!(
            windows_native_link_search_dirs(&args).unwrap(),
            WindowsNativeLinkSearchDirs {
                rustc: vec![native.clone()],
                linker: vec![native, libpath],
            }
        );

        let ambiguous = RustcArgs::parse(&[
            "rustc".into(),
            "--crate-type=bin".into(),
            "-Clink-args=/DEFAULTLIB:foo /LIBPATH".into(),
        ])
        .unwrap();
        assert!(windows_native_link_search_dirs(&ambiguous).is_err());

        for linker_arg in [
            "foo.lib",
            "/DEFAULTLIB:foo",
            "-defaultlib:foo",
            "/DEFAULTLIB:foo.lib",
            "app.res",
            "APP.RES",
            "extra.obj",
            "exports.exp",
            "/DEF:exports.def",
            "-def:exports.def",
            "-Wl,/def:exports.def",
            "/MANIFESTINPUT:extra.manifest",
            "/MANIFESTFILE:app.exe.manifest",
            "/PDBSTRIPPED:app.public.pdb",
        ] {
            let args = RustcArgs::parse(&[
                "rustc".into(),
                "--crate-type=bin".into(),
                format!("-Clink-arg={linker_arg}"),
            ])
            .unwrap();
            let error = windows_native_link_search_dirs(&args).unwrap_err();
            assert!(
                error.to_string().contains("not hashed"),
                "unmodeled Windows link input must fail closed: {linker_arg}: {error:#}"
            );
        }
    }

    #[test]
    fn windows_libpath_parser_accepts_one_exact_argument() {
        for (argument, expected) in [
            (r"/LIBPATH:C:\sdk\lib", r"C:\sdk\lib"),
            (r"/libpath=C:\sdk\lib", r"C:\sdk\lib"),
            (r"-LIBPATH:C:\lld\lib", r"C:\lld\lib"),
            (r"-libpath=C:\lld\lib", r"C:\lld\lib"),
            (
                r#"/LIBPATH:"C:\Program Files\SDK\lib""#,
                r"C:\Program Files\SDK\lib",
            ),
            (
                r#"-Wl,/LIBPATH:"C:\Program Files\SDK\lib""#,
                r"C:\Program Files\SDK\lib",
            ),
            (
                r#"-Wl,-LiBpAtH:"C:\Program Files\LLVM\lib""#,
                r"C:\Program Files\LLVM\lib",
            ),
        ] {
            assert_eq!(
                windows_libpath_argument(argument).unwrap().as_deref(),
                Some(expected),
                "{argument}"
            );
        }
        assert_eq!(windows_libpath_argument("/DEBUG").unwrap(), None);

        for argument in [
            "/LIBPATH:",
            r#"/LIBPATH:"C:\unterminated"#,
            r#"/LIBPATH:"C:\sdk\lib" /DEBUG"#,
            r"/LIBPATH:C:\Program Files\SDK\lib",
            r"/DEBUG /LIBPATH:C:\sdk\lib",
            r"/DEBUG -LIBPATH:C:\lld\lib",
            r"-Wl,/DEBUG,-LIBPATH:C:\lld\lib",
        ] {
            assert!(
                windows_libpath_argument(argument).is_err(),
                "ambiguous or empty argument must fail closed: {argument}"
            );
        }
    }

    #[test]
    fn windows_lld_libpath_preserves_shadowing_order() {
        let directory = tempfile::tempdir().unwrap();
        let first = directory.path().join("lld-first");
        let second = directory.path().join("link-second");
        std::fs::create_dir_all(&first).unwrap();
        std::fs::create_dir_all(&second).unwrap();
        std::fs::write(first.join("shadowed.lib"), b"first").unwrap();
        std::fs::write(second.join("shadowed.lib"), b"second").unwrap();
        let args = RustcArgs::parse(&[
            "rustc".into(),
            "--crate-type=bin".into(),
            format!("-Clink-arg=-LIBPATH:{}", first.display()),
            format!("-Clink-arg=/LIBPATH:{}", second.display()),
        ])
        .unwrap();

        assert_eq!(
            windows_native_link_search_dirs(&args).unwrap(),
            WindowsNativeLinkSearchDirs {
                rustc: Vec::new(),
                linker: vec![first, second],
            }
        );
    }

    #[test]
    fn windows_native_link_search_dirs_honor_only_linker_visible_l_kinds() {
        let directory = tempfile::tempdir().unwrap();
        let native = directory.path().join("native");
        let all = directory.path().join("all");
        let bare = directory.path().join("bare");
        let libpath = directory.path().join("path with spaces");
        let unknown = format!("custom={}", directory.path().join("unknown").display());
        for path in [&native, &all, &bare, &libpath] {
            std::fs::create_dir_all(path).unwrap();
        }
        let args = RustcArgs::parse(&[
            "rustc".into(),
            "--crate-type=bin".into(),
            "-L".into(),
            format!("native={}", native.display()),
            format!("-Lall={}", all.display()),
            format!("-L{}", bare.display()),
            format!("-L{unknown}"),
            format!(
                "-Ldependency={}",
                directory.path().join("dependency").display()
            ),
            format!("-Lcrate={}", directory.path().join("crate").display()),
            format!(
                "-Lframework={}",
                directory.path().join("framework").display()
            ),
            format!(r#"-Clink-arg=/LIBPATH:"{}""#, libpath.display()),
            "-Clink-arg=/DEBUG".into(),
        ])
        .unwrap();
        assert_eq!(
            windows_native_link_search_dirs(&args).unwrap(),
            WindowsNativeLinkSearchDirs {
                rustc: vec![
                    native.clone(),
                    all.clone(),
                    bare.clone(),
                    PathBuf::from(unknown.clone())
                ],
                linker: vec![native, all, bare, PathBuf::from(unknown), libpath],
            }
        );
    }

    #[test]
    fn native_macos_sdk_probe_fails_closed() {
        let bin = parsed_linked_bin(None);
        let mut hasher = blake3::Hasher::new();
        let err = fold_native_link_runtime_identity(
            &mut hasher,
            &bin,
            DARWIN_RUSTC_VERSION,
            false,
            true,
            |_| unreachable!("macOS fold must not probe Linux CRT"),
            |_| anyhow::bail!("sdk missing"),
            None,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("determining macOS SDK identity for cache key")
        );
    }

    #[test]
    fn metadata_only_outputs_do_not_probe_crt_or_sdk() {
        let mut metadata = parsed_linked_bin(None);
        metadata.emit = vec!["metadata".to_string()];
        let mut hasher = blake3::Hasher::new();
        fold_native_link_runtime_identity(
            &mut hasher,
            &metadata,
            GNU_RUSTC_VERSION,
            true,
            true,
            |_| panic!("metadata-only output must not probe CRT"),
            |_| panic!("metadata-only output must not probe SDK"),
            None,
        )
        .unwrap();
    }

    #[test]
    fn crt_fold_requires_linux_os_and_linux_rustc_host() {
        let args = parsed_linked_bin(None);
        let a = crt_fold_key(
            &args,
            DARWIN_RUSTC_VERSION,
            true,
            false,
            "crt1.o=aaa;libc.so.6=bbb",
            "",
            None,
        )
        .unwrap();
        let b = crt_fold_key(
            &args,
            DARWIN_RUSTC_VERSION,
            true,
            false,
            "crt1.o=zzz;libc.so.6=yyy",
            "",
            None,
        )
        .unwrap();
        assert_eq!(
            a, b,
            "a Darwin rustc hosted on Linux must not fold Linux CRT objects"
        );
    }

    #[test]
    fn sdk_fold_requires_macos_os_and_darwin_rustc_host() {
        let args = parsed_linked_bin(None);
        let a = crt_fold_key(&args, GNU_RUSTC_VERSION, false, true, "", "14.0 (a)", None).unwrap();
        let b = crt_fold_key(&args, GNU_RUSTC_VERSION, false, true, "", "15.0 (b)", None).unwrap();
        assert_eq!(
            a, b,
            "a GNU rustc hosted on macOS must not fold the Darwin SDK"
        );
    }

    #[test]
    fn windows_hosts_do_not_key_linux_crt_or_macos_sdk() {
        let bin = parsed_linked_bin(None);
        assert_eq!(
            crt_fold_key(
                &bin,
                GNU_RUSTC_VERSION,
                false,
                false,
                "crt1.o=aaa;libc.so.6=bbb",
                "14.0 (a)",
                Some("11.0"),
            )
            .unwrap(),
            crt_fold_key(
                &bin,
                DARWIN_RUSTC_VERSION,
                false,
                false,
                "crt1.o=zzz;libc.so.6=yyy",
                "15.0 (b)",
                Some("12.0"),
            )
            .unwrap(),
            "Windows hosts keep the existing linker --version identity only"
        );
    }

    #[test]
    fn libc_probe_output_parsing_is_strict_and_canonical() {
        assert_eq!(
            parse_getconf_gnu_libc("glibc 2.39\n").as_deref(),
            Some("2.39")
        );
        assert_eq!(parse_getconf_gnu_libc("musl 1.2.5\n"), None);
        assert_eq!(parse_getconf_gnu_libc("glibc unknown\n"), None);

        assert_eq!(
            parse_ldd_libc("ldd (Debian GLIBC 2.36-9) 2.36\nCopyright ..."),
            Some((LinuxLibcFamily::Gnu, "2.36".to_string()))
        );
        assert_eq!(
            parse_ldd_libc("musl libc (x86_64)\nVersion 1.2.5\nDynamic Program Loader"),
            Some((LinuxLibcFamily::Musl, "1.2.5".to_string()))
        );
        assert_eq!(parse_ldd_libc("BusyBox ldd\n"), None);
    }

    #[test]
    fn is_valid_cache_key_accepts_real_blake3_hex() {
        // A real key is 64 lowercase hex chars (blake3 to_hex).
        let key = fold_labeled("seed".into(), "label", "value");
        assert_eq!(key.len(), 64);
        assert!(is_valid_cache_key(&key));
        assert!(is_valid_cache_key(&"a".repeat(64)));
        assert!(is_valid_cache_key(&"0123456789abcdef".repeat(4)));
    }

    #[test]
    fn apply_key_salt_no_salt_is_identity() {
        let base = "deadbeef".to_string();
        // None and empty/whitespace are both treated as "unsalted" and
        // must return the base key byte-for-byte (no CACHE_KEY_VERSION
        // bump, no effect for projects that never set it).
        assert_eq!(apply_key_salt(base.clone(), None, "crate"), base);
        assert_eq!(apply_key_salt(base.clone(), Some(""), "crate"), base);
    }

    #[test]
    fn apply_key_salt_changes_key_and_is_salt_specific() {
        let base = "deadbeef".to_string();
        let a = apply_key_salt(base.clone(), Some("toolchain-A"), "crate");
        let b = apply_key_salt(base.clone(), Some("toolchain-B"), "crate");
        // A salt re-keys, and distinct salts produce distinct keys.
        assert_ne!(a, base);
        assert_ne!(b, base);
        assert_ne!(a, b);
        // Deterministic: same (base, salt) → same key.
        assert_eq!(a, apply_key_salt(base, Some("toolchain-A"), "crate"));
    }

    /// Set `name` for the duration of the guard, restoring the previous value
    /// (or absence) on drop. Callers must hold [`key_test_lock`]: the process
    /// environment is global and `apply_key_env_vars` reads all of it.
    struct ScopedEnv {
        name: &'static str,
        previous: Option<std::ffi::OsString>,
    }

    impl ScopedEnv {
        fn set(name: &'static str, value: &str) -> Self {
            let previous = std::env::var_os(name);
            // SAFETY: single-threaded test body under `key_test_lock`.
            unsafe { std::env::set_var(name, value) };
            Self { name, previous }
        }

        fn unset(name: &'static str) -> Self {
            let previous = std::env::var_os(name);
            // SAFETY: single-threaded test body under `key_test_lock`.
            unsafe { std::env::remove_var(name) };
            Self { name, previous }
        }
    }

    impl Drop for ScopedEnv {
        fn drop(&mut self) {
            // SAFETY: single-threaded test body under `key_test_lock`.
            unsafe {
                match self.previous.take() {
                    Some(value) => std::env::set_var(self.name, value),
                    None => std::env::remove_var(self.name),
                }
            }
        }
    }

    #[test]
    fn key_env_var_matches_exact_prefix_and_case() {
        let patterns = vec!["BOLTFFI_*".to_string(), "MODE".to_string()];
        // Trailing `*` is a prefix glob, including the degenerate zero-suffix case.
        assert!(key_env_var_matches(&patterns, "BOLTFFI_BINDING_EXPANSION"));
        assert!(key_env_var_matches(&patterns, "BOLTFFI_"));
        // A bare name matches only itself, not names it is a prefix of.
        assert!(key_env_var_matches(&patterns, "MODE"));
        assert!(!key_env_var_matches(&patterns, "MODE_EXTRA"));
        assert!(!key_env_var_matches(&patterns, "BOLTFF"));
        assert!(!key_env_var_matches(&patterns, "UNRELATED"));
        // ASCII case-insensitive, so a Windows environment behaves like a Unix one.
        assert!(key_env_var_matches(&patterns, "mode"));
        assert!(key_env_var_matches(&patterns, "boltffi_root"));
    }

    #[test]
    fn key_env_var_matches_treats_interior_star_literally() {
        // Only a trailing `*` globs; an interior one is a literal character that
        // no real env var name carries. `normalize_key_env_vars` warns about it.
        let patterns = vec!["A*B".to_string()];
        assert!(!key_env_var_matches(&patterns, "AXB"));
        assert!(!key_env_var_matches(&patterns, "AB"));
        assert!(key_env_var_matches(&patterns, "A*B"));
    }

    #[test]
    fn apply_key_env_vars_no_patterns_is_identity() {
        let base = "deadbeef".to_string();
        // Feature off must leave the key byte-for-byte unchanged — that is what
        // lets this ship without a CACHE_KEY_VERSION bump.
        assert_eq!(apply_key_env_vars(base.clone(), &[], "crate"), base);
        assert_eq!(key_env_guard(&[]), None);
    }

    #[test]
    fn adaptive_key_env_guard_changes_with_the_selected_value() {
        let _lock = key_test_lock();
        let patterns = vec!["KACHE_TEST_ADAPTIVE_ENV".to_string()];
        let first = {
            let _guard = ScopedEnv::set("KACHE_TEST_ADAPTIVE_ENV", "one");
            key_env_guard(&patterns).unwrap()
        };
        let second = {
            let _guard = ScopedEnv::set("KACHE_TEST_ADAPTIVE_ENV", "two");
            key_env_guard(&patterns).unwrap()
        };
        assert_ne!(first, second);
    }

    #[test]
    fn apply_key_env_vars_separates_set_from_unset() {
        let _lock = key_test_lock();
        let base = "deadbeef".to_string();
        let patterns = vec!["KACHE_TEST_EXPANSION".to_string()];

        let unset = {
            let _guard = ScopedEnv::unset("KACHE_TEST_EXPANSION");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        let set_empty = {
            let _guard = ScopedEnv::set("KACHE_TEST_EXPANSION", "");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        let set_one = {
            let _guard = ScopedEnv::set("KACHE_TEST_EXPANSION", "1");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        let set_two = {
            let _guard = ScopedEnv::set("KACHE_TEST_EXPANSION", "2");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };

        // The #635 case: a proc macro branching on this var produces different
        // artifacts from a byte-identical rustc command line, so the two modes
        // must not share a key.
        assert_ne!(unset, set_one);
        assert_ne!(set_one, set_two);
        // `var("X")` distinguishes unset from set-to-empty, so the key must too.
        assert_ne!(unset, set_empty);
        // Declaring the var re-keys even when it is unset. Without this the
        // unset build would land back on the poisoned entry that motivated
        // the declaration in the first place.
        assert_ne!(unset, base);
    }

    #[test]
    fn apply_key_env_vars_matches_by_prefix_glob() {
        let _lock = key_test_lock();
        let base = "deadbeef".to_string();
        let patterns = vec!["KACHE_TEST_PREFIX_*".to_string()];

        let none = {
            let _a = ScopedEnv::unset("KACHE_TEST_PREFIX_MODE");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        let one = {
            let _a = ScopedEnv::set("KACHE_TEST_PREFIX_MODE", "on");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        assert_ne!(none, one);
    }

    #[test]
    fn apply_key_env_vars_is_declaration_order_and_case_independent() {
        use crate::config::normalize_key_env_vars;

        let _lock = key_test_lock();
        let base = "deadbeef".to_string();
        let _a = ScopedEnv::set("KACHE_TEST_ORDER_A", "1");
        let _b = ScopedEnv::set("KACHE_TEST_ORDER_B", "2");

        // The patterns are folded, so any two lists that SELECT the same
        // variables have to reduce to the same bytes — otherwise the feature
        // splits the cache between teammates instead of correcting it.
        // `normalize_key_env_vars` (applied by `Config::load`) does the
        // canonicalizing; this pins that the fold actually depends on it.
        let canonical = normalize_key_env_vars(
            [
                "KACHE_TEST_ORDER_A".to_string(),
                "KACHE_TEST_ORDER_B".to_string(),
            ],
            "test",
        );
        let expected = apply_key_env_vars(base.clone(), &canonical, "crate");
        for spelling in [
            // reordered
            vec![
                "KACHE_TEST_ORDER_B".to_string(),
                "KACHE_TEST_ORDER_A".to_string(),
            ],
            // differently cased (matching is case-insensitive)
            vec![
                "kache_test_order_a".to_string(),
                "Kache_Test_Order_B".to_string(),
            ],
            // duplicated, with stray whitespace
            vec![
                " KACHE_TEST_ORDER_A ".to_string(),
                "KACHE_TEST_ORDER_A".to_string(),
                "KACHE_TEST_ORDER_B".to_string(),
            ],
        ] {
            let normalized = normalize_key_env_vars(spelling.clone(), "test");
            assert_eq!(
                apply_key_env_vars(base.clone(), &normalized, "crate"),
                expected,
                "equivalent declaration {spelling:?} must fold identically"
            );
        }
    }

    /// `(name, value)` pair from string literals, for the digest tests.
    fn pair(name: &str, value: &str) -> (Vec<u8>, Vec<u8>) {
        (name.as_bytes().to_vec(), value.as_bytes().to_vec())
    }

    #[test]
    fn key_env_digest_ignores_environ_order() {
        let patterns = vec!["X*".to_string()];
        // `vars_os` order is platform-defined. Two machines listing the same
        // variables in a different order describe the same environment and must
        // land on the same entry, or the feature splits the cache by host.
        let forward = vec![pair("XA", "1"), pair("XB", "2"), pair("XC", "3")];
        let shuffled = vec![pair("XC", "3"), pair("XA", "1"), pair("XB", "2")];
        assert_eq!(
            key_env_digest(&patterns, forward),
            key_env_digest(&patterns, shuffled)
        );
    }

    #[test]
    fn key_env_digest_preserves_order_when_a_name_repeats() {
        let patterns = vec!["X*".to_string()];
        // A duplicated name is only reachable through a hand-built `envp`, but
        // there `getenv` returns the FIRST occurrence — so the order is
        // semantically observable and sorting it away would be a wrong-hit.
        let first_wins = vec![pair("XA", "1"), pair("XA", "2")];
        let second_wins = vec![pair("XA", "2"), pair("XA", "1")];
        assert_ne!(
            key_env_digest(&patterns, first_wins),
            key_env_digest(&patterns, second_wins)
        );
    }

    #[test]
    fn key_env_digest_separates_names_from_values() {
        let patterns = vec!["X*".to_string()];
        // Swapping which name holds which value is a different environment.
        // Folding the pairs (rather than a bag of values) is what pins that.
        assert_ne!(
            key_env_digest(&patterns, vec![pair("XA", "1"), pair("XB", "2")]),
            key_env_digest(&patterns, vec![pair("XA", "2"), pair("XB", "1")])
        );
    }

    #[test]
    fn env_name_key_bytes_distinguishes_names() {
        use std::ffi::OsStr;
        let a = env_name_key_bytes(OsStr::new("KACHE_TEST_NAME_A"));
        let b = env_name_key_bytes(OsStr::new("KACHE_TEST_NAME_B"));
        // A name that folded to a constant would merge every declared variable
        // into one key component.
        assert!(!a.is_empty());
        assert_ne!(a, b);
    }

    #[test]
    fn env_name_key_bytes_case_policy_follows_the_platform() {
        use std::ffi::OsStr;
        let upper = env_name_key_bytes(OsStr::new("KACHE_TEST_CASE"));
        let mixed = env_name_key_bytes(OsStr::new("Kache_Test_Case"));
        if cfg!(windows) {
            // One variable on Windows: folding the OS's reported casing would
            // split the cache between machines describing the same environment.
            assert_eq!(upper, mixed);
        } else {
            // Two genuinely different variables on Unix.
            assert_ne!(upper, mixed);
        }
    }

    #[test]
    fn env_os_key_bytes_distinguishes_values() {
        use std::ffi::OsStr;
        assert_ne!(
            env_os_key_bytes(OsStr::new("expansion")),
            env_os_key_bytes(OsStr::new("normal"))
        );
        assert!(env_os_key_bytes(OsStr::new("")).is_empty());
    }

    /// Every rustup mechanism that can redirect an unchanged shim binary
    /// must move the tool-version memo key: `RUSTUP_TOOLCHAIN`, the
    /// nearest `rust-toolchain{,.toml}` up from the cwd, and the
    /// `settings.toml` behind `rustup default`.
    #[test]
    fn toolchain_selector_fingerprint_tracks_every_selection_source() {
        use std::ffi::OsStr;
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path().join("workspace").join("member");
        std::fs::create_dir_all(&project).unwrap();

        let base = toolchain_selector_fingerprint(None, Some(&project), None);
        assert_eq!(base, "", "no selection state folds to a stable empty");

        let pinned =
            toolchain_selector_fingerprint(Some(OsStr::new("1.93.0")), Some(&project), None);
        assert_ne!(pinned, base);
        assert_ne!(
            toolchain_selector_fingerprint(Some(OsStr::new("nightly")), Some(&project), None),
            pinned,
            "different overrides must fingerprint differently"
        );

        // The nearest directory with a toolchain file ends the ancestor
        // walk, and BOTH spellings fold so rustup's precedence between
        // them never matters: editing either one moves the fingerprint.
        std::fs::write(dir.path().join("workspace").join("rust-toolchain"), "1.88").unwrap();
        std::fs::write(
            dir.path().join("workspace").join("rust-toolchain.toml"),
            "[toolchain]\nchannel = \"1.90\"\n",
        )
        .unwrap();
        let with_files = toolchain_selector_fingerprint(None, Some(&project), None);
        assert_eq!(with_files.matches(";file:").count(), 2, "{with_files}");
        std::fs::write(dir.path().join("workspace").join("rust-toolchain"), "1.89").unwrap();
        let with_edited = toolchain_selector_fingerprint(None, Some(&project), None);
        assert_ne!(
            with_edited, with_files,
            "editing the bare file must move the fingerprint even though \
             the .toml sibling is untouched"
        );

        let settings = dir.path().join("settings.toml");
        std::fs::write(&settings, "default_toolchain = \"stable\"").unwrap();
        let with_default = toolchain_selector_fingerprint(None, Some(&project), Some(&settings));
        assert!(with_default.contains("default:"), "{with_default}");
        assert_ne!(with_default, base);
        std::fs::write(&settings, "default_toolchain = \"beta\"").unwrap();
        assert_ne!(
            toolchain_selector_fingerprint(None, Some(&project), Some(&settings)),
            with_default,
            "a rustup default switch must move the fingerprint"
        );
    }

    /// Both halves have to hold: a build that asked for predictions but has no
    /// index DB (the daemon's store-free hasher) cannot read one.
    #[test]
    fn predictions_need_both_the_request_and_a_table() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("index.db");
        assert!(
            FileHasher::persistent(&db)
                .with_input_predictions(true)
                .uses_input_predictions()
        );
        assert!(
            !FileHasher::persistent(&db).uses_input_predictions(),
            "a hasher nobody asked must not read records"
        );
        assert!(
            !FileHasher::new()
                .with_input_predictions(true)
                .uses_input_predictions(),
            "asking is not enough without a table to read"
        );
        assert!(!FileHasher::new().uses_input_predictions());
    }

    /// Each refusal reaches a human only through the key trace, so the names
    /// have to be distinct and stable enough to grep a build log for.
    #[test]
    fn every_rejection_names_itself_distinctly() {
        let all = [
            Rejection::Disabled,
            Rejection::NotEligible,
            Rejection::NoRecord,
            Rejection::Missing,
            Rejection::NotRegular,
            Rejection::EnvChanged,
            Rejection::Sibling,
        ];
        let mut names: Vec<&str> = all.iter().map(|r| r.as_str()).collect();
        assert!(
            names.iter().all(|name| !name.is_empty()),
            "a nameless refusal tells a reader nothing: {names:?}"
        );
        let before = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(before, names.len(), "two refusals share a name: {names:?}");
        assert_eq!(Rejection::Disabled.as_str(), "disabled");
        assert_eq!(Rejection::Sibling.as_str(), "sibling");
    }

    /// The wrapper reads this to decide whether a key still owes a
    /// re-derivation, and a stale `true` would make it recompute a key that
    /// was never predicted.
    #[test]
    fn the_prediction_marker_is_taken_once() {
        assert!(
            !take_last_key_used_prediction(),
            "nothing has been predicted on this thread"
        );
        LAST_KEY_USED_PREDICTION.with(|stash| stash.set(true));
        assert!(take_last_key_used_prediction());
        assert!(
            !take_last_key_used_prediction(),
            "taking must clear it, or the next key inherits this one's answer"
        );
    }

    /// With no record and deferral allowed, the key stops instead of running
    /// the pre-pass; the closure the wrapper hands back afterwards is used as
    /// is.
    #[test]
    fn discovery_defers_to_the_compile_and_takes_the_emitted_closure() {
        let _lock = key_test_lock();
        if get_rustc_version(Path::new("rustc")).is_err() {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("index.db");
        let out_dir = dir.path().join("target/debug/deps");
        let args = RustcArgs::parse(
            &[
                "rustc",
                "--crate-name",
                "x",
                "src/lib.rs",
                "--edition",
                "2021",
                "--emit=dep-info,metadata",
                "--out-dir",
                &out_dir.display().to_string(),
            ]
            .iter()
            .map(|a| (*a).to_string())
            .collect::<Vec<_>>(),
        )
        .unwrap();
        assert!(
            rustc_shared_prediction_identity(&args).is_some(),
            "a target directory gives the unit a shared record identity"
        );
        let on = FileHasher::persistent(&db).with_input_predictions(true);

        set_defer_discovery(true);
        let deferred = resolve_key_inputs(&args, &on, "x");
        set_defer_discovery(false);
        let error = deferred.expect_err("no record and deferral allowed: no pre-pass");
        assert!(
            error.downcast_ref::<DeferredDiscovery>().is_some(),
            "{error:#}"
        );

        let emitted = dir.path().join("lib.d");
        std::fs::write(
            &emitted,
            "/w/target/debug/deps/lib.rmeta: /w/src/lib.rs /w/src/inner.rs\n\n\
             /w/src/lib.rs:\n/w/src/inner.rs:\n# env-dep:CARGO_PKG_NAME=lib\n",
        )
        .unwrap();
        let closure = dep_info_from_emitted(&emitted, Path::new("/w/src/lib.rs")).unwrap();
        assert_eq!(
            closure.source_files,
            vec![
                PathBuf::from("/w/src/inner.rs"),
                PathBuf::from("/w/src/lib.rs")
            ]
        );
        assert_eq!(
            closure.env_deps,
            vec![("CARGO_PKG_NAME".to_string(), "lib".to_string())]
        );
        provide_dep_info(closure.clone());
        let used = resolve_key_inputs(&args, &on, "x").unwrap();
        assert_eq!(used, Some(closure));
    }

    /// The two gates in front of a record lookup, each refusing for its own
    /// reason so the trace can say which.
    #[test]
    fn a_record_is_only_consulted_for_an_eligible_invocation() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("index.db");
        let parse = |args: &[&str]| {
            RustcArgs::parse(&args.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        let plain = parse(&["rustc", "src/lib.rs", "--edition", "2021"]);
        let with_macro = parse(&[
            "rustc",
            "src/lib.rs",
            "--edition",
            "2021",
            "--extern",
            "my_macro=/t/debug/deps/libmy_macro-3.so",
        ]);

        let off = FileHasher::persistent(&db);
        assert_eq!(
            predicted_key_inputs(&plain, &off),
            Err(Rejection::Disabled),
            "predictions off must not touch the table"
        );

        let on = FileHasher::persistent(&db).with_input_predictions(true);
        assert_eq!(
            predicted_key_inputs(&with_macro, &on),
            Err(Rejection::NotEligible),
            "a proc-macro dependency outside a registry package is refused before any lookup"
        );
        if get_rustc_version(Path::new("rustc")).is_ok() {
            assert_eq!(
                predicted_key_inputs(&plain, &on),
                Err(Rejection::NoRecord),
                "an eligible invocation with nothing recorded falls back"
            );
        }
    }

    /// A proc macro can scan a directory and emit `include_str!` per entry, so
    /// a file can join the closure with nothing already in it changing. The
    /// pre-pass sees it; a prediction would not. Cargo hands rustc a proc
    /// macro as a dynamic library, and that is the test.
    #[test]
    fn predictions_do_not_apply_to_units_with_a_dynamic_library_dependency() {
        let dep = |path: &str| crate::args::ExternDep {
            name: "dep".to_string(),
            path: Some(PathBuf::from(path)),
        };
        let plain = vec![
            dep("/t/debug/deps/libserde-1.rlib"),
            dep("/t/debug/deps/libcore-2.rmeta"),
        ];
        assert!(
            prediction_applies(&plain),
            "rlib and rmeta dependencies cannot scan the filesystem"
        );
        assert!(
            prediction_applies(&[]),
            "a unit with no dependencies is eligible"
        );

        for macro_lib in [
            "/t/debug/deps/libmy_macro-3.so",
            "/t/debug/deps/libmy_macro-3.dylib",
            "/t/debug/deps/my_macro-3.dll",
        ] {
            let mut with_macro = plain.clone();
            with_macro.push(dep(macro_lib));
            assert!(
                !prediction_applies(&with_macro),
                "{macro_lib} may generate includes the record cannot know about"
            );
        }

        // A dependency cargo passed without a path tells us nothing either way
        // and must not be read as a proc macro.
        assert!(prediction_applies(&[crate::args::ExternDep {
            name: "std".to_string(),
            path: None,
        }]));
    }

    /// `src/foo.rs` and `src/foo/mod.rs` both answer `mod foo;`, and rustc
    /// refuses to choose. Only the two spellings of a module have a sibling;
    /// a crate root is named by argv, so it has none.
    #[test]
    fn mod_sibling_is_the_other_spelling_of_the_same_module() {
        assert_eq!(
            mod_sibling_candidate(Path::new("src/foo.rs")),
            Some(PathBuf::from("src/foo/mod.rs"))
        );
        assert_eq!(
            mod_sibling_candidate(Path::new("src/foo/mod.rs")),
            Some(PathBuf::from("src/foo.rs"))
        );
        for root in ["src/lib.rs", "src/main.rs"] {
            assert_eq!(
                mod_sibling_candidate(Path::new(root)),
                None,
                "{root} is named by argv, not by a mod item"
            );
        }
        assert_eq!(
            mod_sibling_candidate(Path::new("assets/data.json")),
            None,
            "an included asset is not a module"
        );
    }

    /// The verification knob is the measurement of the soundness argument on
    /// real code, so its parsing has to be exact about what turns it on.
    #[test]
    fn verify_predictions_parses_its_three_modes() {
        for on in ["always", "ALWAYS", "1", "true", "True"] {
            assert_eq!(
                parse_verify_predictions(Some(on)),
                VerifyPredictions::Always,
                "{on} must verify every prediction"
            );
        }
        for sampled in ["sampled", "SAMPLED"] {
            assert_eq!(
                parse_verify_predictions(Some(sampled)),
                VerifyPredictions::Sampled
            );
        }
        for off in [Some("off"), Some("0"), Some("false"), Some(""), None] {
            assert_eq!(
                parse_verify_predictions(off),
                VerifyPredictions::Off,
                "{off:?} must not cost a pre-pass"
            );
        }

        assert!(!should_verify_this_prediction(
            VerifyPredictions::Off,
            "unit"
        ));
        assert!(should_verify_this_prediction(
            VerifyPredictions::Always,
            "unit"
        ));

        // Sampling is decided by the identity, because the wrapper is a fresh
        // process per compile. A rolling counter would start at zero every
        // time and select every unit, which is how `sampled` silently became
        // `always` and made a nightly measure the cost of both paths.
        let identities: Vec<String> = (0..VERIFY_PREDICTION_RATE * 20)
            .map(|i| format!("identity-{i}"))
            .collect();
        let chosen = identities
            .iter()
            .filter(|id| should_verify_this_prediction(VerifyPredictions::Sampled, id))
            .count();
        assert!(
            (5..=40).contains(&chosen),
            "about 1 in {VERIFY_PREDICTION_RATE} of {} should be checked, got {chosen}",
            identities.len()
        );
        assert!(
            identities
                .iter()
                .any(|id| !should_verify_this_prediction(VerifyPredictions::Sampled, id)),
            "sampling that selects everything is not sampling"
        );

        // Stable: the same unit is checked on every build, so a disagreement
        // is reproducible instead of a one-off nobody can chase.
        let first = identities
            .iter()
            .find(|id| should_verify_this_prediction(VerifyPredictions::Sampled, id))
            .expect("some identity must be selected");
        for _ in 0..5 {
            assert!(should_verify_this_prediction(
                VerifyPredictions::Sampled,
                first
            ));
        }
    }

    /// Two closures naming the same files agree however they are ordered: the
    /// key sorts both before folding, so order cannot change a key and must
    /// not be reported as a disagreement.
    #[test]
    fn closures_agree_on_content_not_order() {
        let dep = |sources: &[&str], env: &[(&str, &str)]| DepInfo {
            source_files: sources.iter().map(PathBuf::from).collect(),
            env_deps: env
                .iter()
                .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                .collect(),
        };
        let a = dep(&["src/lib.rs", "src/helper.rs"], &[("OUT_DIR", "/t")]);
        let reordered = dep(&["src/helper.rs", "src/lib.rs"], &[("OUT_DIR", "/t")]);
        assert!(closures_agree(&a, &reordered));

        assert!(!closures_agree(
            &a,
            &dep(
                &["src/lib.rs", "src/helper.rs", "src/extra.rs"],
                &[("OUT_DIR", "/t")]
            )
        ));
        assert!(!closures_agree(
            &a,
            &dep(&["src/lib.rs"], &[("OUT_DIR", "/t")])
        ));
        assert!(!closures_agree(
            &a,
            &dep(&["src/lib.rs", "src/helper.rs"], &[])
        ));
        assert!(!closures_agree(
            &a,
            &dep(&["src/lib.rs", "src/helper.rs"], &[("OUT_DIR", "/other")])
        ));
    }

    /// The rules, one refusal at a time. Each is a claim that the recorded
    /// closure no longer describes what rustc would read.
    #[test]
    fn a_prediction_is_validated_against_the_tree_as_it_is_now() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let lib = src.join("lib.rs");
        let helper = src.join("helper.rs");
        std::fs::write(&lib, "mod helper;\n").unwrap();
        std::fs::write(&helper, "pub fn n() {}\n").unwrap();

        let record = InputPrediction {
            schema: PREDICTION_SCHEMA,
            sources: vec![lib.clone(), helper.clone()],
            env_deps: vec![("OUT_DIR".to_string(), "/t/build/out".to_string())],
            tree: None,
        };
        let stat = |path: &Path| std::fs::metadata(path).ok();
        let exists = |path: &Path| path.exists();
        let env = |var: &str| (var == "OUT_DIR").then(|| "/t/build/out".to_string());

        let accepted = validate_prediction(&record, stat, exists, env)
            .expect("an unchanged tree must reuse the recorded closure");
        assert_eq!(accepted.source_files, record.sources);
        assert_eq!(accepted.env_deps, record.env_deps);

        // The value the key normalises to a sentinel still has to match raw:
        // a moved OUT_DIR is how an included generated file changes identity
        // without any recorded file changing.
        assert_eq!(
            validate_prediction(&record, stat, exists, |var| (var == "OUT_DIR")
                .then(|| "/t/build/other".to_string())),
            Err(Rejection::EnvChanged)
        );
        assert_eq!(
            validate_prediction(&record, stat, exists, |_| None),
            Err(Rejection::EnvChanged),
            "an unset variable is not the value that was recorded"
        );

        // A file that is gone: the pre-pass would fail too, and the build
        // passes through to rustc's own error.
        std::fs::remove_file(&helper).unwrap();
        assert_eq!(
            validate_prediction(&record, stat, exists, env),
            Err(Rejection::Missing)
        );

        // A path that is no longer a regular file.
        std::fs::create_dir(&helper).unwrap();
        assert_eq!(
            validate_prediction(&record, stat, exists, env),
            Err(Rejection::NotRegular)
        );
        std::fs::remove_dir(&helper).unwrap();
        std::fs::write(&helper, "pub fn n() {}\n").unwrap();

        // Both spellings of `mod helper;` present: rustc errors (E0761), so
        // replaying a recorded success would restore an artifact for a build
        // that should fail.
        std::fs::create_dir(src.join("helper")).unwrap();
        std::fs::write(src.join("helper/mod.rs"), "pub fn n() {}\n").unwrap();
        assert_eq!(
            validate_prediction(&record, stat, exists, env),
            Err(Rejection::Sibling)
        );
    }

    /// The dep-info parser emits `VAR=` both when the variable is unset and
    /// when it is empty, so validation must accept both for an empty record:
    /// otherwise any crate reading an unset `option_env!` would reject every
    /// record and pay a pre-pass on every warm build. A recorded value still
    /// rejects an unset variable.
    #[test]
    fn an_unset_variable_matches_an_empty_record() {
        let dir = tempfile::tempdir().unwrap();
        let lib = dir.path().join("lib.rs");
        std::fs::write(&lib, "pub fn f() {}\n").unwrap();
        let stat = |path: &Path| std::fs::metadata(path).ok();
        let exists = |path: &Path| path.exists();
        let empty = InputPrediction {
            schema: PREDICTION_SCHEMA,
            sources: vec![lib.clone()],
            env_deps: vec![("KACHE_PROBE_UNSET".to_string(), String::new())],
            tree: None,
        };
        assert!(
            validate_prediction(&empty, stat, exists, |_| None).is_ok(),
            "unset matches empty, exactly as the parser would fold it"
        );
        let valued = InputPrediction {
            schema: PREDICTION_SCHEMA,
            sources: vec![lib],
            env_deps: vec![("KACHE_PROBE_UNSET".to_string(), "1".to_string())],
            tree: None,
        };
        assert_eq!(
            validate_prediction(&valued, stat, exists, |_| None),
            Err(Rejection::EnvChanged)
        );
    }

    /// A prediction is only reusable by an invocation that would discover the
    /// same files. Every part of the identity is one such "would discover the
    /// same files" claim, so perturbing any of them has to produce a different
    /// row rather than a wrong answer.
    #[test]
    fn prediction_identity_separates_every_part_it_folds() {
        let base_args: Vec<String> = ["--edition", "2021", "--crate-name", "demo"]
            .iter()
            .map(|a| (*a).to_string())
            .collect();
        let base_env = |extra: &[(&str, &str)]| -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
            let mut env: Vec<(std::ffi::OsString, std::ffi::OsString)> = vec![(
                std::ffi::OsString::from("CARGO_CFG_TARGET_OS"),
                std::ffi::OsString::from("linux"),
            )];
            env.extend(
                extra
                    .iter()
                    .map(|(k, v)| (std::ffi::OsString::from(k), std::ffi::OsString::from(v))),
            );
            env
        };
        let base_parts = PredictionIdentityParts {
            rustc_version: "rustc 1.95.0",
            inner_rustc: None,
            current_dir: Some(Path::new("/w/one")),
            source_file: Path::new("src/lib.rs"),
            closure_args: &base_args,
            skip_path_remap: false,
        };
        let base = prediction_identity_in_env(&base_parts, base_env(&[]));

        assert_eq!(
            prediction_identity_in_env(&base_parts, base_env(&[])),
            base,
            "the same invocation twice is the same identity"
        );

        let other_args: Vec<String> = ["--edition", "2024", "--crate-name", "demo"]
            .iter()
            .map(|a| (*a).to_string())
            .collect();
        let perturbed: Vec<(&str, PredictionIdentityParts<'_>)> = vec![
            (
                "a different compiler build",
                PredictionIdentityParts {
                    rustc_version: "rustc 1.96.0",
                    ..base_parts
                },
            ),
            (
                "a wrapped inner compiler",
                PredictionIdentityParts {
                    inner_rustc: Some(Path::new("/usr/bin/rustc")),
                    ..base_parts
                },
            ),
            (
                "another working directory, which relative args resolve against",
                PredictionIdentityParts {
                    current_dir: Some(Path::new("/w/two")),
                    ..base_parts
                },
            ),
            (
                "another crate root",
                PredictionIdentityParts {
                    source_file: Path::new("src/main.rs"),
                    ..base_parts
                },
            ),
            (
                "an edition change, which changes what resolves",
                PredictionIdentityParts {
                    closure_args: &other_args,
                    ..base_parts
                },
            ),
            (
                "path remapping turned off",
                PredictionIdentityParts {
                    skip_path_remap: true,
                    ..base_parts
                },
            ),
        ];
        for (what, parts) in perturbed {
            assert_ne!(
                prediction_identity_in_env(&parts, base_env(&[])),
                base,
                "{what} must not reuse another invocation's record"
            );
        }

        // The environment the key already folds, one variable at a time.
        for var in PREDICTION_ENV {
            assert_ne!(
                prediction_identity_in_env(&base_parts, base_env(&[(var, "value")])),
                base,
                "{var} must separate identities"
            );
        }
        // Set-but-empty is not unset: `env!` can tell them apart.
        assert_ne!(
            prediction_identity_in_env(&base_parts, base_env(&[("RUSTFLAGS", "")])),
            base,
            "an empty RUSTFLAGS is not an absent one"
        );
        // A cfg change can add or remove whole modules.
        let mut other_cfg = base_env(&[]);
        other_cfg[0].1 = std::ffi::OsString::from("windows");
        assert_ne!(
            prediction_identity_in_env(&base_parts, other_cfg),
            base,
            "CARGO_CFG_* changes which modules compile"
        );
        // Unrelated environment must NOT separate identities: folding it
        // wholesale is what kept the cc preprocessor memo from ever hitting
        // (kunobi-ninja/kache#927).
        assert_eq!(
            prediction_identity_in_env(&base_parts, base_env(&[("PWD", "/somewhere/else")])),
            base,
            "variables that do not change what rustc reads must not be folded"
        );
    }

    /// An invocation with no crate root discovers no closure, so it has no
    /// identity — and two invocations that read different files must not share
    /// one.
    ///
    /// The comparisons run against one environment snapshot rather than the
    /// live process environment: other tests in this binary set and unset
    /// variables concurrently, which would otherwise decide the result.
    #[test]
    fn rustc_prediction_identity_needs_a_crate_root_and_separates_units() {
        // The identity also reads cwd, which other tests change under this lock.
        let _lock = crate::test_support::process_state_test_lock();
        let parse = |args: &[&str]| {
            RustcArgs::parse(&args.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        assert_eq!(
            rustc_prediction_identity(&parse(&["rustc", "--version"])),
            None,
            "a query invocation compiles nothing and predicts nothing"
        );

        if get_rustc_version(Path::new("rustc")).is_err() {
            return; // no compiler on this host; nothing to identify against
        }
        let env: Vec<(std::ffi::OsString, std::ffi::OsString)> = vec![(
            std::ffi::OsString::from("CARGO_CFG_TARGET_OS"),
            std::ffi::OsString::from("linux"),
        )];
        let identity = |args: &[&str]| {
            rustc_prediction_identity_in_env(&parse(args), env.clone())
                .expect("a crate root gives an identity")
        };

        let lib = identity(&["rustc", "src/lib.rs", "--edition", "2021"]);
        assert!(!lib.is_empty());
        assert_ne!(
            lib,
            identity(&["rustc", "src/main.rs", "--edition", "2021"]),
            "different crate roots read different files"
        );
        assert_ne!(
            lib,
            identity(&["rustc", "src/lib.rs", "--edition", "2024"]),
            "a different edition resolves differently"
        );

        // Output naming is not identity: these two read the same files.
        assert_eq!(
            lib,
            identity(&[
                "rustc",
                "src/lib.rs",
                "--edition",
                "2021",
                "-C",
                "extra-filename=-abc123",
            ]),
            "two units of one crate share a record"
        );
    }

    /// The identity is the argv that shapes the closure, not the argv that
    /// names the output. Two units of one crate differing only in where their
    /// artifacts land read exactly the same files.
    #[test]
    fn prediction_identity_ignores_output_naming_flags() {
        let closure = |extra: &[&str]| -> Vec<String> {
            let mut args: Vec<String> = ["--edition", "2021"]
                .iter()
                .map(|a| (*a).to_string())
                .collect();
            args.extend(extra.iter().map(|a| (*a).to_string()));
            closure_shaping_args(Path::new("src/lib.rs"), &args)
        };
        let plain = closure(&[]);
        for naming in [
            vec!["-C", "extra-filename=-abc123"],
            vec!["--out-dir", "/target/debug/deps"],
            vec!["--emit=metadata,link"],
        ] {
            assert_eq!(
                closure(&naming),
                plain,
                "{naming:?} decides where output goes, not what rustc reads"
            );
        }
        assert_ne!(
            closure(&["--cfg", "feature=\"extra\""]),
            plain,
            "a cfg can add a module, so it stays in the identity"
        );
    }

    #[test]
    fn shared_predictions_only_virtualize_dependency_paths() {
        let map = |target: &str, args: &[&str]| {
            shared_prediction_args(
                &args.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
                Path::new(target),
            )
        };
        for (left, right) in [
            (
                vec!["--extern", "dep=/a/target/debug/libdep.rlib"],
                vec!["--extern", "dep=/b/target/debug/libdep.rlib"],
            ),
            (
                vec!["--extern=dep=/a/target/debug/libdep.rmeta"],
                vec!["--extern=dep=/b/target/debug/libdep.rmeta"],
            ),
            (
                vec!["-L", "dependency=/a/target/debug/deps"],
                vec!["-L", "dependency=/b/target/debug/deps"],
            ),
            (
                vec!["-Lnative=/a/target/debug/build/out"],
                vec!["-Lnative=/b/target/debug/build/out"],
            ),
            (
                vec!["-L/a/target/debug/deps"],
                vec!["-L/b/target/debug/deps"],
            ),
        ] {
            assert_eq!(map("/a/target", &left), map("/b/target", &right));
        }
        for (left, right) in [
            (
                vec!["--cfg", "path=\"/a/target/value\""],
                vec!["--cfg", "path=\"/b/target/value\""],
            ),
            (
                vec!["/a/target/generated.rs"],
                vec!["/b/target/generated.rs"],
            ),
            (
                vec!["--extern", "a=/a/target/lib.rlib"],
                vec!["--extern", "b=/b/target/lib.rlib"],
            ),
            (
                vec!["--extern", "a=/a/target/lib.rlib"],
                vec!["--extern", "a=/b/target/other.rlib"],
            ),
            (
                vec!["-Lnative=/a/target/lib"],
                vec!["-Ldependency=/b/target/lib"],
            ),
            (
                vec!["--extern", "a=/a/target-extra/lib.rlib"],
                vec!["--extern", "a=/b/target-extra/lib.rlib"],
            ),
            (
                vec!["--extern", "a=/a/target/../lib.rlib"],
                vec!["--extern", "a=/b/target/../lib.rlib"],
            ),
        ] {
            assert_ne!(map("/a/target", &left), map("/b/target", &right));
        }
        let encoded = map("/a/target", &["-L/a/target/lib"]);
        assert_ne!(encoded, map("/a/target", &[&encoded[0]]));
    }

    #[test]
    fn shared_predictions_reject_target_sources() {
        let _lock = crate::test_support::process_state_test_lock();
        let root = tempfile::tempdir().unwrap();
        let target = root.path().join("target");
        let args = RustcArgs::parse(&[
            "rustc".into(),
            "src/lib.rs".into(),
            "--out-dir".into(),
            target.join("debug/deps").to_string_lossy().into_owned(),
        ])
        .unwrap();
        let mut dep = DepInfo {
            source_files: vec![root.path().join("src/lib.rs")],
            env_deps: vec![],
        };
        assert!(shared_prediction_can_record(&args, &dep));
        dep.source_files
            .push(target.join("debug/build/pkg/out/generated.rs"));
        assert!(!shared_prediction_can_record(&args, &dep));
        let no_target = RustcArgs::parse(&["rustc".into(), "src/lib.rs".into()]).unwrap();
        assert!(!shared_prediction_can_record(&no_target, &dep));
    }

    /// What is written has to be exactly what comes back, or a prediction
    /// would reproduce a different `sources` group than the pre-pass did.
    #[test]
    fn input_prediction_round_trips_through_the_database() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("index.db");
        let dep_info = DepInfo {
            source_files: vec![
                PathBuf::from("/w/src/lib.rs"),
                PathBuf::from("/w/src/generated.rs"),
            ],
            env_deps: vec![("OUT_DIR".to_string(), "/target/build/out".to_string())],
        };

        let hasher = FileHasher::persistent(&db);
        assert!(hasher.supports_input_predictions());
        assert_eq!(
            hasher.input_prediction("unit"),
            None,
            "an identity never recorded has no prediction"
        );
        hasher.record_input_prediction("unit", Some("demo"), &dep_info, None);

        let record = FileHasher::persistent(&db)
            .input_prediction("unit")
            .expect("the recorded closure must survive a new process");
        assert_eq!(record.schema, PREDICTION_SCHEMA);
        assert_eq!(record.sources, dep_info.source_files);
        assert_eq!(record.env_deps, dep_info.env_deps);

        // Re-recording replaces rather than accumulates.
        let narrower = DepInfo {
            source_files: vec![PathBuf::from("/w/src/lib.rs")],
            env_deps: Vec::new(),
        };
        FileHasher::persistent(&db).record_input_prediction(
            "unit",
            Some("demo"),
            &narrower,
            Some("tree-digest".to_string()),
        );
        let record = FileHasher::persistent(&db)
            .input_prediction("unit")
            .unwrap();
        assert_eq!(record.sources, narrower.source_files);
        assert!(record.env_deps.is_empty());
        assert_eq!(record.tree.as_deref(), Some("tree-digest"));
    }

    /// The tree guard: a record for a proc-macro-dependent unit is only usable
    /// while the crate's files are exactly what they were, wherever the tree
    /// lives.
    #[test]
    fn crate_tree_digest_tracks_content_names_and_exclusions() {
        let _lock = crate::test_support::process_state_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("registry/src/index-abc/pkg-1.0.0");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
        std::fs::write(root.join("Cargo.toml"), "[package]\n").unwrap();
        let hasher = FileHasher::new();
        // SAFETY: the process-state lock serialises environment edits.
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", &root) };
        unsafe { std::env::remove_var("OUT_DIR") };
        let baseline = crate_tree_digest(&hasher).unwrap();

        std::fs::write(root.join("src/lib.rs"), "pub fn b() {}\n").unwrap();
        assert_ne!(crate_tree_digest(&hasher).unwrap(), baseline, "content");
        std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
        assert_eq!(
            crate_tree_digest(&hasher).unwrap(),
            baseline,
            "restored content"
        );

        std::fs::write(root.join("src/extra.txt"), "x").unwrap();
        assert_ne!(crate_tree_digest(&hasher).unwrap(), baseline, "a new file");
        std::fs::remove_file(root.join("src/extra.txt")).unwrap();

        std::fs::create_dir_all(root.join("target/debug")).unwrap();
        std::fs::write(root.join("target/debug/x"), "x").unwrap();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git/HEAD"), "ref").unwrap();
        assert_eq!(
            crate_tree_digest(&hasher).unwrap(),
            baseline,
            "build and git dirs"
        );

        // The same tree elsewhere digests the same: the guard follows content.
        let copy = dir.path().join("other/registry/src/index-def/pkg-1.0.0");
        std::fs::create_dir_all(copy.join("src")).unwrap();
        std::fs::write(copy.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
        std::fs::write(copy.join("Cargo.toml"), "[package]\n").unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", &copy) };
        assert_eq!(
            crate_tree_digest(&hasher).unwrap(),
            baseline,
            "relocated tree"
        );
        let workspace = dir.path().join("workspace/member");
        std::fs::create_dir_all(workspace.join("src")).unwrap();
        unsafe { std::env::set_var("CARGO_MANIFEST_DIR", &workspace) };
        assert!(
            crate_tree_digest(&hasher).is_none(),
            "a workspace crate keeps the pre-pass"
        );
        unsafe { std::env::remove_var("CARGO_MANIFEST_DIR") };
        assert!(
            crate_tree_digest(&hasher).is_none(),
            "no crate directory, no guard"
        );
    }

    /// A row this build cannot vouch for reads as absent. The cost of that is
    /// one pre-pass; the cost of guessing at an unknown encoding is a key
    /// derived from someone else's rules.
    #[test]
    fn a_prediction_from_another_schema_is_not_read() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("index.db");
        let hasher = FileHasher::persistent(&db);
        let cache = hasher.cache.as_ref().unwrap();

        cache
            .put_input_prediction("future", PREDICTION_SCHEMA + 1, None, "{\"anything\":1}")
            .unwrap();
        assert_eq!(hasher.input_prediction("future"), None);

        // A row whose column says the right schema but whose bytes do not
        // decode is the same answer.
        cache
            .put_input_prediction("corrupt", PREDICTION_SCHEMA, None, "not json")
            .unwrap();
        assert_eq!(hasher.input_prediction("corrupt"), None);

        // And a row whose stored schema disagrees with its own payload.
        let stale = format!(
            "{{\"schema\":{},\"sources\":[],\"env_deps\":[]}}",
            PREDICTION_SCHEMA + 1
        );
        cache
            .put_input_prediction("mismatched", PREDICTION_SCHEMA, None, &stale)
            .unwrap();
        assert_eq!(hasher.input_prediction("mismatched"), None);
    }

    /// A hasher with no database has nowhere to keep a record. The daemon's
    /// store-free hasher is exactly this case, and it must not panic or
    /// pretend to have recorded anything.
    #[test]
    fn recording_without_a_database_is_a_no_op() {
        let hasher = FileHasher::new();
        assert!(!hasher.supports_input_predictions());
        hasher.record_input_prediction(
            "unit",
            None,
            &DepInfo {
                source_files: vec![PathBuf::from("/w/src/lib.rs")],
                env_deps: Vec::new(),
            },
            None,
        );
        assert_eq!(hasher.input_prediction("unit"), None);
    }

    #[test]
    fn cargo_cfg_pairs_filters_and_sorts() {
        use std::ffi::OsString;
        let pairs = cargo_cfg_pairs(
            [
                (OsString::from("CARGO_CFG_ZED"), OsString::from("1")),
                (OsString::from("PATH"), OsString::from("/usr/bin")),
                (OsString::from("CARGO_CFG_ABI"), OsString::from("eabi")),
                (OsString::from("CARGO_PKG_NAME"), OsString::from("x")),
            ]
            .into_iter(),
        );
        assert_eq!(
            pairs,
            vec![
                (OsString::from("CARGO_CFG_ABI"), OsString::from("eabi")),
                (OsString::from("CARGO_CFG_ZED"), OsString::from("1")),
            ]
        );
    }

    /// A non-UTF-8 variable anywhere in the environment used to panic the
    /// whole key computation via `std::env::vars()`; now the unrelated
    /// variable is filtered out and a `CARGO_CFG_*` pair survives with its
    /// exact bytes.
    #[cfg(unix)]
    #[test]
    fn cargo_cfg_pairs_tolerates_non_utf8_environments() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;
        let invalid = OsString::from_vec(vec![b'a', 0xff, b'b']);
        let pairs = cargo_cfg_pairs(
            [
                (OsString::from_vec(vec![0xff, 0xfe]), invalid.clone()),
                (OsString::from("CARGO_CFG_RAW"), invalid.clone()),
            ]
            .into_iter(),
        );
        assert_eq!(pairs, vec![(OsString::from("CARGO_CFG_RAW"), invalid)]);
    }

    /// Valid UTF-8 folds byte-identically to the old `vars()`-string
    /// hashing (no key change without a version bump); invalid sequences
    /// fold losslessly and distinctly instead of merging under U+FFFD.
    #[test]
    fn env_text_key_bytes_preserves_utf8_and_distinguishes_invalid() {
        use std::ffi::OsStr;
        assert_eq!(
            env_text_key_bytes(OsStr::new("target_os=\"linux\"")),
            b"target_os=\"linux\"".to_vec()
        );
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            let a = env_text_key_bytes(OsStr::from_bytes(&[b'x', 0xff]));
            let b = env_text_key_bytes(OsStr::from_bytes(&[b'x', 0xfe]));
            assert_ne!(a, b);
            // Tagged: cannot collide with any valid-UTF-8 value's bytes.
            assert_eq!(a[0], 0xff);
        }
    }

    /// The write persists where the read looks, creating the cache directory
    /// on a fresh machine. Skipped where that directory cannot be created
    /// (a sandboxed build with no writable home).
    #[test]
    fn tool_version_cache_write_is_read_back() {
        let cache_dir = crate::config::default_cache_dir();
        if std::fs::create_dir_all(&cache_dir).is_err()
            || tempfile::tempfile_in(&cache_dir).is_err()
        {
            eprintln!("skipping: {} is not writable", cache_dir.display());
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let binary = dir.path().join("rustc-probe");
        std::fs::write(&binary, b"not really rustc").unwrap();
        let prefix = "kache-test-version";
        let cache_file = tool_version_cache_path(&binary, prefix).unwrap();
        let _ = std::fs::remove_file(&cache_file);
        assert_eq!(read_tool_version_cache(&binary, prefix), None);

        write_tool_version_cache(&binary, prefix, "rustc 1.0.0 (test)");
        assert_eq!(
            read_tool_version_cache(&binary, prefix).as_deref(),
            Some("rustc 1.0.0 (test)")
        );
        assert_eq!(
            std::fs::read_to_string(&cache_file).unwrap(),
            "rustc 1.0.0 (test)",
            "the file is exactly the version string, as before"
        );
        let _ = std::fs::remove_file(&cache_file);
    }

    #[cfg(unix)]
    #[test]
    fn clippy_identity_follows_version_config_and_lint_arguments() {
        use std::os::unix::fs::PermissionsExt;
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let driver = dir.path().join("clippy-driver");
        std::fs::write(
            &driver,
            "#!/bin/sh\necho 'clippy 0.1.98 (abc 2026-09-01)'\n",
        )
        .unwrap();
        std::fs::set_permissions(&driver, std::fs::Permissions::from_mode(0o755)).unwrap();
        let workspace = dir.path().join("ws");
        let member = workspace.join("member");
        std::fs::create_dir_all(&member).unwrap();
        let env = |vars: Vec<(&'static str, String)>| {
            move |name: &str| {
                vars.iter()
                    .find(|(n, _)| *n == name)
                    .map(|(_, v)| std::ffi::OsString::from(v))
            }
        };
        let manifest = vec![("CARGO_MANIFEST_DIR", member.display().to_string())];

        let bare = clippy_identity_in(&driver, env(manifest.clone()), None).unwrap();
        assert!(bare.starts_with("clippy 0.1.98"));
        assert!(bare.contains("config:none"));
        assert!(bare.contains("manifest:none"));

        // The package manifest feeds the `cargo` lint group.
        std::fs::write(member.join("Cargo.toml"), "[package]\nname = \"m\"\n").unwrap();
        let with_manifest = clippy_identity_in(&driver, env(manifest.clone()), None).unwrap();
        assert_ne!(with_manifest, bare);
        std::fs::write(
            member.join("Cargo.toml"),
            "[package]\nname = \"m\"\ndescription = \"d\"\n",
        )
        .unwrap();
        assert_ne!(
            clippy_identity_in(&driver, env(manifest.clone()), None).unwrap(),
            with_manifest
        );
        let bare = clippy_identity_in(&driver, env(manifest.clone()), None).unwrap();

        // A configuration file above the member is found and keyed by content.
        std::fs::write(workspace.join("clippy.toml"), "msrv = \"1.80\"\n").unwrap();
        let configured = clippy_identity_in(&driver, env(manifest.clone()), None).unwrap();
        assert_ne!(configured, bare);
        assert!(configured.contains("config:clippy.toml:"));
        std::fs::write(workspace.join("clippy.toml"), "msrv = \"1.85\"\n").unwrap();
        let edited = clippy_identity_in(&driver, env(manifest.clone()), None).unwrap();
        assert_ne!(edited, configured);

        // `CLIPPY_CONF_DIR` wins over the manifest directory, and the lint
        // arguments Cargo passes through the environment are part of it.
        let elsewhere = dir.path().join("conf");
        std::fs::create_dir_all(&elsewhere).unwrap();
        std::fs::write(elsewhere.join(".clippy.toml"), "").unwrap();
        let mut with_conf_dir = manifest.clone();
        with_conf_dir.push(("CLIPPY_CONF_DIR", elsewhere.display().to_string()));
        let redirected = clippy_identity_in(&driver, env(with_conf_dir.clone()), None).unwrap();
        assert!(redirected.contains("config:.clippy.toml:"));
        with_conf_dir.push(("CLIPPY_ARGS", "-Dclippy::all".to_string()));
        let with_args = clippy_identity_in(&driver, env(with_conf_dir), None).unwrap();
        assert_ne!(with_args, redirected);
        assert!(with_args.contains("CLIPPY_ARGS=-Dclippy::all"));
    }

    #[test]
    fn tool_version_cache_path_is_a_named_file_in_the_cache_dir() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let binary = dir.path().join("rustc");
        std::fs::write(&binary, b"test rustc").unwrap();

        let cache_file = tool_version_cache_path(&binary, "rustc-ver")
            .expect("a readable binary must produce a cache path");
        let cache_dir = crate::config::default_cache_dir();
        assert_eq!(cache_file.parent(), Some(cache_dir.as_path()));

        let file_name = cache_file
            .file_name()
            .expect("cache path must name a file")
            .to_string_lossy();
        let digest = file_name
            .strip_prefix("rustc-ver-")
            .and_then(|name| name.strip_suffix(".txt"))
            .expect("cache file must retain its prefix and extension");
        assert_eq!(digest.len(), 16, "cache file uses the short BLAKE3 digest");
        assert!(digest.bytes().all(|byte| byte.is_ascii_hexdigit()));
    }

    #[test]
    #[ignore = "spawned by the explicit RUSTUP_HOME regression"]
    fn rustup_settings_path_explicit_home_fixture() {
        let expected_home = std::env::var_os("KACHE_TEST_RUSTUP_HOME")
            .map(std::path::PathBuf::from)
            .expect("fixture requires its isolated expected home");

        assert_eq!(
            rustup_settings_path(),
            Some(expected_home.join("settings.toml"))
        );
    }

    #[test]
    fn tool_version_cache_uses_settings_under_explicit_rustup_home() {
        let dir = tempfile::tempdir().unwrap();
        let output = std::process::Command::new(
            std::env::current_exe().expect("resolve cache-key test executable"),
        )
        .args([
            "--ignored",
            "--exact",
            "cache_key::tests::rustup_settings_path_explicit_home_fixture",
            "--test-threads=1",
        ])
        .env("RUSTUP_HOME", dir.path())
        .env("KACHE_TEST_RUSTUP_HOME", dir.path())
        .output()
        .expect("spawn isolated RUSTUP_HOME fixture");

        assert!(
            output.status.success(),
            "isolated RUSTUP_HOME fixture failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn apply_key_env_vars_keeps_distinct_path_values_distinct() {
        let _lock = key_test_lock();
        let base = "deadbeef".to_string();
        let patterns = vec!["KACHE_TEST_ROOT".to_string()];

        // Deliberately NOT path-normalized. A declared variable is an opaque
        // semantic input — a macro may paste its value straight into the code
        // it emits — so two checkout paths that would collapse to the same
        // `<BASE_DIR>` sentinel must still key apart. This costs cross-machine
        // hits for path-valued declarations and buys back the exact miscompile
        // the feature exists to prevent.
        let alice = {
            let _guard = ScopedEnv::set("KACHE_TEST_ROOT", "/home/alice/proj/src");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        let bob = {
            let _guard = ScopedEnv::set("KACHE_TEST_ROOT", "/srv/build/bob/checkout/src");
            apply_key_env_vars(base.clone(), &patterns, "crate")
        };
        assert_ne!(alice, bob, "declared env values must be folded exactly");
    }

    #[cfg(unix)]
    #[test]
    fn apply_key_env_vars_distinguishes_non_utf8_values() {
        use std::os::unix::ffi::OsStrExt;

        let _lock = key_test_lock();
        let base = "deadbeef".to_string();
        let patterns = vec!["KACHE_TEST_RAW".to_string()];

        // Both byte strings lossy-convert to the same U+FFFD text, and a proc
        // macro reading `var_os` can still tell them apart — so folding the
        // lossy form would be a wrong-hit path.
        let key_for = |bytes: &[u8]| {
            let previous = std::env::var_os("KACHE_TEST_RAW");
            // SAFETY: single-threaded test body under `key_test_lock`.
            unsafe { std::env::set_var("KACHE_TEST_RAW", std::ffi::OsStr::from_bytes(bytes)) };
            let key = apply_key_env_vars(base.clone(), &patterns, "crate");
            // SAFETY: as above.
            unsafe {
                match previous {
                    Some(value) => std::env::set_var("KACHE_TEST_RAW", value),
                    None => std::env::remove_var("KACHE_TEST_RAW"),
                }
            }
            key
        };
        assert_ne!(key_for(&[0xff]), key_for(&[0xfe]));
    }

    #[test]
    fn apply_key_salt_distinguishes_base_keys() {
        // The same salt over different base keys stays distinct (the
        // base is mixed into the hash, not just the salt).
        let salt = Some("nix-rev-abc");
        assert_ne!(
            apply_key_salt("aaaa".to_string(), salt, "crate"),
            apply_key_salt("bbbb".to_string(), salt, "crate"),
        );
    }

    #[test]
    fn source_scanner_detects_runtime_env_use_and_skips_literals() {
        use super::source_has_runtime_env_dep_use as scan;

        // A bare runtime env! use is a real dependency.
        assert!(scan(r#"const X: &str = env!("MYVAR");"#, "MYVAR"));
        assert!(scan(r#"let v = option_env!("MYVAR");"#, "MYVAR"));
        // A different var name doesn't match.
        assert!(!scan(r#"env!("OTHER")"#, "MYVAR"));

        // env! nested inside include!(concat!(...)) is a compile-time include,
        // not a runtime value — must NOT count.
        assert!(!scan(
            r#"include!(concat!(env!("MYVAR"), "/gen.rs"));"#,
            "MYVAR"
        ));

        // Occurrences inside string / char / raw-string literals and comments
        // are not real uses — the scanner must skip them.
        assert!(!scan(r#"let s = "env!(\"MYVAR\")";"#, "MYVAR"));
        assert!(!scan(r###"let s = r#"env!("MYVAR")"#;"###, "MYVAR"));
        assert!(!scan(r#"// env!("MYVAR")"#, "MYVAR"));
        assert!(!scan(r#"/* env!("MYVAR") */"#, "MYVAR"));

        // A char literal earlier in the line must not derail scanning of a real
        // use that follows it (exercises skip_char_literal).
        assert!(scan(r#"let c = '"'; let x = env!("MYVAR");"#, "MYVAR"));
        // A real use after a raw string is still found (exercises skip_raw_string).
        assert!(scan(r###"let r = r#"noise"#; env!("MYVAR")"###, "MYVAR"));
    }

    #[test]
    fn unescape_env_dep_value_undoes_rustc_escaping() {
        // rustc's `escape_dep_env`: `\`→`\\`, newline→`\n`, CR→`\r`.
        // A Windows OUT_DIR arrives doubled; unescaping restores the
        // single-backslash path so the normalizer's rules can match it.
        assert_eq!(
            unescape_env_dep_value(r"C:\\actions-runner\\proj\\target\\out"),
            r"C:\actions-runner\proj\target\out"
        );
        assert_eq!(unescape_env_dep_value(r"a\nb\rc"), "a\nb\rc");
        // Forward-slash / plain values (the Unix case) are untouched.
        assert_eq!(
            unescape_env_dep_value("/home/u/proj/out"),
            "/home/u/proj/out"
        );
        assert_eq!(unescape_env_dep_value("plain-value"), "plain-value");
    }

    #[test]
    fn parse_env_dep_info_unescapes_windows_paths() {
        let dep = "# env-dep:OUT_DIR=C:\\\\proj\\\\build\\\\out\n";
        let deps = parse_env_dep_info(dep);
        assert_eq!(
            deps,
            vec![("OUT_DIR".to_string(), r"C:\proj\build\out".to_string())]
        );
    }

    #[test]
    fn test_cache_key_deterministic() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition=2021".to_string(),
            "-C".to_string(),
            "opt-level=2".to_string(),
        ];

        let parsed1 = RustcArgs::parse(&args_vec).unwrap();
        let parsed2 = RustcArgs::parse(&args_vec).unwrap();

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();
        assert_eq!(key1, key2);
    }

    /// Regression for Finding B from the Firefox bench: mozbuild sets
    /// `-Clinker=/abs/path/to/clang++`, and v6 baked that path into the
    /// key — every clone hashed differently. The linker's semantic
    /// identity is still captured via `linker:<--version>` so the key
    /// stays sensitive to a different toolchain.
    #[test]
    fn cache_key_ignores_linker_path() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mk = |linker: &str| -> Vec<String> {
            vec![
                "rustc".to_string(),
                "--crate-name".to_string(),
                "mylib".to_string(),
                source.to_string_lossy().to_string(),
                "--crate-type".to_string(),
                "lib".to_string(),
                "-C".to_string(),
                format!("linker={linker}"),
            ]
        };

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let a = compute_cache_key(
            &RustcArgs::parse(&mk("/Users/alice/clang++")).unwrap(),
            &fh,
            &pn,
        )
        .unwrap();
        let b = compute_cache_key(
            &RustcArgs::parse(&mk("/home/runner/clang++")).unwrap(),
            &fh,
            &pn,
        )
        .unwrap();
        assert_eq!(a, b, "linker path must not affect the cache key");
    }

    /// Shared base argv for the flag-keying regression tests below.
    fn flag_base(source: &Path, extra: &[&str]) -> Vec<String> {
        let mut v = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "cdylib".to_string(),
        ];
        v.extend(extra.iter().map(|s| s.to_string()));
        v
    }

    fn key_of(args: &[String]) -> String {
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        compute_cache_key(&RustcArgs::parse(args).unwrap(), &fh, &pn).unwrap()
    }

    /// Compute a key for tests that check whether a *flag* (sysroot, custom
    /// target spec, `-Z` codegen flag, cross `--target`, ...) affects the key,
    /// independent of source discovery. Such flags can make the real
    /// `--emit=dep-info` pre-pass fail (a bogus `--sysroot` where rustc can't
    /// find `std`, a `-Z` flag on a stable toolchain, an uninstalled
    /// cross-target's missing `std`); since kunobi-ninja/kache#323 a failing
    /// pre-pass is a hard error (the invocation becomes non-cacheable), so this
    /// clears `source_file` to exercise flag hashing directly.
    fn key_of_flags(args: &[String]) -> String {
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let mut parsed = RustcArgs::parse(args).unwrap();
        parsed.source_file = None;
        compute_cache_key(&parsed, &fh, &pn).unwrap()
    }

    /// H1: build-script `-l` link libs reach rustc on argv (not via
    /// RUSTFLAGS); a different native lib must diverge the key.
    /// Generic `-l` keying, checked on hosts that do not probe native MSVC
    /// inputs. On a Windows host the library must exist (fail closed), so the
    /// Windows shape lives in the `windows_*` tests with an injected probe.
    #[cfg(not(windows))]
    #[test]
    fn link_lib_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let none = key_of(&flag_base(&source, &[]));
        let ssl = key_of(&flag_base(&source, &["-l", "ssl"]));
        let crypto = key_of(&flag_base(&source, &["-l", "crypto"]));
        assert_ne!(none, ssl, "adding -l must change the key");
        assert_ne!(ssl, crypto, "a different -l lib must change the key");
        // Attached form parses identically to the separate form.
        assert_eq!(ssl, key_of(&flag_base(&source, &["-lssl"])));
    }

    #[test]
    fn clean_static_lib_name_accepts_only_plain_static() {
        assert_eq!(clean_static_lib_name("static=foo"), Some("foo"));
        // Modifiers, a :RENAME, other kinds, and bare names are all rejected so
        // the caller falls back to name-only rather than mis-resolve / over-key.
        assert_eq!(clean_static_lib_name("static:+verbatim=foo"), None);
        assert_eq!(clean_static_lib_name("static:-bundle=foo"), None);
        assert_eq!(clean_static_lib_name("static=foo:bar"), None);
        assert_eq!(clean_static_lib_name("dylib=foo"), None);
        assert_eq!(clean_static_lib_name("foo"), None);
        assert_eq!(clean_static_lib_name("static="), None);
    }

    #[test]
    fn resolve_native_static_lib_hashes_only_unambiguous_static_archives() {
        let fh = FileHasher::new();
        let dir = tempfile::tempdir().unwrap();
        let lib = dir.path().join("libfoo.a");
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let dirs = vec![dir.path().to_path_buf()];

        // A `static=` lib present in a search dir resolves and content-hashes.
        let (path, h1) = resolve_native_static_lib("static=foo", &dirs, &fh, StaticLibUse::Bundled)
            .unwrap()
            .expect("static lib in a search dir must resolve");
        assert_eq!(path, lib);

        // `cc` emits the same OUT_DIR once per compiled archive. Repeating an
        // identical `-L native=...` must still resolve the one physical file.
        let duplicate_dirs = vec![dir.path().to_path_buf(), dir.path().to_path_buf()];
        let (duplicate_path, _) =
            resolve_native_static_lib("static=foo", &duplicate_dirs, &fh, StaticLibUse::Bundled)
                .unwrap()
                .expect("duplicate search dirs must not make one archive ambiguous");
        assert_eq!(duplicate_path, lib);

        // Changed bytes → different hash (this is the false hit we close).
        std::fs::write(&lib, b"v2 different bytes").unwrap();
        let (_, h2) = resolve_native_static_lib("static=foo", &dirs, &fh, StaticLibUse::Bundled)
            .unwrap()
            .unwrap();
        assert_ne!(h1, h2, "content change must change the resolved hash");

        // `dylib=`/bare are referenced not bundled → never content-hashed; a
        // missing lib and a modifier/rename spec also do not resolve.
        assert!(
            resolve_native_static_lib("dylib=foo", &dirs, &fh, StaticLibUse::Bundled)
                .unwrap()
                .is_none()
        );
        assert!(
            resolve_native_static_lib("foo", &dirs, &fh, StaticLibUse::Bundled)
                .unwrap()
                .is_none()
        );
        assert!(
            resolve_native_static_lib("static:+verbatim=foo", &dirs, &fh, StaticLibUse::Bundled)
                .unwrap()
                .is_none()
        );
        assert!(
            resolve_native_static_lib("static=absent", &dirs, &fh, StaticLibUse::Bundled)
                .unwrap()
                .is_none()
        );

        // Distinct matches remain uncacheable, so we never hash a file other
        // than the one rustc actually picked.
        let other_dir = tempfile::tempdir().unwrap();
        std::fs::write(other_dir.path().join("libfoo.a"), b"different archive").unwrap();
        assert!(
            resolve_native_static_lib(
                "static=foo",
                &[dir.path().to_path_buf(), other_dir.path().to_path_buf()],
                &fh,
                StaticLibUse::Bundled,
            )
            .is_err(),
            "distinct search-dir matches must fail closed"
        );

        // Both platform filename conventions in one directory are also
        // ambiguous.
        std::fs::write(dir.path().join("foo.lib"), b"msvc import lib").unwrap();
        assert!(
            resolve_native_static_lib("static=foo", &dirs, &fh, StaticLibUse::Bundled).is_err(),
            "ambiguous .a/.lib match must fail closed"
        );
    }

    #[test]
    fn native_linker_side_files_fail_closed() {
        let parsed = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-C".to_string(),
            "link-arg=-Wl,-order_file,/tmp/order.txt".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(&parsed));

        let response_file = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Clink-arg=@/tmp/ld.rsp".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(&response_file));

        for apple_dynamic_path in [
            "link-arg=-Wl,-rpath,@loader_path",
            "link-arg=-Wl,-rpath,@loader_path/../lib",
            "link-arg=-Wl,-rpath,@rpath",
            "link-arg=-Wl,-install_name,@executable_path",
            "link-arg=-Wl,-install_name,@executable_path/lib/libfoo.dylib",
        ] {
            let parsed = RustcArgs::parse(&[
                "rustc".to_string(),
                "src/lib.rs".to_string(),
                "-C".to_string(),
                apple_dynamic_path.to_string(),
                "--target=aarch64-apple-darwin".to_string(),
            ])
            .unwrap();
            assert!(
                !native_linker_side_files_are_unmodeled(&parsed),
                "Apple dynamic path is not a response file: {apple_dynamic_path}"
            );
        }

        let forwarded_response_file = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-C".to_string(),
            "link-arg=-Wl,@/tmp/ld.rsp".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(
            &forwarded_response_file
        ));

        for long_codegen_response_file in [
            "--codegen=link-arg=@/tmp/ld.rsp",
            "--codegen=link-args=-Wl,@/tmp/ld.rsp",
        ] {
            let parsed = RustcArgs::parse(&[
                "rustc".to_string(),
                "src/lib.rs".to_string(),
                long_codegen_response_file.to_string(),
            ])
            .unwrap();
            assert!(
                native_linker_side_files_are_unmodeled(&parsed),
                "long codegen response file must fail closed: {long_codegen_response_file}"
            );
        }

        let non_apple_at_rpath = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Clink-arg=-Wl,@rpath".to_string(),
            "--target=x86_64-unknown-linux-gnu".to_string(),
        ])
        .unwrap();
        assert!(
            native_linker_side_files_are_unmodeled(&non_apple_at_rpath),
            "Apple dynamic-token exemptions must not hide non-Apple response files"
        );

        let custom_apple_named_target = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Clink-arg=-Wl,@rpath".to_string(),
            "--target=/tmp/aarch64-apple-darwin.json".to_string(),
        ])
        .unwrap();
        assert!(
            native_linker_side_files_are_unmodeled(&custom_apple_named_target),
            "an Apple-looking custom target is not proof of Apple linker semantics"
        );

        let rust_target_path_name = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Clink-arg=-Wl,@rpath".to_string(),
            "--target=aarch64-apple-custom".to_string(),
        ])
        .unwrap();
        assert!(
            native_linker_side_files_are_unmodeled(&rust_target_path_name),
            "a RUST_TARGET_PATH name is not proof of built-in Apple semantics"
        );

        let map_file = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Clink-arg=-Wl,-map,/tmp/link.map".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(&map_file));

        let lld_map_file = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "--codegen=link-arg=-Wl,--Map=/tmp/link.map".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(&lld_map_file));

        let coff_map_file = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            r"--codegen=link-arg=/MAP:C:\tmp\link.map".to_string(),
        ])
        .unwrap();
        assert!(native_linker_side_files_are_unmodeled(&coff_map_file));

        for ordering_file in [
            "--codegen=link-arg=-Wl,--symbol-ordering-file=/tmp/order.txt",
            r"--codegen=link-arg=/call-graph-ordering-file:C:\tmp\order.txt",
            r"--codegen=link-arg=/ORDER:@C:\tmp\order.txt",
        ] {
            let parsed = RustcArgs::parse(&[
                "rustc".to_string(),
                "src/lib.rs".to_string(),
                ordering_file.to_string(),
            ])
            .unwrap();
            assert!(
                native_linker_side_files_are_unmodeled(&parsed),
                "linker ordering files must fail closed: {ordering_file}"
            );
        }

        let ordinary = RustcArgs::parse(&[
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "-Copt-level=2".to_string(),
        ])
        .unwrap();
        assert!(!native_linker_side_files_are_unmodeled(&ordinary));

        let fh = FileHasher::new();
        let dir = tempfile::tempdir().unwrap();
        let lib = dir.path().join("libfoo.a");
        std::fs::write(&lib, gnu_ar_one_object(b"object")).unwrap();
        // Exact member identity is retained even without a side-file option,
        // because this archive may be bundled into an rlib and linked later.
        std::fs::write(&lib, gnu_ar_named_object("foo.o", b"same object")).unwrap();
        let named_foo = fh.hash_static_lib(&lib).unwrap();
        std::fs::write(&lib, gnu_ar_named_object("bar.o", b"same object")).unwrap();
        let named_bar = fh.hash_static_lib(&lib).unwrap();
        assert_ne!(named_foo, named_bar);

        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn probe() {}").unwrap();
        let guarded = RustcArgs::parse(&flag_base(
            &source,
            &[
                "-l",
                "static=foo",
                "-C",
                "link-arg=-Wl,-order_file,/tmp/order.txt",
            ],
        ))
        .unwrap();
        let error = compute_cache_key(&guarded, &fh, &PathNormalizer::empty()).unwrap_err();
        assert!(error.to_string().contains("side files are not cacheable"));
    }

    fn elf64le_relocatable(payload: &[u8]) -> Vec<u8> {
        let mut object = vec![0_u8; 64];
        object[..4].copy_from_slice(b"\x7fELF");
        object[4] = 2; // ELFCLASS64
        object[5] = 1; // ELFDATA2LSB
        object[6] = 1; // EV_CURRENT
        object[16..18].copy_from_slice(&1_u16.to_le_bytes()); // ET_REL
        object[18..20].copy_from_slice(&62_u16.to_le_bytes()); // EM_X86_64
        object[20..24].copy_from_slice(&1_u32.to_le_bytes());
        object[52..54].copy_from_slice(&64_u16.to_le_bytes());
        object[58..60].copy_from_slice(&64_u16.to_le_bytes());
        object[60..62].copy_from_slice(&3_u16.to_le_bytes());
        object[62..64].copy_from_slice(&2_u16.to_le_bytes());

        let payload_offset = object.len();
        object.extend_from_slice(payload);
        let names_offset = object.len();
        let names = b"\0.data\0.shstrtab\0";
        object.extend_from_slice(names);
        while !object.len().is_multiple_of(8) {
            object.push(0);
        }
        let section_offset = object.len();
        object.resize(section_offset + 3 * 64, 0);
        object[40..48].copy_from_slice(&(section_offset as u64).to_le_bytes());

        let payload_header = section_offset + 64;
        object[payload_header..payload_header + 4].copy_from_slice(&1_u32.to_le_bytes());
        object[payload_header + 4..payload_header + 8].copy_from_slice(&1_u32.to_le_bytes());
        object[payload_header + 24..payload_header + 32]
            .copy_from_slice(&(payload_offset as u64).to_le_bytes());
        object[payload_header + 32..payload_header + 40]
            .copy_from_slice(&(payload.len() as u64).to_le_bytes());
        object[payload_header + 48..payload_header + 56].copy_from_slice(&1_u64.to_le_bytes());

        let names_header = section_offset + 2 * 64;
        object[names_header..names_header + 4].copy_from_slice(&7_u32.to_le_bytes());
        object[names_header + 4..names_header + 8].copy_from_slice(&3_u32.to_le_bytes());
        object[names_header + 24..names_header + 32]
            .copy_from_slice(&(names_offset as u64).to_le_bytes());
        object[names_header + 32..names_header + 40]
            .copy_from_slice(&(names.len() as u64).to_le_bytes());
        object[names_header + 48..names_header + 56].copy_from_slice(&1_u64.to_le_bytes());
        object
    }

    /// A minimal single-object GNU `ar` archive (no symtab / long-name table).
    fn gnu_ar_raw_named_object(name: &str, object: &[u8]) -> Vec<u8> {
        assert!(!name.is_empty() && name.len() <= 15 && !name.contains('/'));
        let mut a = b"!<arch>\n".to_vec();
        let member_name = format!("{name}/");
        let mut h = format!("{member_name:<16}").into_bytes();
        h.extend_from_slice(format!("{:<12}", 0).as_bytes()); // mtime
        h.extend_from_slice(format!("{:<6}", 0).as_bytes()); // uid
        h.extend_from_slice(format!("{:<6}", 0).as_bytes()); // gid
        h.extend_from_slice(format!("{:<8}", "100644").as_bytes()); // mode
        h.extend_from_slice(format!("{:<10}", object.len()).as_bytes()); // size
        h.extend_from_slice(b"`\n");
        assert_eq!(h.len(), 60);
        a.extend_from_slice(&h);
        a.extend_from_slice(object);
        if object.len() % 2 == 1 {
            a.push(b'\n');
        }
        a
    }

    fn gnu_ar_one_object(payload: &[u8]) -> Vec<u8> {
        gnu_ar_named_object("object.o", payload)
    }

    fn gnu_ar_named_object(name: &str, payload: &[u8]) -> Vec<u8> {
        gnu_ar_raw_named_object(name, &elf64le_relocatable(payload))
    }

    #[test]
    fn hash_static_lib_caches_and_is_namespace_isolated() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::persistent(&dir.path().join("index.db"));
        let lib = dir.path().join("libbig.a");
        // >MIN_PERSISTED_HASH_BYTES so it takes the cached path.
        std::fs::write(&lib, gnu_ar_one_object(&vec![0x41u8; 70_000])).unwrap();

        let portable = fh.hash_static_lib(&lib).unwrap();
        assert!(
            portable.starts_with("gnu-ar-v2:"),
            "a GNU archive gets the structural member digest"
        );
        // Second call returns the SAME value (cache round-trip, not corruption).
        assert_eq!(fh.hash_static_lib(&lib).unwrap(), portable);

        // Namespace isolation: a whole-file hash of the SAME path is a plain-hex
        // digest under a different cache row — it must not be the static-lib value.
        let whole = fh.hash(&lib).unwrap();
        assert!(!whole.starts_with("gnu-ar-v2:"));
        assert_ne!(whole, portable);
        // And the static-lib digest is still the portable one after `hash` ran.
        assert_eq!(fh.hash_static_lib(&lib).unwrap(), portable);
    }

    #[test]
    fn hash_static_lib_ignores_legacy_namespaces() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::persistent(&dir.path().join("index.db"));
        let lib = dir.path().join("libbig.a");
        std::fs::write(&lib, gnu_ar_one_object(&vec![0x41_u8; 70_000])).unwrap();

        let fingerprint = FileFingerprint::from_path(&lib).unwrap();
        let legacy_key = FileFingerprint {
            path: format!("static-ar-v1\0{}", fingerprint.path),
            ..fingerprint.clone()
        };
        let legacy_v2_key = FileFingerprint {
            path: format!("static-ar-v2\0{}", fingerprint.path),
            ..fingerprint.clone()
        };
        let legacy_v3_key = FileFingerprint {
            path: format!("static-ar-v3\0{}", fingerprint.path),
            ..fingerprint.clone()
        };
        let legacy_v4_key = FileFingerprint {
            path: format!("static-ar-v4\0{}", fingerprint.path),
            ..fingerprint.clone()
        };
        let legacy_v5_key = FileFingerprint {
            path: format!("static-ar-v5\0{}", fingerprint.path),
            ..fingerprint.clone()
        };
        let current_key = FileFingerprint {
            path: format!("static-ar-v6\0{}", fingerprint.path),
            ..fingerprint
        };
        let cache = fh.cache.as_ref().expect("persistent cache opens");
        cache
            .put(&legacy_key, "legacy-whole-file-sentinel")
            .unwrap();
        cache.put(&legacy_v2_key, "legacy-member-sentinel").unwrap();
        cache
            .put(&legacy_v3_key, "legacy-unguarded-object-sentinel")
            .unwrap();
        cache
            .put(&legacy_v4_key, "legacy-unguarded-macho-sentinel")
            .unwrap();
        cache
            .put(&legacy_v5_key, "legacy-path-bound-dwarf-sentinel")
            .unwrap();

        let computed = fh.hash_static_lib(&lib).unwrap();
        assert!(computed.starts_with("gnu-ar-v2:"));
        assert_ne!(computed, "legacy-whole-file-sentinel");
        assert_ne!(computed, "legacy-member-sentinel");
        assert_ne!(computed, "legacy-unguarded-object-sentinel");
        assert_ne!(computed, "legacy-unguarded-macho-sentinel");
        assert_ne!(computed, "legacy-path-bound-dwarf-sentinel");
        fh.flush_memo();
        assert_eq!(cache.get(&current_key).unwrap(), Some(computed.clone()));
        assert_eq!(fh.hash_static_lib(&lib).unwrap(), computed);
    }

    #[test]
    fn hash_static_lib_v3_memo_cannot_bypass_object_gate() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::persistent(&dir.path().join("index.db"));
        let lib = dir.path().join("libbitcode.a");
        let mut bitcode = vec![0_u8; 70_000];
        bitcode[..4].copy_from_slice(b"BC\xc0\xde");
        std::fs::write(&lib, gnu_ar_raw_named_object("bitcode.o", &bitcode)).unwrap();

        let fingerprint = FileFingerprint::from_path(&lib).unwrap();
        let stale_key = FileFingerprint {
            path: format!("static-ar-v3\0{}", fingerprint.path),
            ..fingerprint
        };
        let cache = fh.cache.as_ref().expect("persistent cache opens");
        cache.put(&stale_key, "gnu-ar-v2:unguarded").unwrap();

        let computed = fh.hash_static_lib(&lib).unwrap();
        assert!(computed.starts_with("path-ar-v1:"));
        assert_ne!(computed, "gnu-ar-v2:unguarded");
    }

    #[test]
    fn static_lib_fallback_binds_lexical_archive_path() {
        let dir = tempfile::tempdir().unwrap();
        let first_dir = dir.path().join("PerfUtils");
        let second_dir = dir.path().join("OtherName");
        std::fs::create_dir_all(&first_dir).unwrap();
        std::fs::create_dir_all(&second_dir).unwrap();
        let first = first_dir.join("libsame.a");
        let second = second_dir.join("libsame.a");
        std::fs::write(&first, b"unsupported but identical archive bytes").unwrap();
        std::fs::write(&second, b"unsupported but identical archive bytes").unwrap();

        let fh = FileHasher::new();
        let first_hash = fh.hash_static_lib(&first).unwrap();
        let second_hash = fh.hash_static_lib(&second).unwrap();
        assert!(first_hash.starts_with("path-ar-v1:"));
        assert!(second_hash.starts_with("path-ar-v1:"));
        assert_ne!(first_hash, second_hash);
    }

    #[test]
    fn static_lib_use_follows_executable_output() {
        let use_of = |crate_type: &str, test: bool| {
            let mut argv = vec![
                "rustc".to_string(),
                "src/lib.rs".to_string(),
                "--crate-type".to_string(),
                crate_type.to_string(),
            ];
            if test {
                argv.push("--test".to_string());
            }
            static_lib_use(&RustcArgs::parse(&argv).unwrap())
        };
        assert_eq!(use_of("lib", false), StaticLibUse::Bundled);
        assert_eq!(use_of("rlib", false), StaticLibUse::Bundled);
        assert_eq!(use_of("bin", false), StaticLibUse::Linked);
        assert_eq!(use_of("cdylib", false), StaticLibUse::Linked);
        assert_eq!(use_of("proc-macro", false), StaticLibUse::Linked);
        assert_eq!(use_of("lib", true), StaticLibUse::Linked);
    }

    /// A DWARF-bearing Mach-O archive shares its structural digest across
    /// checkouts only when rustc bundles it into an rlib. An invocation that
    /// links it itself writes the archive's absolute path into `N_OSO`, so
    /// the digest stays path-bound there.
    #[test]
    fn linked_dwarf_archive_stays_path_bound() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::new();
        let hash_in = |name: &str, bytes: &[u8], usage: StaticLibUse| {
            let lib_dir = dir.path().join(name);
            std::fs::create_dir_all(&lib_dir).unwrap();
            let lib = lib_dir.join("libprobe.a");
            std::fs::write(&lib, bytes).unwrap();
            fh.hash_static_lib_for(&lib, usage).unwrap()
        };

        let dwarf = crate::native_archive::dwarf_bsd_archive_for_tests(b"debug");
        let bundled = hash_in("a", &dwarf, StaticLibUse::Bundled);
        assert!(bundled.starts_with("bsd-ar-v2:"));
        assert_eq!(bundled, hash_in("b", &dwarf, StaticLibUse::Bundled));

        let linked = hash_in("a", &dwarf, StaticLibUse::Linked);
        assert!(linked.starts_with("path-ar-v1:"));
        assert_ne!(linked, hash_in("b", &dwarf, StaticLibUse::Linked));
        // The unqualified method is the linked reading.
        assert_eq!(
            fh.hash_static_lib(&dir.path().join("a/libprobe.a"))
                .unwrap(),
            linked
        );

        // Without DWARF, a linked archive keeps the structural digest.
        let plain = gnu_ar_one_object(b"object");
        let linked_plain = hash_in("c", &plain, StaticLibUse::Linked);
        assert!(linked_plain.starts_with("gnu-ar-v2:"));
        assert_eq!(linked_plain, hash_in("d", &plain, StaticLibUse::Linked));
    }

    #[test]
    fn hash_static_lib_memo_rows_are_per_use() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::persistent(&dir.path().join("index.db"));
        let lib = dir.path().join("libbig.a");
        // Large enough for the persistent memo.
        std::fs::write(
            &lib,
            crate::native_archive::dwarf_bsd_archive_for_tests(&vec![0x41_u8; 70_000]),
        )
        .unwrap();

        let bundled = fh.hash_static_lib_for(&lib, StaticLibUse::Bundled).unwrap();
        let linked = fh.hash_static_lib_for(&lib, StaticLibUse::Linked).unwrap();
        assert!(bundled.starts_with("bsd-ar-v2:"));
        assert!(linked.starts_with("path-ar-v1:"));
        assert_eq!(
            fh.hash_static_lib_for(&lib, StaticLibUse::Bundled).unwrap(),
            bundled
        );

        fh.flush_memo();
        let fingerprint = FileFingerprint::from_path(&lib).unwrap();
        let cache = fh.cache.as_ref().expect("persistent cache opens");
        for (namespace, expected) in [
            ("static-ar-v6-bundled", &bundled),
            ("static-ar-v6", &linked),
        ] {
            let key = FileFingerprint {
                path: format!("{namespace}\0{}", fingerprint.path),
                ..fingerprint.clone()
            };
            assert_eq!(cache.get(&key).unwrap().as_ref(), Some(expected));
        }
    }

    /// Archives under `MIN_PERSISTED_HASH_BYTES` are hashed without a memo
    /// row; one of exactly that size gets a row.
    #[test]
    fn hash_static_lib_memo_threshold_is_exclusive() {
        let dir = tempfile::tempdir().unwrap();
        let fh = FileHasher::persistent(&dir.path().join("index.db"));
        let cache = fh.cache.as_ref().expect("persistent cache opens");
        let threshold = usize::try_from(MIN_PERSISTED_HASH_BYTES).unwrap();
        for (name, len, memoized) in [
            ("libsmall.a", threshold - 1, false),
            ("libexact.a", threshold, true),
        ] {
            let lib = dir.path().join(name);
            std::fs::write(&lib, vec![b'x'; len]).unwrap();
            let hash = fh.hash_static_lib(&lib).unwrap();
            fh.flush_memo();
            let fingerprint = FileFingerprint::from_path(&lib).unwrap();
            let key = FileFingerprint {
                path: format!("static-ar-v6\0{}", fingerprint.path),
                ..fingerprint
            };
            let expected = memoized.then_some(hash);
            assert_eq!(cache.get(&key).unwrap(), expected, "{name}");
        }
    }

    #[test]
    fn thin_static_archive_is_uncacheable() {
        let dir = tempfile::tempdir().unwrap();
        let archive = dir.path().join("libthin.a");
        std::fs::write(&archive, b"!<thin>\n").unwrap();

        let error = FileHasher::new().hash_static_lib(&archive).unwrap_err();
        assert!(error.to_string().contains("external members"));
    }

    /// The cardinal #421 false hit: a `static=` native lib whose content changes
    /// in place (same `-l` name, same normalized `-L` path) must change the key.
    #[test]
    fn native_static_lib_content_change_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let libdir = dir.path().join("out");
        std::fs::create_dir_all(&libdir).unwrap();
        let lib = libdir.join("libfoo.a");
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let search = format!("native={}", libdir.display());
        let flags = ["-L", search.as_str(), "-l", "static=foo"];

        let k1 = key_of(&flag_base(&source, &flags));
        std::fs::write(&lib, b"v2 archive bytes - DIFFERENT").unwrap();
        let k2 = key_of(&flag_base(&source, &flags));
        assert_ne!(
            k1, k2,
            "a native static lib content change must change the key (#421)"
        );
        // Content-addressed: the original bytes reproduce the original key.
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let k3 = key_of(&flag_base(&source, &flags));
        assert_eq!(k1, k3, "identical bytes must reproduce the key");
    }

    /// `cc::Build::compile` emits its OUT_DIR for every archive it creates.
    /// Repeating that directory must not make the one archive uncacheable.
    #[test]
    fn duplicate_native_search_dir_keeps_static_lib_cacheable() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let libdir = dir.path().join("out");
        std::fs::create_dir_all(&libdir).unwrap();
        std::fs::write(libdir.join("libfoo.a"), b"archive bytes").unwrap();
        let search = format!("native={}", libdir.display());
        let flags = [
            "-L",
            search.as_str(),
            "-L",
            search.as_str(),
            "-l",
            "static=foo",
        ];

        assert!(!key_of(&flag_base(&source, &flags)).is_empty());
    }

    /// A `dylib=` lib is referenced at runtime, not bundled into the output, so
    /// its content must NOT enter the key (guards against over-keying).
    /// Generic `-l` keying, checked on hosts that do not probe native MSVC
    /// inputs. On a Windows host the library must exist (fail closed), so the
    /// Windows shape lives in the `windows_*` tests with an injected probe.
    #[cfg(not(windows))]
    #[test]
    fn native_dylib_content_does_not_change_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let libdir = dir.path().join("out");
        std::fs::create_dir_all(&libdir).unwrap();
        let lib = libdir.join("libfoo.so");
        std::fs::write(&lib, b"so v1").unwrap();
        let search = format!("native={}", libdir.display());
        let flags = ["-L", search.as_str(), "-l", "dylib=foo"];

        let k1 = key_of(&flag_base(&source, &flags));
        std::fs::write(&lib, b"so v2 changed").unwrap();
        let k2 = key_of(&flag_base(&source, &flags));
        assert_eq!(k1, k2, "a dynamic lib's content must not key the consumer");
    }

    /// rustc's default `-L` kind is `all`, which searches native libs too, so a
    /// `static=` lib found under `-L all=<dir>` must be content-keyed (#421).
    #[test]
    fn native_static_lib_in_all_search_dir_is_keyed() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let libdir = dir.path().join("out");
        std::fs::create_dir_all(&libdir).unwrap();
        let lib = libdir.join("libfoo.a");
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let search = format!("all={}", libdir.display());
        let flags = ["-L", search.as_str(), "-l", "static=foo"];

        let k1 = key_of(&flag_base(&source, &flags));
        std::fs::write(&lib, b"v2 archive bytes - DIFFERENT").unwrap();
        let k2 = key_of(&flag_base(&source, &flags));
        assert_ne!(
            k1, k2,
            "a static lib under `-L all=` must be content-keyed too (#421)"
        );
    }

    /// Rustc's `-O` / `-g` shorthands must share keys with their exact `-C`
    /// equivalents rather than living in the unmodeled residual bucket.
    #[test]
    fn codegen_shorthands_match_explicit_forms() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let base = key_of_flags(&flag_base(&source, &[]));
        let debug = key_of_flags(&flag_base(&source, &["-g"]));
        let opt = key_of_flags(&flag_base(&source, &["-O"]));
        let explicit_debug = key_of_flags(&flag_base(&source, &["-Cdebuginfo=2"]));
        let explicit_opt = key_of_flags(&flag_base(&source, &["-Copt-level=3"]));
        let long_debug = key_of_flags(&flag_base(&source, &["--codegen=debuginfo=2"]));
        let long_opt = key_of_flags(&flag_base(&source, &["--codegen", "opt-level=3"]));
        assert_ne!(base, debug, "`-g` must change the key");
        assert_ne!(base, opt, "`-O` must change the key");
        assert_ne!(debug, opt, "`-g` and `-O` must produce distinct keys");
        assert_eq!(debug, explicit_debug, "`-g` is `-Cdebuginfo=2`");
        assert_eq!(opt, explicit_opt, "`-O` is `-Copt-level=3`");
        assert_eq!(debug, long_debug, "`--codegen` is the long `-C` alias");
        assert_eq!(opt, long_opt, "separated `--codegen` must match `-C`");
    }

    #[test]
    fn codegen_shorthand_override_order_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let shorthand_then_explicit =
            key_of_flags(&flag_base(&source, &["-O", "--codegen=opt-level=0"]));
        let explicit_then_shorthand =
            key_of_flags(&flag_base(&source, &["--codegen", "opt-level=0", "-O"]));

        assert_ne!(
            shorthand_then_explicit, explicit_then_shorthand,
            "rustc applies optimization flags last-wins, so opposite orders must not collide"
        );
    }

    #[test]
    fn frontend_jobs_spellings_share_a_key_and_values_remain_ordered() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let none = key_of_flags(&flag_base(&source, &[]));
        let separated = key_of_flags(&flag_base(&source, &["--jobs-frontend", "16"]));
        let attached = key_of_flags(&flag_base(&source, &["--jobs-frontend=16"]));
        let different = key_of_flags(&flag_base(&source, &["--jobs-frontend=8"]));
        let order_4_8 = key_of_flags(&flag_base(
            &source,
            &["--jobs-frontend=4", "--jobs-frontend=8"],
        ));
        let order_8_4 = key_of_flags(&flag_base(
            &source,
            &["--jobs-frontend=8", "--jobs-frontend=4"],
        ));

        assert_ne!(none, attached, "frontend jobs must affect the key");
        assert_eq!(separated, attached, "both rustc spellings are equivalent");
        assert_ne!(attached, different, "worker count must affect the key");
        assert_ne!(
            order_4_8, order_8_4,
            "repeated last-wins values must preserve argv order"
        );
    }

    #[test]
    fn response_file_flags_share_inline_key_and_track_contents() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let response = dir.path().join("rustc.args");
        let at_response = format!("@{}", response.display());

        std::fs::write(&response, "--cfg\nresponse_v1\n-C\nopt-level=1\n").unwrap();
        let inline = key_of_flags(&flag_base(
            &source,
            &["--cfg", "response_v1", "-C", "opt-level=1"],
        ));
        let response_v1 = key_of_flags(&flag_base(&source, &[&at_response]));
        assert_eq!(
            response_v1, inline,
            "transporting identical flags through @file must not change the key"
        );

        std::fs::write(&response, "--cfg\nresponse_v2\n-C\nopt-level=2\n").unwrap();
        let response_v2 = key_of_flags(&flag_base(&source, &[&at_response]));
        assert_ne!(
            response_v1, response_v2,
            "rewriting the same response-file path must change the effective key"
        );
    }

    /// kunobi-ninja/kache#324: residual tokens are sorted before folding, so
    /// argv order does not perturb the key (the fold is a coarse safety net for
    /// unmodeled flags, not an order-sensitive channel).
    #[test]
    fn residual_args_are_order_independent() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let a = key_of_flags(&flag_base(
            &source,
            &["--unmodeled-a", "alpha", "--unmodeled-b", "beta"],
        ));
        let b = key_of_flags(&flag_base(
            &source,
            &["--unmodeled-b", "beta", "--unmodeled-a", "alpha"],
        ));
        assert_eq!(a, b, "residual argv order must not change the key");
    }

    /// kunobi-ninja/kache#324: diagnostics / lint / query / already-keyed path
    /// flags are stripped during parsing, so they must NOT reach the residual
    /// fold and over-key the result. Guards the same invariant as the
    /// `key_matrix_*_does_not_change_key` tests for flags cargo passes routinely.
    ///
    /// Outcome-affecting lint configuration is deliberately NOT in this list:
    /// every lint level and `--check-cfg` must change the key —
    /// see `key_matrix_outcome_lint_configuration_changes_key`.
    #[test]
    fn residual_strips_diagnostic_and_query_flags() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let base = key_of_flags(&flag_base(&source, &[]));
        for extra in [
            vec!["--diagnostic-width=80"],
            vec!["--json=artifacts"],
            vec!["--color", "always"],
            vec!["--verbose"],
        ] {
            assert_eq!(
                base,
                key_of_flags(&flag_base(&source, &extra)),
                "diagnostics/query flag {extra:?} must not change the key"
            );
        }
    }

    /// kunobi-ninja/kache#399: lexical `.`/`..` collapse + separator unification.
    /// Output uses the host separator (so it lines up with canonical rule
    /// prefixes); built with MAIN_SEPARATOR so the test is host-independent.
    #[test]
    fn lexically_resolve_path_collapses_dot_dot() {
        let s = std::path::MAIN_SEPARATOR_STR;
        let j = |parts: &[&str]| parts.join(s);

        // Unix-style absolute.
        assert_eq!(lexically_resolve_path("/a/b/../c"), j(&["", "a", "c"]));
        assert_eq!(lexically_resolve_path("/a/./b"), j(&["", "a", "b"]));
        // `..` cannot escape the root.
        assert_eq!(lexically_resolve_path("/../a"), j(&["", "a"]));

        // Windows drive + mixed separators + unresolved `..` (the #399 input
        // shape: a relative CARGO_TARGET_DIR joined literally with `/`).
        assert_eq!(
            lexically_resolve_path(r"C:\proj\pkg\..\oot-target\x"),
            format!("C:{}", j(&["", "proj", "oot-target", "x"]))
        );
        assert_eq!(
            lexically_resolve_path(r"C:\u\src\../oot-target\rel\deps"),
            format!("C:{}", j(&["", "u", "oot-target", "rel", "deps"]))
        );

        // Relative paths keep a leading `..`.
        assert_eq!(lexically_resolve_path("../a/b"), j(&["..", "a", "b"]));
        assert_eq!(lexically_resolve_path("."), ".");

        // Already-resolved paths are unchanged on the host (the Linux case).
        let resolved = format!("{}home{}u{}oot{}out", s, s, s, s);
        assert_eq!(lexically_resolve_path(&resolved), resolved);
    }

    /// kunobi-ninja/kache#399 (the core property): two out-of-tree build paths
    /// that differ only in the package-dir component cancelled by `..` resolve
    /// so the suffix below their respective roots is identical. That suffix is
    /// what survives after the workspace-root prefix is stripped, so the cache
    /// key converges across build locations.
    #[test]
    fn lexically_resolve_path_makes_out_of_tree_suffix_converge() {
        // Cold and a relocate (different drive subtree, different package-dir
        // name) of the same out-of-tree build. The `..` cancels the package dir,
        // so oot-target attaches directly to the package's parent (= the
        // workspace root). The segment from oot-target onward is then identical,
        // which is what survives after the <WORKSPACE> prefix is stripped.
        let cold =
            lexically_resolve_path(r"C:\proj\scenario\source\..\oot-target\release\build\x\out");
        let reloc = lexically_resolve_path(r"C:\Temp\.tmpAB\..\oot-target\release\build\x\out");
        assert!(!cold.contains(".."), "unresolved .. in {cold}");
        assert!(!reloc.contains(".."), "unresolved .. in {reloc}");
        let from_oot = |p: &str| p[p.find("oot-target").unwrap()..].to_string();
        assert_eq!(from_oot(&cold), from_oot(&reloc));
        let s = std::path::MAIN_SEPARATOR_STR;
        assert_eq!(
            from_oot(&cold),
            ["oot-target", "release", "build", "x", "out"].join(s)
        );
    }

    /// kunobi-ninja/kache#399 end-to-end at the env-dep layer: an out-of-tree
    /// OUT_DIR that arrives with an unresolved `..` (as Windows cargo leaves it
    /// for a relative CARGO_TARGET_DIR) must normalize to the same
    /// <WORKSPACE>-anchored sentinel regardless of absolute build location, so
    /// the key converges and a relocated build hits. Regression for the bug
    /// where `normalize_env_dep_value` returned `Unchanged` before resolving:
    /// the raw `..`-bearing path matched no canonical rule prefix, so the build
    /// location leaked into the key and only the resolved-then-normalized form
    /// (matching the rules' own `canonical_string`) converges.
    #[test]
    fn out_of_tree_out_dir_env_dep_converges_across_locations() {
        let _lock = key_test_lock();

        // Build a real out-of-tree OUT_DIR under `root` with a `..` in the
        // path (root/pkg/../oot-target/...) and return its normalized env-dep
        // value, anchoring <WORKSPACE> at the oot-target dir.
        fn normalized(root: &std::path::Path) -> String {
            let target = root.join("oot-target");
            let out = target
                .join("release")
                .join("build")
                .join("pkg-0000000000000000")
                .join("out");
            std::fs::create_dir_all(&out).unwrap();
            // `pkg` must exist for canonicalize to traverse `pkg/..`.
            std::fs::create_dir_all(root.join("pkg")).unwrap();
            let generated = out.join("generated.rs");
            // Path-only include payload (no `env!("OUT_DIR")` runtime use), so
            // the value is safe to normalize.
            std::fs::write(&generated, b"pub fn marker() -> u8 { 7 }\n").unwrap();

            // The value as Windows cargo hands it over: the package dir is
            // cancelled by a literal `..` rather than pre-resolved.
            let value = root
                .join("pkg")
                .join("..")
                .join("oot-target")
                .join("release")
                .join("build")
                .join("pkg-0000000000000000")
                .join("out")
                .to_string_lossy()
                .into_owned();

            let pn = PathNormalizer::from_env(Some(&target));
            normalize_env_dep_value("test_crate", "OUT_DIR", &value, &[generated], &pn).value
        }

        let cold = tempfile::tempdir().unwrap();
        let reloc = tempfile::tempdir().unwrap();
        let v_cold = normalized(cold.path());
        let v_reloc = normalized(reloc.path());

        assert_eq!(
            v_cold, v_reloc,
            "out-of-tree OUT_DIR must normalize identically across build locations"
        );
        assert!(
            v_cold.contains("<WORKSPACE>"),
            "expected the workspace sentinel, got `{v_cold}`"
        );
        assert!(
            !v_cold.contains(".."),
            "the `..` must be resolved away, got `{v_cold}`"
        );
    }

    /// H1: a build-script native search path must diverge the key, but
    /// cargo's redundant `-L dependency=` (covered by content-hashed
    /// `--extern`) must NOT — else every target-dir move busts the cache.
    /// Generic `-l` keying, checked on hosts that do not probe native MSVC
    /// inputs. On a Windows host the library must exist (fail closed), so the
    /// Windows shape lives in the `windows_*` tests with an injected probe.
    #[cfg(not(windows))]
    #[test]
    fn link_search_native_keys_but_dependency_does_not() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let a = key_of(&flag_base(&source, &["-L", "native=/opt/a/lib"]));
        let b = key_of(&flag_base(&source, &["-L", "native=/opt/b/lib"]));
        assert_ne!(a, b, "a different native -L must change the key");

        let dep_x = key_of(&flag_base(&source, &["-L", "dependency=/x/deps"]));
        let dep_y = key_of(&flag_base(&source, &["-L", "dependency=/y/deps"]));
        assert_eq!(
            dep_x, dep_y,
            "cargo's -L dependency= must not affect the key"
        );
    }

    /// Executable (`bin`) outputs key the linker identity (a different linker
    /// can produce a different binary). A resolvable `-Clinker` is folded in;
    /// an unresolvable one isn't. Exercises compute_cache_key's
    /// is_executable_output() linker branch (716-723) + get_linker_identity.
    ///
    /// Unix-only: the test relies on `cc` resolving on PATH (it folds `cc
    /// --version`), which isn't guaranteed on the Windows CI runner — there
    /// both linkers fail to resolve and the keys match. The branch is still
    /// covered on Linux/macOS CI.
    #[cfg(unix)]
    #[test]
    fn bin_output_keys_linker_identity() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("main.rs");
        std::fs::write(&source, b"fn main() {}").unwrap();
        let bin = |extra: &[&str]| {
            let mut v = vec![
                "rustc".to_string(),
                "--crate-name".to_string(),
                "app".to_string(),
                source.to_string_lossy().to_string(),
                "--crate-type".to_string(),
                "bin".to_string(),
            ];
            v.extend(extra.iter().map(|s| s.to_string()));
            v
        };

        // A resolvable linker (cc on PATH) folds its version and, on Linux,
        // CRT identity. An unresolvable linker cannot place CRT/startup
        // objects, so the invocation is uncacheable rather than keyed with
        // an empty runtime identity.
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key = |args: Vec<String>| {
            let mut parsed = RustcArgs::parse(&args).unwrap();
            parsed.source_file = None;
            compute_cache_key(&parsed, &fh, &pn)
        };
        let with_cc = key(bin(&["-Clinker=cc"]));
        let with_missing = key(bin(&["-Clinker=/nonexistent/kache-linker-xyz"]));
        match (with_cc, with_missing) {
            (Ok(cc), Ok(missing)) => {
                assert_ne!(cc, missing, "linker choice must affect a bin's cache key");
                assert_eq!(cc, key(bin(&["-Clinker=cc"])).unwrap());
            }
            (Ok(_), Err(_)) => {}
            (Err(_), Err(_)) => {}
            (Err(err), Ok(_)) => {
                panic!("unresolvable linker produced a key while cc failed: {err:#}")
            }
        }
    }

    /// A readable `--extern name=path` rlib is content-hashed into the key (not
    /// path-hashed): the same path with different artifact bytes must diverge.
    /// Exercises compute_cache_key's extern Ok(dep_hash) branch (552-557).
    #[test]
    fn extern_artifact_content_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let dep = dir.path().join("libdep.rlib");
        let extern_arg = format!("foo={}", dep.to_str().unwrap());

        std::fs::write(&dep, b"rlib content A").unwrap();
        let key_a = key_of_flags(&flag_base(&source, &["--extern", &extern_arg]));

        std::fs::write(&dep, b"rlib content B (different)").unwrap();
        let key_b = key_of_flags(&flag_base(&source, &["--extern", &extern_arg]));
        assert_ne!(
            key_a, key_b,
            "extern artifact content must change the key (content-hashed)"
        );

        std::fs::write(&dep, b"rlib content A").unwrap();
        let key_a2 = key_of_flags(&flag_base(&source, &["--extern", &extern_arg]));
        assert_eq!(key_a, key_a2, "same extern content -> same key");
    }

    /// H1: `-Z` codegen flags arriving on argv must be keyed.
    #[test]
    fn fold_field_is_unambiguous_across_value_boundaries() {
        // kunobi-ninja/kache#324: length-prefixing free-text key fields removes
        // delimiter/boundary ambiguity that the old `\n`/`=` form allowed.
        let h = |parts: &[(&[u8], &[u8])]| {
            let mut hasher = blake3::Hasher::new();
            for (l, v) in parts {
                fold_field(&mut hasher, l, v);
            }
            hasher.finalize().to_hex().to_string()
        };

        // Same label, value bytes shifted across the boundary: ("a","bc") vs
        // ("ab","c") must not collide.
        assert_ne!(
            h(&[(b"x:", b"a"), (b"x:", b"bc")]),
            h(&[(b"x:", b"ab"), (b"x:", b"c")]),
        );

        // The exact old-encoding collision: a single cfg value that embeds the
        // `\n` delimiter must not equal two separate cfgs.
        assert_ne!(
            h(&[(b"cfg:", b"a\ncfg:b")]),
            h(&[(b"cfg:", b"a"), (b"cfg:", b"b")]),
        );
    }

    #[test]
    fn unstable_flag_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let none = key_of_flags(&flag_base(&source, &[]));
        let san = key_of_flags(&flag_base(&source, &["-Z", "sanitizer=address"]));
        assert_ne!(none, san, "a -Z codegen flag must change the key");
        assert_eq!(
            san,
            key_of_flags(&flag_base(&source, &["-Zsanitizer=address"]))
        );
    }

    /// A `--target` value can be a path to a custom target JSON spec (Firefox /
    /// embedded toolchains). Its file CONTENT — data-layout, target features,
    /// linker, panic strategy — must be folded into the key, so the same path
    /// with different content diverges. Exercises compute_cache_key's
    /// `target_path.is_file()` spec-hashing branch.
    #[test]
    fn custom_target_spec_file_content_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let spec = dir.path().join("my-target.json");
        let spec_arg = format!("--target={}", spec.to_str().unwrap());

        std::fs::write(&spec, br#"{"llvm-target":"x","data-layout":"e-A"}"#).unwrap();
        let key_a = key_of_flags(&flag_base(&source, &[&spec_arg]));

        // Same --target path, different spec content -> different key.
        std::fs::write(&spec, br#"{"llvm-target":"x","data-layout":"e-B"}"#).unwrap();
        let key_b = key_of_flags(&flag_base(&source, &[&spec_arg]));
        assert_ne!(
            key_a, key_b,
            "custom target spec file content must change the key"
        );

        // Restoring the original content reproduces the original key.
        std::fs::write(&spec, br#"{"llvm-target":"x","data-layout":"e-A"}"#).unwrap();
        let key_a2 = key_of_flags(&flag_base(&source, &[&spec_arg]));
        assert_eq!(key_a, key_a2, "same spec content -> same key");
    }

    /// H2: `--sysroot` selects which std rustc links against; with the
    /// same rustc version, a different sysroot must diverge the key.
    #[test]
    fn sysroot_changes_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let a = key_of_flags(&flag_base(&source, &["--sysroot", "/opt/std-a"]));
        let b = key_of_flags(&flag_base(&source, &["--sysroot", "/opt/std-b"]));
        let none = key_of_flags(&flag_base(&source, &[]));
        assert_ne!(a, b, "a different --sysroot must change the key");
        assert_ne!(none, a, "adding --sysroot must change the key");
        assert_eq!(
            a,
            key_of_flags(&flag_base(&source, &["--sysroot=/opt/std-a"]))
        );
    }

    /// H3: a `--target` custom JSON spec must be keyed by its CONTENTS,
    /// so editing the spec in place diverges the key (path string alone
    /// would not).
    #[test]
    fn target_spec_contents_change_key() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let spec = dir.path().join("custom.json");

        std::fs::write(&spec, br#"{"llvm-target":"x86_64","data-layout":"e-m:e"}"#).unwrap();
        let args = flag_base(&source, &["--target", &spec.to_string_lossy()]);
        let before = key_of_flags(&args);

        // Edit the spec in place — same path, different codegen contract.
        std::fs::write(
            &spec,
            br#"{"llvm-target":"x86_64","data-layout":"DIFFERENT"}"#,
        )
        .unwrap();
        let after = key_of_flags(&args);
        assert_ne!(before, after, "editing the target spec must change the key");
    }

    #[test]
    fn test_cache_key_changes_with_source() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");

        // First version
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let parsed1 = RustcArgs::parse(&args_vec).unwrap();
        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();

        // Modified source
        std::fs::write(&source, b"pub fn hello() { println!(\"hi\"); }").unwrap();
        let parsed2 = RustcArgs::parse(&args_vec).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_unreadable_dep_produces_stable_key() {
        let _lock = key_test_lock();
        // Simulate unreadable deps (sysroot crates) from two different paths —
        // the cache key should be identical because we use a sentinel, not the path.
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        // Create two "dep" paths that both point to non-existent files (will fail hash_file)
        let dep_a =
            std::path::PathBuf::from("/home/runner/.rustup/toolchains/stable/lib/libstd.rlib");
        let dep_b =
            std::path::PathBuf::from("/Users/dev/.rustup/toolchains/stable/lib/libstd.rlib");

        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];

        let mut parsed_a = RustcArgs::parse(&args_vec).unwrap();
        parsed_a.externs.push(crate::args::ExternDep {
            name: "std".to_string(),
            path: Some(dep_a),
        });

        let mut parsed_b = RustcArgs::parse(&args_vec).unwrap();
        parsed_b.externs.push(crate::args::ExternDep {
            name: "std".to_string(),
            path: Some(dep_b),
        });

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key_a = compute_cache_key(&parsed_a, &fh, &pn).unwrap();
        let key_b = compute_cache_key(&parsed_b, &fh, &pn).unwrap();
        assert_eq!(
            key_a, key_b,
            "unreadable deps with different paths should produce the same key"
        );
    }

    #[test]
    fn path_is_only_used_for_includes_detects_include_pattern() {
        // serde-style include!() puts a build.rs-generated file into
        // dep-info source_files. The OUT_DIR value is the parent dir
        // of that file → safe to normalize.
        let dir = tempfile::tempdir().unwrap();
        let out_dir = dir.path().join("build/serde-abc/out");
        std::fs::create_dir_all(&out_dir).unwrap();
        let included = out_dir.join("private.rs");
        std::fs::write(&included, b"// generated").unwrap();
        let source_files = vec![std::path::PathBuf::from("/src/lib.rs"), included.clone()];
        assert!(
            path_is_only_used_for_includes(out_dir.to_str().unwrap(), &source_files),
            "OUT_DIR contains an included source file → safe to normalize"
        );
    }

    #[test]
    fn path_is_only_used_for_includes_rejects_env_value_pattern() {
        // out-dir-runtime fixture: const X: &str = env!("OUT_DIR");
        // No source file under OUT_DIR → conservatively keep
        // absolute so cache keys diverge across worktrees.
        let dir = tempfile::tempdir().unwrap();
        let out_dir = dir.path().join("build/foo/out");
        std::fs::create_dir_all(&out_dir).unwrap();
        // dep-info source_files contains only the crate root,
        // nothing under OUT_DIR.
        let source_files = vec![std::path::PathBuf::from("/src/main.rs")];
        assert!(
            !path_is_only_used_for_includes(out_dir.to_str().unwrap(), &source_files),
            "no source under OUT_DIR → unsafe to normalize"
        );
    }

    #[test]
    fn path_is_only_used_for_includes_handles_macos_symlink_form() {
        // The same canonicalization concern that motivated
        // PathNormalizer: on macOS the OUT_DIR value may be in
        // /private/tmp/... form while source paths report /tmp/...
        // (or vice versa). Canonical-path comparison must succeed
        // either way.
        if !cfg!(target_os = "macos") {
            return;
        }
        let unique = format!("kache-cache-key-test-{}", std::process::id());
        let real_out = std::path::Path::new("/tmp").join(&unique).join("out");
        std::fs::create_dir_all(&real_out).unwrap();
        let included = real_out.join("private.rs");
        std::fs::write(&included, b"// generated").unwrap();

        // OUT_DIR comes from cargo as /private/tmp/... form
        let out_dir_value = format!("/private/tmp/{unique}/out");
        // source_files reports /tmp/... (the symlink form)
        let source_files = vec![included];

        let result = path_is_only_used_for_includes(&out_dir_value, &source_files);
        let _ = std::fs::remove_dir_all(std::path::Path::new("/tmp").join(&unique));
        assert!(
            result,
            "canonical-path comparison must see through the symlink"
        );
    }

    #[test]
    fn source_env_dep_use_detector_allows_include_locators() {
        let source = r#"
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
include_str!(concat!(env ! ( "OUT_DIR" ), "/template.txt"));
include_bytes!(env!("BLOB_PATH"));
"#;
        assert!(!source_has_runtime_env_dep_use(source, "OUT_DIR"));
        assert!(!source_has_runtime_env_dep_use(source, "BLOB_PATH"));
    }

    #[test]
    fn source_env_dep_use_detector_rejects_runtime_values() {
        let source = r#"
const OUT_DIR: &str = env!("OUT_DIR");
const MAYBE_OUT_DIR: Option<&str> = option_env!("OUT_DIR");
const PATH: &str = concat!(env!("OUT_DIR"), "/data.txt");
"#;
        assert!(source_has_runtime_env_dep_use(source, "OUT_DIR"));
    }

    #[test]
    fn source_env_dep_use_detector_rejects_dual_pattern() {
        let source = r#"
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
pub const OUT_DIR_AT_COMPILE_TIME: &str = env!("OUT_DIR");
"#;
        assert!(source_has_runtime_env_dep_use(source, "OUT_DIR"));
    }

    #[test]
    fn source_env_dep_use_detector_ignores_comments_and_strings() {
        let source = r##"
// const X: &str = env!("OUT_DIR");
/* const Y: &str = env!("OUT_DIR"); */
const TEXT: &str = "env!(\"OUT_DIR\")";
const RAW: &str = r#"env!("OUT_DIR")"#;
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
"##;
        assert!(!source_has_runtime_env_dep_use(source, "OUT_DIR"));
    }

    #[test]
    fn env_dep_normalization_decision_trace_labels_are_stable() {
        for (decision, expected) in [
            (EnvDepNormalizationDecision::Unchanged, "unchanged"),
            (
                EnvDepNormalizationDecision::NormalizedPathOnly,
                "normalized path-only",
            ),
            (
                EnvDepNormalizationDecision::KeptAbsoluteRuntimePath,
                "kept absolute runtime path",
            ),
            (
                EnvDepNormalizationDecision::ForcedPathOnly,
                "forced path-only (user-asserted)",
            ),
        ] {
            assert_eq!(decision.as_str(), expected);
        }
    }

    #[test]
    fn env_dep_policy_normalizes_out_dir_include_pattern() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let src = workspace.join("src");
        let out_dir = workspace.join("target/debug/build/pkg/out");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&out_dir).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#,
        )
        .unwrap();
        let included = out_dir.join("generated.rs");
        std::fs::write(&included, b"pub fn generated() -> u8 { 1 }").unwrap();

        let source_files = vec![lib, included];
        let path_normalizer = PathNormalizer::from_env(Some(&workspace));
        let out_dir_value = out_dir
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let env_dep = normalize_env_dep_value(
            "test_crate",
            "OUT_DIR",
            &out_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::NormalizedPathOnly
        );
        assert_ne!(env_dep.value, out_dir_value);
        assert!(
            env_dep.value.contains("<WORKSPACE>"),
            "OUT_DIR include pattern should normalize to the workspace sentinel: {env_dep:?}"
        );
    }

    #[test]
    fn env_dep_policy_keeps_out_dir_dual_pattern_absolute() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let src = workspace.join("src");
        let out_dir = workspace.join("target/debug/build/pkg/out");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&out_dir).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            r#"
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
pub const OUT_DIR_AT_COMPILE_TIME: &str = env!("OUT_DIR");
"#,
        )
        .unwrap();
        let included = out_dir.join("generated.rs");
        std::fs::write(&included, b"pub fn generated() -> u8 { 1 }").unwrap();

        let source_files = vec![lib, included];
        let path_normalizer = PathNormalizer::from_env(Some(&workspace));
        let out_dir_value = out_dir
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let env_dep = normalize_env_dep_value(
            "test_crate",
            "OUT_DIR",
            &out_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath
        );
        assert_eq!(env_dep.value, out_dir_value);
    }

    #[test]
    fn env_dep_policy_normalizes_allowlisted_var_but_not_unlisted() {
        // A non-OUT_DIR var that only locates an `include!`'d file (a source
        // file lives under it) is normalized ONLY when opted into the path-only
        // allowlist; otherwise kept absolute. This is the
        // KACHE_PATH_ONLY_ENV_VARS / `[cache] path_only_env_vars` contract.
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let src = workspace.join("src");
        let gen_dir = workspace.join("objdir/build/rust/mozbuild");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&gen_dir).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(&lib, r#"include!(env!("BUILDCONFIG_RS"));"#).unwrap();
        let included = gen_dir.join("buildconfig.rs");
        std::fs::write(&included, b"pub const X: u8 = 1;").unwrap();
        let source_files = vec![lib, included.clone()];
        let value = included
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();

        // Not allowlisted -> kept absolute.
        let pn_off = PathNormalizer::from_env(Some(&workspace));
        let off = normalize_env_dep_value(
            "test_crate",
            "BUILDCONFIG_RS",
            &value,
            &source_files,
            &pn_off,
        );
        assert_eq!(
            off.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath
        );
        assert_eq!(off.value, value);

        // Allowlisted -> normalized (the same gate as OUT_DIR still applies).
        let pn_on = PathNormalizer::from_env(Some(&workspace))
            .with_path_only_env_vars(vec!["BUILDCONFIG_RS".to_string()]);
        let on = normalize_env_dep_value(
            "test_crate",
            "BUILDCONFIG_RS",
            &value,
            &source_files,
            &pn_on,
        );
        assert_eq!(on.decision, EnvDepNormalizationDecision::NormalizedPathOnly);
        assert!(
            on.value.contains("<WORKSPACE>"),
            "allowlisted include locator should normalize: {on:?}"
        );
    }

    #[test]
    fn env_dep_policy_normalizes_rustc_env_var_pointing_under_out_dir() {
        // kunobi-ninja/kache#431, the typenum cascade root: a build script sets
        // `cargo:rustc-env=GEN_BUILD_CONSTS=$OUT_DIR/consts.rs` and the crate does
        // `include!(env!("GEN_BUILD_CONSTS"))`. The var is NOT named OUT_DIR and is
        // NOT allowlisted, but its value lives UNDER OUT_DIR and only locates a
        // generated include — so it must normalize like OUT_DIR (else typenum
        // re-keys per checkout and the whole substrate stack misses cross-clone).
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let out_dir = workspace.join("target/release/build/genlib-abc123/out");
        let src = workspace.join("src");
        std::fs::create_dir_all(&out_dir).unwrap();
        std::fs::create_dir_all(&src).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(&lib, r#"include!(env!("GEN_BUILD_CONSTS"));"#).unwrap();
        let generated = out_dir.join("consts.rs");
        std::fs::write(&generated, b"pub const N: u32 = 42;").unwrap();
        let source_files = vec![lib, generated.clone()];
        let value = generated
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let path_normalizer = PathNormalizer::from_env(Some(&workspace));

        let old_out_dir = std::env::var_os("OUT_DIR");
        // SAFETY: serialized by key_test_lock; restored below.
        unsafe { std::env::set_var("OUT_DIR", &out_dir) };
        let under = normalize_env_dep_value(
            "test_crate",
            "GEN_BUILD_CONSTS",
            &value,
            &source_files,
            &path_normalizer,
        );
        // With OUT_DIR unset there is no anchor, so the same var must stay
        // absolute — proves the gate is the under-OUT_DIR test, not the var name.
        unsafe { std::env::remove_var("OUT_DIR") };
        let no_anchor = normalize_env_dep_value(
            "test_crate",
            "GEN_BUILD_CONSTS",
            &value,
            &source_files,
            &path_normalizer,
        );
        restore_env_var("OUT_DIR", old_out_dir);

        assert_eq!(
            under.decision,
            EnvDepNormalizationDecision::NormalizedPathOnly,
            "a rustc-env var pointing under OUT_DIR, used only as an include locator, \
             must normalize: {under:?}"
        );
        let unit = out_dir
            .canonicalize()
            .unwrap()
            .parent()
            .unwrap()
            .file_name()
            .unwrap()
            .to_string_lossy()
            .into_owned();
        assert_eq!(
            under.value,
            format!("<OUT_DIR:{unit}>/consts.rs"),
            "an OUT_DIR-locator value normalizes relative to OUT_DIR (#330), keeping \
             the per-unit component (file!() observability) but not the location: {under:?}"
        );
        assert_eq!(
            no_anchor.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath,
            "without an OUT_DIR anchor the same non-allowlisted var must stay absolute"
        );
    }

    #[test]
    fn env_dep_policy_keeps_out_dir_runtime_value_absolute() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let out_dir = workspace.join("target/debug/build/pkg/out");
        std::fs::create_dir_all(&out_dir).unwrap();

        let source_files = vec![workspace.join("src/main.rs")];
        let path_normalizer = PathNormalizer::from_env(Some(&workspace));
        let out_dir_value = out_dir
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let env_dep = normalize_env_dep_value(
            "test_crate",
            "OUT_DIR",
            &out_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath
        );
        assert_eq!(env_dep.value, out_dir_value);
    }

    #[test]
    fn env_dep_policy_force_list_overrides_runtime_value_scan() {
        // A crate whose source uses env!("OUT_DIR") as a runtime value is
        // normally kept absolute — but a user-asserted force entry normalizes
        // it anyway (the deployment guarantees the embedding branch is dead).
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let out_dir = dir.path().join("out");
        std::fs::create_dir_all(&out_dir).unwrap();
        let src = dir.path().join("lib.rs");
        std::fs::write(&src, b"pub fn p() -> &'static str { env!(\"OUT_DIR\") }").unwrap();
        let out_dir_value = out_dir.to_string_lossy().to_string();
        let source_files = vec![src];

        let _out_dir = ScopedEnv::set("OUT_DIR", &out_dir_value);

        let pn_plain = PathNormalizer::from_env(Some(dir.path()));
        let kept = normalize_env_dep_value(
            "cef_dll_sys",
            "OUT_DIR",
            &out_dir_value,
            &source_files,
            &pn_plain,
        );

        let pn_forced = PathNormalizer::from_env(Some(dir.path()))
            .with_path_only_env_vars(vec!["cef_dll_sys:OUT_DIR".to_string()]);
        let forced = normalize_env_dep_value(
            "cef_dll_sys",
            "OUT_DIR",
            &out_dir_value,
            &source_files,
            &pn_forced,
        );

        assert_eq!(
            kept.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath
        );
        assert_eq!(
            forced.decision,
            EnvDepNormalizationDecision::ForcedPathOnly,
            "a force-listed var must normalize despite the runtime-value scan: {forced:?}"
        );
        assert!(
            forced.value.starts_with("<OUT_DIR:") || forced.value.starts_with("<WORKSPACE>"),
            "forced OUT_DIR normalizes to a location-free sentinel form              (either the #330 OUT_DIR sentinel or a generic prefix rule): {forced:?}"
        );
        assert!(
            !forced.value.contains(dir.path().to_string_lossy().as_ref()),
            "no absolute build location may survive in a forced value: {forced:?}"
        );
    }

    #[test]
    fn env_dep_policy_force_list_crate_scope_matches_only_that_crate() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let out_dir = dir.path().join("out");
        std::fs::create_dir_all(&out_dir).unwrap();
        let src = dir.path().join("lib.rs");
        std::fs::write(&src, b"pub fn p() -> &'static str { env!(\"OUT_DIR\") }").unwrap();
        let out_dir_value = out_dir.to_string_lossy().to_string();
        let source_files = vec![src];

        let _out_dir = ScopedEnv::set("OUT_DIR", &out_dir_value);

        let pn = PathNormalizer::from_env(Some(dir.path()))
            .with_path_only_env_vars(vec!["cef_dll_sys:OUT_DIR".to_string()]);
        let scoped_match =
            normalize_env_dep_value("cef_dll_sys", "OUT_DIR", &out_dir_value, &source_files, &pn);
        let scoped_other =
            normalize_env_dep_value("other_crate", "OUT_DIR", &out_dir_value, &source_files, &pn);

        assert_eq!(
            scoped_match.decision,
            EnvDepNormalizationDecision::ForcedPathOnly
        );
        assert_eq!(
            scoped_other.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath,
            "a crate-scoped force entry must not leak to other crates: {scoped_other:?}"
        );
    }

    #[test]
    fn env_dep_policy_refuses_to_force_manifest_dir() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let manifest_dir = workspace.join("helper");
        let src = manifest_dir.join("src");
        std::fs::create_dir_all(&src).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            b"pub fn manifest_dir() -> &'static str { env!(\"CARGO_MANIFEST_DIR\") }",
        )
        .unwrap();

        let source_files = vec![lib];
        let path_normalizer = PathNormalizer::from_env(Some(&workspace))
            .with_path_only_env_vars(vec!["test_crate:CARGO_MANIFEST_DIR".to_string()]);
        let manifest_dir_value = manifest_dir
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let env_dep = normalize_env_dep_value(
            "test_crate",
            "CARGO_MANIFEST_DIR",
            &manifest_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath,
            "CARGO_MANIFEST_DIR must stay absolute even when crate-scoped forcing is requested"
        );
        assert_eq!(env_dep.value, manifest_dir_value);
    }

    #[test]
    fn env_dep_policy_keeps_user_path_env_absolute_when_normalized() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        let config_dir = workspace.join("config");
        std::fs::create_dir_all(&config_dir).unwrap();

        let source_files = vec![workspace.join("src/lib.rs")];
        let path_normalizer = PathNormalizer::from_env(Some(&workspace));
        let config_dir_value = config_dir
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let env_dep = normalize_env_dep_value(
            "test_crate",
            "CUSTOM_CONFIG_DIR",
            &config_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::KeptAbsoluteRuntimePath
        );
        assert_eq!(env_dep.value, config_dir_value);
    }

    // `test_normalize_flags` removed: normalize_flags itself is gone,
    // replaced by PathNormalizer (covered by tests in path_normalizer
    // module). The cache_key consumer-side normalization is exercised
    // via the e2e relocate phase + the `path_is_only_used_for_includes` tests.

    #[test]
    fn test_cache_key_changes_with_features() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args1: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--cfg".to_string(),
            "feature=\"std\"".to_string(),
        ];

        let mut args2 = args1.clone();
        args2.push("--cfg".to_string());
        args2.push("feature=\"derive\"".to_string());

        let parsed1 = RustcArgs::parse(&args1).unwrap();
        let parsed2 = RustcArgs::parse(&args2).unwrap();

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();

        assert_ne!(key1, key2);
    }

    #[test]
    fn test_cache_key_changes_with_instrument_coverage() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_normal: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];

        let mut args_coverage = args_normal.clone();
        args_coverage.push("-Cinstrument-coverage".to_string());

        let parsed_normal = RustcArgs::parse(&args_normal).unwrap();
        let parsed_coverage = RustcArgs::parse(&args_coverage).unwrap();

        assert!(!parsed_normal.has_coverage_instrumentation());
        assert!(parsed_coverage.has_coverage_instrumentation());

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key_normal = compute_cache_key(&parsed_normal, &fh, &pn).unwrap();
        let key_coverage = compute_cache_key(&parsed_coverage, &fh, &pn).unwrap();

        assert_ne!(
            key_normal, key_coverage,
            "coverage-instrumented builds must have different cache keys"
        );
    }

    #[test]
    fn test_cache_key_changes_with_instrument_coverage_two_arg() {
        let _lock = key_test_lock();
        // Same test but with -C instrument-coverage (two-arg form)
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_normal: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];

        let mut args_coverage = args_normal.clone();
        args_coverage.extend(["-C".to_string(), "instrument-coverage".to_string()]);

        let parsed_normal = RustcArgs::parse(&args_normal).unwrap();
        let parsed_coverage = RustcArgs::parse(&args_coverage).unwrap();

        assert!(parsed_coverage.has_coverage_instrumentation());

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key_normal = compute_cache_key(&parsed_normal, &fh, &pn).unwrap();
        let key_coverage = compute_cache_key(&parsed_coverage, &fh, &pn).unwrap();

        assert_ne!(
            key_normal, key_coverage,
            "two-arg form -C instrument-coverage must also produce different cache keys"
        );
    }

    #[test]
    fn test_cache_key_changes_with_tarpaulin_cfg() {
        let _lock = key_test_lock();
        // Tarpaulin also passes --cfg=tarpaulin; verify it affects the key
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_normal: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];

        let mut args_tarpaulin = args_normal.clone();
        args_tarpaulin.extend(["--cfg".to_string(), "tarpaulin".to_string()]);

        let parsed_normal = RustcArgs::parse(&args_normal).unwrap();
        let parsed_tarpaulin = RustcArgs::parse(&args_tarpaulin).unwrap();

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key_normal = compute_cache_key(&parsed_normal, &fh, &pn).unwrap();
        let key_tarpaulin = compute_cache_key(&parsed_tarpaulin, &fh, &pn).unwrap();

        assert_ne!(
            key_normal, key_tarpaulin,
            "--cfg=tarpaulin must produce a different cache key"
        );
    }

    #[test]
    fn test_coverage_keys_consistent_across_remap_forms() {
        let _lock = key_test_lock();
        // Both joined and two-arg forms of instrument-coverage should produce
        // the same cache key (both map to codegen opt "instrument-coverage")
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_joined: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "-Cinstrument-coverage".to_string(),
        ];

        let mut args_two = args_joined[..6].to_vec();
        args_two.extend(["-C".to_string(), "instrument-coverage".to_string()]);

        let parsed_joined = RustcArgs::parse(&args_joined).unwrap();
        let parsed_two = RustcArgs::parse(&args_two).unwrap();

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key_joined = compute_cache_key(&parsed_joined, &fh, &pn).unwrap();
        let key_two = compute_cache_key(&parsed_two, &fh, &pn).unwrap();

        assert_eq!(
            key_joined, key_two,
            "joined and two-arg forms of instrument-coverage should produce identical keys"
        );
    }

    #[test]
    fn test_cache_key_version_affects_key() {
        let _lock = key_test_lock();
        // Verify that the key version is hashed by checking that the hasher
        // receives the version string. We do this indirectly: compute a key
        // and then verify the same inputs produce the same key (determinism).

        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
        ];

        // Compute twice — must be deterministic (version baked in)
        let parsed1 = RustcArgs::parse(&args_vec).unwrap();
        let parsed2 = RustcArgs::parse(&args_vec).unwrap();
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();
        assert_eq!(
            key1, key2,
            "key must be deterministic with version baked in"
        );

        // Prove that different version values produce different hashes by
        // simulating what compute_cache_key does with version=N vs version=N+1.
        // We can't change the const, but we can replicate the hashing logic
        // to prove the version input is material.
        let payload = b"rustc_version:1.80.0\n";
        for (v_a, v_b) in [(1u32, 2u32), (0, 1), (1, 100)] {
            let hash = |version: u32| {
                let mut h = blake3::Hasher::new();
                h.update(b"key_version:");
                h.update(version.to_string().as_bytes());
                h.update(b"\n");
                h.update(payload);
                h.finalize().to_hex().to_string()
            };
            assert_ne!(
                hash(v_a),
                hash(v_b),
                "version {} vs {} must produce different hashes",
                v_a,
                v_b
            );
        }
    }

    // --- parse_dep_info tests (pure parser, no I/O) ---

    #[test]
    fn test_parse_dep_info_basic() {
        let input = "target.d: src/lib.rs src/server.rs src/utils.rs\n";
        let files = parse_dep_info(input);
        assert_eq!(files.len(), 3);
        assert_eq!(files[0], std::path::PathBuf::from("src/lib.rs"));
        assert_eq!(files[1], std::path::PathBuf::from("src/server.rs"));
        assert_eq!(files[2], std::path::PathBuf::from("src/utils.rs"));
    }

    #[test]
    fn test_parse_dep_info_escaped_spaces() {
        let input = "target.d: src/my\\ file.rs src/lib.rs\n";
        let files = parse_dep_info(input);
        assert_eq!(files.len(), 2);
        assert!(
            files
                .iter()
                .any(|p| p == &std::path::PathBuf::from("src/my file.rs"))
        );
        assert!(
            files
                .iter()
                .any(|p| p == &std::path::PathBuf::from("src/lib.rs"))
        );
    }

    #[test]
    fn test_parse_dep_info_empty() {
        assert!(parse_dep_info("").is_empty());
        assert!(parse_dep_info("target.d:").is_empty());
        assert!(parse_dep_info("no colon here").is_empty());
    }

    #[test]
    fn test_parse_dep_info_single_file() {
        let input = "deps.d: src/main.rs\n";
        let files = parse_dep_info(input);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0], std::path::PathBuf::from("src/main.rs"));
    }

    #[test]
    fn test_parse_dep_info_absolute_paths() {
        let input = "deps.d: /home/user/project/src/lib.rs /home/user/project/src/mod.rs\n";
        let files = parse_dep_info(input);
        assert_eq!(files.len(), 2);
        assert_eq!(
            files[0],
            std::path::PathBuf::from("/home/user/project/src/lib.rs")
        );
        assert_eq!(
            files[1],
            std::path::PathBuf::from("/home/user/project/src/mod.rs")
        );
    }

    // --- parse_env_dep_info tests (pure parser, no I/O) ---

    #[test]
    fn test_parse_env_deps_basic() {
        let input =
            "deps.d: src/lib.rs\n# env-dep:CARGO_PKG_VERSION=1.0.0\n# env-dep:OUT_DIR=/tmp/out\n";
        let env_deps = parse_env_dep_info(input);
        assert_eq!(env_deps.len(), 2);
        assert!(
            env_deps
                .iter()
                .any(|(k, v)| k == "CARGO_PKG_VERSION" && v == "1.0.0")
        );
        assert!(env_deps.iter().any(|(k, _)| k == "OUT_DIR"));
    }

    #[test]
    fn test_parse_env_deps_returns_raw_values() {
        // Parser stores values verbatim; the normalization decision
        // belongs to `compute_cache_key` (which knows whether OUT_DIR
        // can be safely sentinelized — see `path_is_only_used_for_includes`).
        // Pre-normalizing here would erase the absolute-path
        // information the discriminator needs to read.
        let input = "deps.d: src/lib.rs\n# env-dep:OUT_DIR=/some/abs/path/target/debug/build/foo\n";
        let env_deps = parse_env_dep_info(input);
        assert_eq!(env_deps.len(), 1);
        assert_eq!(env_deps[0].0, "OUT_DIR");
        assert_eq!(env_deps[0].1, "/some/abs/path/target/debug/build/foo");
    }

    #[test]
    fn test_parse_env_deps_empty() {
        let input = "deps.d: src/lib.rs\n";
        let env_deps = parse_env_dep_info(input);
        assert!(env_deps.is_empty());
    }

    #[test]
    fn test_parse_env_deps_no_value() {
        let input = "deps.d: src/lib.rs\n# env-dep:UNSET_VAR\n";
        let env_deps = parse_env_dep_info(input);
        assert_eq!(env_deps.len(), 1);
        assert_eq!(env_deps[0].0, "UNSET_VAR");
    }

    // --- FileHasher tests ---

    #[test]
    fn test_file_hasher_deterministic() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("test.rs");
        std::fs::write(&file, b"fn main() {}").unwrap();

        let hasher = FileHasher::new();
        let hash1 = hasher.hash(&file).unwrap();
        let hash2 = hasher.hash(&file).unwrap();
        assert_eq!(hash1, hash2, "FileHasher must be deterministic");
    }

    #[test]
    fn runtime_env_use_memo_reuses_positive_and_negative_scans() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let source = dir.path().join("lib.rs");
        std::fs::write(
            &source,
            br#"pub const OUT: &str = env!("OUT_DIR"); pub const N: usize = 1;"#,
        )
        .unwrap();

        let hasher = FileHasher::persistent(&db);
        let content_hash = hasher.hash(&source).unwrap();
        assert!(hasher.runtime_env_use(&source, "OUT_DIR").unwrap());
        assert!(!hasher.runtime_env_use(&source, "OTHER_DIR").unwrap());
        drop(hasher);

        // A fresh wrapper can answer both decisions from SQLite using the
        // content hash it already obtained while building the cache key. The
        // source is gone, so either attempted reread would fail this test.
        std::fs::remove_file(&source).unwrap();
        let fresh = FileHasher::persistent(&db);
        assert!(
            fresh
                .runtime_env_use_for_hash(&source, "OUT_DIR", &content_hash)
                .unwrap()
        );
        assert!(
            !fresh
                .runtime_env_use_for_hash(&source, "OTHER_DIR", &content_hash)
                .unwrap()
        );
    }

    #[test]
    fn runtime_env_use_scan_rejects_content_changed_after_hashing() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, br#"include!(concat!(env!("OUT_DIR"), "/x.rs"));"#).unwrap();

        let hasher = FileHasher::new();
        hasher.hash(&source).unwrap();
        std::fs::write(&source, br#"pub const OUT: &str = env!("OUT_DIR");"#).unwrap();

        let error = hasher.runtime_env_use(&source, "OUT_DIR").unwrap_err();
        assert!(
            error
                .to_string()
                .contains("changed between content hashing"),
            "unexpected error: {error:#}"
        );
    }

    #[test]
    fn cc_preprocess_memo_support_requires_persistent_cache() {
        assert!(!FileHasher::new().supports_cc_preprocess_memo());

        let dir = tempfile::tempdir().unwrap();
        let persistent = FileHasher::persistent(&dir.path().join("idx.sqlite"));
        assert!(persistent.supports_cc_preprocess_memo());
    }

    #[test]
    fn cc_preprocess_memo_requires_every_input_fingerprint_to_match() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let source = dir.path().join("source.c");
        let header = dir.path().join("header.h");
        std::fs::write(&source, "#include \"header.h\"\n").unwrap();
        std::fs::write(&header, "#define VALUE 1\n").unwrap();

        let hasher = FileHasher::persistent(&db);
        let inputs = hasher
            .cc_preprocess_fingerprints(
                &[
                    (source.to_string_lossy().into_owned(), source.clone()),
                    (header.to_string_lossy().into_owned(), header.clone()),
                ],
                &no_mapping,
            )
            .unwrap();
        let pp_hash = "a".repeat(64);
        hasher.cc_preprocess_memo_record_if_unchanged("memo-key", &pp_hash, &inputs, &no_mapping);
        assert_eq!(
            hasher
                .cc_preprocess_memo_lookup("memo-key", no_remap, &no_mapping)
                .map(|(hash, _)| hash)
                .as_deref(),
            Some(pp_hash.as_str())
        );

        let inputs_json = serde_json::to_string(&inputs).unwrap();
        let cache = hasher.cache.as_ref().unwrap();
        cache
            .put_cc_preprocess_memo("short-hash", "a", &inputs_json)
            .unwrap();
        cache
            .put_cc_preprocess_memo("non-hex-hash", &"z".repeat(64), &inputs_json)
            .unwrap();
        assert_eq!(
            hasher.cc_preprocess_memo_lookup("short-hash", no_remap, &no_mapping),
            None
        );
        assert_eq!(
            hasher.cc_preprocess_memo_lookup("non-hex-hash", no_remap, &no_mapping),
            None
        );

        // An input written inside the invocation window is what a fresh
        // checkout looks like. It used to refuse both halves of the memo,
        // which meant CI could never memoise anything; the content hash makes
        // the recency irrelevant.
        let mut fresh_hasher = FileHasher::persistent(&db);
        fresh_hasher.arm_too_new_guard(i64::MAX, 0);
        assert_eq!(
            fresh_hasher
                .cc_preprocess_memo_lookup("memo-key", no_remap, &no_mapping)
                .map(|(hash, _)| hash)
                .as_deref(),
            Some(pp_hash.as_str()),
            "unchanged bytes must hit however recently they were written"
        );
        fresh_hasher.cc_preprocess_memo_record_if_unchanged(
            "too-new",
            &pp_hash,
            &inputs,
            &no_mapping,
        );
        assert!(
            fresh_hasher
                .cache
                .as_ref()
                .unwrap()
                .get_cc_preprocess_memo("too-new")
                .unwrap()
                .is_some(),
            "a fresh checkout must still be able to publish a memo"
        );

        std::fs::write(&header, "#define VALUE 12345\n").unwrap();
        assert_eq!(
            hasher.cc_preprocess_memo_lookup("memo-key", no_remap, &no_mapping),
            None,
            "a changed transitive header must force preprocessing"
        );
        hasher.cc_preprocess_memo_record_if_unchanged("changed", &pp_hash, &inputs, &no_mapping);
        assert!(
            hasher
                .cache
                .as_ref()
                .unwrap()
                .get_cc_preprocess_memo("changed")
                .unwrap()
                .is_none(),
            "changed inputs must not publish a memo"
        );
    }

    /// Tests that do not exercise prefix maps hash contents as they are.
    fn no_mapping(path: &Path) -> Option<String> {
        hash_file(path).ok()
    }

    /// A resolver for tests that record and read in one place: the recorded
    /// name is the path.
    fn no_remap(name: &str) -> Vec<PathBuf> {
        vec![PathBuf::from(name)]
    }

    /// The case the benchmark exposed: a generated header names its own build
    /// directory, so two checkouts hold different bytes that the prefix maps
    /// rewrite to the same thing. The expansion is hashed after mapping, so
    /// the key already treats them as equal; comparing raw bytes alone left
    /// the memo stricter than the key it feeds, and every `-sys` unit behind
    /// such a header preprocessed again in the second checkout.
    #[test]
    fn cc_preprocess_memo_compares_contents_as_the_expansion_sees_them() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        for tree in [&a, &b] {
            std::fs::create_dir_all(tree).unwrap();
        }
        // Each tree's header names its own directory, as a build script writes.
        std::fs::write(a.join("gen.h"), format!("#define P \"{}\"\n", a.display())).unwrap();
        std::fs::write(b.join("gen.h"), format!("#define P \"{}\"\n", b.display())).unwrap();

        // The maps each tree would use: its own root onto one shared sentinel.
        let map_under = |root: &std::path::Path| {
            let root = root.to_string_lossy().into_owned();
            move |path: &Path| -> Option<String> {
                let text = std::fs::read_to_string(path).ok()?;
                Some(
                    blake3::hash(text.replace(&root, "<root>").as_bytes())
                        .to_hex()
                        .to_string(),
                )
            }
        };

        let hasher = FileHasher::persistent(&db);
        let inputs = hasher
            .cc_preprocess_fingerprints(
                &[("<root>/gen.h".to_string(), a.join("gen.h"))],
                &map_under(&a),
            )
            .unwrap();
        assert_ne!(
            inputs[0].content, inputs[0].mapped,
            "raw and mapped hashes differ for a file that names its own path"
        );
        let pp_hash = "d".repeat(64);
        hasher.cc_preprocess_memo_record_if_unchanged(
            "memo-key",
            &pp_hash,
            &inputs,
            &map_under(&a),
        );

        let resolve_in_b = |name: &str| vec![b.join(name.trim_start_matches("<root>/"))];
        assert_eq!(
            FileHasher::persistent(&db)
                .cc_preprocess_memo_lookup("memo-key", resolve_in_b, &map_under(&b))
                .map(|(hash, _)| hash)
                .as_deref(),
            Some(pp_hash.as_str()),
            "the same header under another root must reuse the expansion"
        );

        // A real difference still misses, mapping or no mapping.
        std::fs::write(
            b.join("gen.h"),
            format!("#define P \"{}\"\n#define EXTRA 1\n", b.display()),
        )
        .unwrap();
        assert_eq!(
            FileHasher::persistent(&db).cc_preprocess_memo_lookup(
                "memo-key",
                resolve_in_b,
                &map_under(&b)
            ),
            None,
            "a header that gained a definition must force a fresh preprocess"
        );
    }

    /// The hole the relocate-modified e2e phase found: a second checkout with
    /// an edited copy must not be answered by the unedited original, which is
    /// still sitting on disk where the memo recorded it. Reusing that
    /// expansion would derive the unedited key and serve a stale artifact for
    /// modified source.
    #[test]
    fn cc_preprocess_memo_ignores_the_recording_tree_when_reading_another() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let original = dir.path().join("a");
        let relocated = dir.path().join("b");
        for tree in [&original, &relocated] {
            std::fs::create_dir_all(tree).unwrap();
        }
        let source_of = |tree: &std::path::Path| tree.join("source.c");
        std::fs::write(source_of(&original), "int v(void) { return 1; }\n").unwrap();

        // Record in the original tree, under a mapped name both trees share.
        let hasher = FileHasher::persistent(&db);
        let inputs = hasher
            .cc_preprocess_fingerprints(
                &[("<root>/source.c".to_string(), source_of(&original))],
                &no_mapping,
            )
            .unwrap();
        let pp_hash = "c".repeat(64);
        hasher.cc_preprocess_memo_record_if_unchanged("memo-key", &pp_hash, &inputs, &no_mapping);

        // The relocated tree has an EDITED copy. The original still exists,
        // untouched, at the path the record names.
        std::fs::write(source_of(&relocated), "int v(void) { return 999; }\n").unwrap();
        let resolve_in_relocated =
            |name: &str| vec![relocated.join(name.trim_start_matches("<root>/"))];
        assert_eq!(
            FileHasher::persistent(&db).cc_preprocess_memo_lookup(
                "memo-key",
                resolve_in_relocated,
                &no_mapping
            ),
            None,
            "the edited copy must miss even though the original is unchanged"
        );

        // The same resolver on an identical copy is a hit: this is not just
        // rejecting everything from another tree.
        std::fs::write(source_of(&relocated), "int v(void) { return 1; }\n").unwrap();
        assert_eq!(
            FileHasher::persistent(&db)
                .cc_preprocess_memo_lookup("memo-key", resolve_in_relocated, &no_mapping)
                .map(|(hash, _)| hash)
                .as_deref(),
            Some(pp_hash.as_str()),
            "an identical copy in another tree must still reuse the expansion"
        );
    }

    /// The case the memo exists for and used to miss: the same bytes at new
    /// metadata. A second worktree gives every file a new inode and mtime,
    /// and a build script that regenerates a header rewrites it identically.
    /// Neither changes what the preprocessor would produce.
    #[test]
    fn cc_preprocess_memo_survives_new_metadata_for_unchanged_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let source = dir.path().join("source.c");
        let header = dir.path().join("header.h");
        let source_bytes = "#include \"header.h\"\nint v(void) { return VALUE; }\n";
        let header_bytes = "#define VALUE 1\n";
        std::fs::write(&source, source_bytes).unwrap();
        std::fs::write(&header, header_bytes).unwrap();

        let hasher = FileHasher::persistent(&db);
        let inputs = hasher
            .cc_preprocess_fingerprints(
                &[
                    (source.to_string_lossy().into_owned(), source.clone()),
                    (header.to_string_lossy().into_owned(), header.clone()),
                ],
                &no_mapping,
            )
            .unwrap();
        assert!(
            inputs.iter().all(|input| input.content.len() == 64),
            "every recorded input carries a content hash"
        );
        let pp_hash = "b".repeat(64);
        hasher.cc_preprocess_memo_record_if_unchanged("memo-key", &pp_hash, &inputs, &no_mapping);

        // Rewrite both files with identical bytes. Remove first, so the
        // replacement gets a new inode as well as a new mtime — the shape a
        // second checkout produces.
        for (path, bytes) in [(&source, source_bytes), (&header, header_bytes)] {
            std::fs::remove_file(path).unwrap();
            std::fs::write(path, bytes).unwrap();
        }
        let rewritten = FileFingerprint::from_path(&header).unwrap();
        assert_ne!(
            rewritten, inputs[0].fingerprint,
            "the rewrite must actually change the metadata this test is about"
        );

        let reader = FileHasher::persistent(&db);
        assert_eq!(
            reader
                .cc_preprocess_memo_lookup("memo-key", no_remap, &no_mapping)
                .map(|(hash, _)| hash)
                .as_deref(),
            Some(pp_hash.as_str()),
            "identical bytes at new metadata must reuse the expansion"
        );

        // One byte of difference is still a miss, whatever the metadata says.
        std::fs::write(&header, "#define VALUE 2\n").unwrap();
        assert_eq!(
            FileHasher::persistent(&db).cc_preprocess_memo_lookup(
                "memo-key",
                no_remap,
                &no_mapping
            ),
            None,
            "changed bytes must force a fresh preprocess"
        );
    }

    #[test]
    fn too_new_guard_flags_inputs_modified_after_build_start() {
        // kunobi-ninja/kache#324: when armed, the guard flags any hashed input
        // whose mtime/ctime is at/after the build's start (its content is racy
        // vs what the compiler reads). Disabled by default.
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("idx.sqlite");
        let file = dir.path().join("input.rs");
        std::fs::write(&file, b"pub fn x() {}").unwrap();

        let now_ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos() as i64;

        // Disabled (default) → never flagged.
        let off = FileHasher::persistent(&db);
        off.hash(&file).unwrap();
        assert!(!off.too_new(), "guard is off by default");

        // Build "started" in the future → the file predates it → not too-new.
        let mut before = FileHasher::persistent(&db);
        before.arm_too_new_guard(now_ns + 60_000_000_000, 0);
        before.hash(&file).unwrap();
        assert!(
            !before.too_new(),
            "a file modified before the build started is not too-new"
        );

        // Build "started" in the past → the file was modified after → too-new.
        let mut after = FileHasher::persistent(&db);
        after.arm_too_new_guard(now_ns - 60_000_000_000, 0);
        after.hash(&file).unwrap();
        assert!(
            after.too_new(),
            "a file modified after the build started must be flagged too-new"
        );

        // The store-free/daemon wrapper path uses `FileHasher::new()`. Its
        // guard must not silently become a no-op just because no local hash
        // memo is open.
        let mut cacheless = FileHasher::new();
        cacheless.arm_too_new_guard(now_ns - 60_000_000_000, 0);
        cacheless.hash(&file).unwrap();
        assert!(
            cacheless.too_new(),
            "a cacheless hasher must enforce the same too-new guard"
        );
    }

    #[test]
    fn guarded_inputs_record_only_while_armed() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("input.rs");
        std::fs::write(&file, b"pub fn x() {}").unwrap();

        let disarmed = FileHasher::new();
        disarmed.hash(&file).unwrap();
        assert!(
            disarmed.take_guarded_inputs().is_empty(),
            "a disarmed hasher records nothing to verify"
        );

        let mut armed = FileHasher::new();
        armed.arm_too_new_guard(1, 0);
        armed.hash(&file).unwrap();
        armed.hash(&file).unwrap();
        assert_eq!(
            armed.take_guarded_inputs().len(),
            2,
            "every hash while armed is recorded for post-compile verification"
        );
        assert!(
            armed.take_guarded_inputs().is_empty(),
            "taking the snapshot drains it"
        );
    }

    #[test]
    fn guarded_inputs_empty_set_never_excuses() {
        assert!(
            !FileHasher::guarded_inputs_unchanged_since_hash(&[]),
            "a vacuous check must not waive a tripped guard"
        );
    }

    #[test]
    fn guarded_inputs_reject_changed_or_missing_files() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("input.rs");
        std::fs::write(&file, b"pub fn x() {}").unwrap();
        let recorded = FileFingerprint::from_path(&file).unwrap();

        std::fs::write(&file, b"pub fn x() { 1 }").unwrap();
        assert!(
            !FileHasher::guarded_inputs_unchanged_since_hash(std::slice::from_ref(&recorded)),
            "rewritten bytes must fail verification even when the wall clock cannot tell"
        );

        std::fs::remove_file(&file).unwrap();
        assert!(
            !FileHasher::guarded_inputs_unchanged_since_hash(std::slice::from_ref(&recorded)),
            "a file that vanished mid-build must fail verification"
        );
    }

    #[test]
    fn guarded_inputs_reject_weak_identity() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("input.rs");
        std::fs::write(&file, b"pub fn x() {}").unwrap();
        let mut recorded = FileFingerprint::from_path(&file).unwrap();
        recorded.inode = 0;
        assert!(
            !FileHasher::guarded_inputs_unchanged_since_hash(std::slice::from_ref(&recorded)),
            "without an inode a replace-by-rename is invisible, so verification must fail closed"
        );
    }

    #[cfg(unix)]
    #[test]
    fn guarded_inputs_verify_despite_future_mtimes() {
        // The clock-domain case: the filesystem clock runs ahead of the host
        // (NFS skew, a fresh checkout stamped in the future), so the
        // wall-clock guard trips on files the build never touched. Identical
        // fingerprints before and after still prove nothing changed.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("input.rs");
        std::fs::write(&file, b"pub fn x() {}").unwrap();
        filetime::set_file_mtime(&file, filetime::FileTime::from_unix_time(2_000_000_000, 0))
            .unwrap();

        let now_ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos() as i64;
        let mut hasher = FileHasher::new();
        hasher.arm_too_new_guard(now_ns, 0);
        hasher.hash(&file).unwrap();
        assert!(
            hasher.too_new(),
            "a future mtime must still trip the wall-clock guard"
        );
        assert!(
            FileHasher::guarded_inputs_unchanged_since_hash(&hasher.take_guarded_inputs()),
            "untouched bytes verify despite the skewed clock"
        );
    }

    #[test]
    fn test_file_hasher_persistent_cache_invalidates_on_metadata_change() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("index.db");
        let file = dir.path().join("large.rlib");
        std::fs::write(&file, vec![1u8; 70 * 1024]).unwrap();

        let hasher = FileHasher::persistent(&db_path);
        let first = hasher.hash(&file).unwrap();
        hasher.flush_memo();
        let first_stats = hasher.stats();
        assert_eq!(first_stats.cache_hits, 0);
        assert_eq!(first_stats.cache_misses, 1);
        assert!(first_stats.bytes_hashed > 0);

        let second_hasher = FileHasher::persistent(&db_path);
        let second = second_hasher.hash(&file).unwrap();
        let second_stats = second_hasher.stats();
        assert_eq!(first, second);
        assert_eq!(second_stats.cache_hits, 1);
        assert_eq!(second_stats.cache_misses, 0);

        std::fs::write(&file, vec![2u8; 70 * 1024]).unwrap();
        let changed = FileHasher::persistent(&db_path).hash(&file).unwrap();
        assert_ne!(first, changed);
    }

    #[test]
    fn test_file_hasher_persistent_cache_skips_small_files() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("index.db");
        let file = dir.path().join("small.rs");
        std::fs::write(&file, b"fn main() {}").unwrap();

        let hasher = FileHasher::persistent(&db_path);
        let first = hasher.hash(&file).unwrap();
        let second = hasher.hash(&file).unwrap();
        let stats = hasher.stats();
        assert_eq!(first, second);
        assert_eq!(stats.cache_hits, 0);
        assert_eq!(stats.cache_misses, 2);
    }

    // --- dep-info pre-pass integration test ---

    #[test]
    fn test_dep_info_finds_modules() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        std::fs::write(src.join("lib.rs"), b"mod server;\npub fn hello() {}").unwrap();
        std::fs::write(src.join("server.rs"), b"pub fn serve() {}").unwrap();

        let rustc = std::path::PathBuf::from("rustc");
        let source = src.join("lib.rs");
        let args = vec![
            "--crate-name".to_string(),
            "testcrate".to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition".to_string(),
            "2021".to_string(),
        ];

        let runs_before = crate::opcounts::dep_info_runs();
        let ms_before = crate::opcounts::dep_info_ms();
        let dep_info = run_dep_info_pass(&rustc, None, &source, &args, false).unwrap();
        // The pre-pass is a real rustc start; the event log must see it.
        assert!(crate::opcounts::dep_info_runs() > runs_before);
        assert!(
            crate::opcounts::dep_info_ms() > ms_before,
            "a rustc spawn takes more than a millisecond"
        );

        assert!(
            dep_info.source_files.len() >= 2,
            "expected at least 2 files, got {:?}",
            dep_info.source_files
        );
        assert!(dep_info.source_files.iter().any(|p| p.ends_with("lib.rs")));
        assert!(
            dep_info
                .source_files
                .iter()
                .any(|p| p.ends_with("server.rs"))
        );
    }

    #[test]
    fn run_dep_info_pass_errors_on_compile_failure() {
        // A failing dep-info pre-pass must return Err, NOT a crate-root-only
        // DepInfo: keying off an incomplete input set risks a stale-artifact
        // false hit (kunobi-ninja/kache#323). The wrapper turns this Err into a
        // passthrough (real compile, no store).
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        // Syntactically invalid Rust → rustc exits non-zero on the dep-info pass.
        std::fs::write(src.join("lib.rs"), b"fn broken( { this is not valid rust").unwrap();

        let rustc = std::path::PathBuf::from("rustc");
        let source = src.join("lib.rs");
        let args = vec![
            "--crate-name".to_string(),
            "testcrate".to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition".to_string(),
            "2021".to_string(),
        ];

        let runs_before = crate::opcounts::dep_info_runs();
        let Err(err) = run_dep_info_pass(&rustc, None, &source, &args, false) else {
            panic!("expected Err on a failing dep-info pass (source has a syntax error)");
        };
        assert!(
            crate::opcounts::dep_info_runs() > runs_before,
            "a failed pre-pass still spawned rustc and must be counted"
        );
        // The error must CARRY rustc's own reason, not just say the pass
        // failed: the wrapper logs `{e:#}`, and a diagnostic that drops the
        // cause is how the substrate bench's 60 refusals stayed unexplained
        // for two months (kunobi-ninja/kache#431).
        let rendered = format!("{err:#}");
        assert!(
            rendered.contains("dep-info pre-pass failed (exit"),
            "the cause must name the failing exit status: {rendered}"
        );
        assert!(
            rendered.contains("error"),
            "the cause must carry rustc's own first stderr line: {rendered}"
        );
    }

    #[test]
    fn dep_info_pass_args_drops_output_naming_flags() {
        // Cargo's real lib-target argv, plus the `-C extra-filename` the
        // pre-pass used to carry into its own `-o` invocation
        // (kunobi-ninja/kache#896).
        let args: Vec<String> = [
            "--crate-name",
            "mylib",
            "--edition=2021",
            "mylib/src/lib.rs",
            "--error-format=json",
            "--crate-type",
            "lib",
            "--emit=dep-info,metadata,link",
            "-C",
            "metadata=1b2c9f1c31209a4a",
            "-C",
            "extra-filename=-02749d16b52ff8b3",
            "--out-dir",
            "/w/target/debug/deps",
            "-C",
            "incremental=/w/target/debug/incremental",
            "-L",
            "dependency=/w/target/debug/deps",
        ]
        .iter()
        .map(|arg| (*arg).to_string())
        .collect();

        let dep_args = dep_info_pass_args(
            Path::new("mylib/src/lib.rs"),
            &args,
            Path::new("/tmp/kache-depinfo/deps.d"),
        );

        assert_eq!(
            dep_args.first().map(String::as_str),
            Some("mylib/src/lib.rs"),
            "the source file leads the argv exactly once: {dep_args:?}"
        );
        assert_eq!(
            dep_args.iter().filter(|a| a.contains("lib.rs")).count(),
            1,
            "cargo's own positional source must not be re-added: {dep_args:?}"
        );
        assert!(
            !dep_args.iter().any(|a| a.contains("extra-filename")),
            "-C extra-filename names outputs the pre-pass discards, and rustc \
             warns about it as soon as -o is present: {dep_args:?}"
        );
        assert!(
            !dep_args.iter().any(|a| a.contains("incremental")),
            "incremental flags go through the canonical filter: {dep_args:?}"
        );
        assert!(
            !dep_args.iter().any(|a| a.starts_with("--emit=")),
            "cargo's --emit is superseded by the pre-pass's own: {dep_args:?}"
        );
        assert!(
            !dep_args.iter().any(|a| a == "--out-dir"),
            "--out-dir is the other flag rustc reports as ignored due to -o: {dep_args:?}"
        );
        assert!(
            !dep_args.iter().any(|a| a.starts_with("/w/target")),
            "--out-dir's value must go with it: {dep_args:?}"
        );

        // Everything that shapes the source closure survives.
        for kept in [
            "--crate-name",
            "mylib",
            "--edition=2021",
            "--error-format=json",
            "--crate-type",
            "lib",
            "-C",
            "metadata=1b2c9f1c31209a4a",
            "-L",
            "dependency=/w/target/debug/deps",
        ] {
            assert!(
                dep_args.iter().any(|a| a == kept),
                "{kept} shapes the input set and must survive: {dep_args:?}"
            );
        }
        assert_eq!(
            dep_args.iter().filter(|a| a.as_str() == "-C").count(),
            1,
            "only extra-filename's own -C is dropped, not every -C: {dep_args:?}"
        );

        let tail = &dep_args[dep_args.len() - 4..];
        assert_eq!(
            tail,
            [
                "--emit",
                "dep-info",
                "-o",
                "/tmp/kache-depinfo/deps.d".to_string().as_str()
            ]
            .map(String::from),
            "the pre-pass appends exactly one output configuration"
        );
    }

    #[test]
    fn dep_info_pass_args_drops_every_extra_filename_spelling() {
        // rustc accepts four spellings of a codegen option; RUSTFLAGS and
        // hand-rolled invocations use the joined ones cargo never emits.
        for spelling in [
            vec!["-C", "extra-filename=-abc123"],
            vec!["-Cextra-filename=-abc123"],
            vec!["--codegen", "extra-filename=-abc123"],
            vec!["--codegen=extra-filename=-abc123"],
            // rustc normalises `_` to `-` in option names, so the underscore
            // spelling reaches the same flag.
            vec!["-C", "extra_filename=-abc123"],
            vec!["-Cextra_filename=-abc123"],
            vec!["--codegen", "extra_filename=-abc123"],
            vec!["--codegen=extra_filename=-abc123"],
        ] {
            let mut args: Vec<String> = vec!["--crate-type".into(), "lib".into()];
            args.extend(spelling.iter().map(|arg| (*arg).to_string()));
            args.push("--crate-name".into());
            args.push("mylib".into());

            let dep_args =
                dep_info_pass_args(Path::new("src/lib.rs"), &args, Path::new("/tmp/deps.d"));

            assert!(
                !dep_args
                    .iter()
                    .any(|a| a.contains("extra-filename") || a.contains("extra_filename")),
                "{spelling:?} must be dropped: {dep_args:?}"
            );
            assert!(
                dep_args.iter().any(|a| a == "--crate-name"),
                "{spelling:?} must not swallow the following flag: {dep_args:?}"
            );
        }
    }

    #[test]
    fn dep_info_pass_args_keeps_bare_trailing_codegen_flag() {
        // A trailing `-C` with no value is malformed, but the pre-pass must
        // hand it to rustc unchanged rather than guess — rustc's own error is
        // the honest outcome.
        let args = vec![
            "--crate-type".to_string(),
            "lib".to_string(),
            "-C".to_string(),
        ];

        let dep_args = dep_info_pass_args(Path::new("src/lib.rs"), &args, Path::new("/tmp/deps.d"));

        assert!(
            dep_args.iter().any(|a| a == "-C"),
            "a valueless -C is not an extra-filename: {dep_args:?}"
        );
    }

    #[test]
    fn dep_info_pass_args_drops_joined_output_flag() {
        // rustc accepts `-o` with its value attached, and reads single-dash
        // `-out-dir` as `-o` plus junk ("option `-o` has no space between
        // flag name and value"). A leftover joins the pre-pass's own `-o`
        // and rustc exits 1 with "Option 'o' given more than once" — every
        // build using that spelling stays a passthrough
        // (kunobi-ninja/kache#896).
        let args: Vec<String> = [
            "--crate-name",
            "mylib",
            "-o/tmp/original.rlib",
            "--edition=2021",
            "-O",
            "--out-dir=/tmp/original-deps",
            "-out-dir",
            "/tmp/still-positional",
            "src/lib.rs",
        ]
        .iter()
        .map(|arg| (*arg).to_string())
        .collect();

        let dep_args = dep_info_pass_args(Path::new("src/lib.rs"), &args, Path::new("/tmp/deps.d"));

        let outputs: Vec<&String> = dep_args.iter().filter(|a| a.starts_with("-o")).collect();
        assert_eq!(
            outputs,
            ["-o"],
            "only the pre-pass's own -o may survive: {dep_args:?}"
        );
        for dropped in [
            "-o/tmp/original.rlib",
            "-out-dir",
            "--out-dir=/tmp/original-deps",
        ] {
            assert!(
                !dep_args.iter().any(|a| a == dropped),
                "{dropped} names an output the pre-pass discards: {dep_args:?}"
            );
        }
        assert!(
            dep_args.iter().any(|a| a == "/tmp/still-positional"),
            "single-dash -out-dir takes no separate value: rustc reads the next \
             token as a positional, and the pre-pass must fail on it exactly as \
             the real build does: {dep_args:?}"
        );
        assert!(
            dep_args.iter().any(|a| a == "-O"),
            "capital -O is opt-level, not output: {dep_args:?}"
        );
        assert!(
            dep_args.iter().any(|a| a == "--edition=2021"),
            "the token after a joined -o is a real flag, not its value: {dep_args:?}"
        );
        let tail = &dep_args[dep_args.len() - 4..];
        assert_eq!(
            tail,
            [
                "--emit",
                "dep-info",
                "-o",
                "/tmp/deps.d".to_string().as_str()
            ]
            .map(String::from),
            "the pre-pass appends exactly one output configuration"
        );
    }

    #[test]
    fn dep_info_pass_args_strips_every_incremental_spelling() {
        // All four `-C incremental` spellings rustc accepts must go through
        // the canonical filter before the pre-pass runs: a leftover would aim
        // the dep-info run at cargo's incremental dir
        // (kunobi-ninja/kache#896). A bare `-C incremental` (no `=value`) is
        // not valid rustc — it stays, so rustc rejects it exactly as it
        // rejects the real build ("requires a string").
        let args: Vec<String> = [
            "--crate-name",
            "mylib",
            "-Cincremental=/tmp/incr-joined",
            "-C",
            "incremental=/tmp/incr-split",
            "--codegen=incremental=/tmp/incr-long-joined",
            "--codegen",
            "incremental=/tmp/incr-long-split",
            "src/lib.rs",
        ]
        .iter()
        .map(|arg| (*arg).to_string())
        .collect();

        let dep_args = dep_info_pass_args(Path::new("src/lib.rs"), &args, Path::new("/tmp/deps.d"));

        assert!(
            !dep_args.iter().any(|a| a.contains("incremental")),
            "no incremental spelling may reach the pre-pass: {dep_args:?}"
        );
        assert!(
            dep_args.iter().any(|a| a == "mylib"),
            "stripping must not swallow neighbouring flags: {dep_args:?}"
        );

        let bare: Vec<String> = ["--crate-name", "mylib", "-C", "incremental", "src/lib.rs"]
            .iter()
            .map(|arg| (*arg).to_string())
            .collect();
        let dep_bare = dep_info_pass_args(Path::new("src/lib.rs"), &bare, Path::new("/tmp/deps.d"));

        assert!(
            dep_bare.iter().any(|a| a == "incremental"),
            "a valueless incremental is rustc's to reject, not the pre-pass's to guess: {dep_bare:?}"
        );
    }

    #[test]
    fn dep_info_pass_prepass_succeeds_through_response_file() {
        // The `use_response_file` path — taken whenever cargo's own argv
        // arrived via `@file` — had no coverage. A crate under a path with
        // spaces exercises the verbatim one-arg-per-line round-trip, which is
        // exactly what an expanded largest-crate argv looks like
        // (kunobi-ninja/kache#896).
        let dir = tempfile::Builder::new()
            .prefix("kache depinfo space ")
            .tempdir()
            .unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("lib.rs"), b"mod server;\npub fn hello() {}").unwrap();
        std::fs::write(src.join("server.rs"), b"pub fn serve() {}").unwrap();

        let rustc = std::path::PathBuf::from("rustc");
        let source = src.join("lib.rs");
        let args = vec![
            "--crate-name".to_string(),
            "testcrate".to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition".to_string(),
            "2021".to_string(),
        ];

        let dep_info = run_dep_info_pass(&rustc, None, &source, &args, true)
            .expect("the response-file pre-pass must match the direct one");

        assert!(
            dep_info.source_files.iter().any(|p| p.ends_with("lib.rs")),
            "expected the crate root: {:?}",
            dep_info.source_files
        );
        assert!(
            dep_info
                .source_files
                .iter()
                .any(|p| p.ends_with("server.rs")),
            "an incomplete source list is what makes a crate uncacheable: {:?}",
            dep_info.source_files
        );
    }

    #[test]
    fn read_dep_info_file_rejects_non_utf8() {
        // A non-UTF8 filename or env value in the source closure lands
        // verbatim in rustc's dep-info output. The pre-pass must refuse it
        // with the encoding named — not a bare "stream did not contain valid
        // UTF-8" against an unnamed input set (kunobi-ninja/kache#896).
        let dir = tempfile::tempdir().unwrap();
        let dep_file = dir.path().join("deps.d");
        std::fs::write(&dep_file, b"/tmp/x.d: src/lib.rs\n").unwrap();
        assert_eq!(
            read_dep_info_file(&dep_file).unwrap(),
            "/tmp/x.d: src/lib.rs\n"
        );

        std::fs::write(&dep_file, b"/tmp/x.d: src/\xfflib.rs\n").unwrap();
        let err = format!("{:#}", read_dep_info_file(&dep_file).unwrap_err());
        assert!(
            err.contains("not valid UTF-8"),
            "the refusal must name the encoding: {err}"
        );
    }

    #[test]
    fn dep_info_pass_prepass_succeeds_with_extra_filename() {
        // End-to-end regression for kunobi-ninja/kache#896: a lib-target argv
        // shaped like cargo's, carrying `-C extra-filename`, must produce a
        // clean pre-pass and the crate's full source closure — not a refusal.
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join("lib.rs"), b"mod server;\npub fn hello() {}").unwrap();
        std::fs::write(src.join("server.rs"), b"pub fn serve() {}").unwrap();

        let rustc = std::path::PathBuf::from("rustc");
        let source = src.join("lib.rs");
        let out_dir = dir.path().join("deps");
        let args: Vec<String> = vec![
            "--crate-name".into(),
            "testcrate".into(),
            "--edition=2021".into(),
            source.to_string_lossy().into_owned(),
            "--error-format=json".into(),
            "--crate-type".into(),
            "lib".into(),
            "--emit=dep-info,metadata,link".into(),
            "-C".into(),
            "metadata=92ee3169a2c3b7b0".into(),
            "-C".into(),
            "extra-filename=-2cb6bc2ef2b88725".into(),
            "--out-dir".into(),
            out_dir.to_string_lossy().into_owned(),
            "-C".into(),
            "incremental=/nonexistent/incremental".into(),
        ];

        let dep_info = run_dep_info_pass(&rustc, None, &source, &args, false)
            .expect("a cargo-shaped lib argv must not fail the pre-pass");

        assert!(
            dep_info.source_files.iter().any(|p| p.ends_with("lib.rs")),
            "expected the crate root: {:?}",
            dep_info.source_files
        );
        assert!(
            dep_info
                .source_files
                .iter()
                .any(|p| p.ends_with("server.rs")),
            "an incomplete source list is what makes a crate uncacheable: {:?}",
            dep_info.source_files
        );
    }

    #[test]
    fn first_rustc_error_line_skips_leading_json_warnings() {
        // The exact shape of the kunobi-ninja/kache#896 report: rustc emits
        // session-level warnings before any crate diagnostic, so the first
        // line is never the reason the run aborted.
        let stderr = concat!(
            r#"{"$message_type":"diagnostic","message":"ignoring -C extra-filename flag due to -o flag","level":"warning"}"#,
            "\n",
            r#"{"$message_type":"diagnostic","message":"cannot find macro `frobnicate`","level":"error"}"#,
            "\n",
            r#"{"$message_type":"diagnostic","message":"aborting due to 1 previous error","level":"error"}"#,
            "\n",
        );

        let line = first_rustc_error_line(stderr).expect("an error line is present");

        assert!(
            line.contains("cannot find macro"),
            "the first error-level diagnostic wins: {line}"
        );
    }

    #[test]
    fn first_rustc_error_line_skips_leading_human_warnings() {
        let stderr = "warning: ignoring -C extra-filename flag due to -o flag\n\
                      \n\
                      error[E0433]: failed to resolve: use of undeclared crate `nope`\n\
                      error: aborting due to 1 previous error\n";

        let line = first_rustc_error_line(stderr).expect("an error line is present");

        assert_eq!(
            line,
            "error[E0433]: failed to resolve: use of undeclared crate `nope`"
        );
    }

    #[test]
    fn first_rustc_error_line_matches_unnumbered_human_errors() {
        let stderr = "warning: unused import: `std::io`\nerror: expected one of `!` or `::`\n";

        let line = first_rustc_error_line(stderr).expect("an error line is present");

        assert_eq!(line, "error: expected one of `!` or `::`");
    }

    #[test]
    fn first_rustc_error_line_falls_back_to_the_first_content_line() {
        // rustc killed by a signal, or a wrapper that failed before rustc ran,
        // leaves no error-level diagnostic. Report something rather than
        // "(no output)" — a refusal with no stated cause is what
        // kunobi-ninja/kache#431 was about.
        let line = first_rustc_error_line("\n\nwarning: something odd\nnote: more\n");

        assert_eq!(line, Some("warning: something odd"));
        assert_eq!(
            first_rustc_error_line("   \n \n"),
            None,
            "blank is no cause"
        );
        assert_eq!(first_rustc_error_line(""), None);
    }

    // --- cache key module-change detection test ---

    #[test]
    fn test_cache_key_changes_with_module_file() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        std::fs::write(src.join("lib.rs"), b"mod utils;\npub fn hello() {}").unwrap();
        std::fs::write(src.join("utils.rs"), b"pub fn helper() {}").unwrap();

        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mylib".to_string(),
            src.join("lib.rs").to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition=2021".to_string(),
        ];

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();

        let parsed1 = RustcArgs::parse(&args_vec).unwrap();
        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();

        // Modify the module file (NOT lib.rs)
        std::fs::write(
            src.join("utils.rs"),
            b"pub fn helper() { println!(\"changed\"); }",
        )
        .unwrap();

        let parsed2 = RustcArgs::parse(&args_vec).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();

        assert_ne!(
            key1, key2,
            "cache key must change when a module file changes"
        );
    }

    // --- cache key determinism with multiple source files ---

    #[test]
    fn test_cache_key_stable_with_module_files() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();

        std::fs::write(src.join("lib.rs"), b"mod a;\nmod b;\npub fn lib_fn() {}").unwrap();
        std::fs::write(src.join("a.rs"), b"pub fn a_fn() {}").unwrap();
        std::fs::write(src.join("b.rs"), b"pub fn b_fn() {}").unwrap();

        let args_vec: Vec<String> = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "testcrate".to_string(),
            src.join("lib.rs").to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition=2021".to_string(),
        ];

        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();

        let parsed1 = RustcArgs::parse(&args_vec).unwrap();
        let parsed2 = RustcArgs::parse(&args_vec).unwrap();

        let key1 = compute_cache_key(&parsed1, &fh, &pn).unwrap();
        let key2 = compute_cache_key(&parsed2, &fh, &pn).unwrap();

        assert_eq!(
            key1, key2,
            "cache key must be deterministic with multiple source files"
        );
    }

    // ────────────────────────────────────────────────────────────────
    // rustc cache-key correctness matrix
    //
    // Property under test: the key must react to every input that
    // changes rustc's *output artifact*, and must NOT react to inputs
    // that only affect diagnostics. A missed input is a miscache (a
    // false hit serving the wrong artifact); a spurious change is
    // over-keying (a missed hit, wasted work).
    //
    // The testable seam is `compute_cache_key` itself: it forks rustc
    // (`get_rustc_version`, the `--emit=dep-info` pre-pass) and reads
    // source files, so each case builds a real temp `.rs` file plus a
    // `RustcArgs` and compares two keys. Cases that depend on env vars
    // (`RUSTFLAGS`) mutate the process environment and are isolated
    // onto a serial mutex so parallel test threads can't interleave.
    // ────────────────────────────────────────────────────────────────

    /// Serializes every test that computes a cache key through the shared
    /// process-state lock also used by argument-parser tests.
    ///
    /// `compute_cache_key` reads process-wide env (`RUSTFLAGS`,
    /// `CARGO_ENCODED_RUSTFLAGS`, `CARGO_CFG_*`); the env-mutating
    /// matrix case below temporarily changes `RUSTFLAGS`. `cargo test`
    /// runs tests as parallel threads of one process, so without a
    /// shared lock any test's two key computations can straddle that
    /// mutation and observe a spurious key difference — that is exactly
    /// how the `assert_eq` tests `test_cache_key_deterministic` and
    /// `test_coverage_keys_consistent_across_remap_forms` flaked on CI.
    ///
    /// The lock is therefore NOT matrix-scoped: every test that calls
    /// `compute_cache_key` — matrix or not — holds it for its full
    /// duration. New key tests must do the same; that is the price of
    /// `compute_cache_key` reading process-global env directly.
    /// Keep the local name used throughout this large test module while the
    /// underlying lock remains shared with other process-state observers.
    fn key_test_lock() -> crate::test_support::ProcessStateTestGuard {
        process_state_test_lock()
    }

    /// Key computation stashes this compile's unit identity and its per-extern
    /// producer ids, and each is TAKEN — a second read yields `None`, so a
    /// compile that computes no rustc key cannot inherit the previous one's
    /// identities from the same process (kunobi-ninja/kache#627).
    #[test]
    fn key_computation_stashes_unit_identity_and_yields_it_once() {
        let _lock = key_test_lock();
        let args: Vec<String> = [
            "rustc",
            "--crate-name",
            "app",
            "src/lib.rs",
            "-C",
            "extra-filename=-843f02d6a46ebef1",
            "--extern",
            "foo_old=/w/target/debug/deps/libfoo-0532daf0ee3516f0.rlib",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let mut parsed = RustcArgs::parse(&args).unwrap();
        // Skip the dep-info pre-pass: this is about what the externs loop
        // records, not source discovery.
        parsed.source_file = None;

        compute_cache_key(&parsed, &FileHasher::new(), &PathNormalizer::empty()).unwrap();

        assert_eq!(
            take_last_key_unit_id().as_deref(),
            Some("843f02d6a46ebef1"),
            "the compile's own `-C extra-filename`"
        );
        assert_eq!(take_last_key_unit_id(), None, "taken, not copied");

        let units = take_last_key_extern_units().expect("recorded with the digests");
        assert_eq!(
            units.get("foo_old").map(String::as_str),
            // Keyed by the alias the consumer used; the value is the producer's
            // identity, recovered from the artifact filename even though that
            // file does not exist here.
            Some("0532daf0ee3516f0")
        );
        assert_eq!(take_last_key_extern_units(), None, "taken, not copied");
    }

    /// The key stashes are per-thread, so a concurrent key computation can
    /// neither overwrite nor consume another's (kunobi-ninja/kache#777).
    ///
    /// Before the stashes were thread-local this was the shape that made
    /// `key_computation_stashes_unit_identity_and_yields_it_once` flaky under
    /// the default `cargo test` parallelism: any other thread computing a key
    /// between a compute and its take would win the race. The outer
    /// `key_test_lock` still serializes this group against the env-mutating
    /// matrix; what runs concurrently here is the stash access itself.
    #[test]
    fn key_stashes_do_not_leak_across_threads() {
        let _lock = key_test_lock();

        // Distinct unit ids per thread, so a leak shows up as another thread's
        // value rather than as an absence.
        let units = ["aaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbb", "cccccccccccccccc"];
        std::thread::scope(|scope| {
            for unit in units {
                scope.spawn(move || {
                    let extra = format!("extra-filename=-{unit}");
                    let extern_arg = format!("dep_{unit}=/w/target/debug/deps/libdep-{unit}.rlib");
                    let args: Vec<String> = [
                        "rustc",
                        "--crate-name",
                        "app",
                        "src/lib.rs",
                        "-C",
                        &extra,
                        "--extern",
                        &extern_arg,
                    ]
                    .iter()
                    .map(|s| s.to_string())
                    .collect();
                    let mut parsed = RustcArgs::parse(&args).unwrap();
                    // Skip the dep-info pre-pass, as above: forking rustc from
                    // every thread would swamp the point being made.
                    parsed.source_file = None;

                    // Loop so the interleaving windows overlap rather than each
                    // thread racing through its compute/take once.
                    for _ in 0..16 {
                        compute_cache_key(&parsed, &FileHasher::new(), &PathNormalizer::empty())
                            .unwrap();

                        assert_eq!(
                            take_last_key_unit_id().as_deref(),
                            Some(unit),
                            "each thread sees its own unit id"
                        );
                        assert_eq!(take_last_key_unit_id(), None, "taken, not copied");

                        let recorded =
                            take_last_key_extern_units().expect("recorded with the digests");
                        assert_eq!(
                            recorded.get(&format!("dep_{unit}")).map(String::as_str),
                            Some(unit),
                            "each thread sees its own extern units"
                        );
                        assert_eq!(take_last_key_extern_units(), None, "taken, not copied");

                        assert!(
                            take_last_key_externs().is_some(),
                            "digests ride the same thread as their identities"
                        );
                        assert!(take_last_key_fields().is_some(), "per-group digests too");
                    }
                });
            }
        });
    }

    /// True if a bare `rustc` is invocable. `compute_cache_key` forks
    /// rustc for the version probe and dep-info pre-pass; without it
    /// the key still computes (the pre-pass falls back) but the
    /// matrix's intent is to exercise the real path. Guard-skip when
    /// absent, consistent with other compiler-forking tests.
    fn rustc_available() -> bool {
        std::process::Command::new("rustc")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    #[cfg(unix)]
    fn rustc_exe_name() -> &'static str {
        "rustc"
    }

    #[cfg(unix)]
    fn rustc_path_on_path() -> Option<PathBuf> {
        let path_var = std::env::var_os("PATH")?;
        std::env::split_paths(&path_var)
            .map(|dir| dir.join(rustc_exe_name()))
            .find(|path| path.is_file())
    }

    #[cfg(unix)]
    fn shell_single_quote(path: &Path) -> String {
        format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
    }

    #[cfg(unix)]
    fn write_rustc_version_wrapper(root: &Path, subdir: &str, version: &str) -> PathBuf {
        let real_rustc = rustc_path_on_path().expect("rustc should be on PATH");
        let dir = root.join(subdir);
        std::fs::create_dir_all(&dir).unwrap();
        let wrapper = dir.join("rustc");
        let script = format!(
            "#!/bin/sh\n\
if [ \"$1\" = \"--version\" ] && [ \"$2\" = \"--verbose\" ]; then\n\
cat <<'KACHE_RUSTC_VERSION'\n\
{version}\n\
KACHE_RUSTC_VERSION\n\
exit 0\n\
fi\n\
exec {} \"$@\"\n",
            shell_single_quote(&real_rustc)
        );
        std::fs::write(&wrapper, script).unwrap();
        let mut perms = std::fs::metadata(&wrapper).unwrap().permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
        std::fs::set_permissions(&wrapper, perms).unwrap();
        wrapper
    }

    /// Build a minimal lib-crate arg vector around a temp source file.
    /// Callers push the dimension-under-test onto the returned vec.
    fn base_args(source: &Path) -> Vec<String> {
        vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "mxcrate".to_string(),
            source.to_string_lossy().to_string(),
            "--crate-type".to_string(),
            "lib".to_string(),
            "--edition=2021".to_string(),
        ]
    }

    /// Compute a key for an arg vector. The source file path is
    /// already embedded in `args` (positional) — `RustcArgs::parse`
    /// picks it up — so no separate source argument is needed.
    fn key_for(args: &[String]) -> String {
        let parsed = RustcArgs::parse(args).unwrap();
        let fh = FileHasher::new();
        let pn = PathNormalizer::empty();
        compute_cache_key(&parsed, &fh, &pn).unwrap()
    }

    fn restore_env_var(key: &str, old: Option<std::ffi::OsString>) {
        match old {
            Some(value) => unsafe { std::env::set_var(key, value) },
            None => unsafe { std::env::remove_var(key) },
        }
    }

    /// `KACHE_RUSTC_PATH_NORMALIZE=0` bakes real machine-local paths into DWARF
    /// (no `--remap-path-prefix`), so the opt-out key MUST be path-local:
    /// otherwise two checkouts at different paths compute the same key and a
    /// shared cache serves one checkout's real-path artifact to another
    /// (kunobi-ninja/kache#480). This pins the exact regression — two builds
    /// that differ ONLY in cwd (the DWARF `comp_dir`) must get different opt-out
    /// keys, while the default (remapped) build stays cwd-portable.
    #[test]
    fn opt_out_key_is_path_local_but_default_stays_portable() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
        let old_cwd = std::env::current_dir().unwrap();

        // Two identical crates at DIFFERENT paths; source arg is relative
        // ("lib.rs") so cwd is the only thing that varies — exactly what cargo
        // passes and what makes `comp_dir` the discriminator.
        let dir_a = tempfile::tempdir().unwrap();
        let dir_b = tempfile::tempdir().unwrap();
        std::fs::write(dir_a.path().join("lib.rs"), "pub fn f() {}\n").unwrap();
        std::fs::write(dir_b.path().join("lib.rs"), "pub fn f() {}\n").unwrap();
        let args = base_args(Path::new("lib.rs"));

        // SAFETY: env access is serialized by the process-state test lock; restored below.
        unsafe { std::env::set_var("KACHE_RUSTC_PATH_NORMALIZE", "0") };
        std::env::set_current_dir(dir_a.path()).unwrap();
        let optout_a = key_for(&args);
        std::env::set_current_dir(dir_b.path()).unwrap();
        let optout_b = key_for(&args);

        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);
        std::env::set_current_dir(dir_a.path()).unwrap();
        let default_a = key_for(&args);
        std::env::set_current_dir(dir_b.path()).unwrap();
        let default_b = key_for(&args);

        std::env::set_current_dir(&old_cwd).unwrap();
        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);

        assert_ne!(
            optout_a, optout_b,
            "opt-out builds bake real paths, so keys must be cwd-local"
        );
        assert_eq!(
            default_a, default_b,
            "default (remapped) builds must stay cwd-portable"
        );
        assert_ne!(
            optout_a, default_a,
            "opt-out must be a separate namespace from remapped builds"
        );
    }

    /// The opt-out fold must cover EVERY prefix the normalizer would have
    /// remapped — not just cwd/$HOME. A build-script `OUT_DIR` lives under
    /// `$CARGO_TARGET_DIR`, which the default key normalizes to `<TARGET>`; if
    /// the opt-out fold missed that prefix, two builds under different target
    /// dirs (each baking a different real `OUT_DIR` path into DWARF) would
    /// collide on one opt-out key. Folding the normalizer's own `raw_prefixes`
    /// closes that gap by construction. Pins it: changing only
    /// `$CARGO_TARGET_DIR` changes the opt-out key but not the (portable)
    /// default key.
    #[test]
    fn opt_out_key_folds_all_normalizer_prefixes_not_just_home() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
        let old_target = std::env::var_os("CARGO_TARGET_DIR");

        let ws = tempfile::tempdir().unwrap();
        let src = ws.path().join("lib.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        let target_a = tempfile::tempdir().unwrap();
        let target_b = tempfile::tempdir().unwrap();
        // Absolute source (same for both variants) so the pre-pass finds it
        // regardless of cwd; $CARGO_TARGET_DIR is then the only thing that varies.
        let args = base_args(&src);

        // Build the normalizer AFTER setting CARGO_TARGET_DIR so its `<TARGET>`
        // rule reflects the current target dir (from_env reads the env).
        let key = || {
            let parsed = RustcArgs::parse(&args).unwrap();
            let fh = FileHasher::new();
            let pn = PathNormalizer::from_env(Some(ws.path()));
            compute_cache_key(&parsed, &fh, &pn).unwrap()
        };

        // SAFETY: env access is serialized by the process-state test lock; restored below.
        unsafe { std::env::set_var("KACHE_RUSTC_PATH_NORMALIZE", "0") };
        unsafe { std::env::set_var("CARGO_TARGET_DIR", target_a.path()) };
        let optout_a = key();
        unsafe { std::env::set_var("CARGO_TARGET_DIR", target_b.path()) };
        let optout_b = key();

        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);
        unsafe { std::env::set_var("CARGO_TARGET_DIR", target_a.path()) };
        let default_a = key();
        unsafe { std::env::set_var("CARGO_TARGET_DIR", target_b.path()) };
        let default_b = key();

        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);
        restore_env_var("CARGO_TARGET_DIR", old_target);

        assert_ne!(
            optout_a, optout_b,
            "opt-out key must fold the raw $CARGO_TARGET_DIR prefix (OUT_DIR lives under it)"
        );
        assert_eq!(
            default_a, default_b,
            "default build normalizes $CARGO_TARGET_DIR to <TARGET>, so it stays portable"
        );
    }

    /// Coverage builds skip remap injection too (llvm-cov / tarpaulin need real
    /// paths in the profraw), so they bake real machine-local paths into DWARF
    /// exactly like the `KACHE_RUSTC_PATH_NORMALIZE=0` opt-out. Their `remap:none`
    /// key must therefore be path-local as well, or a shared cache serves one
    /// checkout's real-path coverage artifact to another (the coverage analog of
    /// kunobi-ninja/kache#480). Pins it: two coverage builds differing only in
    /// cwd must get different keys.
    #[test]
    fn coverage_key_is_path_local() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let old_cwd = std::env::current_dir().unwrap();
        // Force the opt-out OFF so this test exercises the COVERAGE `remap:none`
        // path specifically. If `KACHE_RUSTC_PATH_NORMALIZE=0` were set in the
        // ambient env, `path_normalize_disabled` would be true and the fold
        // would fire via the opt-out — passing even if coverage regressed to the
        // old opt-out-only condition. Removing it pins the coverage path.
        let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);

        let dir_a = tempfile::tempdir().unwrap();
        let dir_b = tempfile::tempdir().unwrap();
        std::fs::write(dir_a.path().join("lib.rs"), "pub fn f() {}\n").unwrap();
        std::fs::write(dir_b.path().join("lib.rs"), "pub fn f() {}\n").unwrap();
        let mut args = base_args(Path::new("lib.rs"));
        args.push("-Cinstrument-coverage".to_string());

        // Sanity-check the fixture is the coverage path, not the opt-out path.
        let parsed = RustcArgs::parse(&args).unwrap();
        assert!(parsed.has_coverage_instrumentation());
        assert!(
            !parsed.path_normalize_disabled,
            "test must exercise the coverage remap:none path, not the opt-out path"
        );

        std::env::set_current_dir(dir_a.path()).unwrap();
        let cov_a = key_for(&args);
        std::env::set_current_dir(dir_b.path()).unwrap();
        let cov_b = key_for(&args);

        std::env::set_current_dir(&old_cwd).unwrap();
        restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);

        assert_ne!(
            cov_a, cov_b,
            "coverage builds bake real paths, so their keys must be cwd-local"
        );
    }

    #[test]
    fn key_rustc_bootstrap_presence_changes_key_but_empty_is_identity() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let old = std::env::var_os("RUSTC_BOOTSTRAP");

        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("lib.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        let args = base_args(&src);

        unsafe {
            std::env::remove_var("RUSTC_BOOTSTRAP");
        }
        let key_unset = key_for(&args);

        // Empty must hash identically to unset: that is what keeps existing
        // caches valid (no CACHE_KEY_VERSION bump for the common case).
        unsafe {
            std::env::set_var("RUSTC_BOOTSTRAP", "");
        }
        let key_empty = key_for(&args);

        unsafe {
            std::env::set_var("RUSTC_BOOTSTRAP", "1");
        }
        let key_set = key_for(&args);

        unsafe {
            std::env::set_var("RUSTC_BOOTSTRAP", "some_crate");
        }
        let key_other = key_for(&args);

        restore_env_var("RUSTC_BOOTSTRAP", old);

        assert_eq!(
            key_unset, key_empty,
            "empty RUSTC_BOOTSTRAP must equal unset"
        );
        assert_ne!(key_unset, key_set, "RUSTC_BOOTSTRAP=1 must change the key");
        assert_ne!(
            key_set, key_other,
            "different RUSTC_BOOTSTRAP values must differ"
        );
    }

    #[test]
    fn key_cargo_encoded_rustflags_changes_key() {
        // cargo passes flags via CARGO_ENCODED_RUSTFLAGS (\x1f-separated); they
        // affect codegen, so they must be folded into the key.
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let old = std::env::var_os("CARGO_ENCODED_RUSTFLAGS");
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("lib.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        let args = base_args(&src);

        unsafe {
            std::env::remove_var("CARGO_ENCODED_RUSTFLAGS");
        }
        let key_unset = key_for(&args);

        unsafe {
            std::env::set_var("CARGO_ENCODED_RUSTFLAGS", "-C\x1ftarget-cpu=native");
        }
        let key_set = key_for(&args);

        unsafe {
            std::env::set_var("CARGO_ENCODED_RUSTFLAGS", "-C\x1ftarget-cpu=x86-64-v3");
        }
        let key_other = key_for(&args);

        restore_env_var("CARGO_ENCODED_RUSTFLAGS", old);

        assert_ne!(
            key_unset, key_set,
            "setting CARGO_ENCODED_RUSTFLAGS must change the key"
        );
        assert_ne!(
            key_set, key_other,
            "different encoded rustflags must diverge the key"
        );
    }

    #[test]
    fn key_cargo_cfg_env_changes_key() {
        // CARGO_CFG_* vars (cargo's reflection of `--cfg`) are folded into the
        // key so a build-script cfg change diverges it.
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }
        let var = "CARGO_CFG_KACHE_TEST_FLAG";
        let old = std::env::var_os(var);
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("lib.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        let args = base_args(&src);

        unsafe {
            std::env::remove_var(var);
        }
        let key_unset = key_for(&args);

        unsafe {
            std::env::set_var(var, "1");
        }
        let key_set = key_for(&args);

        unsafe {
            std::env::set_var(var, "2");
        }
        let key_other = key_for(&args);

        restore_env_var(var, old);

        assert_ne!(key_unset, key_set, "a CARGO_CFG_* var must change the key");
        assert_ne!(
            key_set, key_other,
            "a different CARGO_CFG_* value must diverge the key"
        );
    }

    // ── "should change" cases — varying a codegen-affecting input ──

    #[cfg(unix)]
    #[test]
    fn key_matrix_rustc_version_changes_key() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        let rustc_a = write_rustc_version_wrapper(
            dir.path(),
            "toolchain-a",
            "rustc 1.95.0-test-a\nbinary: test-a\ncommit-hash: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        );
        let rustc_b = write_rustc_version_wrapper(
            dir.path(),
            "toolchain-b",
            "rustc 1.95.0-test-b\nbinary: test-b\ncommit-hash: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
        );

        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut args_a = base_args(&source);
        args_a[0] = rustc_a.to_string_lossy().into_owned();
        let mut args_b = base_args(&source);
        args_b[0] = rustc_b.to_string_lossy().into_owned();

        assert_ne!(
            key_for(&args_a),
            key_for(&args_b),
            "`rustc --version --verbose` output must affect the cache key"
        );
    }

    #[test]
    fn key_matrix_manifest_dir_runtime_env_path_changes_key_across_workspaces() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }

        let old_manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
        let dir = tempfile::tempdir().unwrap();
        let workspace_a = dir.path().join("checkout-a");
        let workspace_b = dir.path().join("checkout-b");

        fn write_helper(workspace: &Path) -> PathBuf {
            let src = workspace.join("helper/src");
            std::fs::create_dir_all(&src).unwrap();
            let lib = src.join("lib.rs");
            std::fs::write(
                &lib,
                r#"pub fn manifest_dir() -> &'static str {
    env!("CARGO_MANIFEST_DIR")
}
"#,
            )
            .unwrap();
            lib
        }

        let source_a = write_helper(&workspace_a);
        let source_b = write_helper(&workspace_b);
        let fh = FileHasher::new();

        let manifest_a = workspace_a.join("helper").canonicalize().unwrap();
        unsafe {
            std::env::set_var("CARGO_MANIFEST_DIR", manifest_a);
        }
        let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
        let pn_a = PathNormalizer::from_env(Some(&workspace_a));
        let key_a = compute_cache_key(&parsed_a, &fh, &pn_a).unwrap();

        let manifest_b = workspace_b.join("helper").canonicalize().unwrap();
        unsafe {
            std::env::set_var("CARGO_MANIFEST_DIR", manifest_b);
        }
        let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
        let pn_b = PathNormalizer::from_env(Some(&workspace_b));
        let key_b = compute_cache_key(&parsed_b, &fh, &pn_b).unwrap();

        restore_env_var("CARGO_MANIFEST_DIR", old_manifest_dir);

        assert_ne!(
            key_a, key_b,
            "CARGO_MANIFEST_DIR is a runtime env! value and must stay checkout-specific"
        );
    }

    #[test]
    fn key_matrix_out_dir_include_pattern_stays_stable_across_workspaces() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }

        let old_out_dir = std::env::var_os("OUT_DIR");
        let old_manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
        let dir = tempfile::tempdir().unwrap();
        let workspace_a = dir.path().join("checkout-a");
        let workspace_b = dir.path().join("checkout-b");

        fn write_generated_include_crate(workspace: &Path) -> (PathBuf, PathBuf) {
            let src = workspace.join("src");
            let out_dir = workspace.join("target/debug/build/include-crate/out");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::create_dir_all(&out_dir).unwrap();

            let generated = out_dir.join("generated.rs");
            std::fs::write(&generated, b"pub fn generated() -> u8 { 7 }\n").unwrap();

            let lib = src.join("lib.rs");
            std::fs::write(
                &lib,
                r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));

pub fn value() -> u8 {
    generated()
}
"#,
            )
            .unwrap();
            (lib, out_dir)
        }

        let (source_a, out_a) = write_generated_include_crate(&workspace_a);
        let (source_b, out_b) = write_generated_include_crate(&workspace_b);
        let fh = FileHasher::new();

        let out_a = out_a.canonicalize().unwrap();
        unsafe {
            std::env::set_var("OUT_DIR", &out_a);
            std::env::set_var("CARGO_MANIFEST_DIR", &workspace_a);
        }
        let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
        let pn_a = PathNormalizer::from_env(Some(&workspace_a));
        let key_a = compute_cache_key(&parsed_a, &fh, &pn_a).unwrap();

        let out_b = out_b.canonicalize().unwrap();
        unsafe {
            std::env::set_var("OUT_DIR", &out_b);
            std::env::set_var("CARGO_MANIFEST_DIR", &workspace_b);
        }
        let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
        let pn_b = PathNormalizer::from_env(Some(&workspace_b));
        let key_b = compute_cache_key(&parsed_b, &fh, &pn_b).unwrap();

        restore_env_var("OUT_DIR", old_out_dir);
        restore_env_var("CARGO_MANIFEST_DIR", old_manifest_dir);

        assert_eq!(
            key_a, key_b,
            "OUT_DIR include!() paths should stay portable across workspaces"
        );
    }

    #[test]
    fn key_matrix_out_dir_dual_pattern_diverges_across_workspaces() {
        let _lock = key_test_lock();
        if !rustc_available() {
            return;
        }

        let old_out_dir = std::env::var_os("OUT_DIR");
        let dir = tempfile::tempdir().unwrap();
        let workspace_a = dir.path().join("checkout-a");
        let workspace_b = dir.path().join("checkout-b");

        fn write_dual_pattern_crate(workspace: &Path) -> (PathBuf, PathBuf) {
            let src = workspace.join("src");
            let out_dir = workspace.join("target/debug/build/dual-crate/out");
            std::fs::create_dir_all(&src).unwrap();
            std::fs::create_dir_all(&out_dir).unwrap();

            let generated = out_dir.join("generated.rs");
            std::fs::write(&generated, b"pub fn generated() -> u8 { 7 }\n").unwrap();

            let lib = src.join("lib.rs");
            std::fs::write(
                &lib,
                r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));

pub const OUT_DIR_AT_COMPILE_TIME: &str = env!("OUT_DIR");

pub fn value() -> (&'static str, u8) {
    (OUT_DIR_AT_COMPILE_TIME, generated())
}
"#,
            )
            .unwrap();
            (lib, out_dir)
        }

        let (source_a, out_a) = write_dual_pattern_crate(&workspace_a);
        let (source_b, out_b) = write_dual_pattern_crate(&workspace_b);
        let fh = FileHasher::new();

        let out_a = out_a.canonicalize().unwrap();
        unsafe {
            std::env::set_var("OUT_DIR", &out_a);
        }
        let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
        let pn_a = PathNormalizer::from_env(Some(&workspace_a));
        let key_a = compute_cache_key(&parsed_a, &fh, &pn_a).unwrap();

        let out_b = out_b.canonicalize().unwrap();
        unsafe {
            std::env::set_var("OUT_DIR", &out_b);
        }
        let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
        let pn_b = PathNormalizer::from_env(Some(&workspace_b));
        let key_b = compute_cache_key(&parsed_b, &fh, &pn_b).unwrap();

        restore_env_var("OUT_DIR", old_out_dir);

        assert_ne!(
            key_a, key_b,
            "OUT_DIR dual pattern must stay checkout-specific: include!() alone is path-only, \
             but env!(\"OUT_DIR\") as a runtime value bakes the absolute path into the artifact"
        );
    }

    #[test]
    fn key_matrix_emit_changes_key() {
        // `cargo check` runs rustc --emit=metadata (-> .rmeta);
        // `cargo build` runs --emit=link (-> .rlib). Same crate, same
        // everything else the key hashes => without hashing `emit` the
        // two collide and a check entry could be served to a build.
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut metadata = base_args(&source);
        metadata.push("--emit=metadata".to_string());
        let mut link = base_args(&source);
        link.push("--emit=link".to_string());

        assert_ne!(
            key_for(&metadata),
            key_for(&link),
            "`--emit=metadata` vs `--emit=link` must produce different keys"
        );
    }

    #[test]
    fn key_matrix_opt_level_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut o0 = base_args(&source);
        o0.extend(["-C".to_string(), "opt-level=0".to_string()]);
        let mut o3 = base_args(&source);
        o3.extend(["-C".to_string(), "opt-level=3".to_string()]);

        assert_ne!(
            key_for(&o0),
            key_for(&o3),
            "`-C opt-level` must affect the key"
        );
    }

    #[test]
    fn key_matrix_debug_assertions_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut on = base_args(&source);
        on.extend(["-C".to_string(), "debug-assertions=on".to_string()]);
        let mut off = base_args(&source);
        off.extend(["-C".to_string(), "debug-assertions=off".to_string()]);

        assert_ne!(
            key_for(&on),
            key_for(&off),
            "`-C debug-assertions` must affect the key"
        );
    }

    #[test]
    fn key_matrix_cfg_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let base = base_args(&source);
        let mut with_cfg = base_args(&source);
        with_cfg.extend(["--cfg".to_string(), "extra_feature".to_string()]);

        assert_ne!(
            key_for(&base),
            key_for(&with_cfg),
            "a `--cfg` value must affect the key"
        );
    }

    #[test]
    fn key_matrix_feature_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut std_feat = base_args(&source);
        std_feat.extend(["--cfg".to_string(), "feature=\"std\"".to_string()]);
        let mut both = std_feat.clone();
        both.extend(["--cfg".to_string(), "feature=\"derive\"".to_string()]);

        assert_ne!(
            key_for(&std_feat),
            key_for(&both),
            "adding a feature must affect the key"
        );
    }

    #[test]
    fn key_matrix_edition_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let mut e2018 = base_args(&source);
        e2018.retain(|a| a != "--edition=2021");
        e2018.push("--edition=2018".to_string());
        let e2021 = base_args(&source); // already --edition=2021

        assert_ne!(
            key_for(&e2018),
            key_for(&e2021),
            "`--edition` must affect the key"
        );
    }

    #[test]
    fn key_matrix_target_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        // Two distinct triples — neither needs to be installed; the
        // key hashes the `--target` string, it does not invoke a
        // cross-compile.
        let mut t1 = base_args(&source);
        t1.push("--target=x86_64-unknown-linux-gnu".to_string());
        let mut t2 = base_args(&source);
        t2.push("--target=aarch64-apple-darwin".to_string());

        assert_ne!(
            key_of_flags(&t1),
            key_of_flags(&t2),
            "`--target` must affect the key"
        );
    }

    #[test]
    fn key_matrix_crate_type_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let rlib = base_args(&source); // --crate-type lib
        let mut staticlib = base_args(&source);
        for a in staticlib.iter_mut() {
            if a == "lib" {
                *a = "staticlib".to_string();
            }
        }

        assert_ne!(
            key_for(&rlib),
            key_for(&staticlib),
            "`--crate-type` must affect the key"
        );
    }

    #[test]
    fn key_matrix_rustflags_env_changes_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let args = base_args(&source);

        let saved = std::env::var("RUSTFLAGS").ok();

        // SAFETY: env access is serialized by the process-state test lock; restored below.
        unsafe { std::env::remove_var("RUSTFLAGS") };
        let key_none = key_for(&args);

        unsafe { std::env::set_var("RUSTFLAGS", "-C target-cpu=native") };
        let key_set = key_for(&args);

        match saved {
            Some(v) => unsafe { std::env::set_var("RUSTFLAGS", v) },
            None => unsafe { std::env::remove_var("RUSTFLAGS") },
        }

        assert_ne!(key_none, key_set, "`RUSTFLAGS` env var must affect the key");
    }

    /// Direct test of the `normalize_rustflags` helper.
    #[test]
    fn normalize_rustflags_collapses_whitespace() {
        assert_eq!(normalize_rustflags("-C a -C b"), "-C a -C b");
        // Multiple spaces between tokens → single space.
        assert_eq!(normalize_rustflags("-C a    -C b"), "-C a -C b");
        // Leading / trailing whitespace stripped.
        assert_eq!(normalize_rustflags("  -C a   -C b  "), "-C a -C b");
        // Mixed whitespace (tabs, newlines) treated as whitespace.
        assert_eq!(normalize_rustflags("-C a\t\t-C b"), "-C a -C b");
        // Order is preserved (rustc resolves later flags over earlier ones).
        assert_eq!(normalize_rustflags("-Cfoo=b   -Cfoo=a"), "-Cfoo=b -Cfoo=a");
        assert_ne!(
            normalize_rustflags("-Cfoo=a -Cfoo=b"),
            normalize_rustflags("-Cfoo=b -Cfoo=a")
        );
    }

    /// Direct test of the `scrub_remap_from_prefixes` helper.
    #[test]
    fn scrub_remap_from_prefixes_collapses_from_keeps_to() {
        let scrub = |s: &str| scrub_remap_from_prefixes(s.split_whitespace()).join(" ");

        // The core case: two checkouts converge, TO preserved.
        assert_eq!(
            scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
            "--remap-path-prefix=<REMAP_FROM>=/topsrcdir/"
        );
        assert_eq!(
            scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
            scrub("--remap-path-prefix=/abs/clone-b/=/topsrcdir/"),
            "different checkout `from` paths must collapse identically"
        );

        // Space-separated form: value is the next token.
        assert_eq!(
            scrub("--remap-path-prefix /abs/clone-a/=/topsrcdir/"),
            "--remap-path-prefix <REMAP_FROM>=/topsrcdir/"
        );

        // The clang `-f*-prefix-map` family (equals form).
        for flag in [
            "-ffile-prefix-map",
            "-fdebug-prefix-map",
            "-fmacro-prefix-map",
        ] {
            assert_eq!(
                scrub(&format!("{flag}=/abs/clone-a/=/virt/")),
                format!("{flag}=<REMAP_FROM>=/virt/")
            );
        }

        // Split on the LAST `=` (FROM may contain `=`), matching rustc/clang.
        assert_eq!(
            scrub("--remap-path-prefix=/a=b/clone-a/=/topsrcdir/"),
            "--remap-path-prefix=<REMAP_FROM>=/topsrcdir/"
        );

        // Changing TO must NOT be scrubbed away — it stays in the result.
        assert_ne!(
            scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
            scrub("--remap-path-prefix=/abs/clone-a/=/other/")
        );

        // Non-remap flags pass through verbatim.
        assert_eq!(
            scrub("-C opt-level=2 -C debuginfo=2"),
            "-C opt-level=2 -C debuginfo=2"
        );
        // A remap value with no `=` is malformed and left untouched.
        assert_eq!(
            scrub("--remap-path-prefix=garbage"),
            "--remap-path-prefix=garbage"
        );
    }

    #[test]
    fn normalize_direct_remap_normalizes_known_from_but_keeps_to() {
        let dir = tempfile::tempdir().unwrap();
        let workspace = dir.path().join("workspace");
        std::fs::create_dir_all(&workspace).unwrap();
        let workspace =
            PathBuf::from(crate::path_normalizer::canonical_string(&workspace).unwrap());
        let normalizer = PathNormalizer::from_env(Some(&workspace));
        let from = workspace.join("dir=with=equals");
        let to = workspace.join("literal-to");
        let value = format!("{}={}", from.display(), to.display());

        assert_eq!(
            normalize_direct_remap_value(&value, &normalizer),
            format!(
                "{}={}",
                Path::new("<WORKSPACE>").join("dir=with=equals").display(),
                to.display()
            ),
            "only FROM is normalized; TO remains verbatim"
        );
        assert_eq!(
            normalize_direct_remap_value("malformed", &normalizer),
            "malformed"
        );
    }

    #[test]
    fn key_matrix_direct_remap_path_prefix_is_keyed_portably_and_in_order() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let none = key_of_flags(&flag_base(&source, &[]));
        let separated = key_of_flags(&flag_base(
            &source,
            &["--remap-path-prefix", "/work/clone-a=/virtual/src"],
        ));
        let attached = key_of_flags(&flag_base(
            &source,
            &["--remap-path-prefix=/work/clone-a=/virtual/src"],
        ));
        let unrelated_from = key_of_flags(&flag_base(
            &source,
            &["--remap-path-prefix=/work/clone-b=/virtual/src"],
        ));
        let other_target = key_of_flags(&flag_base(
            &source,
            &["--remap-path-prefix=/work/clone-a=/virtual/other"],
        ));
        let remap_root = format!("--remap-path-prefix={}=/virtual/root", dir.path().display());
        let remap_source = format!("--remap-path-prefix={}=/virtual/source", source.display());
        let order_ab = key_of_flags(&flag_base(&source, &[&remap_root, &remap_source]));
        let order_ba = key_of_flags(&flag_base(&source, &[&remap_source, &remap_root]));

        assert_ne!(none, separated, "adding a direct remap must change the key");
        assert_eq!(separated, attached, "both rustc spellings are equivalent");
        assert_ne!(
            separated, unrelated_from,
            "without a matching normalization rule, FROM remains semantic"
        );
        assert_ne!(
            separated, other_target,
            "the remap target is embedded in artifacts and must remain key-visible"
        );
        assert_ne!(order_ab, order_ba, "overlapping remap order is semantic");

        let clone_a = dir.path().join("clone-a");
        let clone_b = dir.path().join("clone-b");
        std::fs::create_dir_all(&clone_a).unwrap();
        std::fs::create_dir_all(&clone_b).unwrap();
        let portable_key = |workspace: &Path| {
            let workspace = workspace.canonicalize().unwrap();
            let remap = format!("--remap-path-prefix={}=/virtual/src", workspace.display());
            let mut parsed = RustcArgs::parse(&flag_base(&source, &[&remap])).unwrap();
            parsed.source_file = None;
            compute_cache_key(
                &parsed,
                &FileHasher::new(),
                &PathNormalizer::from_env(Some(&workspace)),
            )
            .unwrap()
        };
        assert_eq!(
            portable_key(&clone_a),
            portable_key(&clone_b),
            "known workspace prefixes normalize portably across checkouts"
        );
    }

    /// The cross-checkout fix (v14): a build system's own `--remap-path-prefix`
    /// (Firefox `--enable-path-remapping`) carries the checkout path on its
    /// `from` side, so two clones at different paths must still hash identically
    /// — and changing the stable `to` target must still diverge the key.
    #[test]
    fn key_matrix_rustflags_remap_path_prefix_stable_across_checkouts() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let args = base_args(&source);

        let saved = std::env::var("RUSTFLAGS").ok();
        let set = |v: &str| unsafe { std::env::set_var("RUSTFLAGS", v) };

        // SAFETY: env access is serialized by the process-state test lock; restored below.
        set("--remap-path-prefix=/work/clone-a/=/topsrcdir/");
        let key_a = key_for(&args);
        set("--remap-path-prefix=/work/clone-b/=/topsrcdir/");
        let key_b = key_for(&args);
        // Same flag, different stable target → must diverge.
        set("--remap-path-prefix=/work/clone-a/=/elsewhere/");
        let key_other_to = key_for(&args);

        match saved {
            Some(v) => unsafe { std::env::set_var("RUSTFLAGS", v) },
            None => unsafe { std::env::remove_var("RUSTFLAGS") },
        }

        assert_eq!(
            key_a, key_b,
            "different checkout paths under the same remap target must not change the key"
        );
        assert_ne!(
            key_a, key_other_to,
            "changing the remap target (`to`) must still change the key"
        );
    }

    /// Cosmetic whitespace differences between cargo / mach assemblies
    /// of the same logical RUSTFLAGS must not change the cache key.
    /// Firefox bench surfaced this as the dominant source of leaf
    /// cache-key divergence; this test pins the fix.
    #[test]
    fn key_matrix_rustflags_whitespace_does_not_change_key() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let args = base_args(&source);

        let saved = std::env::var("RUSTFLAGS").ok();

        // SAFETY: env access is serialized by the process-state test lock; restored below.
        unsafe { std::env::set_var("RUSTFLAGS", "-C debuginfo=2 -C codegen-units=1") };
        let key_tight = key_for(&args);

        // Same flags, cosmetically different whitespace.
        unsafe { std::env::set_var("RUSTFLAGS", "-C debuginfo=2    -C codegen-units=1") };
        let key_loose = key_for(&args);

        // Same flags, leading whitespace.
        unsafe { std::env::set_var("RUSTFLAGS", "  -C debuginfo=2 -C codegen-units=1  ") };
        let key_padded = key_for(&args);

        match saved {
            Some(v) => unsafe { std::env::set_var("RUSTFLAGS", v) },
            None => unsafe { std::env::remove_var("RUSTFLAGS") },
        }

        assert_eq!(
            key_tight, key_loose,
            "RUSTFLAGS extra-whitespace must not change the key"
        );
        assert_eq!(
            key_tight, key_padded,
            "RUSTFLAGS leading/trailing whitespace must not change the key"
        );
    }

    // ── "should NOT change" cases — diagnostics-only inputs ──
    //
    // These flags steer only what rustc *prints*, never the emitted
    // artifact bytes. If the key changes for one of them, that is
    // over-keying (a missed hit) — the test will fail and surface it
    // rather than silently weakening the key.
    //
    // All lint configuration is deliberately absent from this section: it
    // cannot change successful artifact bytes, but it can change whether the
    // compile FAILS, and a hit replays success. See the tests below.

    #[test]
    fn key_matrix_outcome_lint_configuration_changes_key() {
        // `-D warnings` promotes warnings to hard errors: two builds
        // differing only here can disagree about whether the compile
        // succeeded while emitting byte-identical objects on success.
        // Since a hit replays success, the key MUST move (review
        // finding #2) — otherwise an entry stored without the gate
        // serves green to a build the gate should have failed.
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let base = base_args(&source);
        let mut with_lint = base_args(&source);
        with_lint.extend(["-D".to_string(), "warnings".to_string()]);
        let mut with_forbid = base_args(&source);
        with_forbid.extend(["--forbid".to_string(), "warnings".to_string()]);
        let mut with_cap = base_args(&source);
        with_cap.extend(["--cap-lints".to_string(), "allow".to_string()]);
        let mut with_attached = base_args(&source);
        with_attached.push("-Dwarnings".to_string());
        let mut with_warn = base_args(&source);
        with_warn.extend(["-W".to_string(), "unused".to_string()]);
        let mut with_allow = base_args(&source);
        with_allow.extend(["-A".to_string(), "dead_code".to_string()]);
        let mut with_check_cfg = base_args(&source);
        with_check_cfg.extend(["--check-cfg".to_string(), "cfg(foo)".to_string()]);
        let mut with_other_check_cfg = base_args(&source);
        with_other_check_cfg.push("--check-cfg=cfg(bar)".to_string());

        assert_ne!(
            key_for(&base),
            key_for(&with_lint),
            "an outcome-affecting lint gate (`-D warnings`) changes whether \
             the compile fails and MUST change the key"
        );
        assert_ne!(
            key_for(&base),
            key_for(&with_forbid),
            "`--forbid` is outcome-affecting and must change the key"
        );
        assert_ne!(
            key_for(&base),
            key_for(&with_cap),
            "`--cap-lints` re-levels every lint and must change the key"
        );
        assert_ne!(
            key_for(&with_lint),
            key_for(&with_attached),
            "separated (`-D warnings`) and attached (`-Dwarnings`) spellings \
             carry different tokens; each keys distinctly by design"
        );
        assert_ne!(
            key_for(&base),
            key_for(&with_warn),
            "-W can activate a lint that a deny group makes fatal"
        );
        assert_ne!(
            key_for(&base),
            key_for(&with_allow),
            "-A can relax an otherwise fatal lint"
        );
        assert_ne!(
            key_for(&base),
            key_for(&with_check_cfg),
            "--check-cfg controls the unexpected_cfgs outcome"
        );
        assert_ne!(
            key_for(&with_check_cfg),
            key_for(&with_other_check_cfg),
            "different accepted cfg sets must not share a key"
        );
    }

    #[test]
    fn check_cfg_values_are_not_path_normalized() {
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let root = tempfile::tempdir().unwrap();
        let key_at = |workspace: &Path, with_check_cfg: bool| {
            std::fs::create_dir_all(workspace).unwrap();
            let source = workspace.join("lib.rs");
            std::fs::write(&source, b"pub fn hello() {}").unwrap();
            let mut args = base_args(&source);
            if with_check_cfg {
                let semantic_path = workspace
                    .join("generated")
                    .to_string_lossy()
                    .replace('\\', "/");
                args.extend([
                    "--check-cfg".to_string(),
                    format!("cfg(build_path, values(\"{semantic_path}\"))"),
                ]);
            }
            let parsed = RustcArgs::parse(&args).unwrap();
            compute_cache_key(
                &parsed,
                &FileHasher::new(),
                &PathNormalizer::from_env(Some(workspace)),
            )
            .unwrap()
        };

        let workspace_a = root.path().join("checkout-a");
        let workspace_b = root.path().join("checkout-b");
        assert_eq!(
            key_at(&workspace_a, false),
            key_at(&workspace_b, false),
            "the control must prove ordinary workspace paths normalize portably"
        );
        assert_ne!(
            key_at(&workspace_a, true),
            key_at(&workspace_b, true),
            "path-looking check-cfg values are semantic strings and must stay raw"
        );
    }

    #[test]
    fn key_matrix_outcome_lint_gates_key_by_pairing_not_multiset() {
        // The gates are captured as a flat token stream, so folding them
        // sorted would collapse permutations that mean different things:
        // `-D unsafe_code -F warnings` denies unsafe_code (a `#[allow]` in
        // the crate can still re-allow it) and forbids warnings, while the
        // swap forbids unsafe_code (no `#[allow]` escape) and denies
        // warnings. Same token multiset, different outcomes — so the key
        // must distinguish them.
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let gated = |gates: &[&str]| {
            let mut args = base_args(&source);
            args.extend(gates.iter().map(|s| s.to_string()));
            key_for(&args)
        };

        assert_ne!(
            gated(&["-D", "unsafe_code", "-F", "warnings"]),
            gated(&["-F", "unsafe_code", "-D", "warnings"]),
            "swapping which lint is denied and which is forbidden changes \
             the outcome and MUST change the key"
        );
        // (`--force-warn` takes a single lint, never a group, so both sides
        // name concrete lints.)
        assert_ne!(
            gated(&["-D", "unused_mut", "--force-warn", "deprecated"]),
            gated(&["-D", "deprecated", "--force-warn", "unused_mut"]),
            "swapping the deny and force-warn targets changes the outcome \
             and MUST change the key"
        );
        // Argv order is kept as the conservative choice: rustc resolves
        // repeated levels for the same lint last-wins, so a reordered gate
        // list can be a different build. A given build config emits a stable
        // order, so preserving it costs no hits.
        assert_ne!(
            gated(&["-D", "warnings", "-A", "unused", "-D", "unused"]),
            gated(&["-D", "unused", "-A", "unused", "-D", "warnings"]),
            "gate order is preserved in the key"
        );
    }

    #[test]
    fn key_matrix_error_format_does_not_change_key() {
        // `--error-format=json` changes how diagnostics are rendered
        // (cargo always passes it) — never the artifact. The key must
        // not move.
        if !rustc_available() {
            return;
        }
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();

        let base = base_args(&source);
        let mut with_fmt = base_args(&source);
        with_fmt.push("--error-format=json".to_string());

        assert_eq!(
            key_for(&base),
            key_for(&with_fmt),
            "`--error-format` is diagnostics-only and must NOT change \
             the key — a change here is over-keying"
        );
    }

    #[test]
    fn the_stashed_tree_digest_is_taken_once() {
        let _ = LAST_KEY_TREE_DIGEST.try_with(|stash| *stash.borrow_mut() = None);
        assert_eq!(take_last_tree_digest(), None);
        let _ =
            LAST_KEY_TREE_DIGEST.try_with(|stash| *stash.borrow_mut() = Some("tree-1".to_string()));
        assert_eq!(take_last_tree_digest().as_deref(), Some("tree-1"));
        assert_eq!(take_last_tree_digest(), None, "taken, not peeked");
    }

    #[test]
    fn a_deferred_discovery_says_so_when_displayed() {
        let text = DeferredDiscovery.to_string();
        assert!(text.contains("deferred"), "{text}");
        let error: anyhow::Error = DeferredDiscovery.into();
        assert!(error.downcast_ref::<DeferredDiscovery>().is_some());
    }

    #[test]
    fn a_shared_identity_needs_an_absolute_target_and_a_predictable_unit() {
        let _lock = key_test_lock();
        let parse = |argv: &[&str]| {
            RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("debug").join("deps");
        std::fs::create_dir_all(&out).unwrap();
        let out_str = out.to_str().unwrap();
        let eligible = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            "src/lib.rs",
            "--out-dir",
            out_str,
        ]);
        assert!(rustc_shared_prediction_identity(&eligible).is_some());
        let relative = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            "src/lib.rs",
            "--out-dir",
            "target/debug/deps",
        ]);
        assert!(
            rustc_shared_prediction_identity(&relative).is_none(),
            "a relative target directory is not shareable"
        );
        let with_macro = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            "src/lib.rs",
            "--out-dir",
            out_str,
            "--extern",
            "my_macro=/t/debug/deps/libmy_macro-3.so",
        ]);
        assert!(
            rustc_shared_prediction_identity(&with_macro).is_none(),
            "a proc-macro dependency is not predictable by closure alone"
        );
    }

    #[test]
    fn a_discovery_identity_is_the_shared_one_when_predictions_are_on() {
        let _lock = key_test_lock();
        let parse = |argv: &[&str]| {
            RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("debug").join("deps");
        std::fs::create_dir_all(&out).unwrap();
        let out_str = out.to_str().unwrap();
        let eligible = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            "src/lib.rs",
            "--out-dir",
            out_str,
        ]);
        let with_macro = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            "src/lib.rs",
            "--out-dir",
            out_str,
            "--extern",
            "my_macro=/t/debug/deps/libmy_macro-3.so",
        ]);
        let db = dir.path().join("index.db");
        let off = FileHasher::persistent(&db);
        assert_eq!(prediction_discovery_identity(&eligible, &off), None);
        let on = FileHasher::persistent(&db).with_input_predictions(true);
        let identity = prediction_discovery_identity(&eligible, &on).unwrap();
        assert_eq!(
            Some(identity.clone()),
            rustc_shared_prediction_identity(&eligible),
            "the shared spelling comes first"
        );
        assert!(!identity.is_empty());
        assert_eq!(
            prediction_discovery_identity(&with_macro, &on),
            None,
            "not shareable and not predictable: no flight"
        );
    }

    /// A record for a unit under the tree guard is usable only while the
    /// crate tree it was made from is unchanged; a record without a tree
    /// digest is not usable at all for such a unit.
    #[test]
    fn a_guarded_record_is_refused_when_the_tree_changed() {
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let package = dir
            .path()
            .join("registry")
            .join("src")
            .join("index-1")
            .join("kt-1.0.0");
        std::fs::create_dir_all(package.join("src")).unwrap();
        std::fs::write(package.join("src/lib.rs"), "pub fn v() {}\n").unwrap();
        let parse = |argv: &[&str]| {
            RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        let out = dir.path().join("debug").join("deps");
        std::fs::create_dir_all(&out).unwrap();
        let with_macro = parse(&[
            "rustc",
            "--crate-name",
            "kt",
            package.join("src/lib.rs").to_str().unwrap(),
            "--out-dir",
            out.to_str().unwrap(),
            "--extern",
            "my_macro=/t/debug/deps/libmy_macro-3.so",
        ]);
        let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
        // SAFETY: the key test lock serialises environment edits.
        unsafe {
            std::env::set_var("CARGO_MANIFEST_DIR", &package);
            std::env::remove_var("OUT_DIR");
        }
        let on = FileHasher::persistent(&dir.path().join("index.db")).with_input_predictions(true);
        let tree = crate_tree_digest(&on).expect("a registry package has a tree digest");
        let identity = rustc_prediction_identity(&with_macro).unwrap();
        let closure = DepInfo {
            source_files: vec![package.join("src/lib.rs")],
            env_deps: Vec::new(),
        };

        on.record_input_prediction(&identity, Some("kt"), &closure, None);
        assert_eq!(
            predicted_key_inputs(&with_macro, &on),
            Err(Rejection::NoRecord),
            "a record without a tree digest cannot guard a proc-macro unit"
        );

        on.record_input_prediction(&identity, Some("kt"), &closure, Some("stale".to_string()));
        assert_eq!(
            predicted_key_inputs(&with_macro, &on),
            Err(Rejection::TreeChanged)
        );

        on.record_input_prediction(&identity, Some("kt"), &closure, Some(tree.clone()));
        let current = predicted_key_inputs(&with_macro, &on);
        assert_ne!(current, Err(Rejection::TreeChanged), "{current:?}");
        assert_ne!(current, Err(Rejection::NoRecord), "{current:?}");
        assert_eq!(take_last_tree_digest(), Some(tree));

        std::fs::write(package.join("extra.txt"), "read by the macro").unwrap();
        assert_eq!(
            predicted_key_inputs(&with_macro, &on),
            Err(Rejection::TreeChanged),
            "a file added under the package changes the tree"
        );
        unsafe {
            match manifest_dir {
                Some(value) => std::env::set_var("CARGO_MANIFEST_DIR", value),
                None => std::env::remove_var("CARGO_MANIFEST_DIR"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn clippy_identity_reads_the_process_environment() {
        use std::os::unix::fs::PermissionsExt;
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        let driver = dir.path().join("clippy-driver");
        std::fs::write(
            &driver,
            "#!/bin/sh\necho 'clippy 0.1.98 (abc 2026-09-01)'\n",
        )
        .unwrap();
        std::fs::set_permissions(&driver, std::fs::Permissions::from_mode(0o755)).unwrap();
        let member = dir.path().join("member");
        std::fs::create_dir_all(&member).unwrap();
        let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
        // SAFETY: the key test lock serialises environment edits.
        unsafe {
            std::env::set_var("CARGO_MANIFEST_DIR", &member);
            std::env::remove_var("CLIPPY_CONF_DIR");
            std::env::remove_var("CLIPPY_ARGS");
        }
        let identity = clippy_identity(&driver).unwrap();
        let expected = clippy_identity_in(
            &driver,
            |name| std::env::var_os(name),
            std::env::current_dir().ok(),
        )
        .unwrap();
        unsafe {
            match manifest_dir {
                Some(value) => std::env::set_var("CARGO_MANIFEST_DIR", value),
                None => std::env::remove_var("CARGO_MANIFEST_DIR"),
            }
        }
        assert_eq!(identity, expected);
        assert!(identity.starts_with("clippy 0.1.98"), "{identity}");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn the_linux_libc_signature_names_the_running_libc() {
        let family = if cfg!(target_env = "musl") {
            LinuxLibcFamily::Musl
        } else {
            LinuxLibcFamily::Gnu
        };
        let signature = probe_linux_libc_signature(family).unwrap();
        assert!(!signature.is_empty());
        assert!(
            signature.chars().any(|c| c.is_ascii_digit()),
            "a version, not a label: {signature}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn linker_identity_is_the_first_version_line_of_the_configured_linker() {
        use std::os::unix::fs::PermissionsExt;
        let _lock = key_test_lock();
        let dir = tempfile::tempdir().unwrap();
        // SAFETY: the key test lock serialises environment edits.
        unsafe { std::env::set_var("KACHE_CACHE_DIR", dir.path()) };
        let linker = dir.path().join("my-ld");
        std::fs::write(&linker, "#!/bin/sh\necho 'my-ld 9.9'\necho 'second line'\n").unwrap();
        std::fs::set_permissions(&linker, std::fs::Permissions::from_mode(0o755)).unwrap();
        let parse = |argv: &[&str]| {
            RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
        };
        let args = parse(&[
            "rustc",
            "src/lib.rs",
            "-C",
            &format!("linker={}", linker.display()),
        ]);
        let identity = get_linker_identity(&args);
        let missing = get_linker_identity(&parse(&[
            "rustc",
            "src/lib.rs",
            "-C",
            &format!("linker={}", dir.path().join("absent").display()),
        ]));
        unsafe { std::env::remove_var("KACHE_CACHE_DIR") };
        assert_eq!(identity.as_deref(), Some("my-ld 9.9"));
        assert_eq!(missing, None, "a linker that cannot run has no identity");
    }
}