kache 1.2.0

Compiler cache for Rust, C/C++ and CUDA, with S3, GCS, shared-filesystem and OCI 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
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, OnceCell, RefCell};
use std::collections::{BTreeMap, HashMap};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use crate::key_env::KeyEnv;

mod apple_install_name;

/// 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.
//
// v32: target_dir() now recognizes Cargo's new build-dir layout, where
// `--out-dir` is `<target>/<profile>/build/<pkg>/<hash>/out`. Before, it
// walked up two levels to `<target>/<profile>/build/<pkg>`, so `<TARGET>`
// missed other packages' OUT_DIR paths in `-L native=` and dep-info was
// anchored one package deep. The path remapping prefix and dep-info anchor
// change for every new-layout unit, as they did for cross builds in v22.
// Unreleased with it, the rest of kache learned the same layout: a cc
// compile maps its own and other units' OUT_DIRs, a macOS link strips the
// profile directory from N_OSO paths, and native archives under the target
// dir are keyed by their portable digest. Each changes new-layout keys only.
//
// #1190 needs no bump. A trybuild unit folds a raw prefix only when the
// working directory, the crate source, or `OUT_DIR` sits under it. Those are
// the paths rustc writes into the rmeta; `--out-dir` reaches dep-info, which
// restore already rewrites. Coverage and `KACHE_RUSTC_PATH_NORMALIZE=0` still
// fold every prefix. Only the trybuild `remap:none` bytes change, so a
// previous trybuild entry misses and every other key stays valid.
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_path_only_decision`] 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.
/// The cc preprocessor memo encodes its paths and values the same way.
///
/// `to_string_lossy` would map every distinct invalid sequence onto `U+FFFD`,
/// merging values a macro reading `var_os` can still tell apart.
pub(crate) 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.
pub(crate) 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.
pub(crate) 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)
    }
}

/// What a rustc key computation learned besides the key.
///
/// Returned by [`compute_cache_key_with_outputs`] even when the key is not:
/// a deferred discovery still carries the tree digest it took, and a key that
/// failed late still names the externs it hashed. Every field starts empty or
/// `false` and is filled only on the paths that produce it.
#[derive(Debug, Default)]
pub struct KeyOutputs {
    /// Per-group digests of the key, for the event log and `explain_miss`
    /// (kunobi-ninja/kache#131). Set only once the whole key was hashed.
    pub fields: Option<BTreeMap<String, String>>,
    /// Hashes of normalized compiler-reported environment values, keyed by
    /// variable name. Values are never written to the event log.
    pub env_deps: Option<BTreeMap<String, String>>,
    /// Per-extern artifact digests (kunobi-ninja/kache#609).
    ///
    /// 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". 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. `Some` once the externs group was hashed, even
    /// when the map is empty (a crate with no dependencies).
    pub externs: Option<BTreeMap<String, String>>,
    /// Producing-unit identity per extern, teed off the same loop that fills
    /// [`KeyOutputs::externs`] and set with it (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.
    pub extern_units: Option<BTreeMap<String, String>>,
    /// The compiling unit's own identity: its `-C extra-filename`, `None`
    /// when cargo passed none. Set however the computation ends.
    pub unit_id: Option<String>,
    /// The native archives the key hashed, for the wrapper's store-time
    /// bundle audit.
    pub native_archives: Option<KeyedNativeArchives>,
    /// The input closure the key folded. The wrapper records it as a
    /// prediction only once the compile or restore it belongs to has
    /// succeeded. `None` when the invocation has no source file, or the
    /// computation stopped before the closure was resolved.
    pub dep_info: Option<DepInfo>,
    /// The tree guard a guarded computation used: the workspace or package
    /// tree of a unit under the tree guard ([`needs_tree_guard`]), or the
    /// `OUT_DIR` guard of a registry unit that looked for a relocated record.
    /// A record made from this invocation must carry its digest.
    pub tree_guard: Option<TreeGuard>,
    /// Did the key keep an OUT_DIR path (OUT_DIR itself, or a value under it)
    /// as a literal? A lib whose key does is one whose consumers are worth
    /// recording (see `out_dir_alias`).
    pub bakes_out_dir: bool,
    /// Did the key derive its input set from a record rather than from the
    /// pre-pass? A derived key that misses locally must be recomputed the
    /// slow way before anything reaches the remote, the scheduler or the
    /// store.
    pub used_prediction: bool,
}

/// The tree guard a key computation took before rustc ran: a digest of the
/// files a proc macro could read ([`needs_tree_guard`]), and the stat walks
/// behind it, so a record can check that the trees have not moved since
/// ([`TreeGuard::held`]).
#[derive(Debug, Clone)]
pub struct TreeGuard {
    pub digest: String,
    walks: Vec<GuardWalk>,
}

impl TreeGuard {
    /// Does every tree this guard read still have the stamp it had? The
    /// closure rustc reports is what it saw during the compile, after the
    /// digest was taken. A listed file removed meanwhile is missing from the
    /// closure, and once it is back the digest matches again; its stamp does
    /// not, as it has a new inode or new times. A guard with no walk to
    /// repeat does not hold.
    pub(crate) fn held(&self) -> bool {
        let _trace = crate::phase_trace::phase("tree_recheck");
        let held = !self.walks.is_empty() && self.walks.iter().all(GuardWalk::holds);
        crate::phase_trace::decision("tree_recheck", if held { "held" } else { "moved" });
        held
    }
}

#[cfg(test)]
impl TreeGuard {
    /// A guard carrying `digest`, with a walk of `root` as it is now.
    pub(crate) fn stamping(digest: &str, root: &Path) -> Self {
        let root = TreeRoot::new(root.to_path_buf(), b"root", &[]).walked();
        let stamp = stamp_root(&root, CRATE_TREE_MAX_ENTRIES)
            .expect("a tree to stamp")
            .digest;
        Self {
            digest: digest.to_string(),
            walks: vec![GuardWalk {
                root,
                max_entries: CRATE_TREE_MAX_ENTRIES,
                stamp,
            }],
        }
    }
}

/// One stat walk behind a tree guard: the root it covered, its entry budget,
/// and the stamp it gave.
#[derive(Debug, Clone)]
struct GuardWalk {
    root: WalkedRoot,
    max_entries: usize,
    stamp: String,
}

impl GuardWalk {
    /// Does a walk of the root give the same stamp again?
    fn holds(&self) -> bool {
        stamp_root(&self.root, self.max_entries).is_some_and(|stamp| stamp.digest == self.stamp)
    }
}

/// One root of a [`GuardWalk`], as [`crate::tree_stamp::Stamper::walk_observing`]
/// takes it.
#[derive(Debug, Clone)]
struct WalkedRoot {
    path: PathBuf,
    role: Vec<u8>,
    excluded: Vec<PathBuf>,
    rules: crate::tree_stamp::StampRules,
}

/// Why [`stamp_roots`] gave no stamps.
#[derive(Debug)]
enum StampRefusal {
    /// The root at this index alone holds more entries than the budget.
    TooLarge(usize),
    /// Each root fits, but together they hold more.
    TooLargeTogether,
    /// A root could not be walked.
    Unwalkable,
}

struct StampedRoot {
    stamp: crate::tree_stamp::TreeStamp,
    entries: usize,
    small_files: Vec<FileFingerprint>,
}

// A weak identity can survive replacement while the containing tree changes.
// In particular NTFS can preserve creation time and has no inode here.
fn guard_file_memo_eligible(size: i64, inode: i64) -> bool {
    #[cfg(unix)]
    {
        size < MIN_PERSISTED_HASH_BYTES && inode != 0
    }
    #[cfg(not(unix))]
    {
        let _ = (size, inode);
        false
    }
}

/// One stat walk per root, each of them and all of them together within
/// `max_entries`: the stamp of each, with the entries it holds.
fn stamp_roots(
    roots: &[WalkedRoot],
    max_entries: usize,
    collect_small_files: bool,
) -> std::result::Result<Vec<StampedRoot>, StampRefusal> {
    let mut stamps = Vec::with_capacity(roots.len());
    for (index, root) in roots.iter().enumerate() {
        #[cfg(test)]
        BEFORE_STAMP.with(|hook| {
            if let Some(hook) = hook.borrow_mut().as_mut() {
                hook(&root.path);
            }
        });
        let mut stamper = crate::tree_stamp::Stamper::new();
        let mut budget = max_entries;
        stamper.label(&root.role);
        let mut small_files = Vec::new();
        let mut observe = |path: PathBuf, metadata: &std::fs::Metadata| {
            let size = i64::try_from(metadata.len()).unwrap_or(i64::MAX);
            let inode = metadata_inode(metadata);
            if collect_small_files && metadata.is_file() && guard_file_memo_eligible(size, inode) {
                // The memo stores UTF-8 paths. Lossy spellings could merge
                // distinct names in the path-keyed batch result.
                let absolute = if path.is_absolute() {
                    path
                } else {
                    absolute_path(&path)
                };
                let Ok(path) = absolute.into_os_string().into_string() else {
                    return;
                };
                small_files.push(FileFingerprint {
                    path,
                    size,
                    mtime_ns: metadata_mtime_ns(metadata),
                    ctime_ns: metadata_ctime_ns(metadata),
                    inode,
                });
            }
        };
        match stamper.walk_observing(
            &root.path,
            &root.excluded,
            root.rules,
            &mut budget,
            &mut observe,
        ) {
            crate::tree_stamp::WalkOutcome::Fits => {
                stamps.push(StampedRoot {
                    stamp: stamper.finish(),
                    entries: max_entries - budget,
                    small_files,
                });
            }
            crate::tree_stamp::WalkOutcome::TooLarge => return Err(StampRefusal::TooLarge(index)),
            crate::tree_stamp::WalkOutcome::Unreadable => return Err(StampRefusal::Unwalkable),
        }
    }
    if stamps.iter().map(|root| root.entries).sum::<usize>() > max_entries {
        return Err(StampRefusal::TooLargeTogether);
    }
    Ok(stamps)
}

/// [`stamp_roots`] for one root.
fn stamp_root(root: &WalkedRoot, max_entries: usize) -> Option<crate::tree_stamp::TreeStamp> {
    let stamped = stamp_roots(std::slice::from_ref(root), max_entries, false)
        .ok()?
        .pop()?;
    Some(stamped.stamp)
}

/// Run by [`stamp_roots`] with each root before it walks, so a test can
/// change a tree just before it is stamped.
#[cfg(test)]
type BeforeStamp = Box<dyn FnMut(&Path)>;

#[cfg(test)]
thread_local! {
    static BEFORE_STAMP: std::cell::RefCell<Option<BeforeStamp>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(test)]
fn set_before_stamp(hook: Option<BeforeStamp>) {
    BEFORE_STAMP.with(|slot| *slot.borrow_mut() = hook);
}

/// `digest`, a tree digest computed with `file_hasher`, as a guard with the
/// walks behind it.
fn tree_guard_of(
    file_hasher: &FileHasher<'_>,
    digest: impl FnOnce() -> Option<String>,
) -> Option<TreeGuard> {
    file_hasher.take_tree_walks();
    let digest = digest()?;
    Some(TreeGuard {
        digest,
        walks: file_hasher.take_tree_walks(),
    })
}

/// The native archives a key hashed, with the unit's native search dirs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct KeyedNativeArchives {
    /// Archives whose content the key folded.
    pub archives: Vec<PathBuf>,
    /// The keyed archives the unit's rlib carries, through a bundled `-l
    /// static` spec. The other keyed archives are not in the rlib.
    pub bundled: Vec<BundledArchive>,
    /// On an rlib, the unit's `native=`, `all=` and bare `-L` dirs the scan
    /// reads (see [`NativeLinkContext::scanned_dirs`]), without repeats:
    /// where the bundle audit looks for unkeyed archives. Empty on other
    /// units.
    pub dirs: Vec<PathBuf>,
}

/// A keyed archive an rlib bundles, and how rustc stores it there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundledArchive {
    pub path: PathBuf,
    /// Stored as one member named after the archive file (`+whole-archive`)
    /// rather than member by member.
    pub packed: bool,
}

/// 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)";

/// 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.
pub(crate) 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")?);
    let out_dir = std::env::var_os("OUT_DIR").map(PathBuf::from);
    crate_tree_digest_in(manifest_dir, out_dir, file_hasher)
}

/// [`crate_tree_digest`] for the package at `manifest_dir`.
fn crate_tree_digest_in(
    manifest_dir: PathBuf,
    out_dir: Option<PathBuf>,
    file_hasher: &FileHasher<'_>,
) -> Option<String> {
    // 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![TreeRoot::new(
        manifest_dir,
        b"manifest_dir",
        MANIFEST_DIR_SKIPPED,
    )];
    if let Some(out_dir) = out_dir {
        roots.push(TreeRoot::new(out_dir, b"out_dir", &[]));
    }
    tree_digest(roots, file_hasher, CRATE_TREE_MAX_ENTRIES)
}

/// Names the tree guard skips directly under the crate directory. A build
/// directory or a git checkout there is not what a macro reads, and `target`
/// in particular is rewritten by the build this key belongs to. `OUT_DIR`
/// skips nothing: a build script wrote all of it before this unit, and a
/// macro scanning it reads a nested `target` like any other file.
const MANIFEST_DIR_SKIPPED: &[&str] = &["target", ".git"];

/// Cap on entries digested for the `OUT_DIR` guard. Generated code is a few
/// files; a directory past this is a build tree, and the pre-pass stays
/// cheaper than digesting it.
const OUT_DIR_TREE_MAX_ENTRIES: usize = 256;

/// A content digest of `out_dir` alone: the guard for a relocated record of
/// a unit with no proc-macro dependency. Such a unit reads nothing it does
/// not name, so the package needs no digest; `OUT_DIR` does, because the
/// record says which generated files were read, not what else was generated.
pub(crate) fn out_dir_tree_digest(out_dir: &Path, file_hasher: &FileHasher<'_>) -> Option<String> {
    tree_digest(
        vec![TreeRoot::new(out_dir.to_path_buf(), b"out_dir", &[])],
        file_hasher,
        OUT_DIR_TREE_MAX_ENTRIES,
    )
}

/// One directory a tree digest folds.
struct TreeRoot<'a> {
    path: PathBuf,
    /// What the directory is to the unit. 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.
    role: &'a [u8],
    /// Names directly under the root that the digest leaves out.
    skipped: &'a [&'a str],
    /// Leave out what a directory below the root holds, its tag aside, when
    /// Cargo tagged it as a build directory: a stale `target`, or the target
    /// directory of another build.
    skips_build_dirs: bool,
    /// Kache's own directories, and what Cargo writes in its home, below the
    /// root ([`own_dirs_within`]), left out wherever they lie.
    own: Vec<PathBuf>,
}

impl<'a> TreeRoot<'a> {
    fn new(path: PathBuf, role: &'a [u8], skipped: &'a [&'a str]) -> Self {
        Self {
            path,
            role,
            skipped,
            skips_build_dirs: false,
            own: Vec::new(),
        }
    }

    fn skipping_build_dirs(self) -> Self {
        Self {
            skips_build_dirs: true,
            ..self
        }
    }

    fn excluded(&self) -> Vec<PathBuf> {
        self.skipped
            .iter()
            .map(|name| self.path.join(name))
            .chain(self.own.iter().cloned())
            .collect()
    }

    /// The fold never follows a link, so the stamp may record its text, and
    /// it counts what it cannot read as unreadable. The root's own times show
    /// a name that came and went while the fold ran.
    fn stamp_rules(&self) -> crate::tree_stamp::StampRules {
        crate::tree_stamp::StampRules {
            link_text: true,
            skip_build_dirs: self.skips_build_dirs,
            root_metadata: true,
            unreadable_entries: true,
            top_files_only: false,
            unsearchable_dirs: false,
        }
    }

    fn walked(&self) -> WalkedRoot {
        WalkedRoot {
            path: self.path.clone(),
            role: self.role.to_vec(),
            excluded: self.excluded(),
            rules: self.stamp_rules(),
        }
    }
}

fn tree_digest(
    roots: Vec<TreeRoot<'_>>,
    file_hasher: &FileHasher<'_>,
    max_entries: usize,
) -> Option<String> {
    tree_digest_memoised(
        roots,
        file_hasher,
        max_entries,
        &crate::config::probe_memo_dir(),
        std::time::SystemTime::now(),
    )
}

/// How long a root that ran past its entry budget is taken to still be past
/// it. The answer only ever withholds a digest, which leaves the unit on the
/// pre-pass, so a stale answer costs a shortcut, never a wrong key.
pub(crate) const OVERSIZED_TREE_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60);

/// The marker recording that `root` holds more than `max_entries` entries.
fn oversized_tree_marker(memo_dir: &Path, root: &Path, max_entries: usize) -> PathBuf {
    let mut hasher = blake3::Hasher::new();
    hasher.update(root.as_os_str().as_encoded_bytes());
    hasher.update(&max_entries.to_le_bytes());
    memo_dir
        .join("oversized-trees")
        .join(&hasher.finalize().to_hex()[..32])
}

/// The marker recording that `roots` together hold more than `max_entries`
/// entries, though each of them fits: a workspace and a unit's `OUT_DIR`.
fn oversized_roots_marker(memo_dir: &Path, roots: &[WalkedRoot], max_entries: usize) -> PathBuf {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache-oversized-roots-v1\n");
    for root in roots {
        fold_field(
            &mut hasher,
            b"root:",
            root.path.as_os_str().as_encoded_bytes(),
        );
    }
    hasher.update(&max_entries.to_le_bytes());
    memo_dir
        .join("oversized-trees")
        .join(&hasher.finalize().to_hex()[..32])
}

/// Whether `marker` was written less than [`OVERSIZED_TREE_TTL`] before
/// `now`. A marker from the future counts as fresh.
pub(crate) fn marked_recently(marker: &Path, now: std::time::SystemTime) -> bool {
    std::fs::metadata(marker)
        .and_then(|metadata| metadata.modified())
        .is_ok_and(|marked| {
            now.duration_since(marked)
                .map_or(true, |age| age < OVERSIZED_TREE_TTL)
        })
}

/// Write `marker`, if it can be written.
fn write_marker(marker: &Path) {
    if let Some(parent) = marker.parent() {
        let _ = std::fs::create_dir_all(parent).and_then(|()| std::fs::write(marker, b""));
    }
}

/// The version of [`crate_tree_fold`]'s digest, which a memoised digest is
/// recorded for.
const TREE_DIGEST_VERSION: &[u8] = b"kache-crate-tree-v1\n";

/// The version of the digest of several roots, folded from the digest of
/// each.
const TREE_ROOTS_VERSION: &[u8] = b"kache-crate-tree-roots-v1\n";

/// [`tree_digest`] with its memos in `memo_dir`.
///
/// One stat walk per root stamps it and enforces the budget without reading
/// a file. A root that alone runs past the budget is remembered for
/// [`OVERSIZED_TREE_TTL`]: a workspace root can be a whole monorepo. So are
/// roots that only together run past it, without marking either one.
///
/// Each root is memoised alone: a new target directory gives every `OUT_DIR`
/// a new stamp, and the workspace beside it keeps its memo. While a root has
/// the stamp its digest was recorded under
/// ([`crate::tree_stamp::TreeStamp::memo_key`]), that digest is the answer;
/// otherwise every file in it is hashed, and the digest is recorded
/// once the root has settled ([`crate::tree_stamp::TreeStamp::settled_at`]).
/// Several roots' digests fold into one. The walks go to `file_hasher` for
/// the guard ([`tree_guard_of`]).
fn tree_digest_memoised(
    mut roots: Vec<TreeRoot<'_>>,
    file_hasher: &FileHasher<'_>,
    max_entries: usize,
    memo_dir: &Path,
    now: std::time::SystemTime,
) -> Option<String> {
    for root in &mut roots {
        root.own = own_dirs_within(&root.path, &file_hasher.own_dirs);
    }
    if roots.iter().any(|root| {
        marked_recently(
            &oversized_tree_marker(memo_dir, &root.path, max_entries),
            now,
        )
    }) {
        return None;
    }
    let walked: Vec<WalkedRoot> = roots.iter().map(TreeRoot::walked).collect();
    let together = oversized_roots_marker(memo_dir, &walked, max_entries);
    if marked_recently(&together, now) {
        return None;
    }
    let stamps = match stamp_roots(&walked, max_entries, file_hasher.cache.is_some()) {
        Ok(stamps) => stamps,
        Err(StampRefusal::TooLarge(index)) => {
            write_marker(&oversized_tree_marker(
                memo_dir,
                &walked[index].path,
                max_entries,
            ));
            return None;
        }
        Err(StampRefusal::TooLargeTogether) => {
            write_marker(&together);
            return None;
        }
        Err(StampRefusal::Unwalkable) => return None,
    };
    let total: usize = stamps.iter().map(|root| root.entries).sum();
    let mut digests = Vec::with_capacity(roots.len());
    let mut walks = Vec::with_capacity(roots.len());
    for ((root, walked), stamped) in roots.iter().zip(walked).zip(stamps) {
        let walk = GuardWalk {
            root: walked,
            max_entries,
            stamp: stamped.stamp.digest.clone(),
        };
        // A read may spend what the other roots leave of the budget.
        let budget = max_entries - (total - stamped.entries);
        digests.push(root_digest(
            root,
            &walk,
            &stamped,
            budget,
            file_hasher,
            memo_dir,
            now,
        )?);
        walks.push(walk);
    }
    for walk in walks {
        file_hasher.note_tree_walk(walk);
    }
    if let [digest] = digests.as_slice() {
        return Some(digest.clone());
    }
    let mut hasher = blake3::Hasher::new();
    hasher.update(TREE_ROOTS_VERSION);
    for digest in &digests {
        fold_field(&mut hasher, b"digest:", digest.as_bytes());
    }
    Some(hasher.finalize().to_hex().to_string())
}

/// The digest of `root`, which `walk` stamped: the memoised one while the
/// stamp holds, otherwise a hash of every file within `budget` entries.
fn root_digest(
    root: &TreeRoot<'_>,
    walk: &GuardWalk,
    stamped: &StampedRoot,
    mut budget: usize,
    file_hasher: &FileHasher<'_>,
    memo_dir: &Path,
    now: std::time::SystemTime,
) -> Option<String> {
    let stamp = &stamped.stamp;
    let memo = tree_digest_memo(memo_dir, root);
    if let Some(digest) = crate::tree_stamp::memoised_digest(&memo, stamp.memo_key())
        .filter(|digest| digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit()))
    {
        crate::phase_trace::decision("tree_memo", "hit");
        return Some(digest);
    }
    crate::phase_trace::decision("tree_memo", "miss");
    // A batch result is keyed by path; retain the exact queried fingerprint
    // as well, so the later content walk cannot use a row for another stamp.
    let mut hashes = file_hasher.memoised_hashes(stamped.small_files.iter());
    let memoised: HashMap<FileFingerprint, String> = stamped
        .small_files
        .iter()
        .filter_map(|stamp| hashes.remove(&stamp.path).map(|hash| (stamp.clone(), hash)))
        .collect();
    let mut hasher = blake3::Hasher::new();
    hasher.update(TREE_DIGEST_VERSION);
    fold_field(&mut hasher, b"root:", root.role);
    let read_every_file = crate_tree_fold(
        &root.path,
        &root.path,
        &root.excluded(),
        root.skips_build_dirs,
        &GuardFileHashes {
            hasher: file_hasher,
            memoised,
        },
        &mut hasher,
        &mut budget,
    )?;
    let digest = hasher.finalize().to_hex().to_string();
    // The stamp shows a directory becoming listable, but not a file becoming
    // readable where there is no change time.
    if read_every_file {
        memoise_tree_digest(&memo, walk, stamp, &digest, now);
    }
    Some(digest)
}

/// Record `digest` at `memo` under the memo key of `stamp`, the stamp `walk`
/// gave before the files were read. A tree written in the last moments could
/// be written again within the same timestamp tick, keeping its stamp with
/// other bytes, so it has to have settled. A tree that moved while it was
/// read has a digest of no state it was in, so the walk has to give the same
/// stamp again, the root's own times included: they show a name that came
/// and went meanwhile.
///
/// On Unix a lookup needs only the same entries. The root's own times also
/// move when a name it leaves out, such as the target directory, is created
/// or removed, and every entry the digest read stays as it was.
fn memoise_tree_digest(
    memo: &Path,
    walk: &GuardWalk,
    stamp: &crate::tree_stamp::TreeStamp,
    digest: &str,
    now: std::time::SystemTime,
) {
    if stamp.settled_at(now) && walk.holds() {
        crate::tree_stamp::record_digest(memo, stamp.memo_key(), digest);
    }
}

/// Where the digest of `root` is memoised: one file per root, so every unit
/// of a workspace shares one for the workspace.
fn tree_digest_memo(memo_dir: &Path, root: &TreeRoot<'_>) -> PathBuf {
    let mut hasher = blake3::Hasher::new();
    hasher.update(TREE_DIGEST_VERSION);
    fold_field(
        &mut hasher,
        b"path:",
        root.path.as_os_str().as_encoded_bytes(),
    );
    fold_field(&mut hasher, b"role:", root.role);
    for name in root.skipped {
        fold_field(&mut hasher, b"skipped:", name.as_bytes());
    }
    fold_field(
        &mut hasher,
        b"build_dirs:",
        if root.skips_build_dirs { b"1" } else { b"0" },
    );
    memo_dir
        .join("tree-digests")
        .join(&hasher.finalize().to_hex()[..32])
}

/// The paths of `own`, Kache's own directories and what Cargo writes in its
/// home, that lie below `root`, spelled as a walk of `root` meets them. A
/// build writes to them while units compile, and GitLab CI caches only paths
/// inside the project, so a guard that walked them would move with every
/// store and could run past its budget. A path spelled through a link is
/// matched by its resolved path.
fn own_dirs_within(root: &Path, own: &[PathBuf]) -> Vec<PathBuf> {
    if own.is_empty() {
        return Vec::new();
    }
    let resolved_root = std::fs::canonicalize(root).ok();
    own.iter()
        .filter_map(|dir| {
            let rest = dir
                .strip_prefix(root)
                .ok()
                .or_else(|| dir.strip_prefix(resolved_root.as_deref()?).ok())?;
            (!rest.as_os_str().is_empty()).then(|| root.join(rest))
        })
        .collect()
}

/// Is `manifest_dir` an extracted registry package (`<CARGO_HOME>/registry/src/<index>/<pkg>`)?
pub(crate) 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"
    )
}

/// `<CARGO_HOME>/registry/src` for a registry package, the directory every
/// extracted package lives under whichever checkout builds it.
fn registry_src_root(manifest_dir: &Path) -> Option<&Path> {
    if !is_registry_package(manifest_dir) {
        return None;
    }
    manifest_dir.parent()?.parent()
}

struct GuardFileHashes<'a, 'db> {
    hasher: &'a FileHasher<'db>,
    memoised: HashMap<FileFingerprint, String>,
}

/// Fold the entries under `directory` by path, kind and content. A symlink
/// counts by its text and is not followed. With `skips_build_dirs`, a
/// directory below `root` that Cargo tagged as its build directory counts by
/// its tag alone. Below `root`, what cannot be read counts as unreadable: a
/// proc macro this process starts cannot read it either. `Some(false)` when
/// that includes a file: where there is no change time, a file that becomes
/// readable keeps its stamp.
fn crate_tree_fold(
    root: &Path,
    directory: &Path,
    excluded: &[PathBuf],
    skips_build_dirs: bool,
    files: &GuardFileHashes<'_, '_>,
    hasher: &mut blake3::Hasher,
    budget: &mut usize,
) -> Option<bool> {
    let listed = std::fs::read_dir(directory)
        .and_then(|entries| entries.collect::<std::io::Result<Vec<_>>>());
    let mut entries = match listed {
        Ok(entries) => entries,
        Err(_) if directory != root => {
            fold_field(hasher, b"unreadable:", b"");
            return Some(true);
        }
        Err(_) => return None,
    };
    entries.sort_by_key(std::fs::DirEntry::file_name);
    if skips_build_dirs && directory != root {
        crate::tree_stamp::keep_only_build_tag(&mut entries);
    }
    let mut read_every_file = true;
    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());
        // A memo row settles against the clock before this content walk's
        // fresh stat, never against metadata from the earlier stamp walk.
        let observed_ns = wall_clock_ns();
        let Ok(metadata) = std::fs::symlink_metadata(&path) else {
            fold_field(hasher, b"unreadable:", b"");
            continue;
        };
        if metadata.file_type().is_symlink() {
            match std::fs::read_link(&path) {
                Ok(target) => {
                    fold_field(hasher, b"symlink:", target.as_os_str().as_encoded_bytes());
                }
                Err(_) => fold_field(hasher, b"unreadable:", b""),
            }
        } else if metadata.is_dir() {
            fold_field(hasher, b"dir:", b"");
            read_every_file &= crate_tree_fold(
                root,
                &path,
                excluded,
                skips_build_dirs,
                files,
                hasher,
                budget,
            )?;
        } else if metadata.is_file() {
            match files.hasher.guard_file_hash_from_metadata(
                &path,
                &metadata,
                observed_ns,
                &files.memoised,
            ) {
                Ok(hash) => fold_field(hasher, b"file:", hash.as_bytes()),
                Err(_) => {
                    fold_field(hasher, b"unreadable:", b"");
                    read_every_file = false;
                }
            }
        } else {
            fold_field(hasher, b"other:", b"");
        }
    }
    Some(read_every_file)
}

thread_local! {
    /// 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) };
    /// May the key also defer when a hit is possible, because the wrapper
    /// will stop the compile if the emitted closure keys to a stored entry?
    static COMPILE_WHILE_KEYING: 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, Option<TreeGuard>)>> = const { std::cell::RefCell::new(None) };
}

/// The key stopped before discovering the closure, and the wrapper compiles
/// first (see [`set_defer_discovery`]). With `miss_certain`, no entry for the
/// unit can exist; without it, the wrapper keys from the dep-info the compile
/// writes early and stops the compile on a hit ([`set_compile_while_keying`]).
#[derive(Debug)]
pub struct DeferredDiscovery {
    pub miss_certain: bool,
}

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));
}

/// Also defer when an entry could exist: the pre-pass would take as long as
/// the compile takes to write its own dep-info, so the wrapper starts the
/// compile, keys from that dep-info, and stops the compile if the key hits.
/// Only meaningful with [`set_defer_discovery`] on.
pub fn set_compile_while_keying(allowed: bool) {
    COMPILE_WHILE_KEYING.with(|cell| cell.set(allowed));
}

/// Use `dep_info` for the next key computed on this thread.
///
/// `tree` is the tree guard the deferred computation took before the
/// compile ([`KeyOutputs::tree_guard`]). It rides with the emitted closure,
/// so a changed tree still rejects that prediction rather than blessing old
/// inputs with a new digest.
pub fn provide_dep_info(dep_info: DepInfo, tree: Option<TreeGuard>) {
    PROVIDED_DEP_INFO.with(|cell| *cell.borrow_mut() = Some((dep_info, tree)));
}

/// Is a closure from [`provide_dep_info`] waiting for the next key? It came
/// from a compile, so that key must arm the too-new guard: an input written
/// since may not be what the compiler read.
pub fn dep_info_provided() -> bool {
    PROVIDED_DEP_INFO.with(|cell| cell.borrow().is_some())
}

/// The files of the closure [`provide_dep_info`] left for the next key,
/// spelled as [`FileFingerprint`] records their paths.
pub fn provided_dep_info_sources() -> Option<std::collections::HashSet<String>> {
    PROVIDED_DEP_INFO.with(|cell| {
        cell.borrow().as_ref().map(|(dep_info, _)| {
            dep_info
                .source_files
                .iter()
                .map(|path| absolute_path(path).to_string_lossy().into_owned())
                .collect()
        })
    })
}

/// 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,
    })
}

/// 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.
pub(crate) 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> {
    rustc_shared_prediction_identity_in(args, std::env::vars_os().collect())
}

/// [`rustc_shared_prediction_identity`] against an environment snapshot.
fn rustc_shared_prediction_identity_in(
    args: &RustcArgs,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
) -> Option<String> {
    let target = args.target_dir()?;
    let manifest_dir = env_var_in(&vars, "CARGO_MANIFEST_DIR").map(Path::new);
    if !target.is_absolute() || !shared_prediction_eligible(&args.externs, manifest_dir) {
        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,
        shared_prediction_vars(vars.into_iter(), &target),
        Some(closure_args),
    )?;
    Some(format!("{SHARED_PREDICTION_PREFIX}{identity}"))
}

const SHARED_PREDICTION_PREFIX: &str = "shared-target-v2:";

/// Rows whose `OUT_DIR` sources are written relative to `OUT_DIR`
/// ([`PortablePrediction`]). The hash is the shared one, so a row here and
/// a row there always describe the same unit.
const RELOCATABLE_PREDICTION_PREFIX: &str = "shared-out-dir-v1:";

/// May a unit's record be shared across target directories?
///
/// A unit with no proc-macro dependency of its own can. A workspace unit's
/// row carries the workspace guard ([`needs_tree_guard`]), which also covers
/// a macro an rlib re-exports, and a registry package holds the same files
/// in every checkout. A registry unit with a proc-macro dependency can too,
/// because a macro there reads its package and `OUT_DIR`, and the record
/// carries a digest of both that the reader checks before use. The target
/// paths that differ between checkouts only reach the key as extern content,
/// which the key hashes.
fn shared_prediction_eligible(
    externs: &[crate::args::ExternDep],
    manifest_dir: Option<&Path>,
) -> bool {
    !has_dylib_extern(externs) || manifest_dir.is_some_and(is_registry_package)
}

/// The value of `name` in an environment snapshot.
fn env_var_in<'a>(
    vars: &'a [(std::ffi::OsString, std::ffi::OsString)],
    name: &str,
) -> Option<&'a std::ffi::OsStr> {
    vars.iter()
        .find(|(key, _)| key == name)
        .map(|(_, value)| value.as_os_str())
}

/// The identity of a registry unit's relocated record: the shared hash
/// under its own prefix. `None` for any other unit, and for one with no
/// `OUT_DIR` to relocate.
fn relocatable_prediction_identity(
    args: &RustcArgs,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
) -> Option<String> {
    let manifest_dir = Path::new(env_var_in(&vars, "CARGO_MANIFEST_DIR")?);
    if !is_registry_package(manifest_dir) || env_var_in(&vars, "OUT_DIR").is_none() {
        return None;
    }
    let shared = rustc_shared_prediction_identity_in(args, vars)?;
    let hash = shared.strip_prefix(SHARED_PREDICTION_PREFIX)?;
    Some(format!("{RELOCATABLE_PREDICTION_PREFIX}{hash}"))
}

/// The environment a shared record is identified by, with this build's own
/// `OUT_DIR` written relative to the target directory.
///
/// A build script's `OUT_DIR` is `<target>/<profile>/build/<unit>/out`, so
/// folding it verbatim gave one unit a different record in every build
/// directory: six Cargo jobs sharing a store each discovered `libc` from
/// scratch, and a warm build in another checkout found nothing. Relative, the
/// same unit keeps one record wherever it is built. The unit part still
/// carries Cargo's metadata hash, so two feature sets stay apart.
///
/// A value outside the target directory is left alone: it is not this
/// build's own output and nothing says another checkout would spell it the
/// same way.
fn shared_prediction_vars(
    vars: impl Iterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
    target: &Path,
) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
    vars.map(|(name, value)| {
        if name != "OUT_DIR" {
            return (name, value);
        }
        let relative = target_relative_env_value(&value, target);
        (name, relative.unwrap_or(value))
    })
    .collect()
}

/// `value` rewritten relative to `target`, tagged so a literal value cannot
/// impersonate a rewritten one. `None` when it does not sit under `target`.
fn target_relative_env_value(value: &std::ffi::OsStr, target: &Path) -> Option<std::ffi::OsString> {
    let relative = Path::new(value).strip_prefix(target).ok()?;
    if relative
        .components()
        .any(|component| !matches!(component, std::path::Component::Normal(_)))
    {
        return None;
    }
    Some(std::ffi::OsString::from(format!(
        "kache-target-relative:{}",
        relative.to_str()?
    )))
}

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 {
    let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from);
    shared_prediction_can_record_in(args, dep_info, manifest_dir.as_deref())
}

/// [`shared_prediction_can_record`] for the package at `manifest_dir`.
fn shared_prediction_can_record_in(
    args: &RustcArgs,
    dep_info: &DepInfo,
    manifest_dir: Option<&Path>,
) -> bool {
    args.target_dir().is_some_and(|target| {
        shared_sources_can_record(&dep_info.source_files, &target, manifest_dir)
    })
}

/// No source under `target`, and for a registry unit, every source under the
/// registry. A registry file is the same file for every checkout; anything
/// else a registry unit read, such as a workspace file a macro found through
/// a target path, may name a different file in the next checkout, so that
/// record stays with this one.
fn shared_sources_can_record(
    sources: &[PathBuf],
    target: &Path,
    manifest_dir: Option<&Path>,
) -> bool {
    let registry_src = manifest_dir.and_then(registry_src_root);
    sources.iter().all(|source| {
        !source.starts_with(target)
            && registry_src.is_none_or(|root| under_registry_src(source, root))
    })
}

/// Is `source` spelled as a file under the registry? A `..` may climb back
/// up inside the package the path names, as in the `<pkg>/src/../README.md`
/// rustc reports for `include_str!("../README.md")`, but not out of it. The
/// index and the package are the two levels below the root it has to stay in.
fn under_registry_src(source: &Path, registry_src: &Path) -> bool {
    suffix_within(source.as_os_str(), registry_src, 2).is_some_and(|suffix| !suffix.is_empty())
}

/// The bytes of `value` after `root`, for a path that stays inside `root`.
fn out_dir_suffix(value: &std::ffi::OsStr, root: &Path) -> Option<String> {
    suffix_within(value, root, 0)
}

/// The bytes of `value` after `root`, when `value` is `root` itself (an
/// empty suffix) or `root`, a separator, and components that never leave the
/// directory `floor` levels below `root` ([`stays_below`]). `None` for a
/// longer name that merely starts the same (`/o2` against `/o`), an empty
/// component, a `..` that climbs too far, or a suffix that is not UTF-8. The
/// suffix keeps its `.` and `..`, because a record has to reproduce the
/// spelling rustc reported.
///
/// `\` separates components on Windows only, so the walk has to hold both
/// with and without it: from `root`, `a\b/..` is one level down on Windows
/// and back at `root` on Unix.
fn suffix_within(value: &std::ffi::OsStr, root: &Path, floor: usize) -> Option<String> {
    let rest = value
        .as_encoded_bytes()
        .strip_prefix(root.as_os_str().as_encoded_bytes())?;
    let suffix = std::str::from_utf8(rest).ok()?;
    let Some(components) = suffix.strip_prefix(['/', '\\']) else {
        return suffix.is_empty().then(String::new);
    };
    (stays_below(components.split(['/', '\\']), floor) && stays_below(components.split('/'), floor))
        .then(|| suffix.to_string())
}

/// Does a walk down `components` stay inside the directory it reaches after
/// the first `floor` of them? A `..` is only taken from deeper than that. A
/// `.` stays where it is, as in the `src/./init.js` rustc reports for
/// `include_str!("./init.js")`.
///
/// The walk is lexical. It asks which directory the spelling names, and
/// rustc and the key both open the recorded spelling itself, so a symlink
/// inside an unpacked package resolves the same way for both. The link is
/// part of the package, the same in every checkout that shares the Cargo
/// home, just as it is for a path with no `..`. Resolving links here would
/// cost a syscall per path without changing what either one reads.
fn stays_below<'a>(components: impl IntoIterator<Item = &'a str>, floor: usize) -> bool {
    let mut depth = 0usize;
    components.into_iter().all(|component| match component {
        "" => false,
        "." => true,
        ".." if depth > floor => {
            depth -= 1;
            true
        }
        ".." => false,
        _ => {
            depth += 1;
            true
        }
    })
}

/// 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.
/// [`verifies_prediction`] passes [`prediction_sample_identity`], so every
/// checkout of a project checks the same units too.
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
}

/// Is this validated prediction checked against the pre-pass it replaced?
///
/// The caller reads the working directory and the environment; everything
/// that turns them into the decision is here, where tests reach it.
fn verifies_prediction(
    mode: VerifyPredictions,
    args: &RustcArgs,
    current_dir: Option<&Path>,
    env: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> bool {
    should_verify_this_prediction(mode, &prediction_sample_identity(args, current_dir, env))
}

/// The unit as every checkout of the project names it. The sample is drawn
/// by this.
///
/// Not the prediction identity: that folds the working directory and the
/// absolute extern and search paths, so two checkouts of one project checked
/// different units. A perf gate builds base and head in separate checkouts,
/// so it counted pre-passes that the change under test did not cause.
///
/// Cargo's package name and version separate units that share a crate name,
/// such as every `build_script_build`. Its `-C metadata` would too, but that
/// folds the absolute path of a path dependency outside the workspace root,
/// and every unit depending on one inherits it. A target spec is folded by
/// name because Cargo passes its absolute path.
fn prediction_sample_identity(
    args: &RustcArgs,
    current_dir: Option<&Path>,
    env: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> String {
    let manifest_dir = env("CARGO_MANIFEST_DIR").map(PathBuf::from);
    let source = args.source_file.as_deref().map(|source| {
        checkout_relative(source, &[manifest_dir.as_deref(), current_dir]).to_string_lossy()
    });
    let package = ["CARGO_PKG_NAME", "CARGO_PKG_VERSION"]
        .map(|var| env(var).map(|value| value.to_string_lossy().into_owned()));
    serde_json::to_string(&(
        args.crate_name.as_deref(),
        &args.crate_types,
        args.is_test,
        args.target.as_deref().map(target_name),
        package,
        &args.cfgs,
        source,
    ))
    .unwrap()
}

/// The name rustc knows a target by: a spec file goes by its stem.
fn target_name(target: &str) -> &str {
    target
        .strip_suffix(".json")
        .and_then(|spec| Path::new(spec).file_name()?.to_str())
        .unwrap_or(target)
}

/// `path` relative to the first of `roots` it lies under.
///
/// Cargo runs rustc from the workspace root for a member, whose source is
/// already relative, and from the package root for a dependency, whose source
/// is absolute. Both come out the same in every checkout. The roots include
/// Cargo's package root because Cargo spells it as it spells the source,
/// while the working directory comes back with symlinks resolved (`/tmp`
/// reads as `/private/tmp` on macOS).
fn checkout_relative<'a>(path: &'a Path, roots: &[Option<&Path>]) -> &'a Path {
    roots
        .iter()
        .flatten()
        .find_map(|root| path.strip_prefix(root).ok())
        .unwrap_or(path)
}

/// 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<'_>,
    tree_guard: &mut Option<TreeGuard>,
) -> std::result::Result<DepInfo, Rejection> {
    let _trace = crate::phase_trace::phase("prediction_validate");
    *tree_guard = None;
    if !file_hasher.uses_input_predictions() {
        return Err(Rejection::Disabled);
    }
    let vars: Vec<_> = std::env::vars_os().collect();
    let workspace = workspace_roots(args, &vars);
    let manifest_dir = env_var_in(&vars, "CARGO_MANIFEST_DIR").map(Path::new);
    // A unit under the tree guard is predictable only while the record carries
    // the tree digest and the digest still matches. The tree is the package
    // for a registry or vendored unit and the whole workspace for any other
    // workspace or path one. Computed here and handed back in `tree_guard`,
    // because the same digest is what a record made from this invocation has
    // to carry.
    let tree = if needs_tree_guard(&args.externs, manifest_dir) {
        let _trace = crate::phase_trace::phase(if workspace.is_some() {
            "workspace_tree"
        } else {
            "crate_tree"
        });
        let guard = tree_guard_of(file_hasher, || match &workspace {
            Some(workspace) => workspace_tree_digest(workspace, file_hasher),
            None => crate_tree_digest(file_hasher),
        })
        .ok_or(Rejection::NotEligible)?;
        let digest = guard.digest.clone();
        *tree_guard = Some(guard);
        Some(digest)
    } else {
        None
    };
    let identity = rustc_prediction_identity(args).ok_or(Rejection::Disabled)?;
    let shared = rustc_shared_prediction_identity(args);
    // Filled when the record came from the remote, so a record that checks
    // out is kept here and not asked for again.
    let mut from_remote = None;
    let Some(record) = file_hasher
        .input_prediction(&identity)
        .or_else(|| file_hasher.input_prediction(shared.as_deref()?))
        .or_else(|| {
            let shared = shared.as_deref()?;
            let record = remote_plain_row(shared, &registry_src_of(&vars)?)?;
            from_remote = Some(shared);
            Some(record)
        })
    else {
        return match &workspace {
            Some(workspace) => workspace_key_inputs(args, file_hasher, workspace, vars, tree),
            None => relocated_key_inputs(args, file_hasher, tree, tree_guard),
        };
    };
    if let Some(tree) = &tree {
        match &record.tree {
            Some(recorded) if recorded == tree => {}
            Some(_) => return Err(Rejection::TreeChanged),
            None => return Err(Rejection::NoRecord),
        }
    }
    // The digest only vouches for files its walk sees. A shared row written
    // before this check carries the digest whatever its closure names.
    if let Some(workspace) = &workspace
        && !guard_covers(&record.sources, workspace)
    {
        return Err(Rejection::NoRecord);
    }
    let validated = validate_prediction(
        &record,
        |path| std::fs::metadata(path).ok(),
        |path| path.exists(),
        |var| std::env::var(var).ok(),
    );
    if let Some(shared) = from_remote {
        keep_remote_plain_row(file_hasher, shared, args, &record, &validated);
    }
    validated
}

/// Keep a registry unit's shared row that came from the remote and checked
/// out, so the next build finds it locally.
fn keep_remote_plain_row(
    file_hasher: &FileHasher<'_>,
    identity: &str,
    args: &RustcArgs,
    record: &InputPrediction,
    validated: &std::result::Result<DepInfo, Rejection>,
) {
    crate::phase_trace::decision(
        "remote_prediction",
        if validated.is_ok() { "used" } else { "refused" },
    );
    if let Ok(dep_info) = validated {
        file_hasher.record_input_prediction(
            identity,
            args.crate_name.as_deref(),
            dep_info,
            record.tree.clone(),
        );
    }
}

/// The third lookup, after this checkout's row and the shared one both
/// missed: a registry unit's record from another target directory, with
/// `OUT_DIR` relocated to this one.
///
/// The guard is `tree` for a proc-macro dependent and a digest of `OUT_DIR`
/// otherwise. It goes into `tree_guard` before the lookup, so a record made
/// from this invocation, after a deferred compile included, carries the
/// digest taken before rustc ran. Only this row is checked against it.
fn relocated_key_inputs(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    tree: Option<String>,
    tree_guard: &mut Option<TreeGuard>,
) -> std::result::Result<DepInfo, Rejection> {
    let vars: Vec<_> = std::env::vars_os().collect();
    let out_dir = env_var_in(&vars, "OUT_DIR")
        .and_then(std::ffi::OsStr::to_str)
        .map(str::to_string);
    let registry = registry_src_of(&vars);
    let identity = relocatable_prediction_identity(args, vars).ok_or(Rejection::NoRecord)?;
    let out_dir = out_dir.ok_or(Rejection::NoRecord)?;
    // A `tree` is already in `tree_guard`.
    let guard = match tree {
        Some(tree) => tree,
        None => {
            let _trace = crate::phase_trace::phase("out_dir_tree");
            let guard = tree_guard_of(file_hasher, || {
                out_dir_tree_digest(Path::new(&out_dir), file_hasher)
            })
            .ok_or(Rejection::NoRecord)?;
            let digest = guard.digest.clone();
            *tree_guard = Some(guard);
            digest
        }
    };
    let places = Places {
        out_dir: Some(&out_dir),
        workspace: None,
        registry: registry.as_deref().and_then(Path::to_str),
    };
    portable_key_inputs(file_hasher, &identity, args, &guard, &places)
}

/// Use this machine's row for `identity`, or failing that the remote's
/// ([`set_remote_rows`]), checked the same way. A remote row that passes is
/// kept locally, so the next build does not ask again.
fn portable_key_inputs(
    file_hasher: &FileHasher<'_>,
    identity: &str,
    args: &RustcArgs,
    guard: &str,
    places: &Places<'_>,
) -> std::result::Result<DepInfo, Rejection> {
    let validate = |record: &PortablePrediction| {
        validate_portable_prediction(
            record,
            guard,
            places,
            |path| std::fs::metadata(path).ok(),
            |path| path.exists(),
            |var| std::env::var(var).ok(),
        )
    };
    if let Some(record) = file_hasher.portable_prediction(identity) {
        return validate(&record);
    }
    let record = remote_portable_row(identity).ok_or(Rejection::NoRecord)?;
    let validated = validate(&record);
    crate::phase_trace::decision(
        "remote_prediction",
        if validated.is_ok() { "used" } else { "refused" },
    );
    if validated.is_ok() {
        file_hasher.record_portable_prediction(identity, args.crate_name.as_deref(), &record);
    }
    validated
}

thread_local! {
    /// Where a portable row comes from when this machine has none: the
    /// daemon's remote, installed by the wrapper when a remote is configured.
    static REMOTE_ROWS: std::cell::RefCell<Option<RemoteRows>> =
        const { std::cell::RefCell::new(None) };
}

/// Asks the remote for the row filed under an identity.
pub(crate) type RemoteRows = Box<dyn Fn(&str) -> Option<crate::prediction_share::SharedPrediction>>;

/// Let the key ask `rows` for a portable row this machine lacks, or stop
/// asking with `None` (kunobi-ninja/kache#1011).
pub(crate) fn set_remote_rows(rows: Option<RemoteRows>) {
    REMOTE_ROWS.with(|slot| *slot.borrow_mut() = rows);
}

fn remote_row(identity: &str) -> Option<crate::prediction_share::SharedPrediction> {
    REMOTE_ROWS.with(|slot| slot.borrow().as_ref().and_then(|rows| rows(identity)))
}

fn remote_portable_row(identity: &str) -> Option<PortablePrediction> {
    match remote_row(identity)? {
        crate::prediction_share::SharedPrediction::Portable(row) => Some(row),
        crate::prediction_share::SharedPrediction::Plain(_) => None,
    }
}

fn remote_plain_row(identity: &str, registry: &Path) -> Option<InputPrediction> {
    match remote_row(identity)? {
        crate::prediction_share::SharedPrediction::Plain(row) => {
            crate::prediction_share::plain_from_remote(&row, registry)
        }
        crate::prediction_share::SharedPrediction::Portable(_) => None,
    }
}

/// The bytes of `value` after `registry`, for a path inside one package under
/// it ([`under_registry_src`]), or `None`.
pub(crate) fn registry_suffix(value: &str, registry: &Path) -> Option<String> {
    suffix_within(std::ffi::OsStr::new(value), registry, 2).filter(|suffix| !suffix.is_empty())
}

/// Is a shared row filed under `identity`? A registry unit's may travel
/// (see [`crate::prediction_share`]).
pub(crate) fn is_shared_target_identity(identity: &str) -> bool {
    identity.starts_with(SHARED_PREDICTION_PREFIX)
}

/// `<CARGO_HOME>/registry/src` for a registry unit, from its
/// `CARGO_MANIFEST_DIR`.
pub(crate) fn registry_src_of(
    vars: &[(std::ffi::OsString, std::ffi::OsString)],
) -> Option<PathBuf> {
    registry_src_root(Path::new(env_var_in(vars, "CARGO_MANIFEST_DIR")?)).map(Path::to_path_buf)
}

/// Is a row filed under `identity` free of machine-specific paths, so that it
/// may travel through the remote? The workspace and relocated `OUT_DIR` rows.
pub(crate) fn is_portable_identity(identity: &str) -> bool {
    identity.starts_with(WORKSPACE_PREDICTION_PREFIX)
        || identity.starts_with(RELOCATABLE_PREDICTION_PREFIX)
}

/// The fourth lookup, for a workspace or path unit (kunobi-ninja/kache#1005):
/// a record made in another checkout of the same workspace, with its sources
/// written relative to the workspace root and `OUT_DIR`.
///
/// The guard is `tree`, the digest of the whole workspace (less the target
/// directory and `.git`) and of `OUT_DIR` that the caller took before rustc
/// runs. A record is used only when both are byte for byte what the recorder
/// had, so a macro that scans the workspace, even one reached through an
/// rlib rather than a direct proc-macro dependency, finds the same files
/// here.
fn workspace_key_inputs(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    workspace: &WorkspaceRoots,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
    tree: Option<String>,
) -> std::result::Result<DepInfo, Rejection> {
    let identity =
        workspace_prediction_identity(args, vars, workspace).ok_or(Rejection::NoRecord)?;
    let guard = tree.ok_or(Rejection::NoRecord)?;
    let places = workspace.places().ok_or(Rejection::NoRecord)?;
    let dep_info = portable_key_inputs(file_hasher, &identity, args, &guard, &places)?;
    if !guard_covers(&dep_info.source_files, workspace) {
        return Err(Rejection::NoRecord);
    }
    Ok(dep_info)
}

/// For each of `args`, the argument with the workspace root in a linker path
/// (`-C linker=`) written relative to it, or `None` where there is none. The
/// linker does not change which files rustc reads to build the crate, so two
/// checkouts that differ only there share a record; the cache key itself
/// still sees the argument as it is. Firefox points Cargo's linker at
/// `<checkout>/build/cargo-linker`, which otherwise kept every unit's record
/// to its own checkout. Anything else naming the checkout (an `--extern`
/// outside the target directory, or a `-L` search path, which can change
/// which library resolves) still keeps two checkouts apart.
fn workspace_neutral_link_args(args: &[String], workspace: &WorkspaceRoots) -> Vec<Option<String>> {
    let neutral = |path: &str| {
        [&workspace.root, &workspace.canonical_root]
            .iter()
            .find_map(|root| suffix_within(std::ffi::OsStr::new(path), root, 0))
            .map(|relative| format!("kache-workspace:{relative}"))
    };
    let mut previous: Option<&str> = None;
    args.iter()
        .map(|arg| {
            let flag = previous.replace(arg.as_str());
            match flag {
                Some("-C" | "--codegen") => arg
                    .strip_prefix("linker=")
                    .and_then(neutral)
                    .map(|path| format!("linker={path}")),
                _ => ["-Clinker=", "--codegen=linker="]
                    .iter()
                    .find_map(|prefix| {
                        let path = arg.strip_prefix(prefix)?;
                        Some(format!("{prefix}{}", neutral(path)?))
                    }),
            }
        })
        .collect()
}

/// The directories a workspace unit's record is relocated against.
#[derive(Debug, Clone)]
pub(crate) struct WorkspaceRoots {
    pub(crate) root: PathBuf,
    /// The working directory rustc resolves relative paths against, as the
    /// bytes after `root` (`""` at the root itself).
    pub(crate) cwd: String,
    pub(crate) canonical_root: PathBuf,
    pub(crate) target: PathBuf,
    pub(crate) canonical_target: PathBuf,
    pub(crate) out_dir: Option<PathBuf>,
    /// The package directory, for a vendored package ([`is_vendored_package`]):
    /// its guard is the package, not the workspace.
    pub(crate) vendored_package: Option<PathBuf>,
}

impl WorkspaceRoots {
    /// Where this invocation puts a record's relative entries.
    fn places(&self) -> Option<Places<'_>> {
        Some(Places {
            out_dir: match &self.out_dir {
                Some(out_dir) => Some(out_dir.to_str()?),
                None => None,
            },
            workspace: Some(self.root.to_str()?),
            registry: None,
        })
    }
}

/// This invocation's workspace, when its package is a workspace or path
/// package inside the workspace Cargo builds.
///
/// `None` for a registry package (see [`relocated_key_inputs`]), a package
/// outside the workspace, and any root that
/// cannot be canonicalized: those units keep checkout-local records.
fn workspace_roots(
    args: &RustcArgs,
    vars: &[(std::ffi::OsString, std::ffi::OsString)],
) -> Option<WorkspaceRoots> {
    workspace_roots_in(args, vars, &std::env::current_dir().ok()?)
}

/// The target directory of `args`, which a workspace unit's guard leaves
/// out. Cargo's legacy layout compiles a build script into
/// `<profile>/build/<unit>`, where [`RustcArgs::target_dir`] reads the
/// profile directory.
fn workspace_target_dir(args: &RustcArgs) -> Option<PathBuf> {
    let build_script_profile = args
        .out_dir
        .as_deref()
        .filter(|dir| crate::cargo_layout::per_unit_out_dir(dir).is_none())
        .and_then(crate::cargo_layout::build_script_dir_profile);
    match build_script_profile {
        Some(profile) => profile.parent().map(Path::to_path_buf),
        None => args.target_dir(),
    }
}

/// [`workspace_roots`] for rustc running in `current_dir`. The root is
/// [`RustcArgs::verified_workspace_root`] for an in-workspace target, or
/// Cargo's compiler working directory when it holds a manifest. An external
/// target's parent is never treated as a source root.
fn workspace_roots_in(
    args: &RustcArgs,
    vars: &[(std::ffi::OsString, std::ffi::OsString)],
    current_dir: &Path,
) -> Option<WorkspaceRoots> {
    let manifest_dir = Path::new(env_var_in(vars, "CARGO_MANIFEST_DIR")?);
    if is_registry_package(manifest_dir) {
        return None;
    }
    let root = args.verified_workspace_root(current_dir).or_else(|| {
        manifest_dir
            .ancestors()
            .find(|root| root.join("Cargo.toml").is_file() && same_dir(root, current_dir))
            .map(Path::to_path_buf)
    })?;
    let target = workspace_target_dir(args)?;
    suffix_within(manifest_dir.as_os_str(), &root, 0)?;
    let canonical_root = std::fs::canonicalize(&root).ok()?;
    // Cargo and the working directory can use different spellings: macOS
    // resolves `/var` to `/private/var`, and Windows canonicalization adds
    // a verbatim prefix and normalizes separators.
    let cwd = suffix_within(current_dir.as_os_str(), &root, 0).or_else(|| {
        let canonical_cwd = std::fs::canonicalize(current_dir).ok()?;
        suffix_within(canonical_cwd.as_os_str(), &canonical_root, 0)
    })?;
    Some(WorkspaceRoots {
        cwd,
        canonical_root,
        canonical_target: std::fs::canonicalize(&target).ok()?,
        out_dir: env_var_in(vars, "OUT_DIR").map(PathBuf::from),
        vendored_package: vendored_source(args, manifest_dir, current_dir)
            .then(|| manifest_dir.to_path_buf()),
        root,
        target,
    })
}

/// Rows of workspace and path units, filed under an identity with the
/// checkout taken out ([`workspace_prediction_identity`]).
const WORKSPACE_PREDICTION_PREFIX: &str = "shared-workspace-v1:";

/// The identity of a workspace unit's relocated record: the ordinary
/// identity with the working directory, the crate root and
/// `CARGO_MANIFEST_DIR` written relative to the workspace root, and target
/// paths relative to the target directory as the shared identity writes
/// them. Everything else stays as spelled, so an argument or variable that
/// still names the checkout only keeps two checkouts apart.
fn workspace_prediction_identity(
    args: &RustcArgs,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
    workspace: &WorkspaceRoots,
) -> Option<String> {
    let source = args.source_file.as_ref()?;
    let root = &workspace.root;
    let within = |path: &Path| suffix_within(path.as_os_str(), root, 0);
    let source_spelling = if source.is_absolute() {
        format!("kache-workspace:{}", within(source)?)
    } else {
        format!("kache-cwd:{}", source.to_str()?)
    };
    let current_dir = format!("kache-workspace:{}", workspace.cwd);
    let raw_args = closure_shaping_args(source, &args.all_args);
    let mut closure_args = shared_prediction_args(&raw_args, &workspace.target);
    // A linker in the checkout, under its own tag.
    for (arg, neutral) in closure_args
        .iter_mut()
        .zip(workspace_neutral_link_args(&raw_args, workspace))
    {
        if let Some(neutral) = neutral
            && arg.starts_with("[\"literal\"")
        {
            *arg = serde_json::to_string(&("workspace-link", "", "", neutral.as_str())).ok()?;
        }
    }
    // The crate root leads the closure arguments; spell it as above.
    *closure_args.first_mut()? =
        serde_json::to_string(&("source", "", "", source_spelling.as_str())).ok()?;
    let vars = shared_prediction_vars(vars.into_iter(), &workspace.target)
        .into_iter()
        .map(|(name, value)| {
            if name != "CARGO_MANIFEST_DIR" {
                return Some((name, value));
            }
            let relative = within(Path::new(&value))?;
            Some((name, format!("kache-workspace:{relative}").into()))
        })
        .collect::<Option<Vec<_>>>()?;
    let rustc_version = get_rustc_version(&args.rustc).ok()?;
    let identity = prediction_identity_in_env(
        &PredictionIdentityParts {
            rustc_version: &rustc_version,
            inner_rustc: args.inner_rustc.as_deref(),
            current_dir: Some(Path::new(&current_dir)),
            source_file: Path::new(&source_spelling),
            closure_args: &closure_args,
            skip_path_remap: args.skip_path_remap(),
        },
        vars,
    );
    Some(format!("{WORKSPACE_PREDICTION_PREFIX}{identity}"))
}

/// The guard for a workspace unit's records: a content digest of the
/// workspace, less its target directory and `.git`, and of `OUT_DIR`. A
/// vendored package is guarded by its own directory and `OUT_DIR` instead.
fn workspace_tree_digest(
    workspace: &WorkspaceRoots,
    file_hasher: &FileHasher<'_>,
) -> Option<String> {
    if let Some(package) = &workspace.vendored_package {
        return vendored_package_digest(
            package,
            workspace.out_dir.as_deref(),
            &workspace.root,
            file_hasher,
        );
    }
    workspace_tree_digest_within(workspace, file_hasher, CRATE_TREE_MAX_ENTRIES)
}

/// Is `manifest_dir` a vendored package: a crate `cargo vendor` copied into
/// the tree, as Firefox does for every crates.io and git dependency under
/// `third_party/rust`? Cargo writes `.cargo-checksum.json` into each one and
/// checks it before building from a vendored source. The file alone could
/// be a leftover in an ordinary member; [`vendored_source`] also asks how
/// Cargo invoked rustc.
///
/// A vendored package is a published crate, copied alone: the same package a
/// registry holds, so what [`crate_tree_digest`] relies on holds here too. A
/// macro in it can only read the package and its `OUT_DIR`, and nothing else
/// of the tree it was copied into. Its guard is that package, which costs a
/// few files instead of the whole workspace.
pub(crate) fn is_vendored_package(manifest_dir: &Path) -> bool {
    manifest_dir.join(".cargo-checksum.json").is_file()
}

/// Did Cargo build this unit from a vendored source, not a path package
/// that happens to hold a checksum file? Cargo hands rustc a path package
/// inside the workspace (a member, or a `[patch]` to a path) as a source path
/// relative to the workspace root, run from there. Any other source gets an
/// absolute path, run from the package's own directory, and only Cargo
/// decides which. A path package whose `[lib] path` leaves the workspace gets
/// an absolute path too, so the source must also sit inside the package, as
/// a vendored crate's always does. The lint cap Cargo gives non-path packages is required
/// too; `cargo -vv` omits it, and the unit then keeps the workspace guard.
pub(crate) fn vendored_source(args: &RustcArgs, manifest_dir: &Path, current_dir: &Path) -> bool {
    args.cargo_capped_lints()
        && args
            .source_file
            .as_deref()
            .is_some_and(|source| source.is_absolute() && source.starts_with(manifest_dir))
        && same_dir(current_dir, manifest_dir)
        && is_vendored_package(manifest_dir)
}

/// Whether `a` and `b` name one directory: spelled the same, or resolving to
/// the same place.
fn same_dir(a: &Path, b: &Path) -> bool {
    a == b
        || std::fs::canonicalize(a)
            .ok()
            .zip(std::fs::canonicalize(b).ok())
            .is_some_and(|(a, b)| a == b)
}

/// The guard of a vendored package: its directory (less `target` and `.git`,
/// as for a registry package) and `OUT_DIR`, and what a search upward from
/// the package could find on the way to the workspace root: the files and
/// dot-directories at the top of each directory in between (a `.env`, a
/// `.sqlx`, a config file). A crate built from a registry finds nothing
/// there; vendored into a tree, a lookup that falls back when nothing is
/// found could read one of them, so they count. Other directories on the
/// way (sibling packages, the rest of the tree) do not.
fn vendored_package_digest(
    package: &Path,
    out_dir: Option<&Path>,
    workspace_root: &Path,
    file_hasher: &FileHasher<'_>,
) -> Option<String> {
    let mut roots = vec![TreeRoot::new(
        package.to_path_buf(),
        b"vendored_package",
        MANIFEST_DIR_SKIPPED,
    )];
    if let Some(out_dir) = out_dir {
        roots.push(TreeRoot::new(out_dir.to_path_buf(), b"out_dir", &[]));
    }
    let package_digest = tree_digest(roots, file_hasher, CRATE_TREE_MAX_ENTRIES)?;
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache-vendored-guard-v1\n");
    fold_field(&mut hasher, b"package:", package_digest.as_bytes());
    let mut ancestor = package.parent();
    while let Some(directory) = ancestor.filter(|directory| directory.starts_with(workspace_root)) {
        fold_field(
            &mut hasher,
            b"ancestor:",
            ancestor_top_digest(directory, file_hasher)?.as_bytes(),
        );
        ancestor = directory.parent();
    }
    Some(hasher.finalize().to_hex().to_string())
}

/// The files, symlinks and dot-directories (less `.git`, of either kind) at the top of
/// `directory`, by name and content. A symlink to a file counts by its
/// target and by the content read through it.
fn ancestor_top_digest(directory: &Path, file_hasher: &FileHasher<'_>) -> Option<String> {
    // The guard's walk of the files and symlinks read here, and of the
    // directory's own times, taken before the listing: a name that appears
    // after the stamp, or comes and goes before the record is written, moves
    // those times. A dot-directory's own digest walks that directory.
    let top = WalkedRoot {
        path: directory.to_path_buf(),
        role: b"ancestor".to_vec(),
        excluded: vec![directory.join(".git")],
        rules: crate::tree_stamp::StampRules {
            link_text: true,
            skip_build_dirs: false,
            root_metadata: true,
            unreadable_entries: true,
            top_files_only: true,
            unsearchable_dirs: false,
        },
    };
    let stamp = stamp_root(&top, CRATE_TREE_MAX_ENTRIES)?;
    let mut entries: Vec<_> = std::fs::read_dir(directory)
        .ok()?
        .collect::<std::io::Result<_>>()
        .ok()?;
    entries.sort_by_key(std::fs::DirEntry::file_name);
    file_hasher.note_tree_walk(GuardWalk {
        root: top,
        max_entries: CRATE_TREE_MAX_ENTRIES,
        stamp: stamp.digest,
    });
    let own = own_dirs_within(directory, &file_hasher.own_dirs);
    let mut hasher = blake3::Hasher::new();
    for entry in entries {
        let name = entry.file_name();
        // A directory in a clone, a file naming the repository in a git
        // worktree: either way it is not what a macro reads, and it differs
        // between checkouts.
        if name == ".git" {
            continue;
        }
        let path = entry.path();
        // Kache's own directories, and what Cargo writes in its home, change
        // while units build.
        if own.contains(&path) {
            continue;
        }
        // What this process cannot read, a macro it starts cannot read either.
        let unreadable = || "unreadable".to_string();
        let content = match std::fs::symlink_metadata(&path) {
            Err(_) => unreadable(),
            Ok(metadata) if metadata.file_type().is_symlink() => match std::fs::read_link(&path) {
                // Where it points, and what a read through it would find.
                Ok(target) => {
                    let found = if path.is_file() {
                        file_hasher
                            .hash_unkeyed(&path)
                            .unwrap_or_else(|_| unreadable())
                    } else {
                        String::new()
                    };
                    format!("symlink:{}:{found}", target.display())
                }
                Err(_) => unreadable(),
            },
            Ok(metadata) if metadata.is_file() => match file_hasher.hash_unkeyed(&path) {
                Ok(hash) => format!("file:{hash}"),
                Err(_) => unreadable(),
            },
            Ok(metadata)
                if metadata.is_dir()
                    && name.as_encoded_bytes().starts_with(b".")
                    && name != ".git" =>
            {
                let roots = vec![TreeRoot::new(path.clone(), b"dot_dir", &[])];
                format!(
                    "dir:{}",
                    tree_digest(roots, file_hasher, CRATE_TREE_MAX_ENTRIES)?
                )
            }
            Ok(_) => continue,
        };
        fold_field(&mut hasher, b"name:", name.as_encoded_bytes());
        fold_field(&mut hasher, b"entry:", content.as_bytes());
    }
    Some(hasher.finalize().to_hex().to_string())
}

/// [`workspace_tree_digest`] with its entry budget supplied.
fn workspace_tree_digest_within(
    workspace: &WorkspaceRoots,
    file_hasher: &FileHasher<'_>,
    max_entries: usize,
) -> Option<String> {
    let target =
        suffix_within(workspace.target.as_os_str(), &workspace.root, 0).unwrap_or_default();
    let target = target.trim_start_matches(['/', '\\']);
    let skipped = [target, ".git"];
    let mut roots =
        vec![TreeRoot::new(workspace.root.clone(), b"workspace", &skipped).skipping_build_dirs()];
    if let Some(out_dir) = &workspace.out_dir {
        roots.push(TreeRoot::new(out_dir.clone(), b"out_dir", &[]));
    }
    tree_digest(roots, file_hasher, max_entries)
}

/// 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() || has_dylib_extern(&args.externs) {
        return None;
    }
    rustc_shared_prediction_identity(args).or_else(|| rustc_prediction_identity(args))
}

/// The flight two processes discovering the same unit share. With
/// predictions on it is the record identity where one applies, so the
/// waiter can read what the owner publishes. Otherwise the same identity
/// is only a name for the unit: the waiter finds the owner's entry in the
/// store instead. A unit with a proc-macro dependency gets that name too;
/// its record needs the crate-tree guard, but a flight is only a lock, and
/// compiling before keying never reads a record.
fn discovery_flight_identity(args: &RustcArgs, file_hasher: &FileHasher<'_>) -> Option<String> {
    prediction_discovery_identity(args, file_hasher)
        .or_else(|| 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,
    env: &KeyEnv,
    out: &mut KeyOutputs,
) -> Result<Option<DepInfo>> {
    if let Some((provided, tree)) = PROVIDED_DEP_INFO.with(|cell| cell.borrow_mut().take()) {
        out.tree_guard = tree;
        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, &mut out.tree_guard);
        // Whether this process holds the unit's discovery flight. Only the
        // holder may compile before keying: a peer that also found nothing
        // would compile the same unit a second time instead of waiting for
        // the entry the holder stores.
        let mut owns_flight = false;
        if prediction.is_err()
            && let Some(cache_dir) = &file_hasher.prediction_flight_dir
            && let Some(identity) = discovery_flight_identity(args, file_hasher)
        {
            let flight = crate::scheduler::join_discovery_flight(cache_dir, &identity);
            owns_flight = flight.lock.is_some();
            *file_hasher.discovery_flight.borrow_mut() = flight.lock;
            // The previous owner may have published while this process
            // waited; a flight taken at once had no owner to publish. The
            // tree is digested again: the owner's record carries the digest
            // from before its compile, and the tree may have changed since.
            if flight.waited {
                prediction = predicted_key_inputs(args, file_hasher, &mut out.tree_guard);
            }
        }
        match prediction {
            Ok(dep_info) => {
                crate::phase_trace::decision("prediction", "validated");
                let mode =
                    parse_verify_predictions(env.var("KACHE_VERIFY_INPUT_PREDICTIONS").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 verifies_prediction(mode, args, env.cwd(), |var| env.var_os(var)) {
                    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);
                out.used_prediction = true;
                return Ok(Some(dep_info));
            }
            // A missing prediction only describes this checkout. Another
            // checkout may have stored a portable entry, so compile first
            // only when the store has never held this unit.
            Err(Rejection::NoRecord | Rejection::Disabled | Rejection::NotEligible)
                if owns_flight
                    && DEFER_DISCOVERY.with(std::cell::Cell::get)
                    && file_hasher.store_lacks_unit(
                        crate_name,
                        args.get_codegen_opt("metadata").unwrap_or(""),
                    ) =>
            {
                crate::phase_trace::decision("prediction", "deferred-new-crate");
                tracing::trace!("[key:{}] inputs=deferred(new crate)", crate_name);
                return Err(anyhow::Error::new(DeferredDiscovery { miss_certain: true }));
            }
            Err(reason)
                if owns_flight
                    && DEFER_DISCOVERY.with(std::cell::Cell::get)
                    && COMPILE_WHILE_KEYING.with(std::cell::Cell::get) =>
            {
                crate::phase_trace::decision("prediction", reason.as_str());
                tracing::trace!(
                    "[key:{}] inputs=compile-while-keying({})",
                    crate_name,
                    reason.as_str()
                );
                return Err(anyhow::Error::new(DeferredDiscovery {
                    miss_certain: false,
                }));
            }
            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, with what the
/// computation learned on the way ([`KeyOutputs`]).
///
/// 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)
///
/// The outputs come back whether or not the key does, and belong to this
/// computation alone: nothing carries over from an earlier one (#609).
pub fn compute_cache_key_with_outputs(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
    env: &KeyEnv,
) -> (Result<String>, KeyOutputs) {
    let mut out = KeyOutputs {
        unit_id: args.unit_id(),
        ..KeyOutputs::default()
    };
    let key = compute_key_into(args, file_hasher, path_normalizer, env, &mut out);
    (key, out)
}

/// [`compute_cache_key_with_outputs`], for tests that need only the key.
#[cfg(test)]
pub(crate) fn compute_cache_key(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
    env: &KeyEnv,
) -> Result<String> {
    compute_cache_key_with_outputs(args, file_hasher, path_normalizer, env).0
}

fn compute_key_into(
    args: &RustcArgs,
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
    env: &KeyEnv,
    out: &mut KeyOutputs,
) -> 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");

    // The unit's OUT_DIR, read here once and passed to everything below that
    // needs it.
    let out_dir = env.var_os("OUT_DIR");

    // 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, env)?;
        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, env, out)?;
    // Hand the closure back 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.
    out.dep_info = 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");
        let aliased_out_dir = crate::out_dir_alias::active_alias();
        let env_dep_paths = EnvDepPaths::new(out_dir.as_deref(), &dep_info.source_files);
        let mut bakes_out_dir = false;
        let mut env_fields = BTreeMap::new();
        for (var, val) in &dep_info.env_deps {
            let value = EnvDepValue::new(val);
            let normalized_env_dep = normalize_env_dep_value_with_hasher(
                crate_name,
                var,
                &value,
                &env_dep_paths,
                file_hasher,
                path_normalizer,
                aliased_out_dir,
            );
            bakes_out_dir |= env_dep_bakes_out_dir(var, normalized_env_dep.decision, || {
                env_dep_paths.value_is_under_out_dir(&value)
            });
            env_fields.insert(
                var.clone(),
                blake3::hash(normalized_env_dep.value.as_bytes()).to_hex()[..KEY_FIELD_HEX]
                    .to_string(),
            );
            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()
            );
        }
        out.env_deps = Some(env_fields);
        out.bakes_out_dir = bakes_out_dir;
    }

    // ── 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);
                }
            }
        }
    }
    out.externs = Some(extern_digests);
    out.extern_units = 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 Some(rustflags) = 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 Some(flags) = 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 Some(bootstrap) = 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();
    // `framework=` dirs, the only ones rustc hands the linker as `-F`.
    let mut framework_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));
        }
        if kind == Some("framework") {
            framework_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).
    // [`fold_native_link_inputs`] hashes the archives a unit's output carries:
    // its `static` specs, the archives a Unix link picks for its other `-l`
    // specs, files named in its link arguments, and every archive in its `-L`
    // dirs outside Cargo's packages and the system library dirs. A `:RENAME`
    // or unknown modifier is uncacheable.
    // 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, which refuses files handed to LINK
    // through `-C link-arg` (`.res`, `.def`, `.obj`, `/DEF:`, ...).
    // 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");
    }
    // Native MSVC links resolve their libraries and link-argument files in
    // the MSVC identity below, so the Unix rules here stay off for them.
    let native_windows_msvc = is_native_windows_msvc_link(
        args,
        &rustc_version,
        cfg!(target_os = "windows"),
        get_rustc_version,
    )?;
    // Only a link searches for libraries, so only a link reads the host.
    let link_rustc_version = if args.invokes_linker() {
        Some(rustc_version_for_native_link(
            args,
            &rustc_version,
            get_rustc_version,
        )?)
    } else {
        None
    };
    let rustc_host = link_rustc_version.as_deref().and_then(rustc_host_triple);
    let target = link_target(args.target.as_deref(), rustc_host);
    let unit_out_dir = out_dir.map(PathBuf::from);
    let native_archives = fold_native_link_inputs(
        &mut hasher,
        args,
        &NativeSearchDirs {
            native: &native_search_dirs,
            framework: &framework_search_dirs,
        },
        &NativeLinkContext {
            native_windows_msvc,
            target,
            default_dirs: default_library_dirs(
                target,
                rustc_host,
                env.var_os("LIBRARY_PATH").as_deref(),
            ),
            out_dir: unit_out_dir.as_deref(),
            build_tree: build_tree_roots(args),
            system_dirs: system_library_dirs(),
            path_normalizer,
        },
        file_hasher,
    )?;
    // An rlib that bundles an archive the key did not hash is refused at
    // store time (see the wrapper's bundle audit). Entries stored by clients
    // without that audit must not serve this one.
    if needs_native_bundle_audit(args, &native_archives.dirs) {
        hasher.set_group("native_bundle_audit");
        fold_field(&mut hasher, b"native_bundle_audit.v2", b"");
        tracing::trace!("[key:{}] native_bundle_audit", crate_name);
    }
    out.native_archives = Some(native_archives);

    // Unstable `-Z` flags arriving on argv outside RUSTFLAGS. Can change
    // codegen (`-Zsanitizer`, `-Zshare-generics`, …); hashed raw.
    hasher.set_group("args");
    let backend_dylib = args.codegen_backend_dylib();
    for z in &args.unstable_flags {
        // A backend dylib is keyed by its content, not its path: the wrapper
        // only reaches here for one when the user trusts it, and rebuilding
        // the backend in place must change the key while another checkout's
        // identical backend must not.
        if let Some(path) = z
            .strip_prefix("codegen-backend=")
            .filter(|path| Some(*path) == backend_dylib)
        {
            let content = file_hasher
                .hash(Path::new(path))
                .with_context(|| format!("hashing codegen backend {path}"))?;
            fold_field(
                &mut hasher,
                b"codegen_backend_content.v1:",
                content.as_bytes(),
            );
            tracing::trace!("[key:{}] codegen_backend_content:{}", crate_name, content);
            continue;
        }
        hasher.update(b"unstable:");
        hasher.update(z.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] unstable:{}", crate_name, z);
    }
    // A backend selected by name (`cranelift`, `gcc`) is a library in the
    // toolchain that `rustc -vV` does not describe: a toolchain built from
    // source can replace it without reporting a new version.
    if let Some(backend) = args.codegen_backend_name() {
        for (library, content) in
            toolchain_codegen_backends(args, &rustc_version, backend, file_hasher)?
        {
            fold_field(
                &mut hasher,
                b"codegen_backend_library.v1:",
                library.as_bytes(),
            );
            fold_field(
                &mut hasher,
                b"codegen_backend_content.v1:",
                content.as_bytes(),
            );
            tracing::trace!(
                "[key:{}] codegen_backend_library:{} {}",
                crate_name,
                library,
                content
            );
        }
    }

    // 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(env.cargo_cfgs());
    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");
    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"),
        },
        env,
    )?;

    // 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, host| {
            let search_dirs = windows_native_link_search_dirs(args)?;
            crate::native_link_key::probe_windows_msvc_identity_with_library_dirs(
                linker,
                architecture,
                &rustc_tool_dirs(args, host)?,
                &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, env);
        "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();
    out.fields = Some(fields);
    let key = hash.to_hex().to_string();
    tracing::trace!("[key:{}] final={}", crate_name, &key[..16]);
    complete_key(env, key)
}

/// `key`, unless key computation read a variable its snapshot does not hold.
/// That input would have folded as unset whatever its value, so two builds
/// that differ in it could share the key; the invocation runs uncached.
fn complete_key(env: &KeyEnv, key: String) -> Result<String> {
    anyhow::ensure!(
        !env.read_undeclared(),
        "key computation read an environment variable missing from KEY_ENV_VARS"
    );
    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.
///
/// trybuild is the exception (kunobi-ninja/kache#1190). It skips remapping so
/// its diagnostics still match the snapshots, and every crate it builds,
/// including registry dependencies, takes that path. A registry rmeta records
/// the package directory and the source file, not `--out-dir`. Folding the
/// per-worktree target prefix anyway made those dependencies miss in every
/// checkout. A trybuild unit therefore folds a prefix only when the working
/// directory, the source, or `OUT_DIR` is under it. A build script that
/// `include!`s `OUT_DIR` writes that absolute path into the rmeta, so the
/// prefix that holds `OUT_DIR` stays. Coverage and the normalize opt-out keep
/// folding every prefix: their artifacts carry the paths the profraw and the
/// debugger look up.
fn fold_unremapped_path_identity<H: KeyFold>(
    hasher: &mut H,
    args: &RustcArgs,
    path_normalizer: &PathNormalizer,
    env: &KeyEnv,
) {
    hasher.update(b"unremapped_path_identity:v1\n");

    if let Some(cwd) = env.cwd() {
        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();
    if args.is_trybuild_unit() {
        let reached = trybuild_paths_in_the_artifact(args, env);
        prefixes.retain(|prefix| reached.iter().any(|path| path_is_under(path, prefix)));
    }
    prefixes.sort_unstable();
    prefixes.dedup();
    for prefix in prefixes {
        fold_field(hasher, b"unremapped:prefix:", prefix.as_bytes());
    }
}

/// Paths an unremapped trybuild compile writes into the rmeta.
///
/// A relative source or `OUT_DIR` is resolved against the working directory,
/// which is where rustc records it. An empty `OUT_DIR` is not a path.
fn trybuild_paths_in_the_artifact(args: &RustcArgs, env: &KeyEnv) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    if let Some(cwd) = env.cwd() {
        paths.push(cwd.to_path_buf());
    }
    if let Some(source) = &args.source_file {
        paths.push(joined_under(env.cwd(), source));
    }
    if let Some(out_dir) = env.var_os("OUT_DIR").filter(|value| !value.is_empty()) {
        paths.push(joined_under(env.cwd(), Path::new(&out_dir)));
    }
    paths
}

fn joined_under(cwd: Option<&Path>, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else if let Some(cwd) = cwd {
        cwd.join(path)
    } else {
        path.to_path_buf()
    }
}

fn path_is_under(path: &Path, prefix: &str) -> bool {
    path.starts_with(prefix)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EnvDepNormalizationDecision {
    Unchanged,
    NormalizedPathOnly,
    /// Kept absolute: the var is not OUT_DIR, not allowlisted, and its value
    /// is not under OUT_DIR.
    KeptAbsoluteNotPathOnly,
    /// Kept absolute: CARGO_MANIFEST_DIR, which no allowlist entry can make
    /// path-only.
    KeptAbsoluteManifestDir,
    /// Kept absolute: dep-info lists no include under the value, or no Rust
    /// source shows the var inside an include argument (for example when the
    /// include comes from another crate's macro).
    KeptAbsoluteNoIncludeProof,
    /// Kept absolute: a source uses the var outside an include argument, or
    /// has an env macro whose var name the scanner cannot read.
    KeptAbsoluteRuntimeUse,
    /// Kept absolute: a source could not be read, or changed during the scan.
    KeptAbsoluteScanError,
    /// Normalized because the var (optionally crate-scoped) is in the
    /// user-asserted force list, bypassing the source scans.
    ForcedPathOnly,
    /// Kept raw: the value is at or under the shared read-only OUT_DIR this
    /// unit compiles with (see `out_dir_alias`), the same string in every
    /// checkout.
    AliasedOutDir,
}

impl EnvDepNormalizationDecision {
    /// Does the key hold the value as rustc sees it, rather than a sentinel?
    fn keeps_literal_value(self) -> bool {
        !matches!(self, Self::NormalizedPathOnly | Self::ForcedPathOnly)
    }

    fn as_str(self) -> &'static str {
        match self {
            Self::Unchanged => "unchanged",
            Self::NormalizedPathOnly => "normalized path-only",
            Self::KeptAbsoluteNotPathOnly => "kept absolute: not a path-only var",
            Self::KeptAbsoluteManifestDir => "kept absolute: CARGO_MANIFEST_DIR is never path-only",
            Self::KeptAbsoluteNoIncludeProof => "kept absolute: no include proof",
            Self::KeptAbsoluteRuntimeUse => "kept absolute: value use in source",
            Self::KeptAbsoluteScanError => "kept absolute: source scan failed",
            Self::ForcedPathOnly => "forced path-only (user-asserted)",
            Self::AliasedOutDir => "aliased OUT_DIR",
        }
    }
}

#[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 `static` archive in one of `search_dirs` and
/// return `(path, content_hash)`, or `None` when it is not a `static` kind, no
/// candidate is found, or the unit neither links (`links`) nor bundles it
/// (`-bundle`). A `static` spec whose file cannot be modelled (`:RENAME`,
/// unknown modifier) is an error. Ambiguous/read/identity failures return an
/// error so the invocation passes through uncached; candidates with the same
/// bytes are not ambiguous. `usage` picks the digest for the archive found.
/// 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).
fn resolve_native_static_lib(
    spec: &str,
    search_dirs: &[PathBuf],
    file_hasher: &FileHasher<'_>,
    links: bool,
    usage: impl Fn(&Path) -> StaticLibUse,
) -> Result<Option<(PathBuf, String)>> {
    let file_names = match static_lib_spec(spec) {
        StaticLibSpec::NotStatic => return Ok(None),
        // An rlib or staticlib leaves a `-bundle` archive out of its output;
        // the unit that links it later hashes it.
        StaticLibSpec::Archive { bundle: false, .. } if !links => return Ok(None),
        StaticLibSpec::Archive { files, .. } => files,
        // The archive is bundled or linked, but we cannot tell which file.
        StaticLibSpec::Unmodeled(spec) => {
            anyhow::bail!("native static library spec {spec:?} is not cacheable")
        }
    };
    // 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. Nor are distinct candidates with the same bytes: for an MSVC
    // target `cc` hard-links or copies each `lib<name>.a` it builds to
    // `<name>.lib`, and whichever one rustc or the linker takes, it reads the
    // same contents. The first one found is hashed. Which copy rustc takes is
    // target-specific, and a bundling output records that file's name, so
    // where the copies are is part of the key. If candidates differ —
    // `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;
    // Each distinct candidate, with its search-dir index and file name.
    let mut copies: Vec<(PathBuf, String)> = Vec::new();
    for (index, dir) in search_dirs.iter().enumerate() {
        for filename in &file_names {
            let candidate = dir.join(filename);
            if candidate.is_file() {
                if copies.iter().any(|(path, _)| path == &candidate) {
                    continue;
                }
                if let Some(first) = &found
                    && file_hasher.hash(first)? != file_hasher.hash(&candidate)?
                {
                    anyhow::bail!("ambiguous native static library {spec:?}");
                }
                copies.push((candidate.clone(), format!("{index}:{filename}")));
                found.get_or_insert(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 mut hash = file_hasher.hash_static_lib_for(&path, usage(&path))?;
    // One candidate keys as before; identical copies add where they are.
    if copies.len() > 1 {
        let places: Vec<&str> = copies.iter().map(|(_, place)| place.as_str()).collect();
        hash = format!("{hash};copies={}", places.join(","));
    }
    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 archive's path never reaches the output: rustc bundles it into its
    /// rlib (or staticlib) output, or ld64 strips it through the
    /// `-oso_prefix` kache injects. A later cached debug link names rlib
    /// members `<rlib>(member)` under `--out-dir`, which that prefix 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-v8-bundled",
            Self::Linked => "static-ar-v8",
        }
    }
}

/// Whether `archive` is reached under the `-oso_prefix` root as spelled but
/// resolves into a sealed hermetic build-script `OUT_DIR`. The linker names
/// it by the spelled path, which the prefix strips, and the directory it
/// resolves to is read-only and has the same path in every target directory
/// that shares it, so its bytes decide the link as much as a copy under the
/// profile directory would.
fn hermetic_archive_under(archive: &Path, resolved: &Path, spelled_root: &Path) -> bool {
    std::path::absolute(archive).is_ok_and(|spelled| spelled.starts_with(spelled_root))
        && !resolved.starts_with(spelled_root)
        && crate::build_script::in_sealed_out_dir(resolved)
}

/// [`linked_archive_use`] for a link that gets `-oso_prefix` at
/// `spelled_root`, which resolves to `root`. Compared resolved, like OUT_DIR
/// in [`dirs_under`], except for an archive in a sealed hermetic `OUT_DIR`.
fn oso_archive_use(
    args: &RustcArgs,
    archive: &Path,
    spelled_root: &Path,
    root: &Path,
) -> StaticLibUse {
    let resolved = resolved_path(archive);
    if hermetic_archive_under(archive, &resolved, spelled_root) {
        linked_archive_use(args, archive, Some(spelled_root))
    } else {
        linked_archive_use(args, &resolved, Some(root))
    }
}

/// How this invocation uses `archive`. A unit that does not link bundles it.
/// A link keeps the archive's path in its debug map unless the `-oso_prefix`
/// kache injects (`oso_root`, from
/// [`crate::compiler::rustc::oso_prefix_root_for_key`]) strips it.
fn linked_archive_use(args: &RustcArgs, archive: &Path, oso_root: Option<&Path>) -> StaticLibUse {
    if !args.is_executable_output() || oso_root.is_some_and(|root| archive.starts_with(root)) {
        StaticLibUse::Bundled
    } else {
        StaticLibUse::Linked
    }
}

/// Whether a `static` spec that resolves in none of the unit's dirs refuses
/// the key. A linking unit hands the name to the linker, which may take a
/// copy from a system dir the key does not see; rustc itself fails an rlib or
/// staticlib that bundles a missing archive. Native MSVC links resolve the
/// name through `LIB` in their own identity.
fn unresolved_static_lib_is_error(links: bool, native_windows_msvc: bool) -> bool {
    links && !native_windows_msvc
}

/// The name and `+verbatim` flag of a kindless or `dylib` `-l` spec, which a
/// Unix linker may still satisfy with an archive. `None` for other kinds.
fn unix_library_request(spec: &str) -> Option<(&str, bool)> {
    let (kind, name) = spec.split_once('=').unwrap_or(("dylib", spec));
    let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
    if kind != "dylib" || name.is_empty() {
        return None;
    }
    let verbatim = modifiers
        .split(',')
        .fold(false, |verbatim, modifier| match modifier {
            "+verbatim" => true,
            "-verbatim" => false,
            _ => verbatim,
        });
    Some((name, verbatim))
}

/// The archive a Unix linker takes for `-l name`, if it takes one. The first
/// dir with a candidate wins. It supplies the archive when it holds no shared
/// library for the name (`lib{name}.{ext}` for each of `shared_extensions`),
/// or when the link is static (`prefer_static`), where shared libraries are
/// not candidates. A verbatim name is its own only candidate.
fn resolve_unix_library(
    name: &str,
    verbatim: bool,
    dirs: &[PathBuf],
    prefer_static: bool,
    shared_extensions: &[&str],
    is_file: impl Fn(&Path) -> bool,
) -> Option<PathBuf> {
    let (archive, shared) = if verbatim {
        if !is_native_archive_name(name) {
            return None;
        }
        (name.to_string(), Vec::new())
    } else if prefer_static {
        (format!("lib{name}.a"), Vec::new())
    } else {
        let shared = shared_extensions
            .iter()
            .map(|extension| format!("lib{name}.{extension}"))
            .collect();
        (format!("lib{name}.a"), shared)
    };
    for dir in dirs {
        let has_archive = is_file(&dir.join(&archive));
        let has_shared = shared.iter().any(|file| is_file(&dir.join(file)));
        if has_archive || has_shared {
            return (!has_shared).then(|| dir.join(&archive));
        }
    }
    None
}

/// The shared libraries a Unix linker for `target` prefers to `lib{name}.a`
/// in the same dir: ld64 also reads `.tbd` and `.dylib`, ELF linkers only
/// `.so`.
fn shared_library_extensions(target: &str) -> &'static [&'static str] {
    if target.contains("-apple-") {
        &["tbd", "dylib", "so"]
    } else {
        &["so"]
    }
}

/// Whether the linker takes only archives for `-l`: the last `crt-static`
/// target feature is on, or none is given for a musl target, where it is on
/// by default.
fn prefers_static_libraries(target_features: &[&str], target: &str) -> bool {
    target_features
        .iter()
        .flat_map(|features| features.split(','))
        .filter_map(|feature| match feature.trim() {
            "+crt-static" => Some(true),
            "-crt-static" => Some(false),
            _ => None,
        })
        .next_back()
        .unwrap_or_else(|| target.contains("musl"))
}

/// The target a unit links for: `--target`, or else the wrapped rustc's host
/// (from `rustc -vV`), never the target kache itself was built for.
fn link_target<'a>(target: Option<&'a str>, rustc_host: Option<&'a str>) -> &'a str {
    target.or(rustc_host).unwrap_or("unknown")
}

/// The dirs a host-native Unix linker searches for `-l` after the `-L` dirs,
/// in its order: `LIBRARY_PATH`, then the system and local install dirs,
/// where a library the build names only by `-l` may live. A cross link
/// searches its own sysroot, and other targets resolve libraries elsewhere,
/// so both get none. The compiler's private library dir is left to its
/// identity.
fn default_library_dirs(
    target: &str,
    rustc_host: Option<&str>,
    library_path: Option<&std::ffi::OsStr>,
) -> Vec<PathBuf> {
    if rustc_host != Some(target) {
        return Vec::new();
    }
    let fixed: Vec<String> = if target.contains("-apple-") {
        vec!["/usr/lib".into(), "/usr/local/lib".into()]
    } else if target.contains("-linux-") {
        let multiarch = multiarch_name(target);
        vec![
            format!("/usr/local/lib/{multiarch}"),
            format!("/lib/{multiarch}"),
            format!("/usr/lib/{multiarch}"),
            "/usr/local/lib64".into(),
            "/lib64".into(),
            "/usr/lib64".into(),
            "/usr/local/lib".into(),
            "/lib".into(),
            "/usr/lib".into(),
        ]
    } else {
        return Vec::new();
    };
    library_path
        .map(std::env::split_paths)
        .into_iter()
        .flatten()
        .filter(|dir| !dir.as_os_str().is_empty())
        .chain(fixed.into_iter().map(PathBuf::from))
        .collect()
}

/// A Debian-style multiarch dir name: the triple without its vendor
/// (`x86_64-unknown-linux-gnu` is `x86_64-linux-gnu`).
fn multiarch_name(target: &str) -> String {
    match target.split('-').collect::<Vec<_>>()[..] {
        [arch, _vendor, os, env] => format!("{arch}-{os}-{env}"),
        _ => target.to_string(),
    }
}

/// Whether a file name marks a native archive: `*.a` or `*.lib`, in any case.
fn is_native_archive_name(name: &str) -> bool {
    crate::native_link_key::ends_with_ignore_ascii_case(name, ".a")
        || crate::native_link_key::ends_with_ignore_ascii_case(name, ".lib")
}

/// Whether a path, in the key's normalized spelling, lies inside a Cargo
/// registry package or git checkout. Cargo treats both as fixed for the
/// version or revision the path names, and so does the scan: the key holds
/// that path, so an archive shipped in such a package is not read.
fn is_cargo_package_dir(normalized: &str) -> bool {
    let Some(rest) = normalized.strip_prefix("<CARGO_HOME>") else {
        return false;
    };
    let mut parts = rest.split(['/', '\\']).filter(|part| !part.is_empty());
    matches!(
        (parts.next(), parts.next()),
        (Some("registry"), Some("src")) | (Some("git"), Some("checkouts"))
    )
}

/// `dirs` in order, without repeats.
fn unique_dirs<'a>(dirs: impl IntoIterator<Item = &'a PathBuf>) -> Vec<PathBuf> {
    let mut kept: Vec<PathBuf> = Vec::new();
    for dir in dirs {
        if !kept.contains(dir) {
            kept.push(dir.clone());
        }
    }
    kept
}

/// The dirs among `dirs` outside Cargo packages (see [`is_cargo_package_dir`]),
/// each spelled for the key by `normalize`.
fn dirs_outside_packages<'a>(
    dirs: &'a [PathBuf],
    normalize: impl Fn(&str) -> String + 'a,
) -> impl Iterator<Item = &'a PathBuf> {
    dirs.iter()
        .filter(move |dir| !is_cargo_package_dir(&normalize(&dir.to_string_lossy())))
}

/// The dirs among `dirs` inside `root`. Both are compared resolved: a build
/// script can spell its OUT_DIR through a symlink the environment does not,
/// and macOS reaches `/var` as `/private/var`.
fn dirs_under(dirs: &[PathBuf], root: &Path) -> Vec<PathBuf> {
    if dirs.is_empty() {
        return Vec::new();
    }
    let root = resolved_path(root);
    dirs.iter()
        .filter(|dir| resolved_path(dir).starts_with(&root))
        .cloned()
        .collect()
}

/// Whether `path` lies inside one of `roots`, compared as spelled.
fn is_under_any(path: &Path, roots: &[PathBuf]) -> bool {
    roots.iter().any(|root| path.starts_with(root))
}

/// Where the OS, system package managers and Apple's SDKs install libraries.
/// A `-L` dir under one of these and outside the build tree is not scanned
/// (see [`native_scan_dirs`]). Windows has none, so every dir outside Cargo's
/// packages is scanned there.
const SYSTEM_LIBRARY_DIRS: &[&str] = &[
    // The OS and its distribution packages.
    "/lib",
    "/lib32",
    "/lib64",
    "/libx32",
    "/usr/lib",
    "/usr/lib32",
    "/usr/lib64",
    "/usr/libx32",
    "/usr/local/lib",
    "/usr/local/lib64",
    // Homebrew, MacPorts, Nix and Guix.
    "/opt/homebrew",
    "/usr/local/Cellar",
    "/usr/local/opt",
    "/home/linuxbrew/.linuxbrew",
    "/opt/local",
    "/nix/store",
    "/gnu/store",
    // macOS and its frameworks, and Xcode with its SDKs and toolchains.
    "/System",
    "/Library",
    "/Applications",
];

/// [`SYSTEM_LIBRARY_DIRS`] as paths.
fn system_library_dirs() -> Vec<PathBuf> {
    SYSTEM_LIBRARY_DIRS.iter().map(PathBuf::from).collect()
}

/// The roots of this unit's build tree: Cargo's target dir above the profile
/// dir that holds `--out-dir`, and the workspace root the key normalizes
/// paths against. The scan reads a dir inside them even under a system
/// library dir (see [`NativeLinkContext::scanned_dirs`]).
fn build_tree_roots(args: &RustcArgs) -> Vec<PathBuf> {
    build_tree_roots_of(
        args.out_dir.as_deref(),
        args.target.as_deref(),
        args.path_normalization_root(),
    )
}

/// [`build_tree_roots`] from a unit's `--out-dir`, `--target` and workspace
/// root. An `--out-dir` outside Cargo's layout adds no root.
fn build_tree_roots_of(
    out_dir: Option<&Path>,
    target: Option<&str>,
    workspace: Option<&Path>,
) -> Vec<PathBuf> {
    out_dir
        .and_then(crate::compiler::platform::cargo_profile_dir)
        .map(|profile| cargo_target_dir(&profile, target))
        .into_iter()
        .chain(workspace.map(Path::to_path_buf))
        .collect()
}

/// Cargo's target dir above `profile`: its parent, or its grandparent when
/// the parent is the dir Cargo names after `--target`
/// (`<target>/<triple>/<profile>`). A target spec file names that dir by
/// its stem.
fn cargo_target_dir(profile: &Path, target: Option<&str>) -> PathBuf {
    let Some(parent) = profile.parent() else {
        return profile.to_path_buf();
    };
    let target_name = target.map(|target| match target.strip_suffix(".json") {
        Some(spec) => Path::new(spec).file_name().unwrap_or_default(),
        None => std::ffi::OsStr::new(target),
    });
    match (parent.parent(), target_name) {
        (Some(grandparent), Some(name)) if parent.file_name() == Some(name) => {
            grandparent.to_path_buf()
        }
        _ => parent.to_path_buf(),
    }
}

/// The regular `*.a` and `*.lib` files directly in `dir`, sorted. A missing
/// dir holds none; any other read failure is an error.
pub(crate) fn native_dir_archives(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut archives = Vec::new();
    for path in native_dir_entries(dir)? {
        if path
            .file_name()
            .is_some_and(|name| is_native_archive_name(&name.to_string_lossy()))
            && path.is_file()
        {
            archives.push(path);
        }
    }
    Ok(archives)
}

/// The static frameworks directly in `dir`, sorted: `Name.framework/Name`
/// when it is an `ar` archive. ld64 links such a framework into the output
/// like an archive; a dynamic one is referenced by name.
fn native_dir_static_frameworks(dir: &Path) -> Result<Vec<PathBuf>> {
    let mut frameworks = Vec::new();
    for path in native_dir_entries(dir)? {
        let Some(name) = path
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(|name| name.strip_suffix(".framework"))
        else {
            continue;
        };
        let binary = path.join(name);
        if binary.is_file() && crate::native_archive::has_archive_magic(&binary)? {
            frameworks.push(binary);
        }
    }
    Ok(frameworks)
}

/// The framework a `framework` `-l` spec links: its rename when it has one.
/// `None` for other kinds.
fn framework_request(spec: &str) -> Option<&str> {
    let (kind, name) = spec.split_once('=')?;
    let kind = kind.split_once(':').map_or(kind, |(kind, _)| kind);
    let name = name.split_once(':').map_or(name, |(_, rename)| rename);
    (kind == "framework" && !name.is_empty()).then_some(name)
}

/// Whether a `-l` spec is of the `link-arg` kind (`-Z unstable-options`),
/// whose value rustc hands the linker as a raw argument.
fn is_link_arg_spec(spec: &str) -> bool {
    spec.split_once('=')
        .is_some_and(|(kind, _)| kind.split_once(':').map_or(kind, |(kind, _)| kind) == "link-arg")
}

/// The static framework ld64 takes for `-framework name` from `dirs`: the
/// first `name.framework/name` found, when it is an `ar` archive.
fn resolve_static_framework(name: &str, dirs: &[PathBuf]) -> Result<Option<PathBuf>> {
    for dir in dirs {
        let binary = dir.join(format!("{name}.framework")).join(name);
        if binary.is_file() {
            return Ok(crate::native_archive::has_archive_magic(&binary)?.then_some(binary));
        }
    }
    Ok(None)
}

/// The entries of `dir`, sorted. A missing dir has none; any other read
/// failure is an error.
fn native_dir_entries(dir: &Path) -> Result<Vec<PathBuf>> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => {
            return Err(error)
                .with_context(|| format!("reading native search dir {}", dir.display()));
        }
    };
    let mut paths = Vec::new();
    for entry in entries {
        paths.push(
            entry
                .with_context(|| format!("reading native search dir {}", dir.display()))?
                .path(),
        );
    }
    paths.sort();
    Ok(paths)
}

/// Fold every archive `list` finds in `dirs` as `<dir index>/<path in the
/// dir>=<digest>`, and return the archives hashed.
fn fold_native_dir_archives<H: KeyFold>(
    hasher: &mut H,
    dirs: &[PathBuf],
    list: impl Fn(&Path) -> Result<Vec<PathBuf>>,
    hash: impl Fn(&Path) -> Result<String>,
) -> Result<Vec<PathBuf>> {
    let mut hashed = Vec::new();
    for (index, dir) in dirs.iter().enumerate() {
        for archive in list(dir)? {
            let digest = hash(&archive)?;
            let name = archive
                .strip_prefix(dir)
                .unwrap_or(&archive)
                .to_string_lossy();
            fold_field(
                hasher,
                b"native_dir_archive.v1:",
                format!("{index}/{name}={digest}").as_bytes(),
            );
            hashed.push(archive);
        }
    }
    Ok(hashed)
}

/// `path` with symlinks resolved, or made absolute when it does not exist.
fn resolved_path(path: &Path) -> PathBuf {
    std::fs::canonicalize(path)
        .or_else(|_| std::path::absolute(path))
        .unwrap_or_else(|_| path.to_path_buf())
}

/// Whether an rlib compile must pass the store-time bundle audit: it writes
/// an rlib and has a native dir rustc could bundle from.
pub(crate) fn needs_native_bundle_audit(args: &RustcArgs, native_dirs: &[PathBuf]) -> bool {
    args.emits_rlib() && !native_dirs.is_empty()
}

/// Whether `-Z packed-bundled-libs` makes rustc store every bundled archive
/// as one member. Its value is not read: counting the flag as on only
/// credits an rlib less (see the wrapper's bundle audit).
fn packs_bundled_libs(unstable_flags: &[String]) -> bool {
    unstable_flags.iter().any(|flag| {
        let name = flag.split_once('=').map_or(flag.as_str(), |(name, _)| name);
        name.replace('_', "-") == "packed-bundled-libs"
    })
}

/// Whether this compile's rlib carries the archive a `static` `spec`
/// resolves to, and if so whether packed as one member (`Some(true)`) or
/// member by member (`Some(false)`). `packs_all` is [`packs_bundled_libs`].
fn rlib_bundle(spec: &StaticLibSpec<'_>, emits_rlib: bool, packs_all: bool) -> Option<bool> {
    match spec {
        StaticLibSpec::Archive {
            bundle: true,
            whole_archive,
            ..
        } if emits_rlib => Some(*whole_archive || packs_all),
        _ => None,
    }
}

/// The `-L` dirs, input files and `-l` libraries of this unit's
/// `link-arg`/`link-args` values.
fn unix_link_arguments(args: &RustcArgs) -> Result<crate::native_link_key::LinkArgInputs> {
    let mut inputs = crate::native_link_key::LinkArgInputs::default();
    for (key, value) in &args.codegen_opts {
        if let ("link-arg" | "link-args", Some(value)) = (key.as_str(), value.as_deref()) {
            let parsed = crate::native_link_key::unix_link_arg_inputs(key, value)?;
            inputs.files.extend(parsed.files);
            inputs.dirs.extend(parsed.dirs);
            inputs.libs.extend(parsed.libs);
        }
    }
    Ok(inputs)
}

/// A unit's `-L` dirs that name native libraries: `native=`, `all=` and bare
/// (`native`), and `framework=` (`framework`).
struct NativeSearchDirs<'a> {
    native: &'a [PathBuf],
    framework: &'a [PathBuf],
}

/// What [`fold_native_link_inputs`] knows about a unit beyond its argv.
struct NativeLinkContext<'a> {
    /// A native Windows MSVC link, whose libraries and link-argument files
    /// the MSVC identity keys instead.
    native_windows_msvc: bool,
    /// The target the unit links for (see [`link_target`]).
    target: &'a str,
    /// Where a Unix linker looks for `-l` after the `-L` dirs (see
    /// [`default_library_dirs`]).
    default_dirs: Vec<PathBuf>,
    /// The unit's own OUT_DIR, which Cargo sets for a package with a build
    /// script.
    out_dir: Option<&'a Path>,
    /// The roots of the unit's build tree (see [`build_tree_roots`]).
    build_tree: Vec<PathBuf>,
    /// Where system libraries live (see [`SYSTEM_LIBRARY_DIRS`]), compared
    /// as spelled with a dir's resolved path.
    system_dirs: Vec<PathBuf>,
    /// Gives dirs their key spelling (see [`is_cargo_package_dir`]).
    path_normalizer: &'a PathNormalizer,
}

impl NativeLinkContext<'_> {
    /// Apple dylibs can reach the linker through dependency metadata, so
    /// inspect custom search dirs even when this unit has no `-l`.
    fn apple_dynamic_dirs(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
        let build_tree = std::cell::OnceCell::new();
        unique_dirs(dirs)
            .into_iter()
            .filter(|dir| {
                let resolved = resolved_path(dir);
                !is_under_any(&resolved, &self.system_dirs)
                    || is_under_any(
                        &resolved,
                        build_tree.get_or_init(|| {
                            self.build_tree
                                .iter()
                                .map(|root| resolved_path(root))
                                .collect::<Vec<_>>()
                        }),
                    )
            })
            .collect()
    }

    /// The dirs among `dirs` whose every archive can key the unit, without
    /// repeats: those outside Cargo's packages and outside the system library
    /// dirs, or inside the build tree. Each dir is compared resolved, and the
    /// build tree is resolved only for a dir under a system library dir.
    fn scanned_dirs(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
        let unique = unique_dirs(dirs);
        let build_tree = std::cell::OnceCell::new();
        let resolved_build_tree = || {
            build_tree.get_or_init(|| {
                self.build_tree
                    .iter()
                    .map(|root| resolved_path(root))
                    .collect::<Vec<_>>()
            })
        };
        dirs_outside_packages(&unique, |dir| self.path_normalizer.normalize(dir))
            .filter(|dir| {
                let dir = resolved_path(dir);
                !is_under_any(&dir, &self.system_dirs) || is_under_any(&dir, resolved_build_tree())
            })
            .cloned()
            .collect()
    }
}

/// The `-L` dirs (`dirs`) whose every archive keys this unit. A unit whose
/// output carries the native closure (see [`RustcArgs::links_native_closure`])
/// takes those [`NativeLinkContext::scanned_dirs`] keeps. An rlib takes those
/// under its own OUT_DIR, which a `#[link(kind = "static")]` attribute can
/// bundle from with no `-l` on argv. Other units take none.
///
/// Every dir outside Cargo's packages is scanned, wherever it is: the build
/// tree, a sibling build, a monorepo's native build above the workspace, a
/// path dependency beside it, a vcpkg or conda install. The exception is a
/// dir under a system library dir (`/usr/lib`, `/opt/homebrew`, see
/// [`SYSTEM_LIBRARY_DIRS`]) outside the build tree: a package upgrade there
/// would re-key every link, and one thin archive would make every link
/// uncacheable. There only what an `-l` of this unit resolves to is keyed,
/// so an archive that reaches the output with no such `-l` (through a
/// dependency's rlib, a `#[link]` attribute or a `-bundle` spec) is not.
fn native_scan_dirs(
    args: &RustcArgs,
    dirs: &[PathBuf],
    context: &NativeLinkContext<'_>,
) -> Vec<PathBuf> {
    if args.links_native_closure() {
        context.scanned_dirs(dirs)
    } else if args.emits_rlib()
        && let Some(out_dir) = context.out_dir
    {
        dirs_under(&unique_dirs(dirs), out_dir)
    } else {
        Vec::new()
    }
}

/// Fold the native inputs that reach this unit's output and return what was
/// hashed, for the store-time bundle audit:
///
/// - each `-l` spec by name, and the archive a `static` spec names (a linking
///   unit that finds it in no `-L` dir refuses the key, since the linker may
///   take a system copy);
/// - on a Unix link, the archive the linker picks for a kindless or `dylib`
///   spec, and the files and `-l` libraries its link arguments name, looked
///   up in the `-L` dirs and then the linker's default dirs;
/// - on a linking unit, the static framework a `framework` spec names;
/// - on Apple links, raw install names from custom native and framework
///   search dirs, including libraries named only by dependency metadata;
/// - every archive in the `-L` dirs [`native_scan_dirs`] picks, and on a
///   linking unit every static framework in the `framework=` dirs
///   [`NativeLinkContext::scanned_dirs`] keeps. Cargo hands a build script's
///   `-L` to every dependent, so this keys archives that reach the output
///   only through a dependency's rlib, whose own bytes no `--extern` of this
///   unit covers.
///
/// A linking unit with a `link-arg` `-l` spec is refused: rustc hands its
/// value to the linker as is, and no rule here reads it.
///
/// The scan keys a linked output to every archive its scanned `-L` dirs
/// hold, so an archive a build script rebuilds with different bytes each run
/// (a build date, say) re-keys every linked unit downstream, as its output
/// changes too. An archive whose members the portable digest does not admit
/// (wasm or COFF objects, LTO bitcode) keys with its path, so a linked output
/// that finds one in a build-tree dir hits only in the checkout that stored
/// it.
///
/// Not keyed: a library a dependency's metadata names and the linker finds
/// only in its default dirs, which no argv of this unit shows, and the
/// compiler's own library dirs, which its identity stands for.
fn fold_native_link_inputs<H: KeyFold>(
    hasher: &mut H,
    args: &RustcArgs,
    search: &NativeSearchDirs<'_>,
    context: &NativeLinkContext<'_>,
    file_hasher: &FileHasher<'_>,
) -> Result<KeyedNativeArchives> {
    let crate_name = args.crate_name.as_deref().unwrap_or("unknown");
    let links = args.invokes_linker();
    let unix_link = links && !context.native_windows_msvc;
    let link_arguments = if unix_link {
        unix_link_arguments(args)?
    } else {
        crate::native_link_key::LinkArgInputs::default()
    };
    let spelled_oso_root = crate::compiler::rustc::oso_prefix_root_for_key(args);
    let oso_root = spelled_oso_root.as_deref().map(resolved_path);
    let archive_use = |path: &Path| match (spelled_oso_root.as_deref(), oso_root.as_deref()) {
        (Some(spelled_root), Some(root)) => oso_archive_use(args, path, spelled_root, root),
        _ => linked_archive_use(args, path, None),
    };
    let hash_archive = |path: &Path| {
        let usage = archive_use(path);
        let digest = file_hasher.hash_static_lib_for(path, usage)?;
        tracing::trace!(
            "[key:{}] native_archive:{}={} ({usage:?})",
            crate_name,
            path.display(),
            &digest[..digest.len().min(24)]
        );
        Ok::<_, anyhow::Error>(digest)
    };
    let mut lib_dirs = search.native.to_vec();
    lib_dirs.extend(link_arguments.dirs.iter().cloned());
    // Where a Unix linker looks for an `-l`: the `-L` dirs, then its own.
    let mut library_dirs = lib_dirs.clone();
    library_dirs.extend(context.default_dirs.iter().cloned());
    let target_features: Vec<&str> = args
        .codegen_opts
        .iter()
        .filter(|(key, _)| key == "target-feature")
        .filter_map(|(_, value)| value.as_deref())
        .collect();
    let prefer_static = prefers_static_libraries(&target_features, context.target);
    let shared_extensions = shared_library_extensions(context.target);
    let packs_all = packs_bundled_libs(&args.unstable_flags);

    if unix_link && context.target.contains("-apple-") {
        // Older entries did not inspect install names, even when a native
        // library is now missing from its search directory.
        fold_field(hasher, b"apple_install_names.v1:", b"");
        // ld64 embeds LC_ID_DYLIB (or a stub's install-name) verbatim. A
        // normalized -L path cannot identify an absolute build-tree name.
        for (index, dir) in context.apple_dynamic_dirs(&library_dirs).iter().enumerate() {
            for path in native_dir_entries(dir)? {
                if path.is_file()
                    && path
                        .extension()
                        .is_some_and(|ext| matches!(ext.to_str(), Some("tbd" | "dylib" | "so")))
                {
                    fold_apple_install_name(hasher, &path, dir, index)?;
                }
            }
        }
        for (index, dir) in context
            .apple_dynamic_dirs(search.framework)
            .iter()
            .enumerate()
        {
            for path in native_dir_entries(dir)? {
                let Some(name) = path
                    .file_name()
                    .and_then(|name| name.to_str())
                    .and_then(|name| name.strip_suffix(".framework"))
                else {
                    continue;
                };
                for binary in [path.join(format!("{name}.tbd")), path.join(name)] {
                    if binary.is_file() && !crate::native_archive::has_archive_magic(&binary)? {
                        fold_apple_install_name(hasher, &binary, dir, index)?;
                    }
                }
            }
        }
        // +verbatim and linker -l:file can name an extensionless dylib,
        // which the directory scan above cannot recognize.
        let requests = args
            .link_libs
            .iter()
            .filter_map(|spec| unix_library_request(spec))
            .chain(
                link_arguments
                    .libs
                    .iter()
                    .map(|(name, verbatim)| (name.as_str(), *verbatim)),
            );
        for (index, (name, verbatim)) in requests.enumerate() {
            if !verbatim {
                continue;
            }
            for dir in &library_dirs {
                let path = dir.join(name);
                if path.is_file() {
                    if !context
                        .apple_dynamic_dirs(std::slice::from_ref(dir))
                        .is_empty()
                        && !crate::native_archive::has_archive_magic(&path)?
                    {
                        fold_apple_install_name(hasher, &path, dir, index)?;
                    }
                    break;
                }
            }
        }
    }

    let mut archives = Vec::new();
    let mut bundled = Vec::new();
    let effective_libs = effective_native_libraries(&args.link_libs);
    for (index, lib) in args.link_libs.iter().enumerate() {
        hasher.update(b"link_lib:");
        hasher.update(lib.as_bytes());
        hasher.update(b"\n");
        tracing::trace!("[key:{}] link_lib:{}", crate_name, lib);
        let Some(&lib) = effective_libs.get(&index) else {
            continue;
        };
        if links && is_link_arg_spec(lib) {
            anyhow::bail!(
                "native library spec {lib:?} hands the linker a raw argument the key does not \
                 model"
            );
        }

        let dirs = if unix_link { &lib_dirs } else { search.native };
        let spec = static_lib_spec(lib);
        let mut resolved = resolve_native_static_lib(lib, dirs, file_hasher, links, archive_use)?;
        let is_static = matches!(spec, StaticLibSpec::Archive { .. });
        if resolved.is_none()
            && is_static
            && unresolved_static_lib_is_error(links, context.native_windows_msvc)
        {
            anyhow::bail!(
                "native static library {lib:?} is in no -L directory; the linker could take \
                 a copy the key does not hash"
            );
        }
        if let Some((path, _)) = &resolved
            && let Some(packed) = rlib_bundle(&spec, args.emits_rlib(), packs_all)
        {
            bundled.push(BundledArchive {
                path: path.clone(),
                packed,
            });
        }
        if resolved.is_none()
            && unix_link
            && let Some((name, verbatim)) = unix_library_request(lib)
            && let Some(path) = resolve_unix_library(
                name,
                verbatim,
                &library_dirs,
                prefer_static,
                shared_extensions,
                Path::is_file,
            )
        {
            let hash = hash_archive(&path)?;
            resolved = Some((path, hash));
        }
        if links
            && let Some(name) = framework_request(lib)
            && let Some(path) = resolve_static_framework(name, search.framework)?
        {
            let hash = hash_archive(&path)?;
            resolved = Some((path, hash));
        }
        if let Some((path, content_hash)) = resolved {
            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()
            );
            archives.push(path);
        }
    }

    for (index, file) in link_arguments.files.iter().enumerate() {
        if !file.is_file() {
            anyhow::bail!("linker input {} is not a regular file", file.display());
        }
        let digest = if is_native_archive_name(&file.to_string_lossy()) {
            hash_archive(file)?
        } else {
            file_hasher
                .hash(file)
                .with_context(|| format!("hashing linker input {}", file.display()))?
        };
        fold_field(
            hasher,
            b"link_arg_input.v1:",
            format!("{index}={digest}").as_bytes(),
        );
        tracing::trace!("[key:{}] link_arg_input:{}", crate_name, file.display());
    }

    // A `-Bstatic` in the link arguments can make the linker skip a shared
    // library, so the first archive for the name counts.
    for (index, (name, verbatim)) in link_arguments.libs.iter().enumerate() {
        if let Some(path) = resolve_unix_library(
            name,
            *verbatim,
            &library_dirs,
            true,
            shared_extensions,
            Path::is_file,
        ) {
            let digest = hash_archive(&path)?;
            fold_field(
                hasher,
                b"link_arg_library.v1:",
                format!("{index}={digest}").as_bytes(),
            );
            tracing::trace!("[key:{}] link_arg_library:{}", crate_name, path.display());
            archives.push(path);
        }
    }

    let scan_dirs = native_scan_dirs(args, &lib_dirs, context);
    archives.extend(fold_native_dir_archives(
        hasher,
        &scan_dirs,
        native_dir_archives,
        hash_archive,
    )?);
    if links {
        archives.extend(fold_native_dir_archives(
            hasher,
            &context.scanned_dirs(search.framework),
            native_dir_static_frameworks,
            hash_archive,
        )?);
    }
    // Only an rlib's store runs the bundle audit.
    let audit_dirs = if args.emits_rlib() {
        context.scanned_dirs(search.native)
    } else {
        Vec::new()
    };

    Ok(KeyedNativeArchives {
        archives,
        bundled,
        dirs: audit_dirs,
    })
}

/// rustc merges libraries by name at their last mention. An explicit kind
/// replaces the previous kind and its modifiers; a kindless spec keeps it.
fn effective_native_libraries(libraries: &[String]) -> BTreeMap<usize, &str> {
    let mut by_name: BTreeMap<&str, (usize, &str)> = BTreeMap::new();
    for (index, library) in libraries.iter().enumerate() {
        let (kind, name) = library.split_once('=').unwrap_or(("", library));
        let spec = if kind.is_empty() {
            by_name
                .get(name)
                .map_or(library.as_str(), |(_, spec)| *spec)
        } else {
            library.as_str()
        };
        by_name.insert(name, (index, spec));
    }
    by_name.into_values().collect()
}

fn fold_apple_install_name<H: KeyFold>(
    hasher: &mut H,
    path: &Path,
    dir: &Path,
    index: usize,
) -> Result<()> {
    let name = apple_install_name::read(path)?;
    let file = path.strip_prefix(dir).unwrap_or(path).to_string_lossy();
    fold_field(
        hasher,
        b"apple_install_name.v1:",
        format!("{index}/{file}={name}").as_bytes(),
    );
    Ok(())
}

/// 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))
}

/// How a `-l` spec maps to an archive the cache key must hash.
#[derive(Debug, PartialEq, Eq)]
enum StaticLibSpec<'a> {
    /// Not a `static` kind (`dylib=`, `framework=`, bare `-l name`). Archive
    /// fallback and Apple dynamic install names are handled separately.
    NotStatic,
    /// A `static` archive rustc looks up under these file names in the `-L`
    /// dirs. `+whole-archive` and `+as-needed` change how the archive is
    /// linked, not which file it is; the raw spec already keys them. `bundle`
    /// is the last `±bundle`: an rlib or staticlib leaves a `-bundle` archive
    /// out of its output. `whole_archive` is the last `±whole-archive`, under
    /// which an rlib stores the archive as one member.
    Archive {
        files: Vec<String>,
        bundle: bool,
        whole_archive: bool,
    },
    /// A `:RENAME` or an unknown modifier. Which file rustc reads is not
    /// modelled, so the invocation must not be cached on the name alone.
    Unmodeled(&'a str),
}

/// Classify a `-l` spec (`[KIND[:MODIFIERS]=]NAME[:RENAME]`). A rename is
/// unmodeled for every kind but `framework`: a kindless or `dylib` rename can
/// retarget a `#[link(kind = "static")]` attribute, which bundles.
fn static_lib_spec(spec: &str) -> StaticLibSpec<'_> {
    let (kind, name) = spec.split_once('=').unwrap_or(("", spec));
    let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
    if kind != "framework" && name.contains(':') {
        return StaticLibSpec::Unmodeled(spec);
    }
    if kind != "static" {
        return StaticLibSpec::NotStatic;
    }
    if name.is_empty() {
        return StaticLibSpec::Unmodeled(spec);
    }
    let mut verbatim = false;
    let mut bundle = true;
    let mut whole_archive = false;
    for modifier in modifiers.split(',').filter(|m| !m.is_empty()) {
        match modifier {
            "+verbatim" => verbatim = true,
            "-verbatim" => verbatim = false,
            "+bundle" => bundle = true,
            "-bundle" => bundle = false,
            "+whole-archive" => whole_archive = true,
            "-whole-archive" => whole_archive = false,
            "+as-needed" | "-as-needed" => {}
            _ => return StaticLibSpec::Unmodeled(spec),
        }
    }
    let files = if verbatim {
        vec![name.to_string()]
    } else {
        vec![format!("lib{name}.a"), format!("{name}.lib")]
    };
    StaticLibSpec::Archive {
        files,
        bundle,
        whole_archive,
    }
}

/// 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(
    paths: &EnvDepPaths<'_>,
    resolved: &EnvDepValue<'_>,
    normalized: &str,
) -> String {
    if let Some(rel) = paths.out_dir_suffix(resolved) {
        let unit = out_dir_unit(paths.out_dir);
        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,
    value: &EnvDepValue<'_>,
    paths: &EnvDepPaths<'_>,
    file_hasher: &FileHasher<'_>,
    path_normalizer: &PathNormalizer,
    aliased_out_dir: Option<&Path>,
) -> NormalizedEnvDep {
    let val = value.raw;
    // The shared OUT_DIR is one string on this machine whatever the checkout,
    // and the artifact bakes exactly that string. A sentinel from a rule that
    // happens to cover the cache dir (`<HOME>`) would give one key to
    // artifacts that bake different strings, so the value stays raw.
    if aliased_out_dir.is_some_and(|dir| value_at_or_under(val, dir)) {
        return NormalizedEnvDep {
            value: val.to_string(),
            decision: EnvDepNormalizationDecision::AliasedOutDir,
        };
    }
    // 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 = value
        .canonical()
        .and_then(crate::path_normalizer::canonical_form)
        .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 = !is_manifest_dir_var(var)
        && path_normalizer.path_only_env_vars().iter().any(|entry| {
            matches!(entry.split_once(':'), Some((krate, v)) if krate == crate_name && v == var)
        });
    // The checks below read the resolved form. It is the raw value, and so
    // shares its canonical path, unless resolution changed the string.
    let resolved_value = (resolved != val).then(|| EnvDepValue::new(&resolved));
    let resolved_value = resolved_value.as_ref().unwrap_or(value);
    if forced {
        return NormalizedEnvDep {
            value: sentinelized_env_dep_value(paths, resolved_value, &normalized),
            decision: EnvDepNormalizationDecision::ForcedPathOnly,
        };
    }

    let decision = env_dep_path_only_decision(
        var,
        resolved_value,
        paths,
        path_normalizer.path_only_env_vars(),
        file_hasher,
    );
    if decision == EnvDepNormalizationDecision::NormalizedPathOnly {
        // 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(paths, resolved_value, &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. The decision
    // names the reason for the trace.
    NormalizedEnvDep {
        value: val.to_string(),
        decision,
    }
}

#[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_in(crate_name, var, val, source_files, path_normalizer, None)
}

/// [`normalize_env_dep_value`] for a unit whose `OUT_DIR` is `out_dir`.
#[cfg(test)]
fn normalize_env_dep_value_in(
    crate_name: &str,
    var: &str,
    val: &str,
    source_files: &[std::path::PathBuf],
    path_normalizer: &PathNormalizer,
    out_dir: Option<&OsStr>,
) -> NormalizedEnvDep {
    normalize_env_dep_value_with_hasher(
        crate_name,
        var,
        &EnvDepValue::new(val),
        &EnvDepPaths::new(out_dir, source_files),
        &FileHasher::new(),
        path_normalizer,
        None,
    )
}

/// Is `value` the path `dir` or a path under it, by components?
pub(crate) fn value_at_or_under(value: &str, dir: &Path) -> bool {
    Path::new(value).starts_with(dir)
}

/// Does this env dep leave an OUT_DIR path in the key as a literal? `under`
/// answers whether the value sits under the unit's OUT_DIR; it is only asked
/// when the rest cannot settle it.
fn env_dep_bakes_out_dir(
    var: &str,
    decision: EnvDepNormalizationDecision,
    under: impl FnOnce() -> bool,
) -> bool {
    decision.keeps_literal_value() && (var == "OUT_DIR" || under())
}

/// Whether `var`'s value may be path-normalized in the cache key:
/// [`EnvDepNormalizationDecision::NormalizedPathOnly`], or the reason it stays
/// absolute. `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_path_only_decision(
    var: &str,
    value: &EnvDepValue<'_>,
    paths: &EnvDepPaths<'_>,
    allowlist: &[String],
    file_hasher: &FileHasher<'_>,
) -> EnvDepNormalizationDecision {
    // 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 shows an env macro use inside an `include*!(...)`
    // path-locator context and no use outside one (see
    // [`env_dep_source_decision`]). 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.
    // CARGO_MANIFEST_DIR is refused in every form, listed or not: rustc can
    // embed it in crate metadata and generated code, and a crate's own sources
    // always live under it, so the include proof below is trivially satisfied
    // and normalizing it restores another checkout's path (#167).
    if is_manifest_dir_var(var) {
        return EnvDepNormalizationDecision::KeptAbsoluteManifestDir;
    }
    if !(var == "OUT_DIR"
        || allowlist.iter().any(|v| v == var)
        || paths.value_is_under_out_dir(value))
    {
        return EnvDepNormalizationDecision::KeptAbsoluteNotPathOnly;
    }
    if !path_is_only_used_for_includes(value.probe(), paths.source_probes()) {
        return EnvDepNormalizationDecision::KeptAbsoluteNoIncludeProof;
    }
    env_dep_source_decision(var, paths.source_files, file_hasher)
}

/// Whether `var` names Cargo's manifest dir. Windows matches environment
/// names case-insensitively, so dep-info can carry any spelling of it; on
/// Unix a differently-cased name is a different variable, and refusing it
/// costs misses only.
pub(crate) fn is_manifest_dir_var(var: &str) -> bool {
    var.eq_ignore_ascii_case("CARGO_MANIFEST_DIR")
}

/// The form a path is compared in: canonical when it resolves, else as given.
///
/// Canonical comparison keeps the macOS `/tmp` ↔ `/private/tmp` symlink from
/// producing a spurious mismatch. A path that cannot be canonicalized (file
/// moved, etc.) falls back to its raw components, and `Path::starts_with`
/// still compares whole components without requiring lexical matching.
fn path_probe(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// The probe form of `OUT_DIR`, or `None` when it is unset or its probe is
/// not absolute. An empty or relative OUT_DIR cannot anchor a meaningful
/// "under" test.
fn out_dir_probe(out_dir: Option<&OsStr>) -> Option<PathBuf> {
    let probe = path_probe(Path::new(out_dir?));
    probe.is_absolute().then_some(probe)
}

/// Cargo's per-unit directory name (`<pkg>-<unit hash>`), the parent of
/// `OUT_DIR`; empty when it has none.
fn out_dir_unit(out_dir: Option<&OsStr>) -> String {
    out_dir
        .map(Path::new)
        .and_then(Path::parent)
        .and_then(Path::file_name)
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// An env-dep value and its canonical path, resolved at most once however
/// many checks read it (kunobi-ninja/kache#560).
struct EnvDepValue<'a> {
    raw: &'a str,
    canonical: OnceCell<Option<PathBuf>>,
}

impl<'a> EnvDepValue<'a> {
    fn new(raw: &'a str) -> Self {
        Self {
            raw,
            canonical: OnceCell::new(),
        }
    }

    fn canonical(&self) -> Option<&Path> {
        self.canonical
            .get_or_init(|| std::fs::canonicalize(self.raw).ok())
            .as_deref()
    }

    /// The value in [`path_probe`] form.
    fn probe(&self) -> &Path {
        self.canonical().unwrap_or(Path::new(self.raw))
    }
}

/// The paths env-dep values are compared against, resolved once per key
/// computation rather than once per env dep (kunobi-ninja/kache#560).
///
/// `out_dir` is the invocation's `OUT_DIR`, passed in rather than read from
/// the process environment. Both probes resolve on first use, so a unit
/// whose env deps never reach a path check canonicalizes nothing.
struct EnvDepPaths<'a> {
    out_dir: Option<&'a OsStr>,
    out_probe: OnceCell<Option<PathBuf>>,
    source_files: &'a [PathBuf],
    source_probes: OnceCell<Vec<PathBuf>>,
}

impl<'a> EnvDepPaths<'a> {
    fn new(out_dir: Option<&'a OsStr>, source_files: &'a [PathBuf]) -> Self {
        Self {
            out_dir,
            out_probe: OnceCell::new(),
            source_files,
            source_probes: OnceCell::new(),
        }
    }

    fn out_probe(&self) -> Option<&Path> {
        self.out_probe
            .get_or_init(|| out_dir_probe(self.out_dir))
            .as_deref()
    }

    /// The dep-info source files in [`path_probe`] form, in the same order.
    fn source_probes(&self) -> &[PathBuf] {
        self.source_probes
            .get_or_init(|| self.source_files.iter().map(|f| path_probe(f)).collect())
    }

    /// The value's path relative to the build's own `OUT_DIR`; see
    /// [`out_dir_relative_suffix`]. `None` when `OUT_DIR` cannot anchor the
    /// test, which then never resolves the value.
    fn out_dir_suffix(&self, value: &EnvDepValue<'_>) -> Option<String> {
        out_dir_relative_suffix(value.probe(), self.out_probe()?)
    }

    /// True when the value is a 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).
    ///
    /// 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(&self, value: &EnvDepValue<'_>) -> bool {
        self.out_dir_suffix(value).is_some()
    }
}

/// The value's path relative to the build's own `OUT_DIR`, when it lives
/// under it (`Some("")` for `OUT_DIR` itself). Both arguments are in
/// [`path_probe`] form. 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(value_probe: &Path, out_probe: &Path) -> Option<String> {
    value_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_source_decision`] 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.
///
/// Both arguments are in [`path_probe`] form.
fn path_is_only_used_for_includes(value_probe: &Path, source_probes: &[PathBuf]) -> bool {
    source_probes.iter().any(|f| f.starts_with(value_probe))
}

/// Normalizes only when source text proves `var` is only an `include*!(...)`
/// path locator: at least one Rust file shows `env!(var)` / `option_env!(var)`
/// inside an include argument, and no file shows a use the scanner cannot
/// place there.
///
/// The proof must be positive. An env macro expanded from another crate's
/// `macro_rules!` resolves in this crate, so dep-info reports the env dep while
/// this crate's sources never name the var; without a visible include use, its
/// value may be baked into the artifact. Such crates keep the absolute value.
/// Proof comes only from files whose path ends in `.rs`, so an `include_str!`'d
/// README that quotes an include is not proof. The test is the path, not what
/// rustc did with the file: a `.rs` file read as text (`include_str!` of a
/// codegen template or a UI-test fixture) still counts. Every file, whatever
/// its extension, still counts AGAINST the var.
///
/// Residual gaps, where the text looks like a locator but the compiled crate
/// can still bake the value:
/// - another crate's macro, invoked alongside a visible include use, that
///   expands to a value use of the same var;
/// - a macro named `include`, `include_str` or `include_bytes` that is not the
///   builtin (a local `macro_rules!`, an import, or a path like
///   `mycrate::include!`);
/// - an include inside another macro's arguments, or on an item under an
///   attribute macro, which can move the tokens out of the include;
/// - a `.rs` file rustc only read as text, whose quoted include reads as proof.
///
/// The `.rs` rule also costs hits: an `include!`'d fragment named `.in`,
/// `.txt` or without an extension supplies no proof, so its crate keeps the
/// absolute value.
///
/// Missing or changed files fail closed.
fn env_dep_source_decision(
    var: &str,
    source_files: &[std::path::PathBuf],
    file_hasher: &FileHasher<'_>,
) -> EnvDepNormalizationDecision {
    let mut proven = false;
    for file in source_files {
        match file_hasher.env_dep_use(file, var) {
            Ok(SourceEnvDepUse::Unused) => {}
            Ok(SourceEnvDepUse::IncludeLocator) => {
                proven |= file.extension().is_some_and(|ext| ext == "rs");
            }
            Ok(SourceEnvDepUse::RuntimeValue) => {
                return EnvDepNormalizationDecision::KeptAbsoluteRuntimeUse;
            }
            Err(e) => {
                tracing::debug!(
                    "keeping env dep {var} absolute: failed to inspect source {}: {}",
                    file.display(),
                    e
                );
                return EnvDepNormalizationDecision::KeptAbsoluteScanError;
            }
        }
    }
    if proven {
        EnvDepNormalizationDecision::NormalizedPathOnly
    } else {
        EnvDepNormalizationDecision::KeptAbsoluteNoIncludeProof
    }
}

/// Version of [`source_env_dep_use`] answers in the persistent memo. Bump it
/// whenever the scanner can classify unchanged source text differently;
/// otherwise wrappers keep reusing the old answer for every file that did not
/// change.
///
/// 2: computed env var names, `[`/`{` delimiters, comments between tokens,
/// lifetimes, nested block comments and raw C strings; answers gained the
/// include-locator state that the positive proof needs.
///
/// 3: number suffixes, non-ASCII identifier bytes, and the non-ASCII
/// whitespace and byte-order mark rustc accepts between tokens.
const SOURCE_ENV_DEP_SCANNER_VERSION: u32 = 3;

/// How one source file's text uses an env var.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SourceEnvDepUse {
    /// No env macro names the var, and none has a name the scanner cannot read
    /// outside an include argument.
    Unused,
    /// At least one `env!(var)` / `option_env!(var)` inside an `include*!`
    /// argument, and no use outside one.
    IncludeLocator,
    /// `env!(var)` / `option_env!(var)` outside an include argument, or an env
    /// macro outside one whose name is not a plain string literal
    /// (`env!(concat!(..))`, `env!($name)` in a forwarding macro). Such a
    /// macro may read any var, so it counts against every var.
    RuntimeValue,
}

impl SourceEnvDepUse {
    fn memo_code(self) -> i64 {
        match self {
            Self::Unused => 0,
            Self::IncludeLocator => 1,
            Self::RuntimeValue => 2,
        }
    }

    fn from_memo_code(code: i64) -> Option<Self> {
        match code {
            0 => Some(Self::Unused),
            1 => Some(Self::IncludeLocator),
            2 => Some(Self::RuntimeValue),
            _ => None,
        }
    }
}

fn source_env_dep_use(source: &str, var: &str) -> SourceEnvDepUse {
    let bytes = source.as_bytes();
    let mut i = 0usize;
    // One entry per open delimiter, true when it opens an `include*!`
    // argument. Tracking every delimiter kind keeps `include!{..}` and
    // `env![..]` in step with their closing token; the depth counter keeps
    // the include test constant-time however deep the nesting goes.
    let mut groups: Vec<bool> = Vec::new();
    let mut include_depth = 0usize;
    let mut include_locator = false;

    // Every pass consumes at least one byte, so a scan needs no more passes
    // than the source has bytes. Each loop in the scanner carries that bound:
    // it makes a change that stops advancing end with a wrong answer instead
    // of running forever, which is the difference between a test that fails
    // and a test that never finishes.
    for _ in 0..bytes.len() {
        let Some(&byte) = bytes.get(i) else { break };
        let whitespace = rust_whitespace_len(bytes, i);
        if whitespace > 0 {
            i += whitespace;
            continue;
        }
        match byte {
            b'/' if comment_starts_at(bytes, i) => i = skip_comment(bytes, i),
            b'"' => i = skip_quoted_string(bytes, i + 1),
            b'\'' => i = skip_char_literal_or_lifetime(source, i),
            b'b' | b'c' | b'r' if raw_string_starts_at(bytes, i).is_some() => {
                i = skip_raw_string(bytes, i);
            }
            b'(' | b'[' | b'{' => {
                groups.push(false);
                i += 1;
            }
            b')' | b']' | b'}' => {
                if groups.pop() == Some(true) {
                    include_depth -= 1;
                }
                i += 1;
            }
            // A number with its suffix (`1u8`, `1r`), so a suffix cannot
            // start a raw string that hides the code after it.
            b'0'..=b'9' => i = skip_ident_bytes(bytes, i),
            b if is_ident_start(b) => {
                let ident_start = i;
                i = skip_ident_bytes(bytes, i);
                let ident = &bytes[ident_start..i];
                let Some(open) = parse_macro_open(bytes, i) else {
                    continue;
                };

                if matches!(ident, b"env" | b"option_env") {
                    match parse_env_macro_name(source, open + 1) {
                        Some(name) if name != var => {}
                        Some(_) if include_depth > 0 => include_locator = true,
                        None if include_depth > 0 => {}
                        _ => return SourceEnvDepUse::RuntimeValue,
                    }
                }
                let include = is_include_macro(ident);
                groups.push(include);
                include_depth += usize::from(include);
                i = open + 1;
            }
            _ => i += 1,
        }
    }

    if include_locator {
        SourceEnvDepUse::IncludeLocator
    } else {
        SourceEnvDepUse::Unused
    }
}

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

/// The var an env macro names, when its first token is a plain string literal
/// without escapes. `None` means the name is computed or spelled in a form the
/// scanner does not decode (`concat!`, `$v`, `"OUT\x5FDIR"`, raw strings).
fn parse_env_macro_name(source: &str, after_open: usize) -> Option<&str> {
    let bytes = source.as_bytes();
    let start = skip_trivia(bytes, after_open);
    if bytes.get(start) != Some(&b'"') {
        return None;
    }
    let len = bytes[start + 1..]
        .iter()
        .position(|b| matches!(b, b'"' | b'\\'))?;
    let end = start + 1 + len;
    (bytes[end] == b'"').then(|| &source[start + 1..end])
}

/// Position of the opening delimiter when `after_ident` starts `! (`, `! [`
/// or `! {`, with whitespace or comments allowed between the tokens.
fn parse_macro_open(bytes: &[u8], after_ident: usize) -> Option<usize> {
    let bang = skip_trivia(bytes, after_ident);
    if bytes.get(bang) != Some(&b'!') {
        return None;
    }
    let open = skip_trivia(bytes, bang + 1);
    matches!(bytes.get(open), Some(b'(' | b'[' | b'{')).then_some(open)
}

fn skip_trivia(bytes: &[u8], mut i: usize) -> usize {
    for _ in 0..bytes.len() {
        let whitespace = rust_whitespace_len(bytes, i);
        if whitespace > 0 {
            i += whitespace;
        } else if comment_starts_at(bytes, i) {
            i = skip_comment(bytes, i);
        } else {
            break;
        }
    }
    i
}

fn comment_starts_at(bytes: &[u8], i: usize) -> bool {
    bytes.get(i) == Some(&b'/') && matches!(bytes.get(i + 1), Some(b'/' | b'*'))
}

/// Byte length of the Rust whitespace character at `i`, or 0. Rust also
/// accepts vertical tab and a few non-ASCII `Pattern_White_Space` characters
/// between tokens; reading those as identifier bytes would hide `env` from
/// the scanner. A byte-order mark counts as whitespace wherever it appears:
/// rustc strips one only at the head of a file and rejects the rest, so the
/// extra reach concerns files that do not compile.
fn rust_whitespace_len(bytes: &[u8], i: usize) -> usize {
    match bytes.get(i..).unwrap_or_default() {
        [b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r' | b' ', ..] => 1,
        // U+0085
        [0xC2, 0x85, ..] => 2,
        // U+200E, U+200F, U+2028, U+2029
        [0xE2, 0x80, 0x8E | 0x8F | 0xA8 | 0xA9, ..] => 3,
        // U+FEFF, which rustc strips from the head of a file.
        // See the note above on accepting it anywhere.
        [0xEF, 0xBB, 0xBF, ..] => 3,
        _ => 0,
    }
}

/// Skip the comment starting at `i`. Block comments nest in Rust, so an inner
/// `*/` must not end the outer comment.
fn skip_comment(bytes: &[u8], mut i: usize) -> usize {
    if bytes.get(i + 1) == Some(&b'/') {
        for _ in 0..bytes.len() {
            match bytes.get(i) {
                Some(b'\n') | None => break,
                Some(_) => i += 1,
            }
        }
        return i;
    }
    let mut depth = 1usize;
    i += 2;
    for _ in 0..bytes.len() {
        match (bytes.get(i), bytes.get(i + 1)) {
            (Some(b'/'), Some(b'*')) => {
                depth += 1;
                i += 2;
            }
            (Some(b'*'), Some(b'/')) => {
                depth -= 1;
                i += 2;
                if depth == 0 {
                    return i;
                }
            }
            (Some(_), _) => i += 1,
            (None, _) => break,
        }
    }
    bytes.len()
}

fn skip_quoted_string(bytes: &[u8], mut i: usize) -> usize {
    for _ in 0..bytes.len() {
        match bytes.get(i) {
            Some(b'\\') => i += 2,
            Some(b'"') => return i + 1,
            Some(_) => i += 1,
            None => break,
        }
    }
    bytes.len()
}

/// Skip the char literal starting at the quote `quote`, or only the quote
/// when it starts a lifetime or label (`'a`, `'static`). Skipping to the next
/// quote after a lifetime would hide the code in between from the scanner.
fn skip_char_literal_or_lifetime(source: &str, quote: usize) -> usize {
    let bytes = source.as_bytes();
    if bytes.get(quote + 1) == Some(&b'\\') {
        return skip_char_literal(bytes, quote + 1);
    }
    let Some(ch) = source[quote + 1..].chars().next() else {
        return bytes.len();
    };
    let close = quote + 1 + ch.len_utf8();
    if bytes.get(close) == Some(&b'\'') {
        close + 1
    } else {
        quote + 1
    }
}

/// Skip a char literal from its first content byte through the closing quote.
fn skip_char_literal(bytes: &[u8], mut i: usize) -> usize {
    for _ in 0..bytes.len() {
        match bytes.get(i) {
            Some(b'\\') => i += 2,
            Some(b'\'') => return i + 1,
            Some(_) => i += 1,
            None => break,
        }
    }
    bytes.len()
}

fn raw_string_starts_at(bytes: &[u8], i: usize) -> Option<usize> {
    let mut cursor = i;
    if matches!(bytes.get(cursor), Some(b'b' | b'c')) {
        cursor += 1;
    }
    if bytes.get(cursor) != Some(&b'r') {
        return None;
    }
    cursor += 1;
    for _ in 0..bytes.len() {
        if bytes.get(cursor) != Some(&b'#') {
            break;
        }
        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'r') - 1;
    for cursor in open_quote + 1..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;
        }
    }
    bytes.len()
}

/// Non-ASCII bytes count as identifier bytes: reading `éinclude` as
/// `include` would invent an include context.
fn is_ident_start(byte: u8) -> bool {
    byte == b'_' || byte.is_ascii_alphabetic() || !byte.is_ascii()
}

/// Consume identifier bytes from `i`, which the caller has already read as
/// an identifier start or a digit.
fn skip_ident_bytes(bytes: &[u8], mut i: usize) -> usize {
    for _ in 0..bytes.len() {
        let Some(&byte) = bytes.get(i) else { break };
        if !(is_ident_start(byte) || byte.is_ascii_digit()) || rust_whitespace_len(bytes, i) > 0 {
            break;
        }
        i += 1;
    }
    i
}

// `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_path_only_decision`). 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)>,
    /// The tree digest of a unit under the tree guard ([`needs_tree_guard`]):
    /// the workspace for a workspace or path unit, the package for a registry
    /// unit with a proc-macro dependency. A macro can read any file there
    /// 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, on rows whose closure the guard
    /// does not cover, and on rows written before it existed, which the
    /// guard then treats as unusable. A registry unit with no proc macro may
    /// carry its `OUT_DIR` guard here, which nothing checks on this row.
    #[serde(default)]
    pub(crate) tree: Option<String>,
}

impl InputPrediction {
    pub(crate) 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,
        }
    }
}

/// Version of [`PortablePrediction`]. Far from [`PREDICTION_SCHEMA`] so the
/// two decoders can never accept each other's rows.
pub(crate) const PORTABLE_PREDICTION_SCHEMA: u32 = 101;

/// A registry unit's closure with its own `OUT_DIR` written as a placeholder,
/// so another target directory can use it.
///
/// Only a registry unit, whose other inputs are the same files in every
/// checkout, and only when `OUT_DIR` holds what it held for the recorder:
/// `tree` is a digest of it, and the reader refuses the row without an equal
/// one.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct PortablePrediction {
    pub(crate) schema: u32,
    pub(crate) sources: Vec<Portable>,
    pub(crate) env_deps: Vec<(String, Portable)>,
    pub(crate) tree: String,
}

/// One recorded path or env value: as spelled, or as the bytes after
/// `OUT_DIR` ([`out_dir_suffix`]) or after the workspace root.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum Portable {
    Literal(String),
    OutDir(String),
    Workspace(String),
    /// The bytes after `<CARGO_HOME>/registry/src`. Written only for a row
    /// that travels through the remote ([`crate::prediction_share`]), so it
    /// carries no local path.
    Registry(String),
}

/// Where a portable record's relative entries land for this invocation. A
/// record with an entry whose place this invocation lacks is not used.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Places<'a> {
    pub(crate) out_dir: Option<&'a str>,
    pub(crate) workspace: Option<&'a str>,
    pub(crate) registry: Option<&'a str>,
}

/// The directories a portable record is written against.
#[derive(Debug, Clone)]
pub(crate) struct PortableRoots {
    pub(crate) out_dir: PathBuf,
    pub(crate) target: PathBuf,
    pub(crate) canonical_target: PathBuf,
    pub(crate) registry_src: PathBuf,
}

/// The closure with `OUT_DIR` made relative, or `None` when any part of it
/// could name a different file in another target directory.
///
/// A source is either under `OUT_DIR` or under the registry. Anything else
/// is refused: another unit's output, a canonical spelling of the target, a
/// checkout path, a relative path, a `..` that leaves `OUT_DIR` or the
/// package. At least one source must be under `OUT_DIR`, or the plain shared
/// record already covers the unit. An env value under `OUT_DIR` is relocated
/// too; any other value spelling the target is refused, and the rest are
/// kept as they are.
pub(crate) fn portable_prediction(
    dep_info: &DepInfo,
    roots: &PortableRoots,
    tree: Option<&str>,
) -> Option<PortablePrediction> {
    let tree = tree?;
    let sources = dep_info
        .source_files
        .iter()
        .map(|source| portable_source(source, roots))
        .collect::<Option<Vec<_>>>()?;
    if !sources
        .iter()
        .any(|source| matches!(source, Portable::OutDir(_)))
    {
        return None;
    }
    let env_deps = dep_info
        .env_deps
        .iter()
        .map(|(name, value)| Some((name.clone(), portable_env_value(value, roots)?)))
        .collect::<Option<Vec<_>>>()?;
    Some(PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources,
        env_deps,
        tree: tree.to_string(),
    })
}

fn portable_source(source: &Path, roots: &PortableRoots) -> Option<Portable> {
    if let Some(suffix) = out_dir_suffix(source.as_os_str(), &roots.out_dir) {
        return Some(Portable::OutDir(suffix));
    }
    if !under_registry_src(source, &roots.registry_src) {
        return None;
    }
    Some(Portable::Literal(source.to_str()?.to_string()))
}

fn portable_env_value(value: &str, roots: &PortableRoots) -> Option<Portable> {
    if let Some(suffix) = out_dir_suffix(std::ffi::OsStr::new(value), &roots.out_dir) {
        return Some(Portable::OutDir(suffix));
    }
    let spells = |root: &Path| {
        value
            .as_bytes()
            .starts_with(root.as_os_str().as_encoded_bytes())
    };
    if spells(&roots.target) || spells(&roots.canonical_target) {
        return None;
    }
    Some(Portable::Literal(value.to_string()))
}

impl PortablePrediction {
    /// The record this invocation would have made: each relocated entry gets
    /// its root's bytes in front of its suffix. The result is then checked
    /// like any other record, raw env values included. `None` when an entry
    /// is relative to a root `places` does not have.
    pub(crate) fn resolve(&self, places: &Places<'_>) -> Option<InputPrediction> {
        let place = |portable: &Portable| match portable {
            Portable::Literal(value) => Some(value.clone()),
            Portable::OutDir(suffix) => Some(format!("{}{suffix}", places.out_dir?)),
            Portable::Workspace(suffix) => Some(format!("{}{suffix}", places.workspace?)),
            Portable::Registry(suffix) => Some(format!("{}{suffix}", places.registry?)),
        };
        Some(InputPrediction {
            schema: PREDICTION_SCHEMA,
            sources: self
                .sources
                .iter()
                .map(|source| place(source).map(PathBuf::from))
                .collect::<Option<_>>()?,
            env_deps: self
                .env_deps
                .iter()
                .map(|(name, value)| Some((name.clone(), place(value)?)))
                .collect::<Option<_>>()?,
            tree: Some(self.tree.clone()),
        })
    }
}

/// Use a relocated record: its digest must equal the guard this invocation
/// computed, and the resolved closure must pass [`validate_prediction`].
fn validate_portable_prediction(
    record: &PortablePrediction,
    guard: &str,
    places: &Places<'_>,
    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> {
    if record.tree != guard {
        return Err(Rejection::TreeChanged);
    }
    let resolved = record.resolve(places).ok_or(Rejection::NoRecord)?;
    validate_prediction(&resolved, stat, exists, env_value)
}

/// Does `content` spell any of `roots`, as-is or with each `\` doubled the
/// way a string literal escapes it?
///
/// A generated file that names the target could make rustc read a file
/// relocation does not move, so such an `OUT_DIR` is not relocated.
pub(crate) fn mentions_root(content: &[u8], roots: &[&Path]) -> bool {
    roots.iter().any(|root| {
        let raw = root.as_os_str().as_encoded_bytes();
        let doubled: Vec<u8> = raw
            .iter()
            .flat_map(|&byte| std::iter::repeat_n(byte, if byte == b'\\' { 2 } else { 1 }))
            .collect();
        crate::build_script::find_bytes(content, raw).is_some()
            || crate::build_script::find_bytes(content, &doubled).is_some()
    })
}

/// True only when every entry under `out_dir` was read and none spells any
/// of `roots`: file content and symlink text alike. Past
/// [`OUT_DIR_TREE_MAX_ENTRIES`], or on any read error, the answer is false.
fn out_dir_spells_no_root(out_dir: &Path, roots: &[&Path]) -> bool {
    fn walk(directory: &Path, roots: &[&Path], budget: &mut usize) -> Option<()> {
        for entry in std::fs::read_dir(directory).ok()? {
            let path = entry.ok()?.path();
            *budget = budget.checked_sub(1)?;
            let metadata = std::fs::symlink_metadata(&path).ok()?;
            let content = if metadata.file_type().is_symlink() {
                std::fs::read_link(&path)
                    .ok()?
                    .into_os_string()
                    .into_encoded_bytes()
            } else if metadata.is_dir() {
                walk(&path, roots, budget)?;
                continue;
            } else if metadata.is_file() {
                std::fs::read(&path).ok()?
            } else {
                return None;
            };
            if mentions_root(&content, roots) {
                return None;
            }
        }
        Some(())
    }
    let mut budget = OUT_DIR_TREE_MAX_ENTRIES;
    walk(out_dir, roots, &mut budget).is_some()
}

/// The relocated record for this invocation and the identity to file it
/// under, or `None` when the unit or its closure is not relocatable.
pub(crate) fn relocatable_record(
    args: &RustcArgs,
    dep_info: &DepInfo,
    tree: Option<&str>,
) -> Option<(String, PortablePrediction)> {
    relocatable_record_in(args, dep_info, tree, std::env::vars_os().collect())
}

/// [`relocatable_record`] against an environment snapshot.
fn relocatable_record_in(
    args: &RustcArgs,
    dep_info: &DepInfo,
    tree: Option<&str>,
    vars: Vec<(std::ffi::OsString, std::ffi::OsString)>,
) -> Option<(String, PortablePrediction)> {
    let roots = portable_roots(args, &vars)?;
    let identity = relocatable_prediction_identity(args, vars)?;
    let record = portable_prediction(dep_info, &roots, tree)?;
    out_dir_spells_no_root(&roots.out_dir, &[&roots.target, &roots.canonical_target])
        .then_some((identity, record))
}

/// The guard this checkout's own rows carry, the local row and the shared
/// one ([`same_tree_guard`]).
pub(crate) fn same_checkout_guard(
    args: &RustcArgs,
    dep_info: &DepInfo,
    tree: Option<String>,
) -> Option<String> {
    let workspace = workspace_roots(args, &std::env::vars_os().collect::<Vec<_>>());
    same_tree_guard(
        tree,
        workspace.is_some(),
        workspace.is_some_and(|workspace| guard_covers(&dep_info.source_files, &workspace)),
    )
}

/// A workspace unit whose closure the guard does not cover (`covered` false,
/// see [`guard_covers`]) keeps no guard: a macro that scans a directory the
/// guard does not see could find a new file there with the guard unchanged.
/// Without a guard, the row of a workspace unit is never used, and the unit
/// keeps discovering its closure. This checkout's rows are never relocated,
/// so a generated file naming the checkout costs nothing here.
fn same_tree_guard(tree: Option<String>, workspace_unit: bool, covered: bool) -> Option<String> {
    if workspace_unit && !covered {
        None
    } else {
        tree
    }
}

/// A workspace unit's record for another checkout and the identity to file it
/// under (kunobi-ninja/kache#1005), or `None` when the unit or its closure is
/// not relocatable, or the guard does not see every file the closure names
/// ([`guard_covers`]). `tree` is the workspace guard taken before rustc ran.
pub(crate) fn workspace_record(
    args: &RustcArgs,
    dep_info: &DepInfo,
    tree: Option<&str>,
) -> Option<(String, PortablePrediction)> {
    let vars: Vec<_> = std::env::vars_os().collect();
    let workspace = workspace_roots(args, &vars)?;
    let record = workspace_portable_prediction(dep_info, &workspace, tree)?;
    if !guard_covers(&dep_info.source_files, &workspace) {
        return None;
    }
    let identity = workspace_prediction_identity(args, vars, &workspace)?;
    let named = [
        workspace.root.as_path(),
        &workspace.canonical_root,
        &workspace.target,
        &workspace.canonical_target,
    ];
    if let Some(out_dir) = &workspace.out_dir
        && !out_dir_spells_no_root(out_dir, &named)
    {
        return None;
    }
    Some((identity, record))
}

/// Does the workspace guard see every file of `sources`? It sees a file its
/// walk reaches: one under `OUT_DIR`, or under the workspace root and outside
/// the target directory, with no symlinked directory on the way (the walk
/// does not follow one) and no directory Cargo tagged as its build directory
/// (the walk leaves those out). A relative source must stay inside the root.
/// A macro that lists a directory the guard does not see could find a new
/// file there with the digest unchanged.
fn guard_covers(sources: &[PathBuf], workspace: &WorkspaceRoots) -> bool {
    let mut entered = HashMap::new();
    sources.iter().all(|source| {
        guard_place(source, workspace).is_some_and(|(root, below, skips_build_dirs)| {
            walk_reaches(root, &below, skips_build_dirs, &mut entered)
        })
    })
}

/// The root the guard's walk reaches `source` from, the path below it, and
/// whether that walk leaves Cargo's build directories out. `None` for a
/// source no walk reaches: outside the workspace, under the target
/// directory, or relative and leaving the root.
fn guard_place<'a>(
    source: &Path,
    workspace: &'a WorkspaceRoots,
) -> Option<(&'a Path, String, bool)> {
    if !source.has_root() {
        workspace_relative_source(source, workspace)?;
        let below = format!("{}/{}", workspace.cwd, source.to_str()?);
        return Some((&workspace.root, below, true));
    }
    match workspace_portable_value(source.as_os_str(), workspace)? {
        Portable::OutDir(below) => Some((workspace.out_dir.as_deref()?, below, false)),
        Portable::Workspace(below) => Some((&workspace.root, below, true)),
        Portable::Literal(_) | Portable::Registry(_) => None,
    }
}

/// Does a walk from `root` that follows no symlink reach the file at
/// `below`, a lexical path inside `root`? With `skips_build_dirs`, not
/// through a directory Cargo tagged as its build directory either.
/// `entered` keeps the answer for each directory checked.
fn walk_reaches(
    root: &Path,
    below: &str,
    skips_build_dirs: bool,
    entered: &mut HashMap<(PathBuf, bool), bool>,
) -> bool {
    use std::path::Component;
    let components: Vec<Component<'_>> = Path::new(below)
        .components()
        .filter(|component| matches!(component, Component::Normal(_) | Component::ParentDir))
        .collect();
    let Some((_, directories)) = components.split_last() else {
        return true;
    };
    let mut directory = root.to_path_buf();
    let mut depth = 0usize;
    for component in directories {
        if *component == Component::ParentDir {
            let Some(up) = depth.checked_sub(1) else {
                return false;
            };
            depth = up;
            directory.pop();
            continue;
        }
        directory.push(component);
        depth += 1;
        let walked = *entered
            .entry((directory.clone(), skips_build_dirs))
            .or_insert_with(|| {
                std::fs::symlink_metadata(&directory).is_ok_and(|metadata| metadata.is_dir())
                    && !(skips_build_dirs && crate::tree_stamp::holds_cargo_build_tag(&directory))
            });
        if !walked {
            return false;
        }
    }
    true
}

/// The closure with every source written relative to `OUT_DIR` or the
/// workspace root, or `None` when any part could name a different file in
/// another checkout: a file outside the workspace, another unit's output
/// under the target directory, a `..` that leaves the workspace.
fn workspace_portable_prediction(
    dep_info: &DepInfo,
    workspace: &WorkspaceRoots,
    tree: Option<&str>,
) -> Option<PortablePrediction> {
    let tree = tree?;
    let sources = dep_info
        .source_files
        .iter()
        .map(|source| {
            if !source.has_root() {
                return workspace_relative_source(source, workspace);
            }
            let relocated = workspace_portable_value(source.as_os_str(), workspace)?;
            (!matches!(relocated, Portable::Literal(_))).then_some(relocated)
        })
        .collect::<Option<Vec<_>>>()?;
    let env_deps = dep_info
        .env_deps
        .iter()
        .map(|(name, value)| {
            let value = workspace_portable_value(std::ffi::OsStr::new(value), workspace)?;
            Some((name.clone(), value))
        })
        .collect::<Option<Vec<_>>>()?;
    Some(PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources,
        env_deps,
        tree: tree.to_string(),
    })
}

/// A source rustc reported relative to its working directory, as Cargo does
/// for a workspace member: kept as spelled, because the identity pins that
/// directory relative to the workspace root, when a lexical walk from it
/// never leaves the workspace.
fn workspace_relative_source(source: &Path, workspace: &WorkspaceRoots) -> Option<Portable> {
    let spelled = source.to_str()?;
    let from_root = format!("{}/{spelled}", workspace.cwd);
    let components = from_root.strip_prefix(['/', '\\'])?;
    (stays_below(components.split(['/', '\\']), 0) && stays_below(components.split('/'), 0))
        .then(|| Portable::Literal(spelled.to_string()))
}

/// One path or env value of a workspace unit: under `OUT_DIR`, under the
/// workspace (either spelling of its root), refused when it names the target
/// directory any other way, and otherwise kept as spelled.
fn workspace_portable_value(
    value: &std::ffi::OsStr,
    workspace: &WorkspaceRoots,
) -> Option<Portable> {
    if let Some(out_dir) = &workspace.out_dir
        && let Some(suffix) = out_dir_suffix(value, out_dir)
    {
        return Some(Portable::OutDir(suffix));
    }
    let bytes = value.as_encoded_bytes();
    let spells = |root: &Path| bytes.starts_with(root.as_os_str().as_encoded_bytes());
    if spells(&workspace.target) || spells(&workspace.canonical_target) {
        return None;
    }
    if let Some(suffix) = suffix_within(value, &workspace.root, 0)
        .or_else(|| suffix_within(value, &workspace.canonical_root, 0))
    {
        return Some(Portable::Workspace(suffix));
    }
    Some(Portable::Literal(value.to_str()?.to_string()))
}

/// This invocation's roots: its `OUT_DIR`, a target directory that exists,
/// and a registry package.
fn portable_roots(
    args: &RustcArgs,
    vars: &[(std::ffi::OsString, std::ffi::OsString)],
) -> Option<PortableRoots> {
    let out_dir = PathBuf::from(env_var_in(vars, "OUT_DIR")?);
    let target = args.target_dir()?;
    let registry_src = registry_src_root(Path::new(env_var_in(vars, "CARGO_MANIFEST_DIR")?))?;
    Some(PortableRoots {
        canonical_target: std::fs::canonicalize(&target).ok()?,
        registry_src: registry_src.to_path_buf(),
        out_dir,
        target,
    })
}

/// 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.
    /// Also a relocated record whose `OUT_DIR` held something else.
    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",
        }
    }
}

/// Must this unit's records carry a tree digest that still matches?
///
/// A proc macro can list a directory 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. The tree digest is what sees the new file.
///
/// The macro need not be a direct dependency: an rlib can re-export one
/// (`sqlx::migrate!`, `include_dir!`), and rustc is told only about the rlib.
/// So every workspace or path unit takes the guard, whatever it links. A
/// registry unit takes it only with a proc-macro dependency of its own
/// ([`has_dylib_extern`]): its package is the same files wherever it is
/// built. A unit with no `CARGO_MANIFEST_DIR` keeps the dynamic-library
/// rule. A unit that takes the guard but has no tree to digest is not
/// predicted.
fn needs_tree_guard(externs: &[crate::args::ExternDep], manifest_dir: Option<&Path>) -> bool {
    has_dylib_extern(externs) || manifest_dir.is_some_and(|dir| !is_registry_package(dir))
}

/// Does the unit depend on a dynamic library? Cargo hands rustc each
/// proc-macro dependency as one. `dylib` crate-type dependencies get swept in
/// too, which only costs a guard they did not need.
fn has_dylib_extern(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>>,
    env_dep_uses: RefCell<HashMap<(String, String), SourceEnvDepUse>>,
    stats: FileHashStatsCells,
    too_new: TooNewGuard,
    /// Fingerprints of every file hashed, or proved by a memo's stamp, while
    /// the too-new guard was armed, with the time each was observed. Checked
    /// again after the compile so the wrapper can prove clock-independently
    /// that none of them changed mid-build (see
    /// [`FileHasher::inputs_changed_since_keyed`] and
    /// [`FileHasher::guarded_inputs_unchanged_since_hash`]).
    guard_inputs: RefCell<Vec<ObservedFingerprint>>,
    /// 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. Each row keeps the time its file was observed, which alone
    /// decides whether it may be written.
    pending_memo: RefCell<Vec<(ObservedFingerprint, String)>>,
    /// The stat walks behind the tree digests computed since the last
    /// [`FileHasher::take_tree_walks`] (see [`tree_guard_of`]).
    tree_walks: RefCell<Vec<GuardWalk>>,
    /// Kache's own directories and what Cargo writes in its home, in each
    /// spelling, which tree guards leave out ([`FileHasher::with_own_dirs`]).
    own_dirs: Vec<PathBuf>,
}

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 stamp shows a write at or after `margin_ns` before the
/// build's start ([`stamp_written_since`]) 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>,
    /// Tripped by a stamp no later than the wall clock read after its stat:
    /// a write since the start by this host's clock. A stamp still ahead of
    /// the clock then was not written during the build here; it comes from
    /// a skewed file clock or a future-dated file. Only a key taken before
    /// the compile tells the two apart
    /// ([`FileHasher::inputs_changed_since_keyed`]).
    saw_write_since_start: 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>,
}

/// [`hash_file`], for a read that follows a stat of the same file.
fn read_file_hash(path: &Path) -> Result<String> {
    #[cfg(test)]
    BEFORE_READ.with(|hook| {
        if let Some(hook) = hook.borrow_mut().as_mut() {
            hook(path);
        }
    });
    hash_file(path)
}

/// Run by [`read_file_hash`] before it reads, so a test can write to a file
/// between a hasher's stat and its read.
#[cfg(test)]
pub(crate) type BeforeRead = Box<dyn FnMut(&Path)>;

#[cfg(test)]
thread_local! {
    static BEFORE_READ: std::cell::RefCell<Option<BeforeRead>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(test)]
pub(crate) fn set_before_read(hook: Option<BeforeRead>) {
    BEFORE_READ.with(|slot| *slot.borrow_mut() = hook);
}

/// A file's raw blake3 and its blake3 with the prefix maps applied, both
/// from one read, so the raw one shows which bytes the mapped one is of.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CcContentHashes {
    pub(crate) raw: String,
    pub(crate) mapped: String,
}

/// Why [`FileHasher::cc_inputs_hide_assembler_input`] gave no verdict: the
/// scan read other bytes than the input was fingerprinted with.
pub(crate) const CC_INPUT_CHANGED_WHILE_SCANNED: &str = "an input changed while it was scanned";

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()),
            env_dep_uses: RefCell::new(HashMap::new()),
            stats: FileHashStatsCells::default(),
            too_new: TooNewGuard::default(),
            guard_inputs: RefCell::new(Vec::new()),
            pending_memo: RefCell::new(Vec::new()),
            tree_walks: RefCell::new(Vec::new()),
            own_dirs: 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()),
                env_dep_uses: RefCell::new(HashMap::new()),
                stats: FileHashStatsCells::default(),
                too_new: TooNewGuard::default(),
                guard_inputs: RefCell::new(Vec::new()),
                pending_memo: RefCell::new(Vec::new()),
                tree_walks: RefCell::new(Vec::new()),
                own_dirs: 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.
    ///
    /// A file that had changed within [`HASH_SETTLE_NS`] of when it was
    /// observed is left out: its hash was right for this process, but a
    /// second write in the same timestamp tick would leave a row that no
    /// stamp check could catch. Flushing later does not change that, since
    /// the bytes were read back then. 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 mut pending = std::mem::take(&mut *self.pending_memo.borrow_mut());
        pending.retain(|(observed, _)| observed.settled());
        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 (observed, hash) in &pending {
                if let Err(error) = cache.put(&observed.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: {error}");
        }
    }

    /// Flush as if every pending file had been observed one settle window
    /// later, for tests that write a file and then expect its row.
    #[cfg(test)]
    pub(crate) fn flush_memo_as_if_settled(&self) {
        for (observed, _) in self.pending_memo.borrow_mut().iter_mut() {
            observed.observed_ns = observed.observed_ns.saturating_add(HASH_SETTLE_NS);
        }
        self.flush_memo();
    }

    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()),
            env_dep_uses: RefCell::new(HashMap::new()),
            stats: FileHashStatsCells::default(),
            too_new: TooNewGuard::default(),
            guard_inputs: RefCell::new(Vec::new()),
            pending_memo: RefCell::new(Vec::new()),
            tree_walks: RefCell::new(Vec::new()),
            own_dirs: 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
    }

    /// Leave `paths` out of every tree a guard walks ([`own_dirs_within`]):
    /// Kache's cache, runtime and probe directories, and what Cargo writes in
    /// its home. Each comes in every spelling a walk may meet it by
    /// ([`crate::build_script_inputs::excluded_roots`]), and the declared
    /// build-script inputs leave out the same paths.
    pub(crate) fn with_own_dirs(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
        self.own_dirs.extend(paths);
        self
    }

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

    fn note_tree_walk(&self, walk: GuardWalk) {
        self.tree_walks.borrow_mut().push(walk);
    }

    fn take_tree_walks(&self) -> Vec<GuardWalk> {
        std::mem::take(&mut *self.tree_walks.borrow_mut())
    }

    /// 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 stamp shows a write at or after `margin_ns` before
    /// `invocation_start_ns` (the build's start, read from [`stamp_clock_ns`]),
    /// allowing for coarse file clocks ([`stamp_written_since`]). 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()
    }

    /// Keep `observed` for the post-compile revalidation, when the guard is
    /// armed.
    fn guard_input(&self, observed: &ObservedFingerprint) {
        if self.too_new.invocation_start_ns > 0 {
            self.guard_inputs.borrow_mut().push(observed.clone());
        }
    }

    /// 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<ObservedFingerprint> {
        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: &[ObservedFingerprint]) -> bool {
        if inputs.is_empty() {
            return false;
        }
        inputs.iter().all(|input| {
            let expected = &input.fingerprint;
            expected.inode != 0
                && FileFingerprint::from_path(Path::new(&expected.path))
                    .is_ok_and(|current| current == *expected)
        })
    }

    /// Whether any guarded input visibly changed since it was hashed: it is
    /// gone, or its size, write time or inode differ from the fingerprint
    /// taken then. Unlike [`Self::guarded_inputs_unchanged_since_hash`] this
    /// needs no strong identity, as it only reports what it sees change.
    ///
    /// The change time does not count: linking a dependency's output
    /// elsewhere, as store ingest and Cargo's uplift do while its dependents
    /// compile, moves it and leaves the bytes alone. So a rewrite that keeps
    /// the size and write time is missed, and on Windows, where fingerprints
    /// carry no inode, so is a replacement with the same size and write time.
    pub fn guarded_inputs_moved_since_hash(inputs: &[ObservedFingerprint]) -> bool {
        inputs.iter().any(|input| {
            let expected = &input.fingerprint;
            FileFingerprint::from_path(Path::new(&expected.path)).map_or(true, |current| {
                current.size != expected.size
                    || current.mtime_ns != expected.mtime_ns
                    || current.inode != expected.inode
            })
        })
    }

    /// Whether a compile that ran after this key may have read other bytes
    /// than the key hashed. Ask once the compile has run.
    ///
    /// A stamp written since the invocation started refuses: a save between
    /// the preprocessor's read and the key's changes the read set while
    /// every file the key hashed still matches what it saw. A stamp ahead of
    /// the clock when the key took it does not refuse on its own (see
    /// `saw_write_since_start`). Every input the key took in, hashed or
    /// proved by a memo's stamp, must then still match a fresh stat. One
    /// whose stamp had not settled when the invocation started is read again
    /// as well, since a second write in the same timestamp tick keeps the
    /// stamp; only such fresh files pay a read.
    pub(crate) fn inputs_changed_since_keyed(&self) -> bool {
        if self.too_new.saw_write_since_start.get() {
            return true;
        }
        let start_ns = self.too_new.invocation_start_ns;
        let guarded = self.guard_inputs.borrow();
        let recent = self.recent_hashes.borrow();
        let distinct: std::collections::HashSet<&FileFingerprint> = guarded
            .iter()
            .map(|observed| &observed.fingerprint)
            .collect();
        distinct.into_iter().any(|keyed| {
            let path = Path::new(&keyed.path);
            let holds_hashed_bytes = || {
                recent.get(path).is_some_and(|hashed| {
                    hashed.fingerprint.as_ref() == Some(keyed)
                        && hash_file(path).is_ok_and(|bytes| bytes == hashed.hash)
                })
            };
            !FileFingerprint::from_path(path).is_ok_and(|current| current == *keyed)
                || (!stamp_is_settled(keyed, start_ns) && !holds_hashed_bytes())
        })
    }

    fn note_too_new(&self, fingerprint: &FileFingerprint) {
        if self.too_new.invocation_start_ns > 0 {
            let since = self
                .too_new
                .invocation_start_ns
                .saturating_sub(self.too_new.margin_ns);
            if stamp_written_since(fingerprint, since) {
                self.too_new.saw_too_new.set(true);
                // Read after the stat: a write before it cannot carry a later
                // stamp by this host's clock.
                let now_ns = wall_clock_ns();
                if [fingerprint.mtime_ns, fingerprint.ctime_ns]
                    .into_iter()
                    .any(|stamp| {
                        stamp >= since.saturating_sub(stamp_window_ns(stamp)) && stamp <= now_ns
                    })
                {
                    self.too_new.saw_write_since_start.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()
    }

    /// True only when the local store is known to hold no entry for this
    /// unit: `crate_name` under Cargo's `-C metadata` hash, or any unit of
    /// that name when the hash is absent. No store, or a failed query, is
    /// "unknown": false.
    fn store_lacks_unit(&self, crate_name: &str, unit: &str) -> bool {
        let _trace = crate::phase_trace::phase("crate_presence");
        let Some(cache) = self.cache.as_ref() else {
            return false;
        };
        match cache.has_entry_for_unit(crate_name, unit) {
            Ok(present) => !present,
            Err(error) => {
                tracing::debug!("crate presence lookup failed: {error}");
                false
            }
        }
    }

    /// 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
            }
        }
    }

    /// Remember a relocated closure. Best-effort, like
    /// [`FileHasher::record_input_prediction`].
    pub(crate) fn record_portable_prediction(
        &self,
        identity: &str,
        crate_name: Option<&str>,
        record: &PortablePrediction,
    ) {
        let Some(cache) = self.cache.as_ref() else {
            return;
        };
        let json = match serde_json::to_string(record) {
            Ok(json) => json,
            Err(error) => {
                tracing::debug!("portable prediction encode failed: {error}");
                return;
            }
        };
        if let Err(error) = cache.put_input_prediction(identity, record.schema, crate_name, &json) {
            tracing::debug!("portable prediction record failed: {error}");
        }
    }

    /// The relocated closure recorded for `identity`, read under the same
    /// rules as [`FileHasher::input_prediction`].
    pub(crate) fn portable_prediction(&self, identity: &str) -> Option<PortablePrediction> {
        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!("portable prediction lookup failed: {error}");
                return None;
            }
        };
        if schema != PORTABLE_PREDICTION_SCHEMA {
            return None;
        }
        match serde_json::from_str::<PortablePrediction>(&json) {
            Ok(record) if record.schema == PORTABLE_PREDICTION_SCHEMA => Some(record),
            Ok(_) => None,
            Err(error) => {
                tracing::debug!("portable prediction decode failed: {error}");
                None
            }
        }
    }

    /// 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(_))))
    }

    /// 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.
    ///
    /// A recent write alone does not refuse the hit. A recorded stamp is
    /// trusted only because it had settled when it was taken, so any later
    /// write has moved it; an input observed sooner was recorded without a
    /// stamp and is compared by content every time. Any database, decoding,
    /// or metadata uncertainty is still a miss.
    pub(crate) fn cc_preprocess_memo_lookup(
        &self,
        memo_key: &str,
        resolve: impl Fn(&str) -> Vec<PathBuf>,
        mapped_content: &impl Fn(&Path) -> Option<CcContentHashes>,
    ) -> 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; a row recorded without
    /// a stamp matches no file's metadata. 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<CcContentHashes>,
    ) -> 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) = ObservedFingerprint::from_path(path) else {
                continue;
            };
            self.note_too_new(&current.fingerprint);
            // 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.fingerprint == expected.fingerprint {
                // Unhashed, so registered here with the bytes its stamp
                // proves: the recheck after a compile has to cover it like
                // any input the key hashed.
                self.guard_input(&current);
                self.recent_hashes.borrow_mut().insert(
                    absolute_path(path),
                    RecentHash {
                        hash: expected.content.clone(),
                        fingerprint: Some(current.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(|read| read.mapped == expected.mapped)
            {
                return Some(path.clone());
            }
        }
        tracing::debug!(
            "cc preprocess memo input {} matched none of {} candidate paths",
            expected.name,
            candidates.len()
        );
        None
    }

    /// Fingerprint every file a preprocessor run or a compile read, under its
    /// mapped name. The caller revalidates this snapshot after a successful
    /// compile or restore before committing it.
    ///
    /// The raw content hash comes from the file-hash memo by stamp. The
    /// mapped hash (the bytes with this invocation's prefix maps applied) is
    /// memoised by raw hash and map set in the same index, so the headers a
    /// build's translation units share are read and rewritten once per map
    /// set rather than once per unit; `maps_key` names the map set. A mapped
    /// hash is learned only from a read whose raw hash is the content hash:
    /// a file written between the two reads fails the whole capture.
    ///
    /// Every input carries the wall clock read before its stamp was taken.
    /// The store keeps a stamp only if it had settled by then.
    pub(crate) fn cc_preprocess_fingerprints(
        &self,
        paths: &[(String, PathBuf)],
        maps_key: &str,
        mapped_content: &impl Fn(&Path) -> Option<CcContentHashes>,
    ) -> Option<Vec<CcPreprocessMemoInput>> {
        if paths.is_empty() {
            return None;
        }
        let _trace = crate::phase_trace::phase("cc_fingerprints");
        // Every stamp first, then one lookup for all of them. A translation
        // unit reads a couple of hundred headers, most of them the same ones
        // its neighbours read; opening and hashing each again cost more than
        // the compile's own header work did on macOS.
        let mut stamped: Vec<(&String, &PathBuf, ObservedFingerprint)> =
            Vec::with_capacity(paths.len());
        for (name, path) in paths {
            let observed = match ObservedFingerprint::from_path(path) {
                Ok(observed) => observed,
                Err(error) => {
                    tracing::debug!(
                        "cc preprocess memo input {} could not be fingerprinted: {error}",
                        path.display()
                    );
                    return None;
                }
            };
            self.note_too_new(&observed.fingerprint);
            stamped.push((name, path, observed));
        }
        let memoised = self.memoised_hashes(stamped.iter().map(|(_, _, stamp)| &stamp.fingerprint));
        let mut pending: Vec<(String, ObservedFingerprint, String, PathBuf)> =
            Vec::with_capacity(stamped.len());
        for (name, path, observed) in stamped {
            let content = match self.header_hash(path, &observed, &memoised) {
                Ok(content) => content,
                Err(error) => {
                    tracing::debug!(
                        "cc preprocess memo input {} could not be hashed: {error}",
                        path.display()
                    );
                    return None;
                }
            };
            pending.push((name.clone(), observed, content, path.clone()));
        }
        let memo = self.cache.as_ref().filter(|_| !maps_key.is_empty());
        let known = match memo {
            Some(cache) => {
                let contents: Vec<&str> = pending.iter().map(|p| p.2.as_str()).collect();
                cache
                    .get_cc_mapped_hashes(maps_key, &contents)
                    .unwrap_or_else(|error| {
                        tracing::debug!("cc mapped hash memo lookup failed: {error}");
                        Default::default()
                    })
            }
            None => Default::default(),
        };
        let mut known = known;
        let mut learned: Vec<(String, String)> = Vec::new();
        let mut inputs = Vec::with_capacity(pending.len());
        for (name, observed, content, path) in pending {
            let mapped = match known.get(&content) {
                Some(mapped) => mapped.clone(),
                None => {
                    let read = mapped_content(&path)?;
                    if read.raw != content {
                        // Written since it was hashed: the mapped hash is of
                        // other bytes than the content hash names.
                        tracing::debug!(
                            "cc preprocess memo input {} changed while it was fingerprinted",
                            path.display()
                        );
                        return None;
                    }
                    known.insert(content.clone(), read.mapped.clone());
                    learned.push((content.clone(), read.mapped.clone()));
                    read.mapped
                }
            };
            inputs.push(CcPreprocessMemoInput {
                name,
                fingerprint: observed.fingerprint,
                content,
                mapped,
                observed_ns: observed.observed_ns,
            });
        }
        if let Some(cache) = memo
            && let Err(error) = cache.put_cc_mapped_hashes(maps_key, &learned)
        {
            tracing::debug!("cc mapped hash memo update failed: {error}");
        }
        inputs.sort_by(|a, b| a.name.cmp(&b.name));
        inputs.dedup_by(|a, b| a.name == b.name);
        Some(inputs)
    }

    /// The first input whose raw text hides a file the assembler would read,
    /// scanning each distinct content once: the verdict is memoised by raw
    /// content hash, so a header shared by many units is read once. `scan`
    /// reads a file once and returns the raw hash of those bytes with
    /// `None` for clean text or the construct found; `None` for a file it
    /// cannot read (skipped, not recorded).
    ///
    /// A verdict counts only for the bytes the input was fingerprinted
    /// with. When the scan read others, nothing is recorded and the inputs
    /// are reported as [`CC_INPUT_CHANGED_WHILE_SCANNED`], since no verdict
    /// covers what the key holds.
    pub(crate) fn cc_inputs_hide_assembler_input(
        &self,
        inputs: &[CcPreprocessMemoInput],
        scan: &impl Fn(&Path) -> Option<(String, Option<&'static str>)>,
    ) -> Option<String> {
        let _trace = crate::phase_trace::phase("cc_asm_scan");
        let known = match &self.cache {
            Some(cache) => {
                let contents: Vec<&str> = inputs.iter().map(|i| i.content.as_str()).collect();
                cache.get_cc_asm_scans(&contents).unwrap_or_else(|error| {
                    tracing::debug!("cc assembler scan memo lookup failed: {error}");
                    Default::default()
                })
            }
            None => Default::default(),
        };
        let mut known = known;
        let mut learned: Vec<(String, String)> = Vec::new();
        let mut found: Option<String> = None;
        for input in inputs {
            let verdict = match known.get(&input.content) {
                Some(construct) => construct.clone(),
                None => {
                    let Some((raw, scanned)) = scan(Path::new(&input.fingerprint.path)) else {
                        continue;
                    };
                    if raw != input.content {
                        found.get_or_insert_with(|| CC_INPUT_CHANGED_WHILE_SCANNED.to_string());
                        continue;
                    }
                    let construct = scanned.unwrap_or("").to_string();
                    known.insert(input.content.clone(), construct.clone());
                    learned.push((input.content.clone(), construct.clone()));
                    construct
                }
            };
            if !verdict.is_empty() && found.is_none() {
                found = Some(verdict);
            }
        }
        if let Some(cache) = &self.cache
            && let Err(error) = cache.put_cc_asm_scans(&learned)
        {
            tracing::debug!("cc assembler scan memo update failed: {error}");
        }
        found
    }

    /// 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 does not block the record; the
    /// store decides what its stamp may prove. A stamp that had settled when
    /// the input was observed moves on any later write. One taken sooner can
    /// survive a second write in the same timestamp tick, so the input is
    /// recorded by content alone and every lookup compares that content. For
    /// a file of 64 KiB or more the comparison goes through the file-hash
    /// memo, which answers by stamp, so it is only as fresh as that memo's
    /// rows. Refusing the record instead would keep a fresh checkout from
    /// memoising anything.
    pub(crate) fn cc_preprocess_memo_record_if_unchanged(
        &self,
        memo_key: &str,
        preprocessed_hash: &str,
        inputs: &[CcPreprocessMemoInput],
        mapped_content: &impl Fn(&Path) -> Option<CcContentHashes>,
    ) {
        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, observed) = self.hash_inner(path, true)?;
        if let Some(observed) = &observed {
            self.guard_input(observed);
        }
        self.recent_hashes.borrow_mut().insert(
            absolute_path(path),
            RecentHash {
                hash: hash.clone(),
                fingerprint: observed.map(|observed| observed.fingerprint),
            },
        );
        Ok(hash)
    }

    /// Hash a file that is not a key input, such as one a tree guard reads,
    /// through the persistent cache. It neither trips the too-new guard nor
    /// joins the inputs checked again after the compile: a file saved
    /// anywhere in the workspace while a unit builds must not keep that unit
    /// out of the store. Its memo row follows the same rules as a key
    /// input's: none for a stamp that had not settled when it was observed,
    /// or that moved while the file was read under the guard.
    pub(crate) fn hash_unkeyed(&self, path: &Path) -> Result<String> {
        let _trace = crate::phase_trace::phase("input_hash");
        self.hash_inner(path, false).map(|(hash, _)| hash)
    }

    /// Small tree-guard files share one memo lookup per root. The row must
    /// still match the content walk's fresh stat; misses keep the usual settle
    /// and read checks, without making a workspace file a key input.
    fn guard_file_hash_from_metadata(
        &self,
        path: &Path,
        metadata: &std::fs::Metadata,
        observed_ns: i64,
        memoised: &HashMap<FileFingerprint, String>,
    ) -> Result<String> {
        #[cfg(unix)]
        {
            if self.cache.is_none() || absolute_path(path).to_str().is_none() {
                return self.hash_unkeyed(path);
            }
            let observed = ObservedFingerprint {
                fingerprint: FileFingerprint {
                    path: absolute_path(path).to_string_lossy().into_owned(),
                    size: i64::try_from(metadata.len()).unwrap_or(i64::MAX),
                    mtime_ns: metadata_mtime_ns(metadata),
                    ctime_ns: metadata_ctime_ns(metadata),
                    inode: metadata_inode(metadata),
                },
                observed_ns,
            };
            self.guard_file_hash_observed(path, observed, memoised)
        }
        #[cfg(not(unix))]
        {
            let _ = (metadata, observed_ns, memoised);
            self.hash_unkeyed(path)
        }
    }

    #[cfg(test)]
    fn guard_file_hash(
        &self,
        path: &Path,
        memoised: &HashMap<FileFingerprint, String>,
    ) -> Result<String> {
        let observed_ns = wall_clock_ns();
        let metadata = std::fs::symlink_metadata(path)?;
        self.guard_file_hash_from_metadata(path, &metadata, observed_ns, memoised)
    }

    #[cfg(any(unix, test))]
    fn guard_file_hash_observed(
        &self,
        path: &Path,
        observed: ObservedFingerprint,
        memoised: &HashMap<FileFingerprint, String>,
    ) -> Result<String> {
        if !guard_file_memo_eligible(observed.fingerprint.size, observed.fingerprint.inode) {
            return self.hash_unkeyed(path);
        }
        let _trace = crate::phase_trace::phase("input_hash");
        if let Some(hash) = memoised.get(&observed.fingerprint) {
            self.record_hit();
            return Ok(hash.clone());
        }
        let hash = read_file_hash(path)?;
        self.record_miss(observed.fingerprint.size);
        // These rows also need a post-read check when key-input guarding is
        // unarmed; no workspace file joins that guard's bookkeeping.
        if FileFingerprint::from_path(path).is_ok_and(|after| after == observed.fingerprint) {
            self.pending_memo
                .borrow_mut()
                .push((observed, hash.clone()));
        }
        Ok(hash)
    }

    /// With `keyed`, the file is a key input and the too-new guard sees it.
    fn hash_inner(
        &self,
        path: &Path,
        keyed: bool,
    ) -> Result<(String, Option<ObservedFingerprint>)> {
        let Some(cache) = &self.cache else {
            // Read before any stat and before the bytes, so it is no later
            // than whichever stamp is returned.
            let observed_ns = wall_clock_ns();
            let observed = |fingerprint| ObservedFingerprint {
                fingerprint,
                observed_ns,
            };
            if !keyed || self.too_new.invocation_start_ns == 0 {
                let hash = hash_file(path)?;
                return Ok((hash, FileFingerprint::from_path(path).ok().map(observed)));
            }
            let Ok(before) = FileFingerprint::from_path(path).map(observed) else {
                // No stamp before the read: whatever follows it is too new.
                let hash = read_file_hash(path)?;
                let after = FileFingerprint::from_path(path).ok();
                if after.is_some() {
                    self.too_new.saw_too_new.set(true);
                }
                return Ok((hash, after.map(observed)));
            };
            self.note_too_new(&before.fingerprint);
            let hash = read_file_hash(path)?;
            let (observed, _) = self.restat_after_read(path, before, true);
            return Ok((hash, Some(observed)));
        };

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

        if keyed {
            self.note_too_new(fingerprint);
        }

        if fingerprint.size < MIN_PERSISTED_HASH_BYTES {
            let hash = read_file_hash(path)?;
            self.record_miss(fingerprint.size);
            let (observed, _) = self.restat_after_read(path, observed, keyed);
            return Ok((hash, Some(observed)));
        }

        // A hash from the daemon or the memo belongs to this stamp; no read
        // here can fall between the stat and the bytes.
        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(observed)));
        }

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

        let hash = read_file_hash(path)?;
        self.record_miss(fingerprint.size);
        let (observed, unchanged) = self.restat_after_read(path, observed, keyed);
        if unchanged {
            self.pending_memo
                .borrow_mut()
                .push((observed.clone(), hash.clone()));
        }
        Ok((hash, Some(observed)))
    }

    /// Stat `path` again after reading the bytes `before` was taken for, when
    /// the guard is armed. A write between the two stats means the bytes may
    /// belong to neither stamp. A key input (`keyed`) then counts as too new,
    /// and `before`, which no longer matches the file, stays among the
    /// guarded inputs so that no later check can excuse it; any other file
    /// only loses its memo row. Returns the fingerprint to report for the
    /// read, the later one when they differ (still observed when `before`
    /// was), and whether they agreed.
    fn restat_after_read(
        &self,
        path: &Path,
        before: ObservedFingerprint,
        keyed: bool,
    ) -> (ObservedFingerprint, bool) {
        if self.too_new.invocation_start_ns == 0 {
            return (before, true);
        }
        match FileFingerprint::from_path(path) {
            Ok(after) if after == before.fingerprint => (before, true),
            Ok(after) => {
                if keyed {
                    self.too_new.saw_too_new.set(true);
                    self.guard_input(&before);
                }
                let observed_ns = before.observed_ns;
                (
                    ObservedFingerprint {
                        fingerprint: after,
                        observed_ns,
                    },
                    false,
                )
            }
            // Gone since the read: `before` fails any later check.
            Err(_) => {
                if keyed {
                    self.too_new.saw_too_new.set(true);
                }
                (before, false)
            }
        }
    }

    /// Classify how this source uses `var` (see [`source_env_dep_use`]).
    /// Decisions are keyed by the already-computed content hash, so warm key
    /// construction can reuse them without opening the source again (#557).
    fn env_dep_use(&self, path: &Path, var: &str) -> Result<SourceEnvDepUse> {
        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.env_dep_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_env_dep_use(path, var, &recent.hash)
    }

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

        // Rows written by another scanner version are invisible, so a scanner
        // fix reclassifies files that did not change.
        if let Some(cache) = &self.cache {
            match cache.get_source_env_dep_use(content_hash, var, SOURCE_ENV_DEP_SCANNER_VERSION) {
                Ok(Some(code)) => {
                    if let Some(result) = SourceEnvDepUse::from_memo_code(code) {
                        self.env_dep_uses.borrow_mut().insert(key, result);
                        return Ok(result);
                    }
                }
                Ok(None) => {}
                Err(error) => {
                    tracing::debug!("env-use cache lookup failed: {error}");
                }
            }
        }

        self.scan_env_dep_use(path, var, content_hash)
    }

    fn scan_env_dep_use(
        &self,
        path: &Path,
        var: &str,
        content_hash: &str,
    ) -> Result<SourceEnvDepUse> {
        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_env_dep_use(&source, var);
        if let Some(cache) = &self.cache
            && let Err(error) = cache.put_source_env_dep_use(
                content_hash,
                var,
                SOURCE_ENV_DEP_SCANNER_VERSION,
                result.memo_code(),
            )
        {
            tracing::debug!("env-use cache update failed: {error}");
        }
        self.env_dep_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 ObservedFingerprint {
            fingerprint,
            observed_ns,
        } = match ObservedFingerprint::from_path(path) {
            Ok(observed) => observed,
            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. `v8`: v1/v2 rows used older
        // identity definitions, v3 predates the fail-closed ELF gate, v4
        // predates the GCC Mach-O LTO gate, v5 predates admitting
        // DWARF-bearing Mach-O members, and v6 predates accepting the blank
        // `//` header GNU `ar` writes (a v5 or v6 row would keep serving the
        // path-bound digest of an unchanged archive). v7 predates accepting
        // ELF members in BSD archives. 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((
            ObservedFingerprint {
                fingerprint: key,
                observed_ns,
            },
            hash.clone(),
        ));
        Ok(hash)
    }

    /// Memoised hashes for many stamps in one lookup, keyed by path. Nothing
    /// memoised, or no index, reads as an empty map: every file is hashed.
    fn memoised_hashes<'a>(
        &self,
        stamps: impl Iterator<Item = &'a FileFingerprint>,
    ) -> HashMap<String, String> {
        let Some(cache) = &self.cache else {
            return HashMap::new();
        };
        let stamps: Vec<&FileFingerprint> = stamps.collect();
        cache.get_many(&stamps).unwrap_or_else(|error| {
            tracing::debug!("file hash memo batch lookup failed: {error}");
            HashMap::new()
        })
    }

    /// A header's content hash, from the daemon's prefetch or the memo when
    /// either has this exact stamp, else read and queued for the memo.
    ///
    /// Unlike [`hash`](Self::hash), small files are memoised too: a header
    /// is read by every unit that includes it, so the lookup is paid back
    /// many times. [`flush_memo`](Self::flush_memo) still holds back any file
    /// changed too recently, when `observed`, to trust its stamp. The
    /// bookkeeping matches `hash`, so the too-new guard and later
    /// revalidation see these files.
    fn header_hash(
        &self,
        path: &Path,
        observed: &ObservedFingerprint,
        memoised: &HashMap<String, String>,
    ) -> Result<String> {
        if self.cache.is_none() {
            return self.hash(path);
        }
        let fingerprint = &observed.fingerprint;
        let prefetched = self.prefetched.borrow().get(fingerprint).map(|prefetched| {
            (
                prefetched.hash.clone(),
                prefetched.cache_hit,
                prefetched.bytes_hashed,
            )
        });
        let (hash, reported) = if let Some((hash, cache_hit, bytes_hashed)) = prefetched {
            if cache_hit {
                self.record_hit();
            } else {
                self.record_miss_count();
                self.record_miss_bytes(bytes_hashed);
            }
            (hash, observed.clone())
        } else if let Some(hash) = memoised.get(&fingerprint.path) {
            self.record_hit();
            (hash.clone(), observed.clone())
        } else {
            let hash = read_file_hash(path)?;
            self.record_miss(fingerprint.size);
            let (reported, unchanged) = self.restat_after_read(path, observed.clone(), true);
            if unchanged {
                self.pending_memo
                    .borrow_mut()
                    .push((observed.clone(), hash.clone()));
            }
            (hash, reported)
        };
        self.guard_input(&reported);
        self.recent_hashes.borrow_mut().insert(
            absolute_path(path),
            RecentHash {
                hash: hash.clone(),
                fingerprint: Some(reported.fingerprint),
            },
        );
        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).
///
/// A compiler panic is the exception. rustc prints the panic first, then a
/// generic "error: the compiler unexpectedly panicked" banner, and only the
/// panic's message says what went wrong, so that message wins.
pub(crate) fn first_rustc_error_line(stderr: &str) -> Option<&str> {
    let mut fallback = None;
    let mut lines = stderr.lines();
    while let Some(line) = lines.next() {
        if line.trim().is_empty() {
            continue;
        }
        if is_panic_header(line)
            && let Some(message) = lines.clone().find(|next| !next.trim().is_empty())
        {
            return Some(message);
        }
        // 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
}

/// `thread 'rustc' panicked at compiler/…/source_map.rs:221:14:`, the line
/// before a panic's message. Newer toolchains add the thread id after the name.
fn is_panic_header(line: &str) -> bool {
    line.starts_with("thread '") && line.contains(" panicked at ")
}

/// 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.
/// `rustc -vV` of `rustc`, as the cache key reads it (cached per binary), or
/// `None` when it cannot be run.
pub(crate) fn rustc_version_text(rustc: &Path) -> Option<String> {
    get_rustc_version(rustc).ok()
}

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, env: &KeyEnv) -> Result<String> {
    clippy_identity_in(
        driver,
        |name| env.var_os(name),
        env.cwd().map(Path::to_path_buf),
    )
}

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());
    }
    default_rustc_sysroot(&args.rustc)
}

/// `rustc --print sysroot` without `--sysroot`: the toolchain's own sysroot,
/// file-cached like the version probe.
fn default_rustc_sysroot(rustc: &Path) -> Option<PathBuf> {
    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))
}

/// Where rustc looks first for a linker named without a directory, such as
/// `-C linker=rust-lld.exe`: the tool directory of an explicit `--sysroot`,
/// then that of the toolchain's own sysroot. rustc puts these before `PATH`
/// for the linker it runs. In a double-wrapper invocation the sysroot is
/// the inner rustc's, like the host triple. Without the toolchain's sysroot
/// the lookup could find a different linker than rustc, so that is an error.
fn rustc_tool_dirs(args: &RustcArgs, host: &str) -> Result<Vec<PathBuf>> {
    let rustc = args.inner_rustc.as_deref().unwrap_or(&args.rustc);
    let sysroot = default_rustc_sysroot(rustc).context("rustc --print sysroot failed")?;
    Ok(args
        .sysroot
        .iter()
        .cloned()
        .chain([sysroot])
        .map(|sysroot| crate::native_link_key::rustc_tool_dir(&sysroot, host))
        .collect())
}

/// The libraries rustc may load for the codegen backend `name`, with their
/// content hashes, under an explicit `--sysroot` and under the toolchain's own
/// sysroot. Both are hashed because which one rustc searches first depends on
/// its release. Finding none is an error, so the compile is not cached under a
/// key that describes no backend.
fn toolchain_codegen_backends(
    args: &RustcArgs,
    rustc_version: &str,
    name: &str,
    file_hasher: &FileHasher,
) -> Result<Vec<(String, String)>> {
    let host = rustc_host_triple(rustc_version).context("rustc -vV reports no host")?;
    let sysroots = args
        .sysroot
        .iter()
        .cloned()
        .chain(default_rustc_sysroot(&args.rustc));
    let found = codegen_backend_libraries(sysroots, host, name, file_hasher)?;
    anyhow::ensure!(
        !found.is_empty(),
        "codegen backend {name} is not installed in the toolchain"
    );
    Ok(found)
}

/// `{DLL_PREFIX}rustc_codegen_<name>[-<release>]{DLL_SUFFIX}` in each
/// sysroot's `lib/rustlib/<host>/codegen-backends`, where rustc looks for a
/// backend it loads by name, as (file name, content hash) in sysroot order.
fn codegen_backend_libraries(
    sysroots: impl IntoIterator<Item = PathBuf>,
    host: &str,
    name: &str,
    file_hasher: &FileHasher,
) -> Result<Vec<(String, String)>> {
    let stem = format!("rustc_codegen_{name}");
    let mut found = Vec::new();
    for sysroot in sysroots {
        let directory = sysroot
            .join("lib")
            .join("rustlib")
            .join(host)
            .join("codegen-backends");
        let entries = match std::fs::read_dir(&directory) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            entries => entries.with_context(|| format!("listing {}", directory.display()))?,
        };
        let mut libraries = BTreeMap::new();
        for entry in entries {
            let path = entry?.path();
            if let Some(library) = path
                .file_name()
                .and_then(|file| file.to_str())
                .filter(|file| is_codegen_backend_library(file, &stem))
            {
                libraries.insert(library.to_string(), path.clone());
            }
        }
        for (library, path) in libraries {
            let content = file_hasher
                .hash(&path)
                .with_context(|| format!("hashing codegen backend {}", path.display()))?;
            found.push((library, content));
        }
    }
    Ok(found)
}

/// Whether `file` is a library rustc loads for the backend whose library
/// stem is `stem` (`rustc_codegen_cranelift`), bare or release-suffixed.
fn is_codegen_backend_library(file: &str, stem: &str) -> bool {
    file.strip_prefix(std::env::consts::DLL_PREFIX)
        .and_then(|file| file.strip_suffix(std::env::consts::DLL_SUFFIX))
        .and_then(|file| file.strip_prefix(stem))
        .is_some_and(|release| release.is_empty() || release.starts_with('-'))
}

/// 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`]) and the installed toolchains
/// (see [`installed_toolchains_fingerprint`]).
fn tool_version_cache_path(binary: &Path, prefix: &str) -> Option<std::path::PathBuf> {
    tool_version_cache_path_in(binary, prefix, std::env::var_os("PATH").as_deref())
}

/// [`tool_version_cache_path`] with `PATH` given.
fn tool_version_cache_path_in(
    binary: &Path,
    prefix: &str,
    path_var: Option<&OsStr>,
) -> Option<std::path::PathBuf> {
    let canon = std::fs::canonicalize(program_path(binary, path_var)?).ok()?;
    let mtime = std::fs::metadata(&canon)
        .ok()?
        .modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs();
    let rustup_home = rustup_home();
    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_home
                .as_ref()
                .map(|home| home.join("settings.toml"))
                .as_deref(),
        ),
        installed_toolchains_fingerprint(
            rustup_home
                .as_ref()
                .map(|home| home.join("toolchains"))
                .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
}

/// Each installed toolchain's own `bin/rustc`, by name, mtime and size.
///
/// `rustup update nightly` replaces the toolchain behind an unchanged shim
/// and an unchanged selection, so neither the shim's mtime nor
/// [`toolchain_selector_fingerprint`] moves, and the old `rustc -vV` would
/// keep keying entries the new compiler cannot read (#1406). Every
/// installed toolchain is folded rather than the selected one, so this
/// needs none of rustup's resolution rules: a directory read and one stat
/// per toolchain. Installing, updating, removing or rebuilding a linked
/// toolchain re-probes every tool once.
fn installed_toolchains_fingerprint(toolchains: Option<&Path>) -> String {
    let Some(entries) = toolchains.and_then(|dir| std::fs::read_dir(dir).ok()) else {
        return String::new();
    };
    let rustc = format!("rustc{}", std::env::consts::EXE_SUFFIX);
    let mut stamps: Vec<String> = entries
        .filter_map(|entry| entry.ok())
        .map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            // `metadata` follows a linked toolchain to its build directory.
            match std::fs::metadata(entry.path().join("bin").join(&rustc)) {
                Ok(meta) => {
                    let mtime = meta
                        .modified()
                        .ok()
                        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
                        .map_or(0, |since| since.as_nanos());
                    format!("{name}={mtime}:{}", meta.len())
                }
                Err(_) => format!("{name}=none"),
            }
        })
        .collect();
    stamps.sort();
    stamps.join(";")
}

/// `$RUSTUP_HOME` (or its `~/.rustup` default): `settings.toml` records the
/// `rustup default` toolchain, `toolchains/` holds the installed ones.
fn rustup_home() -> Option<std::path::PathBuf> {
    std::env::var_os("RUSTUP_HOME")
        .map(std::path::PathBuf::from)
        .or_else(|| dirs::home_dir().map(|home| home.join(".rustup")))
}

/// 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.
pub(crate) 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,
    env: &KeyEnv,
) -> 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 deployment_target = env.var("MACOSX_DEPLOYMENT_TARGET");
        let identity = sdk_probe(env.var("SDKROOT"))
            .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.
/// It gets the selected linker, the MSVC architecture and rustc's host.
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, &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);
    // rustc runs `rust-lld` as lld-link only for an lld-link flavor: one
    // given with `-C linker-flavor`, or inferred from the file stem, which
    // rustc compares case-sensitively. Otherwise it runs it without
    // `-flavor` and the link fails. The identity is the banner, the same as
    // a real lld-link's, so such a unit must not borrow that key.
    // `-C linker-features` can turn LLD off and is not modeled.
    if let Some(linker) = linker
        && crate::native_link_key::is_rust_lld(linker)
    {
        let as_lld_link = match args.get_codegen_opt("linker-flavor") {
            Some(flavor) => matches!(flavor, "lld-link" | "msvc-lld"),
            None => linker.file_stem().is_some_and(|stem| stem == "rust-lld"),
        };
        if !as_lld_link || args.get_codegen_opt("linker-features").is_some() {
            anyhow::bail!(
                "rustc may not run {} as lld-link; passing through",
                linker.display()
            );
        }
    }
    let identity = probe(linker, architecture, host)
        .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> {
    resolve_in(name, &std::env::var_os("PATH")?)
}

/// The first file named `name` in `path_var` that a spawn could run: on
/// Unix, one with an execute bit, as `execvp` skips the others.
fn resolve_in(name: &str, path_var: &OsStr) -> Option<std::path::PathBuf> {
    std::env::split_paths(path_var)
        .map(|dir| dir.join(name))
        .find(|p| runnable_file(p))
}

fn runnable_file(path: &Path) -> bool {
    let Ok(metadata) = std::fs::metadata(path) else {
        return false;
    };
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        metadata.is_file() && metadata.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        metadata.is_file()
    }
}

/// The file a spawn of `binary` runs: on Unix a bare name is searched on
/// `path_var` as `execvp` would, anything with a directory is left as it is.
/// Cargo hands the wrapper a bare `rustc` when a toolchain's `bin` directory
/// is on PATH without rustup's proxy, and canonicalizing that name against
/// the working directory fails. Windows searches the wrapper's own directory
/// and adds `.exe` first, so a bare name there is not resolved and the
/// caller runs the tool as before.
fn program_path<'a>(binary: &'a Path, path_var: Option<&OsStr>) -> Option<Cow<'a, Path>> {
    let mut components = binary.components();
    match (components.next(), components.next()) {
        (Some(std::path::Component::Normal(name)), None) => {
            bare_program_path(name, path_var).map(Cow::Owned)
        }
        _ => Some(Cow::Borrowed(binary)),
    }
}

/// One function with a cfg block per platform, so the Linux mutation lane
/// mutates the body it compiles and tests.
fn bare_program_path(name: &OsStr, path_var: Option<&OsStr>) -> Option<std::path::PathBuf> {
    #[cfg(unix)]
    {
        resolve_in(name.to_str()?, path_var?)
    }
    #[cfg(not(unix))]
    {
        let _ = (name, path_var);
        None
    }
}

#[cfg(test)]
mod tests;