kache 1.2.2

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
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
use super::*;
use crate::args::RustcArgs;
use crate::test_support::process_state_test_lock;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// The probe gets the linker `-C linker` names, the MSVC architecture and
/// rustc's host, whose tool directory rustc searches for that linker.
#[test]
fn native_windows_msvc_probe_gets_linker_architecture_and_host() {
    let bin = RustcArgs::parse(&[
        "rustc".into(),
        "--crate-type=bin".into(),
        "src/main.rs".into(),
        "-Clinker=rust-lld.exe".into(),
    ])
    .unwrap();
    let mut seen = None;
    fold_native_windows_msvc_identity(
        &mut blake3::Hasher::new(),
        &bin,
        WINDOWS_RUSTC_VERSION,
        true,
        |linker, architecture, host| {
            seen = Some((
                linker.map(Path::to_path_buf),
                architecture.to_string(),
                host.to_string(),
            ));
            Ok("identity".into())
        },
    )
    .unwrap();
    assert_eq!(
        seen,
        Some((
            Some(PathBuf::from("rust-lld.exe")),
            "x64".to_string(),
            "x86_64-pc-windows-msvc".to_string()
        ))
    );
}

#[test]
fn rust_lld_keys_only_with_a_flavor_that_runs_it_as_lld_link() {
    let fold = |flags: &[&str]| {
        let mut argv: Vec<String> = ["rustc", "--crate-type=bin", "src/main.rs"]
            .map(String::from)
            .to_vec();
        argv.extend(flags.iter().map(|flag| flag.to_string()));
        let args = RustcArgs::parse(&argv).unwrap();
        let mut probed = false;
        let result = fold_native_windows_msvc_identity(
            &mut blake3::Hasher::new(),
            &args,
            WINDOWS_RUSTC_VERSION,
            true,
            |_, _, _| {
                probed = true;
                Ok("identity".into())
            },
        );
        (result, probed)
    };
    for flags in [
        &["-Clinker=rust-lld.exe"][..],
        &["-Clinker=rust-lld"],
        &["-Clinker=rust-lld.exe", "-Clinker-flavor=lld-link"],
        &["-Clinker=rust-lld.exe", "-Clinker-flavor=msvc-lld"],
        &["-Clinker=RUST-LLD.EXE", "-Clinker-flavor=lld-link"],
        &["-Clinker-flavor=msvc"],
    ] {
        let (result, probed) = fold(flags);
        assert!(result.is_ok() && probed, "{flags:?}");
    }
    for flags in [
        &["-Clinker=rust-lld.exe", "-Clinker-flavor=msvc"][..],
        &["-Clinker=rust-lld.exe", "-Clinker-flavor=gcc"],
        // rustc infers the flavor from the stem case-sensitively.
        &["-Clinker=RUST-LLD.EXE"],
        &[
            "-Clinker=rust-lld.exe",
            "-Clinker-flavor=lld-link",
            "-Clinker-features=-lld",
        ],
    ] {
        let (result, probed) = fold(flags);
        let error = format!("{:#}", result.unwrap_err());
        assert!(error.contains("as lld-link"), "{flags:?}: {error}");
        assert!(!probed, "{flags:?}");
    }
}

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

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

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

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

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

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

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

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

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

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

#[test]
fn the_sdk_probe_gets_sdkroot_from_the_snapshot() {
    let bin = parsed_linked_bin(None);
    let probed = |env: &KeyEnv| {
        let mut sdkroot = None;
        fold_native_link_runtime_identity(
            &mut blake3::Hasher::new(),
            &bin,
            DARWIN_RUSTC_VERSION,
            false,
            true,
            |_| unreachable!("macOS fold must not probe Linux CRT"),
            |value| {
                sdkroot = Some(value);
                Ok("sdk".to_string())
            },
            env,
        )
        .unwrap();
        sdkroot.expect("the SDK was probed")
    };
    assert_eq!(
        probed(&env_with("SDKROOT", "/sdk")).as_deref(),
        Some("/sdk")
    );
    assert_eq!(probed(&KeyEnv::default()), None);
}

/// An unremapped build bakes its working directory into DWARF, so the
/// snapshot's cwd is part of its identity.
#[test]
fn unremapped_identity_folds_the_snapshot_cwd() {
    let args = RustcArgs::parse(&["rustc".to_string(), "lib.rs".to_string()]).unwrap();
    let fold = |cwd: Option<&str>| {
        let mut hasher = blake3::Hasher::new();
        let env = KeyEnv::from_parts([] as [(&str, &str); 0], cwd.map(PathBuf::from));
        fold_unremapped_path_identity(&mut hasher, &args, &PathNormalizer::empty(), &env);
        hasher.finalize()
    };
    assert_ne!(fold(Some("/work/a")), fold(Some("/work/b")));
    assert_ne!(fold(Some("/work/a")), fold(None));
    assert_eq!(fold(Some("/work/a")), fold(Some("/work/a")));
}

fn hash_unremapped(args: &RustcArgs, normalizer: &PathNormalizer, env: &KeyEnv) -> blake3::Hash {
    let mut hasher = blake3::Hasher::new();
    fold_unremapped_path_identity(&mut hasher, args, normalizer, env);
    hasher.finalize()
}

fn normalizer_for(target: &std::path::Path, base: &std::path::Path) -> PathNormalizer {
    PathNormalizer::empty()
        .with_target_dir(Some(target))
        .with_base_dirs(&[base.to_string_lossy().into_owned()])
}

/// A registry crate built by trybuild records its package directory, not the
/// per-worktree target directory. Two targets must share that key. `OUT_DIR`
/// is recorded when the crate includes it, and a coverage build still folds
/// a target nothing in the compile reaches.
#[test]
fn trybuild_folds_only_prefixes_the_artifact_reaches() {
    let dir = tempfile::tempdir().unwrap();
    let registry = dir.path().join("registry/src/dep-hash");
    std::fs::create_dir_all(registry.join("src")).unwrap();
    let target_a = dir.path().join("wt-a/target");
    let target_b = dir.path().join("wt-b/target");
    std::fs::create_dir_all(&target_a).unwrap();
    std::fs::create_dir_all(&target_b).unwrap();
    let registry = registry.canonicalize().unwrap();
    let target_a = target_a.canonicalize().unwrap();
    let target_b = target_b.canonicalize().unwrap();
    let source = registry.join("src/lib.rs");

    let trybuild = RustcArgs::parse(&[
        "rustc".into(),
        "--cfg".into(),
        "trybuild".into(),
        source.display().to_string(),
    ])
    .unwrap();
    assert!(trybuild.is_trybuild_unit());
    let env = KeyEnv::from_parts([] as [(&str, &str); 0], Some(registry.clone()));
    let shared = |target: &std::path::Path| {
        hash_unremapped(&trybuild, &normalizer_for(target, &registry), &env)
    };
    assert_eq!(
        shared(&target_a),
        shared(&target_b),
        "a target prefix the rmeta does not reach stays out of the key"
    );

    let out_a = target_a.join("debug/build/dep/out");
    let out_b = target_b.join("debug/build/dep/out");
    let with_out = |out: &std::path::Path, target: &std::path::Path| {
        let env = KeyEnv::from_parts([("OUT_DIR", out.to_str().unwrap())], Some(registry.clone()));
        hash_unremapped(&trybuild, &normalizer_for(target, &registry), &env)
    };
    assert_ne!(
        with_out(&out_a, &target_a),
        with_out(&out_b, &target_b),
        "OUT_DIR is inside the rmeta, so its prefix stays"
    );

    let coverage = RustcArgs::parse(&[
        "rustc".into(),
        "-C".into(),
        "instrument-coverage".into(),
        source.display().to_string(),
    ])
    .unwrap();
    assert!(coverage.skip_path_remap());
    assert!(!coverage.is_trybuild_unit());
    let covered = |target: &std::path::Path| {
        hash_unremapped(&coverage, &normalizer_for(target, &registry), &env)
    };
    assert_ne!(
        covered(&target_a),
        covered(&target_b),
        "coverage still folds a target prefix the compile does not reach"
    );
}

#[test]
fn trybuild_artifact_paths_join_a_relative_source_and_ignore_an_empty_out_dir() {
    let relative = RustcArgs::parse(&[
        "rustc".into(),
        "--cfg".into(),
        "trybuild".into(),
        "src/lib.rs".into(),
    ])
    .unwrap();
    let joined = trybuild_paths_in_the_artifact(
        &relative,
        &KeyEnv::from_parts(
            [] as [(&str, &str); 0],
            Some(std::path::PathBuf::from("/registry/dep")),
        ),
    );
    assert!(
        joined
            .iter()
            .any(|path| path == std::path::Path::new("/registry/dep/src/lib.rs"))
    );
    assert!(path_is_under(
        std::path::Path::new("/registry/dep/src/lib.rs"),
        "/registry/dep"
    ));
    assert!(!path_is_under(
        std::path::Path::new("/registry/dep/src/lib.rs"),
        "/registry/depot"
    ));

    let absolute = RustcArgs::parse(&[
        "rustc".into(),
        "--cfg".into(),
        "trybuild".into(),
        "/registry/dep/src/lib.rs".into(),
    ])
    .unwrap();
    let kept = trybuild_paths_in_the_artifact(
        &absolute,
        &KeyEnv::from_parts(
            [("OUT_DIR", "")],
            Some(std::path::PathBuf::from("/somewhere/else")),
        ),
    );
    assert!(
        kept.iter()
            .any(|path| path == std::path::Path::new("/registry/dep/src/lib.rs"))
    );
    assert_eq!(kept.len(), 2, "an empty OUT_DIR is not a path");
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// The verification switch comes from the snapshot. With it on, a
/// validated prediction is checked against the pre-pass, and the pass's
/// answer is used instead.
#[test]
fn prediction_verification_reads_the_snapshot() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    // Cargo and nextest set kache's own package and OUT_DIR on the test
    // process; this is a bare rustc unit.
    let _manifest = crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", None);
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", None);
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, "pub fn f() {}\n").unwrap();
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "x".to_string(),
        source.to_str().unwrap().to_string(),
        "--edition=2021".to_string(),
        "--emit=dep-info,metadata".to_string(),
    ])
    .unwrap();
    let db = dir.path().join("index.db");
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch(
            "CREATE TABLE entries (cache_key TEXT PRIMARY KEY, crate_name TEXT NOT NULL);",
        )
        .unwrap();
    let hasher = FileHasher::persistent(&db).with_input_predictions(true);
    let closure = DepInfo {
        source_files: vec![source.clone()],
        env_deps: Vec::new(),
    };
    let identity = rustc_prediction_identity(&args).unwrap();
    hasher.record_input_prediction(&identity, Some("x"), &closure, None);
    let resolve = |env: &KeyEnv| {
        let mut out = KeyOutputs::default();
        let inputs = resolve_key_inputs(&args, &hasher, "x", env, &mut out).unwrap();
        (inputs, out.used_prediction)
    };

    assert_eq!(resolve(&KeyEnv::default()), (Some(closure), true));
    let (verified, predicted) = resolve(&env_with("KACHE_VERIFY_INPUT_PREDICTIONS", "always"));
    assert!(!predicted, "the pre-pass answered, not the record");
    assert!(verified.is_some());
}

/// With no record and deferral allowed, the key stops instead of running
/// the pre-pass; the closure the wrapper hands back afterwards is used as
/// is.
#[test]
fn discovery_defers_to_the_compile_and_takes_the_emitted_closure() {
    let _lock = key_test_lock();
    // Exercise a unit without generated inputs. Cargo and nextest set
    // kache's own OUT_DIR on the test process, so clear it for this unit.
    let out_dir = std::env::var_os("OUT_DIR");
    // SAFETY: the key-test lock serialises environment edits.
    unsafe { std::env::remove_var("OUT_DIR") };
    struct RestoreOutDir(Option<std::ffi::OsString>);
    impl Drop for RestoreOutDir {
        fn drop(&mut self) {
            if let Some(value) = self.0.take() {
                // SAFETY: still under the key-test lock, dropped first.
                unsafe { std::env::set_var("OUT_DIR", value) };
            }
        }
    }
    let _restore = RestoreOutDir(out_dir);
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    let out_dir = dir.path().join("target/debug/deps");
    let args = RustcArgs::parse(
        &[
            "rustc",
            "--crate-name",
            "x",
            "src/lib.rs",
            "--edition",
            "2021",
            "--emit=dep-info,metadata",
            "--out-dir",
            &out_dir.display().to_string(),
        ]
        .iter()
        .map(|a| (*a).to_string())
        .collect::<Vec<_>>(),
    )
    .unwrap();
    assert!(
        rustc_shared_prediction_identity(&args).is_some(),
        "a target directory gives the unit a shared record identity"
    );
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch(
            "CREATE TABLE entries (cache_key TEXT PRIMARY KEY, crate_name TEXT NOT NULL);",
        )
        .unwrap();
    let on = FileHasher::persistent(&db)
        .with_input_predictions(true)
        .with_prediction_flights(Some(dir.path().join("cache")));

    set_defer_discovery(true);
    let deferred = resolve_key_inputs(
        &args,
        &on,
        "x",
        &KeyEnv::default(),
        &mut KeyOutputs::default(),
    );
    set_defer_discovery(false);
    let error = deferred.expect_err("no record and deferral allowed: no pre-pass");
    assert!(
        error.downcast_ref::<DeferredDiscovery>().is_some(),
        "{error:#}"
    );
    // A broken handoff must fail instead of waiting on our own flight.
    drop(on.take_discovery_flight());

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

/// The discovery flight names the unit whether or not predictions are on,
/// and stays off for a unit predictions cannot describe.
#[test]
fn discovery_flight_identity_names_the_unit_with_or_without_predictions() {
    // Identity helpers read cwd and environment, which other tests mutate.
    let _lock = key_test_lock();
    let _workspace = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(std::ffi::OsStr::new("/w/a")),
    );
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    let parse = |args: &[&str]| {
        RustcArgs::parse(&args.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
    };
    let out_dir = dir.path().join("target/debug/deps").display().to_string();
    let a = parse(&[
        "rustc",
        "--crate-name",
        "a",
        "src/a.rs",
        "--out-dir",
        &out_dir,
    ]);
    let b = parse(&[
        "rustc",
        "--crate-name",
        "b",
        "src/b.rs",
        "--out-dir",
        &out_dir,
    ]);
    let with_macro = parse(&[
        "rustc",
        "--crate-name",
        "a",
        "src/a.rs",
        "--out-dir",
        &out_dir,
        "--extern",
        "my_macro=/t/debug/deps/libmy_macro-3.so",
    ]);

    let off = FileHasher::persistent(&db);
    let a_off = discovery_flight_identity(&a, &off).expect("predictions off still names the unit");
    assert_eq!(
        a_off,
        rustc_shared_prediction_identity(&a).unwrap(),
        "the flight is the unit's shared identity"
    );
    assert_ne!(a_off, discovery_flight_identity(&b, &off).unwrap());
    assert!(rustc_shared_prediction_identity(&with_macro).is_none());
    assert_eq!(
        discovery_flight_identity(&with_macro, &off),
        rustc_prediction_identity(&with_macro),
        "a proc-macro dependent still gets a name: the flight is only a lock"
    );

    let on = FileHasher::persistent(&db).with_input_predictions(true);
    assert_eq!(
        discovery_flight_identity(&a, &on),
        prediction_discovery_identity(&a, &on),
        "with predictions on the flight is the record identity"
    );
    assert!(prediction_discovery_identity(&with_macro, &on).is_none());
    assert_eq!(
        discovery_flight_identity(&with_macro, &on),
        rustc_prediction_identity(&with_macro),
        "no record identity, so the unit's name serves as the flight"
    );

    // In a registry package the same unit shares its record under the
    // tree guard, so it flies under the shared identity.
    let _manifest = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(std::ffi::OsStr::new("/h/registry/src/index-1/a-1.0.0")),
    );
    let shared = rustc_shared_prediction_identity(&with_macro)
        .expect("a registry proc-macro dependent has a shared identity");
    assert_eq!(
        discovery_flight_identity(&with_macro, &off),
        Some(shared.clone())
    );
    assert_eq!(discovery_flight_identity(&with_macro, &on), Some(shared));
}

/// A crate the store has never held is a certain miss under any key, so
/// discovery defers even where no record can vouch for it: an OUT_DIR
/// unit, and a build with predictions off.
#[test]
fn a_crate_the_store_never_held_defers_discovery() {
    let _lock = key_test_lock();
    let out_dir = std::env::var_os("OUT_DIR");
    // SAFETY: the key-test lock serialises environment edits.
    unsafe { std::env::set_var("OUT_DIR", "/t/debug/build/x-1/out") };
    struct RestoreOutDir(Option<std::ffi::OsString>);
    impl Drop for RestoreOutDir {
        fn drop(&mut self) {
            // SAFETY: still under the key-test lock, dropped first.
            match self.0.take() {
                Some(value) => unsafe { std::env::set_var("OUT_DIR", value) },
                None => unsafe { std::env::remove_var("OUT_DIR") },
            }
        }
    }
    let _restore = RestoreOutDir(out_dir);
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch(
            "CREATE TABLE entries (cache_key TEXT PRIMARY KEY, crate_name TEXT NOT NULL);",
        )
        .unwrap();
    let args = RustcArgs::parse(
        &[
            "rustc",
            "--crate-name",
            "x",
            "src/lib.rs",
            "--edition",
            "2021",
            "--emit=dep-info,metadata",
            "--out-dir",
            &dir.path().join("target/debug/deps").display().to_string(),
        ]
        .iter()
        .map(|a| (*a).to_string())
        .collect::<Vec<_>>(),
    )
    .unwrap();
    let deferred = |hasher: &FileHasher<'_>| {
        set_defer_discovery(true);
        let outcome = resolve_key_inputs(
            &args,
            hasher,
            "x",
            &KeyEnv::default(),
            &mut KeyOutputs::default(),
        );
        set_defer_discovery(false);
        outcome.is_err_and(|error| error.downcast_ref::<DeferredDiscovery>().is_some())
    };
    let flights = Some(dir.path().join("cache"));
    for predictions in [false, true] {
        let hasher = FileHasher::persistent(&db)
            .with_input_predictions(predictions)
            .with_prediction_flights(flights.clone());
        assert!(deferred(&hasher), "predictions={predictions}");
    }
    {
        // Scoped: the hasher holds the unit's discovery flight until it
        // is dropped, and the hashers below need to take it.
        let hasher = FileHasher::persistent(&db).with_prediction_flights(flights.clone());
        let not_allowed = resolve_key_inputs(
            &args,
            &hasher,
            "x",
            &KeyEnv::default(),
            &mut KeyOutputs::default(),
        );
        assert!(
            !not_allowed.is_err_and(|error| error.downcast_ref::<DeferredDiscovery>().is_some()),
            "the wrapper did not allow deferral"
        );
    }
    assert!(
        !deferred(&FileHasher::persistent(&db)),
        "without a flight nobody owns the unit, so nobody compiles first"
    );

    rusqlite::Connection::open(&db)
        .unwrap()
        .execute(
            "INSERT INTO entries (cache_key, crate_name) VALUES ('k', 'x')",
            [],
        )
        .unwrap();
    for predictions in [false, true] {
        let hasher = FileHasher::persistent(&db)
            .with_input_predictions(predictions)
            .with_prediction_flights(flights.clone());
        assert!(
            !deferred(&hasher),
            "an entry for the crate may match: predictions={predictions}"
        );
    }

    // Compiling while keying defers that case too, but not as a certain
    // miss: the wrapper still stops the compile if the emitted closure hits.
    let while_keying = |hasher: &FileHasher<'_>, defer: bool| {
        set_defer_discovery(defer);
        set_compile_while_keying(true);
        let outcome = resolve_key_inputs(
            &args,
            hasher,
            "x",
            &KeyEnv::default(),
            &mut KeyOutputs::default(),
        );
        set_compile_while_keying(false);
        set_defer_discovery(false);
        outcome.err().and_then(|error| {
            error
                .downcast_ref::<DeferredDiscovery>()
                .map(|d| d.miss_certain)
        })
    };
    {
        let hasher = FileHasher::persistent(&db).with_prediction_flights(flights.clone());
        assert_eq!(while_keying(&hasher, true), Some(false));
    }
    {
        let hasher = FileHasher::persistent(&db).with_prediction_flights(flights.clone());
        assert_eq!(
            while_keying(&hasher, false),
            None,
            "only with deferral allowed"
        );
    }
    assert_eq!(
        while_keying(&FileHasher::persistent(&db), true),
        None,
        "without a flight nobody owns the unit"
    );
}

/// Every build script is `build_script_build`; Cargo's `-C metadata` hash
/// is what tells them apart, and the presence probe must read it.
#[test]
fn a_unit_the_store_never_held_defers_even_when_its_name_is_taken() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch(
            "CREATE TABLE entries (cache_key TEXT PRIMARY KEY, crate_name TEXT NOT NULL,
                                       unit_id TEXT NOT NULL DEFAULT '');
                 INSERT INTO entries VALUES ('k', 'build_script_build', 'unit-a');",
        )
        .unwrap();
    let parse = |unit: &str| {
        RustcArgs::parse(
            &[
                "rustc",
                "--crate-name",
                "build_script_build",
                "build.rs",
                "--edition",
                "2021",
                "--emit=dep-info,link",
                "-C",
                &format!("metadata={unit}"),
                "--out-dir",
                &dir.path().join("target/debug/build").display().to_string(),
            ]
            .iter()
            .map(|a| (*a).to_string())
            .collect::<Vec<_>>(),
        )
        .unwrap()
    };
    let deferred = |args: &RustcArgs| {
        let hasher =
            FileHasher::persistent(&db).with_prediction_flights(Some(dir.path().join("cache")));
        set_defer_discovery(true);
        let outcome = resolve_key_inputs(
            args,
            &hasher,
            "build_script_build",
            &KeyEnv::default(),
            &mut KeyOutputs::default(),
        );
        set_defer_discovery(false);
        outcome.is_err_and(|error| error.downcast_ref::<DeferredDiscovery>().is_some())
    };
    assert!(
        deferred(&parse("unit-b")),
        "another unit of the same name is absent"
    );
    assert!(!deferred(&parse("unit-a")), "this unit was stored");
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch("INSERT INTO entries VALUES ('k2', 'build_script_build', '');")
        .unwrap();
    assert!(
        !deferred(&parse("unit-b")),
        "a row that never learned its unit stands for every unit of the name"
    );
}

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

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

    let on = FileHasher::persistent(&db).with_input_predictions(true);
    assert_eq!(
        predicted_key_inputs(&with_macro, &on, &mut None),
        Err(Rejection::NotEligible),
        "a proc-macro dependency with no package to digest is refused before any lookup"
    );
    if get_rustc_version(Path::new("rustc")).is_ok() {
        let mut tree = Some(TreeGuard {
            digest: "earlier".to_string(),
            walks: Vec::new(),
        });
        assert_eq!(
            predicted_key_inputs(&plain, &on, &mut tree),
            Err(Rejection::NoRecord),
            "an eligible invocation with nothing recorded falls back"
        );
        assert!(tree.is_none(), "only a guard this lookup took comes back");
    }
    let elsewhere = dir.path().join("elsewhere");
    let _path_unit =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(elsewhere.as_os_str()));
    assert_eq!(
        predicted_key_inputs(&plain, &on, &mut None),
        Err(Rejection::NotEligible),
        "a path package with no workspace to digest is refused before any lookup"
    );
}

/// Cargo hands rustc each proc-macro dependency as a dynamic library. That
/// finds a unit's own macros, not one an rlib re-exports, so it decides only
/// whether a registry unit needs the tree guard ([`needs_tree_guard`]).
#[test]
fn a_dynamic_library_extern_is_how_cargo_hands_over_a_proc_macro() {
    let dep = |path: &str| crate::args::ExternDep {
        name: "dep".to_string(),
        path: Some(PathBuf::from(path)),
    };
    let plain = vec![
        dep("/t/debug/deps/libserde-1.rlib"),
        dep("/t/debug/deps/libcore-2.rmeta"),
    ];
    assert!(!has_dylib_extern(&plain), "rlib and rmeta dependencies");
    assert!(!has_dylib_extern(&[]), "no dependencies");

    for macro_lib in [
        "/t/debug/deps/libmy_macro-3.so",
        "/t/debug/deps/libmy_macro-3.dylib",
        "/t/debug/deps/my_macro-3.dll",
    ] {
        let mut with_macro = plain.clone();
        with_macro.push(dep(macro_lib));
        assert!(has_dylib_extern(&with_macro), "{macro_lib}");
    }

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

/// A macro an rlib re-exports (`sqlx::migrate!`, `include_dir!`) reaches
/// rustc through the rlib alone, so every workspace or path unit takes the
/// guard. A registry package is the same files wherever it is built.
#[test]
fn every_workspace_or_path_unit_takes_the_tree_guard() {
    let dep = |path: &str| crate::args::ExternDep {
        name: "dep".to_string(),
        path: Some(PathBuf::from(path)),
    };
    let rlib = [dep("/t/debug/deps/libfacade-1.rlib")];
    let proc_macro = [dep("/t/debug/deps/libscan-2.so")];
    let member = Path::new("/w/kt");
    let registry = Path::new("/h/registry/src/index-1/kt-1.0.0");
    for (externs, manifest_dir, guarded, why) in [
        (&rlib[..], Some(member), true, "a member that links an rlib"),
        (&[][..], Some(member), true, "a member with no dependency"),
        (
            &proc_macro[..],
            Some(member),
            true,
            "a member with a proc macro",
        ),
        (
            &rlib[..],
            Some(registry),
            false,
            "a registry unit that links an rlib",
        ),
        (
            &proc_macro[..],
            Some(registry),
            true,
            "a registry unit with a proc macro",
        ),
        (
            &rlib[..],
            None,
            false,
            "no package: the dynamic-library rule",
        ),
        (&proc_macro[..], None, true, "no package, with a proc macro"),
    ] {
        assert_eq!(needs_tree_guard(externs, manifest_dir), guarded, "{why}");
    }
}

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

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

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

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

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

/// Where a unit's package lives, which decides how Cargo runs rustc.
#[derive(Clone, Copy)]
enum SamplePlace {
    /// A workspace member: run from the workspace root, relative source.
    Member,
    /// A path dependency outside the workspace root: run from its package
    /// root, absolute source.
    OutsideWorkspace,
    /// A registry package under the Cargo home, run the same way.
    Registry,
}

/// One Cargo unit, placed in a checkout by [`SampleUnit::in_checkout`].
struct SampleUnit {
    package: String,
    version: &'static str,
    place: SamplePlace,
    crate_name: &'static str,
    source: &'static str,
    crate_type: &'static str,
    target: Option<&'static str>,
}

/// What the wrapper sees for one unit: argv, the working directory as
/// `getcwd` reports it, and the environment Cargo sets.
struct SampleCall {
    args: RustcArgs,
    cwd: PathBuf,
    env: HashMap<&'static str, std::ffi::OsString>,
}

impl SampleCall {
    fn identity(&self) -> String {
        prediction_sample_identity(&self.args, Some(&self.cwd), |var| {
            self.env.get(var).cloned()
        })
    }

    fn verified(&self) -> bool {
        verifies_prediction(
            VerifyPredictions::Sampled,
            &self.args,
            Some(&self.cwd),
            |var| self.env.get(var).cloned(),
        )
    }
}

/// `path` as macOS `getcwd` spells it: `/tmp` is a symlink there.
fn physical(path: &str) -> String {
    match path.strip_prefix("/tmp/") {
        Some(rest) => format!("/private/tmp/{rest}"),
        None => path.to_string(),
    }
}

impl SampleUnit {
    /// This unit in the checkout at `root`, whose workspace is `rust/`,
    /// with its registry under `cargo_home`.
    ///
    /// Cargo hashes a registry package id the same way everywhere, but a
    /// path dependency outside the workspace root by its absolute path,
    /// and every member depending on one inherits that in its
    /// `-C metadata`. The metadata here does the same. A target spec is
    /// passed as an absolute path, as Cargo does.
    fn in_checkout(&self, root: &str, cargo_home: &str) -> SampleCall {
        let workspace = format!("{root}/rust");
        let package_dir = match self.place {
            SamplePlace::Member => format!("{workspace}/{}", self.package),
            SamplePlace::OutsideWorkspace => format!("{root}/{}", self.package),
            SamplePlace::Registry => format!(
                "{cargo_home}/registry/src/index.crates.io-0000/{}-{}",
                self.package, self.version
            ),
        };
        let (cwd, source, hashed) = match self.place {
            SamplePlace::Member => (
                workspace.clone(),
                format!("{}/{}", self.package, self.source),
                package_dir.clone(),
            ),
            SamplePlace::OutsideWorkspace => (
                package_dir.clone(),
                format!("{package_dir}/{}", self.source),
                package_dir.clone(),
            ),
            SamplePlace::Registry => (
                package_dir.clone(),
                format!("{package_dir}/{}", self.source),
                format!("{}-{}", self.package, self.version),
            ),
        };
        let metadata = blake3::hash(hashed.as_bytes()).to_hex()[..16].to_string();
        let deps = format!("{workspace}/target/debug/deps");
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            self.crate_name.to_string(),
            "--edition=2021".to_string(),
            source,
            "--error-format=json".to_string(),
            "--crate-type".to_string(),
            self.crate_type.to_string(),
            "--emit=dep-info,metadata,link".to_string(),
            "--cfg".to_string(),
            "feature=\"default\"".to_string(),
            "-C".to_string(),
            format!("metadata={metadata}"),
            "-C".to_string(),
            format!("extra-filename=-{metadata}"),
            "--out-dir".to_string(),
            deps.clone(),
            "-L".to_string(),
            format!("dependency={deps}"),
            "--extern".to_string(),
            format!("dep={deps}/libdep-0123456789abcdef.rmeta"),
        ];
        if let Some(target) = self.target {
            argv.push("--target".to_string());
            argv.push(if target.ends_with(".json") {
                format!("{workspace}/{target}")
            } else {
                target.to_string()
            });
        }
        let env = HashMap::from([
            ("CARGO_MANIFEST_DIR", package_dir.into()),
            ("CARGO_PKG_NAME", self.package.clone().into()),
            ("CARGO_PKG_VERSION", self.version.into()),
        ]);
        SampleCall {
            args: RustcArgs::parse(&argv).unwrap(),
            cwd: PathBuf::from(physical(&cwd)),
            env,
        }
    }
}

/// The units `sampled` picks in one checkout.
fn sampled_units(units: &[SampleUnit], root: &str, cargo_home: &str) -> Vec<usize> {
    units
        .iter()
        .enumerate()
        .filter(|(_, unit)| unit.in_checkout(root, cargo_home).verified())
        .map(|(i, _)| i)
        .collect()
}

/// Two checkouts of one project, as a perf gate builds base and head. The
/// base Cargo home sits behind a symlink, as anything under `/tmp` does on
/// macOS.
const SAMPLE_BASE: (&str, &str) = ("/scratch/base/hk", "/tmp/cargo");
const SAMPLE_HEAD: (&str, &str) = ("/scratch/head/hk", "/home/ci/.cargo");

/// A perf gate builds base and head in separate checkouts. Sampling by
/// the prediction identity checked different units in each, because that
/// identity folds the working directory and absolute paths: hk counted 7
/// checks against 2, and eza showed a significant speedup that was only 3
/// checks against none. Both checkouts must check the same units.
#[test]
fn prediction_sample_is_the_same_in_every_checkout() {
    let units: Vec<SampleUnit> = (0..VERIFY_PREDICTION_RATE * 8)
        .map(|i| SampleUnit {
            package: format!("pkg{i}"),
            version: "1.0.0",
            place: [
                SamplePlace::Member,
                SamplePlace::OutsideWorkspace,
                SamplePlace::Registry,
            ][i % 3],
            crate_name: ["alpha", "beta", "build_script_build", "delta"][i % 4],
            source: ["src/lib.rs", "src/main.rs", "build.rs", "src/lib.rs"][i % 4],
            crate_type: ["lib", "bin", "bin", "lib"][i % 4],
            target: [
                None,
                Some("aarch64-apple-darwin"),
                Some("specs/os.json"),
                None,
                None,
            ][i % 5],
        })
        .collect();
    for (i, unit) in units.iter().enumerate() {
        assert_eq!(
            unit.in_checkout(SAMPLE_BASE.0, SAMPLE_BASE.1).identity(),
            unit.in_checkout(SAMPLE_HEAD.0, SAMPLE_HEAD.1).identity(),
            "unit {i} must be sampled the same way in both checkouts"
        );
    }
    let in_base = sampled_units(&units, SAMPLE_BASE.0, SAMPLE_BASE.1);
    assert!(!in_base.is_empty(), "some unit must be checked");
    assert_eq!(in_base, sampled_units(&units, SAMPLE_HEAD.0, SAMPLE_HEAD.1));
}

/// A path dependency outside the workspace root, such as `rust/`
/// depending on `../proto`, gets a `-C metadata` that names the checkout,
/// and so does every member that depends on it. The sample must not read
/// it.
#[test]
fn prediction_sample_ignores_metadata_that_names_the_checkout() {
    for place in [SamplePlace::OutsideWorkspace, SamplePlace::Member] {
        let unit = SampleUnit {
            package: "proto".to_string(),
            version: "0.1.0",
            place,
            crate_name: "proto",
            source: "src/lib.rs",
            crate_type: "lib",
            target: None,
        };
        let base = unit.in_checkout(SAMPLE_BASE.0, SAMPLE_BASE.1);
        let head = unit.in_checkout(SAMPLE_HEAD.0, SAMPLE_HEAD.1);
        assert_ne!(
            base.args.get_codegen_opt("metadata"),
            head.args.get_codegen_opt("metadata")
        );
        assert_eq!(base.identity(), head.identity());
    }
}

/// Cargo names a registry package's root and its source through the Cargo
/// home as given, but `getcwd` resolves symlinks. Stripping only the
/// working directory left the source absolute behind a symlinked Cargo
/// home, and every registry unit sampled differently.
#[test]
fn prediction_sample_strips_the_package_root_as_cargo_spells_it() {
    let unit = SampleUnit {
        package: "serde".to_string(),
        version: "1.0.0",
        place: SamplePlace::Registry,
        crate_name: "serde",
        source: "src/lib.rs",
        crate_type: "lib",
        target: None,
    };
    let base = unit.in_checkout(SAMPLE_BASE.0, SAMPLE_BASE.1);
    assert!(base.cwd.starts_with("/private/tmp"));
    assert!(base.args.source_file.as_ref().unwrap().starts_with("/tmp"));
    assert_eq!(
        base.identity(),
        unit.in_checkout(SAMPLE_HEAD.0, SAMPLE_HEAD.1).identity()
    );
}

/// The same in every checkout must not mean one decision for a whole
/// crate name: every registry build script is `build_script_build` from
/// `build.rs` in its package root, and only its package tells them apart.
#[test]
fn prediction_sample_spreads_across_units_that_share_a_name() {
    let build_scripts: Vec<SampleUnit> = (0..VERIFY_PREDICTION_RATE * 20)
        .map(|i| SampleUnit {
            package: format!("pkg{i}"),
            version: "1.0.0",
            place: SamplePlace::Registry,
            crate_name: "build_script_build",
            source: "build.rs",
            crate_type: "bin",
            target: None,
        })
        .collect();
    let chosen = sampled_units(&build_scripts, SAMPLE_BASE.0, SAMPLE_BASE.1);
    assert!(
        (5..=40).contains(&chosen.len()),
        "about 1 in {VERIFY_PREDICTION_RATE} of {} should be checked, got {}",
        build_scripts.len(),
        chosen.len()
    );
    assert_eq!(
        chosen,
        sampled_units(&build_scripts, SAMPLE_HEAD.0, SAMPLE_HEAD.1),
        "another checkout checks the same build scripts"
    );

    // Each part of the unit's name separates it from its neighbours.
    let sample = |argv: &str, package: [&str; 2]| {
        let argv: Vec<String> = argv.split(' ').map(str::to_string).collect();
        let env = |var: &str| match var {
            "CARGO_PKG_NAME" => Some(package[0].into()),
            "CARGO_PKG_VERSION" => Some(package[1].into()),
            _ => None,
        };
        prediction_sample_identity(
            &RustcArgs::parse(&argv).unwrap(),
            Some(Path::new("/w")),
            env,
        )
    };
    let unit = "rustc --crate-name a a.rs --crate-type lib";
    let package = ["a", "1.0.0"];
    let base = sample(unit, package);
    for (part, other) in [
        ("package name", sample(unit, ["b", "1.0.0"])),
        ("package version", sample(unit, ["a", "2.0.0"])),
        (
            "crate type",
            sample(&format!("{unit} --crate-type rlib"), package),
        ),
        ("test harness", sample(&format!("{unit} --test"), package)),
        (
            "target",
            sample(&format!("{unit} --target wasm32-wasip1"), package),
        ),
        (
            "cfg",
            sample(&format!("{unit} --cfg feature=\"std\""), package),
        ),
        (
            "crate name",
            sample("rustc --crate-name b a.rs --crate-type lib", package),
        ),
        (
            "source",
            sample("rustc --crate-name a b.rs --crate-type lib", package),
        ),
    ] {
        assert_ne!(other, base, "{part} must separate units");
    }
    assert_ne!(
        sample(&format!("{unit} --target /w/a.json"), package),
        sample(&format!("{unit} --target /w/b.json"), package),
        "target specs must separate units"
    );
}

/// Cargo passes a target spec as an absolute path; rustc names the target
/// by the file's stem.
#[test]
fn target_name_is_a_spec_file_stem() {
    assert_eq!(target_name("wasm32-wasip1"), "wasm32-wasip1");
    assert_eq!(target_name("/scratch/base/hk/specs/os.json"), "os");
    assert_eq!(target_name("os.json"), "os");
}

/// The source a unit is sampled by is the one every checkout spells the
/// same way.
#[test]
fn checkout_relative_drops_the_first_root_the_path_is_under() {
    let package = Path::new("/tmp/cargo/registry/src/index/serde-1.0.0");
    let resolved = Path::new("/private/tmp/cargo/registry/src/index/serde-1.0.0");
    let source = package.join("src/lib.rs");
    let relative = Path::new("src/lib.rs");
    assert_eq!(
        checkout_relative(&source, &[Some(package), Some(resolved)]),
        relative
    );
    assert_eq!(
        checkout_relative(&source, &[Some(resolved), Some(package)]),
        relative
    );
    assert_eq!(checkout_relative(&source, &[None, Some(resolved)]), source);
    assert_eq!(checkout_relative(&source, &[]), source);
    assert_eq!(checkout_relative(relative, &[Some(package)]), relative);
    assert_eq!(
        checkout_relative(Path::new("/elsewhere/src/lib.rs"), &[Some(package)]),
        Path::new("/elsewhere/src/lib.rs")
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// A build script's `OUT_DIR` identifies the unit, not the build
/// directory: the same unit in two target directories shares a record,
/// two feature sets keep their own, and a value outside the target
/// directory (or one that escapes it) is left exactly as it was.
#[test]
fn shared_predictions_place_out_dir_inside_its_target() {
    let vars = |target: &str, out_dir: &str| {
        let pairs = vec![
            (
                std::ffi::OsString::from("OUT_DIR"),
                std::ffi::OsString::from(out_dir),
            ),
            (
                std::ffi::OsString::from("CARGO_MANIFEST_DIR"),
                std::ffi::OsString::from("/registry/libc-0.2"),
            ),
        ];
        shared_prediction_vars(pairs.into_iter(), Path::new(target))
    };
    let value = |v: &[(std::ffi::OsString, std::ffi::OsString)], name: &str| {
        v.iter()
            .find(|(n, _)| n == name)
            .map(|(_, value)| value.to_string_lossy().into_owned())
            .unwrap()
    };

    let a = vars(
        "/a/target",
        "/a/target/debug/build/libc-abc123def4567890/out",
    );
    let b = vars(
        "/b/target",
        "/b/target/debug/build/libc-abc123def4567890/out",
    );
    assert_eq!(value(&a, "OUT_DIR"), value(&b, "OUT_DIR"));
    assert_eq!(
        value(&a, "OUT_DIR"),
        "kache-target-relative:debug/build/libc-abc123def4567890/out"
    );
    assert_eq!(
        value(&a, "CARGO_MANIFEST_DIR"),
        "/registry/libc-0.2",
        "only OUT_DIR is rewritten"
    );
    let other_features = vars(
        "/a/target",
        "/a/target/debug/build/libc-0123456789abcdef/out",
    );
    assert_ne!(
        value(&a, "OUT_DIR"),
        value(&other_features, "OUT_DIR"),
        "Cargo's metadata hash still separates two feature sets"
    );
    for outside in [
        "/elsewhere/build/libc-abc123def4567890/out",
        "/a/target/../sneaky/out",
    ] {
        assert_eq!(
            value(&vars("/a/target", outside), "OUT_DIR"),
            outside,
            "a value the target directory does not contain is left alone"
        );
    }
    assert!(
        target_relative_env_value(
            std::ffi::OsStr::new("/a/target/debug/build/x/out"),
            Path::new("/a/target")
        )
        .is_some()
    );
    assert!(
        target_relative_env_value(std::ffi::OsStr::new("/a/target"), Path::new("/a/target"))
            .is_some(),
        "the target directory itself is relative to itself"
    );
}

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

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

const REGISTRY_PACKAGE_DIR: &str = "/h/registry/src/index-1/kt-1.0.0";

fn os_vars(pairs: &[(&str, &str)]) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
    pairs
        .iter()
        .map(|(name, value)| (name.into(), value.into()))
        .collect()
}

/// An absolute target directory for checkout `name` on any platform.
fn checkout_target(name: &str) -> String {
    if cfg!(windows) {
        format!("C:/{name}/target")
    } else {
        format!("/{name}/target")
    }
}

fn registry_unit_args(checkout: &str, externs: &[&str]) -> RustcArgs {
    let target = checkout_target(checkout);
    let mut argv = vec![
        "rustc".to_string(),
        "--crate-name".to_string(),
        "kt".to_string(),
        format!("{REGISTRY_PACKAGE_DIR}/src/lib.rs"),
        "--out-dir".to_string(),
        format!("{target}/debug/deps"),
    ];
    for name in externs {
        argv.push("--extern".to_string());
        argv.push(format!("{name}={target}/debug/deps/lib{name}-1.so"));
    }
    RustcArgs::parse(&argv).unwrap()
}

fn unit_vars(checkout: &str, manifest_dir: &str) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
    let target = checkout_target(checkout);
    os_vars(&[
        ("CARGO_MANIFEST_DIR", manifest_dir),
        ("OUT_DIR", &format!("{target}/debug/build/kt-1/out")),
    ])
}

#[test]
fn shared_prediction_eligibility_takes_either_rule() {
    let dep = |path: &str| crate::args::ExternDep {
        name: "dep".to_string(),
        path: Some(PathBuf::from(path)),
    };
    let plain = [dep("/t/debug/deps/libserde-1.rlib")];
    let with_macro = [dep("/t/debug/deps/libpm-1.so")];
    let registry = Path::new(REGISTRY_PACKAGE_DIR);
    let workspace = Path::new("/w/kt");
    assert!(shared_prediction_eligible(&plain, Some(workspace)));
    assert!(shared_prediction_eligible(&plain, None));
    assert!(
        shared_prediction_eligible(&with_macro, Some(registry)),
        "a registry unit's record carries the tree guard"
    );
    assert!(!shared_prediction_eligible(&with_macro, Some(workspace)));
    assert!(!shared_prediction_eligible(&with_macro, None));
}

/// A proc-macro dependent in a registry package gets one shared identity
/// whichever target directory builds it; in a workspace it gets none.
#[test]
fn shared_identity_covers_tree_guarded_registry_units() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let identity = |checkout: &str, manifest_dir: &str| {
        rustc_shared_prediction_identity_in(
            &registry_unit_args(checkout, &["pm"]),
            unit_vars(checkout, manifest_dir),
        )
    };
    let a = identity("a", REGISTRY_PACKAGE_DIR);
    assert!(
        a.as_deref()
            .is_some_and(|a| a.starts_with("shared-target-v2:"))
    );
    assert_eq!(a, identity("b", REGISTRY_PACKAGE_DIR));
    assert_eq!(identity("a", "/w/kt"), None);
}

/// The relocated row is filed under the shared hash, the same for every
/// target directory, and only for a registry unit with an `OUT_DIR`.
#[test]
fn a_relocatable_identity_is_the_shared_hash_of_a_registry_unit_with_an_out_dir() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let args = registry_unit_args("a", &[]);
    let vars = unit_vars("a", REGISTRY_PACKAGE_DIR);
    let shared = rustc_shared_prediction_identity_in(&args, vars.clone()).unwrap();
    let relocatable = relocatable_prediction_identity(&args, vars).unwrap();
    assert_eq!(
        relocatable.strip_prefix("shared-out-dir-v1:"),
        shared.strip_prefix("shared-target-v2:")
    );
    assert_eq!(
        relocatable_prediction_identity(
            &registry_unit_args("b", &[]),
            unit_vars("b", REGISTRY_PACKAGE_DIR)
        ),
        Some(relocatable)
    );
    assert_eq!(
        relocatable_prediction_identity(
            &args,
            os_vars(&[("CARGO_MANIFEST_DIR", REGISTRY_PACKAGE_DIR)])
        ),
        None,
        "no OUT_DIR to relocate"
    );
    let workspace = unit_vars("a", "/w/kt");
    assert!(rustc_shared_prediction_identity_in(&args, workspace.clone()).is_some());
    assert_eq!(
        relocatable_prediction_identity(&args, workspace),
        None,
        "a workspace unit"
    );
}

#[test]
fn the_registry_src_root_is_two_levels_above_a_registry_package() {
    assert_eq!(
        registry_src_root(Path::new(REGISTRY_PACKAGE_DIR)),
        Some(Path::new("/h/registry/src"))
    );
    assert_eq!(registry_src_root(Path::new("/w/kt")), None);
}

#[test]
fn an_out_dir_suffix_is_the_bytes_after_the_directory() {
    let suffix =
        |value: &str, root: &str| out_dir_suffix(std::ffi::OsStr::new(value), Path::new(root));
    assert_eq!(
        suffix("/o", "/o").as_deref(),
        Some(""),
        "the directory itself"
    );
    assert_eq!(suffix("/o/x/y.rs", "/o").as_deref(), Some("/x/y.rs"));
    assert_eq!(suffix("/o\\x\\y.rs", "/o").as_deref(), Some("\\x\\y.rs"));
    assert_eq!(
        suffix("/o2/x", "/o"),
        None,
        "a longer name is another directory"
    );
    assert_eq!(suffix("/p/x", "/o"), None);
    assert_eq!(suffix("/o/../x", "/o"), None);
    assert_eq!(suffix("/o\\..\\x", "/o"), None);
    assert_eq!(suffix("/o/./x", "/o").as_deref(), Some("/./x"));
    assert_eq!(suffix("/o/./../x", "/o"), None);
    assert_eq!(suffix("/o//x", "/o"), None);
    assert_eq!(suffix("/o/", "/o"), None);
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        assert_eq!(
            out_dir_suffix(std::ffi::OsStr::from_bytes(b"/o/\xff"), Path::new("/o")),
            None,
            "a suffix that is not UTF-8"
        );
    }
    assert!(under_registry_src(
        Path::new("/r/src/i/p/lib.rs"),
        Path::new("/r/src")
    ));
    assert!(
        !under_registry_src(Path::new("/r/src"), Path::new("/r/src")),
        "the root is not a file under it"
    );
}

/// Every source of a registry unit's shared row is a registry file; the
/// rule for other units is unchanged.
#[test]
fn a_registry_unit_shares_only_sources_under_the_registry() {
    let target = Path::new("/w/target");
    let can = |sources: &[&str], manifest_dir: Option<&str>| {
        let sources: Vec<PathBuf> = sources.iter().map(PathBuf::from).collect();
        shared_sources_can_record(&sources, target, manifest_dir.map(Path::new))
    };
    let lib = "/h/registry/src/index-1/kt-1.0.0/src/lib.rs";
    let registry = Some(REGISTRY_PACKAGE_DIR);
    assert!(can(
        &[lib, "/h/registry/src/index-2/other-1.0.0/x.rs"],
        registry
    ));
    assert!(!can(&[lib, "/w/Cargo.lock"], registry), "a checkout file");
    assert!(!can(&["/h/registry/src/index-1/../../x.rs"], registry));
    assert!(can(&["/w/kt/src/lib.rs"], Some("/w/kt")));
    assert!(can(&["/w/kt/src/lib.rs"], None));
    assert!(
        !can(&["/w/target/debug/build/kt-1/out/gen.rs"], Some("/w/kt")),
        "no unit shares a target source"
    );
}

/// A `..` counts only from deeper than `floor`, and a walk that leaves
/// never comes back in.
#[test]
fn a_walk_stays_below_its_floor() {
    let walk = |path: &str, floor| stays_below(path.split('/'), floor);
    assert!(walk("a/../b", 0));
    assert!(!walk("../b", 0), "a `..` at the floor leaves it");
    assert!(!walk("a/../../a/b", 0), "leaving and coming back");
    assert!(walk("i/p/src/../README.md", 2));
    assert!(walk("i/p/src/a/b/../../x.rs", 2));
    assert!(!walk("i/p/src/../../q/x.rs", 2));
    assert!(!walk("i/../j/p/x.rs", 2), "below the floor too");
    assert!(walk("a/./b", 0), "a `.` stays where it is");
    assert!(walk("./a", 0));
    assert!(!walk("./../b", 0), "a `.` does not go down a level");
    assert!(!walk("i/p/./../q/x.rs", 2));
    assert!(!walk("a//b", 0));
}

/// rustc reports `include_str!("../README.md")` as `src/../README.md`
/// and never normalizes it. Refusing every `..` kept such a package's
/// record out of other checkouts; one that stays inside the directory is
/// as portable as a path without it.
#[test]
fn an_out_dir_suffix_keeps_a_parent_component_that_stays_inside() {
    let suffix =
        |value: &str, root: &str| out_dir_suffix(std::ffi::OsStr::new(value), Path::new(root));
    assert_eq!(
        suffix("/o/x/../y.rs", "/o").as_deref(),
        Some("/x/../y.rs"),
        "spelled as rustc spelled it"
    );
    assert_eq!(
        suffix("/o\\x\\..\\y.rs", "/o").as_deref(),
        Some("\\x\\..\\y.rs")
    );
    assert_eq!(suffix("/o/x/../../y.rs", "/o"), None);
    assert_eq!(
        suffix("/o/x\\y/../../z.rs", "/o"),
        None,
        "on Unix `x\\y` is one level, so this leaves `/o`"
    );
    assert_eq!(
        suffix("/o/x\\..\\..\\y.rs", "/o"),
        None,
        "on Windows this leaves `/o`"
    );
}

/// Path shapes rustc reported for registry dependencies, all refused
/// while any `..` or `.` was: the `..` ones from hk, `src/./init.js` from
/// `include_str!("./init.js")`. A `..` that leaves the package is still
/// refused, even into another registry package.
#[test]
fn a_registry_unit_shares_a_parent_path_that_stays_in_its_package() {
    let target = Path::new("/w/target");
    let can = |source: &str| {
        shared_sources_can_record(
            &[PathBuf::from(source)],
            target,
            Some(Path::new(REGISTRY_PACKAGE_DIR)),
        )
    };
    let index = "/h/registry/src/index-1";
    for inside in [
        "kt-1.0.0/src/../README.md",
        "kt-1.0.0/src/crypto/aws_lc_rs/../ring/hash.rs",
        "kt-1.0.0/src/new/glibc/sysdeps/nptl/bits/../../x86/mod.rs",
        "other-1.0.0/src/../data/mod.rs",
        "kt-1.0.0/src/./init.js",
    ] {
        assert!(can(&format!("{index}/{inside}")), "{inside}");
    }
    for outside in [
        "kt-1.0.0/src/../../other-1.0/lib.rs",
        "kt-1.0.0/../other-1.0/lib.rs",
        "kt-1.0.0/src/../../../../../w/src/lib.rs",
        "kt-1.0.0/./../other-1.0/lib.rs",
    ] {
        assert!(!can(&format!("{index}/{outside}")), "{outside}");
    }
}

fn portable_roots_for_test() -> PortableRoots {
    PortableRoots {
        out_dir: PathBuf::from("/t/debug/build/kt-1/out"),
        target: PathBuf::from("/t"),
        canonical_target: PathBuf::from("/private/t"),
        registry_src: PathBuf::from("/h/registry/src"),
    }
}

fn portable_test_record() -> PortablePrediction {
    PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![
            Portable::Literal("/h/registry/src/index-1/kt-1.0.0/src/lib.rs".to_string()),
            Portable::OutDir("\\version.expr".to_string()),
            Portable::OutDir("/gen.rs".to_string()),
        ],
        env_deps: vec![
            ("OUT_DIR".to_string(), Portable::OutDir(String::new())),
            (
                "CARGO_PKG_NAME".to_string(),
                Portable::Literal("kt".to_string()),
            ),
        ],
        tree: "tree-1".to_string(),
    }
}

/// A workspace at `/w`, reached through `/private/w` as macOS spells
/// temporary directories, with its target inside.
fn workspace_test_roots() -> WorkspaceRoots {
    WorkspaceRoots {
        root: PathBuf::from("/w"),
        cwd: String::new(),
        canonical_root: PathBuf::from("/private/w"),
        target: PathBuf::from("/w/target"),
        canonical_target: PathBuf::from("/private/w/target"),
        out_dir: Some(PathBuf::from("/w/target/debug/build/kt-1/out")),
        vendored_package: None,
    }
}

#[test]
fn a_workspace_row_keeps_its_guard_only_while_the_guard_covers_the_closure() {
    let tree = || Some("tree".to_string());
    assert_eq!(same_tree_guard(tree(), true, true), tree());
    assert_eq!(same_tree_guard(tree(), true, false), None);
    assert_eq!(
        same_tree_guard(tree(), false, false),
        tree(),
        "registry and other units"
    );
    assert_eq!(same_tree_guard(tree(), false, true), tree());
    assert_eq!(same_tree_guard(None, true, true), None);
}

/// A two-member-free workspace at `dir/<name>` with its target inside,
/// and the member invocation Cargo would run there.
fn workspace_invocation(dir: &Path, name: &str, crate_name: &str) -> (PathBuf, RustcArgs) {
    let root = dir.join(name);
    std::fs::create_dir_all(root.join("kt/src")).unwrap();
    std::fs::create_dir_all(root.join("target/debug/deps")).unwrap();
    std::fs::write(root.join("Cargo.toml"), "[workspace]\n").unwrap();
    let deps = root.join("target/debug/deps").display().to_string();
    let argv: Vec<String> = [
        "rustc",
        "--crate-name",
        crate_name,
        "--edition=2021",
        "kt/src/lib.rs",
        "--crate-type",
        "lib",
        "--out-dir",
        &deps,
        "-L",
        &format!("dependency={deps}"),
    ]
    .iter()
    .map(|arg| arg.to_string())
    .collect();
    (root, RustcArgs::parse(&argv).unwrap())
}

fn manifest_vars(manifest_dir: &Path) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
    vec![(
        "CARGO_MANIFEST_DIR".into(),
        manifest_dir.as_os_str().to_owned(),
    )]
}

/// The member `kt` of a workspace at `base/w`, linking only an rlib that may
/// re-export a proc macro, as Cargo runs it from the workspace root.
fn rlib_only_member(base: &Path) -> (PathBuf, RustcArgs) {
    let (root, args) = workspace_invocation(base, "w", "kt");
    let deps = root.join("target/debug/deps");
    let mut argv = args.all_args.clone();
    argv.insert(0, "rustc".to_string());
    argv.extend([
        "--extern".to_string(),
        format!(
            "facade={}",
            deps.join("libfacade-0123456789abcdef.rlib").display()
        ),
    ]);
    (root, RustcArgs::parse(&argv).unwrap())
}

/// A member that links only an rlib, which may re-export a macro that lists
/// a directory, is predicted only under the workspace guard. A row without
/// the digest or with another one is refused, and so is a row whose closure
/// the guard does not cover: this checkout's, the shared one, or one made in
/// another checkout.
#[test]
fn an_rlib_only_member_is_predicted_only_under_the_workspace_guard() {
    let mut lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let base = lock.enter();
    let (root, args) = rlib_only_member(&base);
    std::env::set_current_dir(&root).unwrap();
    write_file(&root.join("kt/src/lib.rs"), "facade::scan!();\n");
    write_file(&root.join("kt/assets/a.txt"), "a");
    write_file(&root.join("stale/x.txt"), "x");
    write_file(&root.join("stale/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    write_file(&base.join("outside.txt"), "o");
    let manifest_dir = root.join("kt");
    let _manifest = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(manifest_dir.as_os_str()),
    );
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", None);
    let hasher = |name: &str| FileHasher::persistent(&base.join(name)).with_input_predictions(true);
    let closure = |sources: &[PathBuf]| DepInfo {
        source_files: sources.to_vec(),
        env_deps: Vec::new(),
    };
    let lib = PathBuf::from("kt/src/lib.rs");
    let inside = closure(&[lib.clone(), root.join("kt/assets/a.txt")]);

    let local = hasher("local.db");
    let mut tree = None;
    assert_eq!(
        predicted_key_inputs(&args, &local, &mut tree),
        Err(Rejection::NoRecord)
    );
    let guard = tree.expect("an rlib-only member is digested").digest;
    let identity = rustc_prediction_identity(&args).unwrap();
    local.record_input_prediction(&identity, Some("kt"), &inside, None);
    assert_eq!(
        predicted_key_inputs(&args, &local, &mut None),
        Err(Rejection::NoRecord),
        "a row without the digest"
    );
    local.record_input_prediction(&identity, Some("kt"), &inside, Some("other".into()));
    assert_eq!(
        predicted_key_inputs(&args, &local, &mut None),
        Err(Rejection::TreeChanged)
    );
    local.record_input_prediction(&identity, Some("kt"), &inside, Some(guard.clone()));
    assert_eq!(
        predicted_key_inputs(&args, &local, &mut None),
        Ok(inside.clone())
    );
    write_file(&root.join("kt/assets/b.txt"), "b");
    assert_eq!(
        predicted_key_inputs(&args, &local, &mut None),
        Err(Rejection::TreeChanged),
        "a file joins the directory a macro lists"
    );
    std::fs::remove_file(root.join("kt/assets/b.txt")).unwrap();
    for uncovered in [base.join("outside.txt"), root.join("stale/x.txt")] {
        let leaves = closure(&[lib.clone(), uncovered.clone()]);
        local.record_input_prediction(&identity, Some("kt"), &leaves, Some(guard.clone()));
        assert_eq!(
            predicted_key_inputs(&args, &local, &mut None),
            Err(Rejection::NoRecord),
            "{}",
            uncovered.display()
        );
    }

    // A shared row written before the coverage rule carries the digest
    // whatever its closure names.
    let shared_rows = hasher("shared.db");
    let shared = rustc_shared_prediction_identity(&args).unwrap();
    let leaves = closure(&[lib.clone(), base.join("outside.txt")]);
    shared_rows.record_input_prediction(&shared, Some("kt"), &leaves, Some(guard.clone()));
    assert_eq!(
        predicted_key_inputs(&args, &shared_rows, &mut None),
        Err(Rejection::NoRecord)
    );
    shared_rows.record_input_prediction(&shared, Some("kt"), &inside, Some(guard.clone()));
    assert_eq!(
        predicted_key_inputs(&args, &shared_rows, &mut None),
        Ok(inside.clone())
    );

    let portable_rows = hasher("portable.db");
    let vars: Vec<_> = std::env::vars_os().collect();
    let roots = workspace_roots(&args, &vars).unwrap();
    let portable = workspace_prediction_identity(&args, vars, &roots).unwrap();
    let record = |below: &str| PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![
            Portable::Literal("kt/src/lib.rs".to_string()),
            Portable::Workspace(below.to_string()),
        ],
        env_deps: Vec::new(),
        tree: guard.clone(),
    };
    portable_rows.record_portable_prediction(&portable, Some("kt"), &record("/stale/x.txt"));
    assert_eq!(
        predicted_key_inputs(&args, &portable_rows, &mut None),
        Err(Rejection::NoRecord),
        "a row from another checkout naming a file in a Cargo build directory"
    );
    portable_rows.record_portable_prediction(&portable, Some("kt"), &record("/kt/assets/a.txt"));
    assert_eq!(
        predicted_key_inputs(&args, &portable_rows, &mut None),
        Ok(inside)
    );
}

/// A process that waited on a discovery flight digests the tree again. The
/// owner's record carries the digest from before its compile, and the tree
/// may have changed while the owner compiled.
#[test]
fn a_flight_waiter_digests_the_tree_again() {
    let mut lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let base = lock.enter();
    let (root, args) = rlib_only_member(&base);
    std::env::set_current_dir(&root).unwrap();
    write_file(&root.join("kt/src/lib.rs"), "");
    let manifest_dir = root.join("kt");
    let _manifest = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(manifest_dir.as_os_str()),
    );
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", None);
    let hasher = FileHasher::persistent(&base.join("index.db")).with_input_predictions(true);
    let closure = DepInfo {
        source_files: vec![PathBuf::from("kt/src/lib.rs")],
        env_deps: Vec::new(),
    };
    let identity = rustc_prediction_identity(&args).unwrap();
    hasher.record_input_prediction(&identity, Some("kt"), &closure, Some("before".into()));
    let mut tree = Some(TreeGuard {
        digest: "before".to_string(),
        walks: Vec::new(),
    });
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut tree),
        Err(Rejection::TreeChanged),
        "the guard from before the wait is not used again"
    );
    let now = tree.expect("the guard is taken again").digest;
    hasher.record_input_prediction(&identity, Some("kt"), &closure, Some(now.clone()));
    let mut tree = None;
    assert_eq!(predicted_key_inputs(&args, &hasher, &mut tree), Ok(closure));
    assert_eq!(tree.map(|guard| guard.digest), Some(now));
}

/// This checkout's rows keep the guard while it covers the closure. They are
/// never relocated, so a generated file naming the checkout costs nothing
/// here, though it keeps the row for other checkouts out.
#[test]
fn this_checkouts_rows_keep_the_guard_while_it_covers_the_closure() {
    let mut lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let base = lock.enter();
    let (root, args) = rlib_only_member(&base);
    std::env::set_current_dir(&root).unwrap();
    write_file(&root.join("kt/src/lib.rs"), "");
    let out = root.join("target/debug/build/kt-1/out");
    write_file(
        &out.join("gen.rs"),
        &format!("// generated in {}\n", root.display()),
    );
    write_file(&base.join("outside.txt"), "o");
    let manifest_dir = root.join("kt");
    let _manifest = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(manifest_dir.as_os_str()),
    );
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", Some(out.as_os_str()));
    let tree = || Some("tree".to_string());
    let closure = |extra: PathBuf| DepInfo {
        source_files: vec![PathBuf::from("kt/src/lib.rs"), extra],
        env_deps: Vec::new(),
    };
    let generated = closure(out.join("gen.rs"));
    assert_eq!(same_checkout_guard(&args, &generated, tree()), tree());
    assert!(workspace_record(&args, &generated, Some("tree")).is_none());
    let outside = closure(base.join("outside.txt"));
    assert_eq!(same_checkout_guard(&args, &outside, tree()), None);

    let registry = base.join("home/registry/src/index-1/kt-1.0.0");
    let _registry =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(registry.as_os_str()));
    assert_eq!(
        same_checkout_guard(&args, &outside, tree()),
        tree(),
        "a registry unit keeps its own guard"
    );
}

#[test]
fn only_a_package_inside_the_workspace_is_a_workspace_unit() {
    let dir = tempfile::tempdir().unwrap();
    let (root, args) = workspace_invocation(dir.path(), "a", "kt");
    let inside = workspace_roots_in(&args, &manifest_vars(&root.join("kt")), &root).unwrap();
    assert_eq!(inside.cwd, "");
    assert_eq!(inside.target, root.join("target"));
    let member_cwd = workspace_roots_in(&args, &manifest_vars(&root.join("kt")), &root.join("kt"));
    assert_eq!(
        member_cwd.map(|roots| roots.cwd),
        Some(format!("{}kt", std::path::MAIN_SEPARATOR))
    );
    assert!(
        workspace_roots_in(&args, &manifest_vars(&dir.path().join("elsewhere")), &root).is_none(),
        "a package outside the workspace"
    );
    let registry = dir.path().join("home/registry/src/index-1/kt-1.0.0");
    assert!(workspace_roots_in(&args, &manifest_vars(&registry), &root).is_none());
    assert!(
        workspace_roots_in(&args, &[], &root).is_none(),
        "no package at all"
    );
}

/// Cargo's legacy layout compiles a build script one level below where a
/// library goes. Its guard leaves out the same target directory as every
/// other unit's, and so shares their memo.
#[test]
fn a_build_script_compile_leaves_out_the_whole_target_directory() {
    let dir = tempfile::tempdir().unwrap();
    let (root, mut args) = workspace_invocation(dir.path(), "a", "build_script_build");
    let vars = manifest_vars(&root.join("kt"));
    let target_of =
        |args: &RustcArgs| workspace_roots_in(args, &vars, &root).map(|roots| roots.target);
    for out_dir in [
        "target/debug/build/kt-0123456789abcdef",
        "target/debug/build/kt/0123456789abcdef/out",
    ] {
        args.out_dir = Some(root.join(out_dir));
        assert_eq!(target_of(&args), Some(root.join("target")), "{out_dir}");
    }
    args.target = Some("x86_64-unknown-linux-gnu".to_string());
    args.out_dir =
        Some(root.join("target/x86_64-unknown-linux-gnu/debug/build/kt/0123456789abcdef/out"));
    assert_eq!(
        target_of(&args),
        Some(root.join("target")),
        "a cross-compiled library in the per-unit layout"
    );
}

#[test]
fn a_linker_or_search_path_in_the_checkout_does_not_split_the_identity() {
    let dir = tempfile::tempdir().unwrap();
    let identity = |name: &str, extra: &[String]| {
        let (root, mut args) = workspace_invocation(dir.path(), name, "kt");
        args.all_args.extend(
            extra
                .iter()
                .map(|arg| arg.replace("ROOT", &root.display().to_string())),
        );
        let vars = manifest_vars(&root.join("kt"));
        let roots = workspace_roots_in(&args, &vars, &root).unwrap();
        workspace_prediction_identity(&args, vars, &roots).unwrap()
    };
    let strings = |args: &[&str]| args.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
    let linker = strings(&["-C", "linker=ROOT/build/cargo-linker"]);
    assert_eq!(identity("a", &linker), identity("b", &linker));
    let joined = strings(&["-Clinker=ROOT/build/cargo-linker"]);
    assert_eq!(identity("a", &joined), identity("b", &joined));
    let search = strings(&["-L", "native=ROOT/lib"]);
    assert_ne!(
        identity("a", &search),
        identity("b", &search),
        "a search path can change which library resolves"
    );
    let external = strings(&["--extern", "x=ROOT/prebuilt/libx.rlib"]);
    assert_ne!(
        identity("a", &external),
        identity("b", &external),
        "a crate in the checkout can change what a macro expands to"
    );
}

#[test]
fn external_targets_keep_predictions_anchored_to_the_source_workspace() {
    let dir = tempfile::tempdir().unwrap();
    let (root, mut args) = workspace_invocation(dir.path(), "source", "kt");
    let other = dir.path().join("shared-output");
    let target = other.join("target");
    std::fs::create_dir_all(target.join("debug/deps")).unwrap();
    std::fs::write(other.join("Cargo.toml"), "[workspace]\n").unwrap();
    args.out_dir = Some(target.join("debug/deps"));
    assert_eq!(args.verified_workspace_root(&root), None);

    let vars = manifest_vars(&root.join("kt"));
    let roots = workspace_roots_in(&args, &vars, &root).unwrap();
    assert_eq!(roots.root, root);
    assert_eq!(roots.target, target);
    assert_eq!(roots.cwd, "");
    assert!(workspace_roots_in(&args, &manifest_vars(&other), &root).is_none());
    assert!(workspace_roots_in(&args, &vars, &root.join("kt")).is_none());
    std::fs::remove_file(root.join("Cargo.toml")).unwrap();
    assert!(workspace_roots_in(&args, &vars, &root).is_none());
}

#[test]
fn external_target_predictions_guard_sources_and_generated_inputs() {
    let dir = tempfile::tempdir().unwrap();
    let (root, mut args) = workspace_invocation(dir.path(), "source", "kt");
    let target = dir.path().join("output/target");
    let out = target.join("debug/build/kt-1/out");
    std::fs::create_dir_all(target.join("debug/deps")).unwrap();
    std::fs::create_dir_all(&out).unwrap();
    let source = root.join("kt/src/lib.rs");
    std::fs::write(&source, "pub fn value() {}\n").unwrap();
    let generated = out.join("generated.rs");
    std::fs::write(&generated, "pub const VALUE: u8 = 1;\n").unwrap();
    args.out_dir = Some(target.join("debug/deps"));
    let mut vars = manifest_vars(&root.join("kt"));
    vars.push(("OUT_DIR".into(), out.clone().into_os_string()));
    let roots = workspace_roots_in(&args, &vars, &root).unwrap();
    let hasher = FileHasher::new();
    let digest = || workspace_tree_digest(&roots, &hasher).unwrap();
    let original = digest();
    std::fs::write(target.join("debug/deps/unrelated.rlib"), "output").unwrap();
    assert_eq!(digest(), original);
    std::fs::create_dir_all(root.join("assets")).unwrap();
    std::fs::write(root.join("assets/new.txt"), "macro input").unwrap();
    assert_ne!(digest(), original);
    std::fs::remove_dir_all(root.join("assets")).unwrap();
    assert_eq!(digest(), original);
    std::fs::write(&generated, "pub const VALUE: u8 = 2;\n").unwrap();
    assert_ne!(digest(), original);

    let closure = DepInfo {
        source_files: vec![source.clone(), generated.clone()],
        env_deps: vec![],
    };
    assert!(workspace_portable_prediction(&closure, &roots, Some("tree")).is_some());
    for external in [
        target.join("debug/deps/unrelated.rlib"),
        dir.path().join("outside.rs"),
    ] {
        let closure = DepInfo {
            source_files: vec![source.clone(), external],
            env_deps: vec![],
        };
        assert!(workspace_portable_prediction(&closure, &roots, Some("tree")).is_none());
    }
}

#[cfg(windows)]
#[test]
fn external_target_predictions_accept_mixed_manifest_separators() {
    let dir = tempfile::tempdir().unwrap();
    let (root, mut args) = workspace_invocation(dir.path(), "source/checkout", "kt");
    let target = dir.path().join("output/target");
    std::fs::create_dir_all(target.join("debug/deps")).unwrap();
    args.out_dir = Some(target.join("debug/deps"));
    let vars = manifest_vars(&root.join("kt"));
    // GetCurrentDirectory uses backslashes without canonicalize's verbatim
    // prefix, while Cargo's manifest path may contain forward slashes.
    let cwd = PathBuf::from(root.to_str().unwrap().replace('/', "\\"));
    assert!(suffix_within(cwd.as_os_str(), &root, 0).is_none());
    let roots = workspace_roots_in(&args, &vars, &cwd).unwrap();
    assert_eq!(roots.root, root);
    assert_eq!(roots.cwd, "");
    assert_eq!(roots.canonical_root, std::fs::canonicalize(&cwd).unwrap());
}

#[cfg(unix)]
#[test]
fn external_target_predictions_keep_cargos_symlinked_source_spelling() {
    let dir = tempfile::tempdir().unwrap();
    let (root, mut args) = workspace_invocation(dir.path(), "source", "kt");
    let alias = dir.path().join("alias");
    std::os::unix::fs::symlink(&root, &alias).unwrap();
    let target = dir.path().join("output/target");
    std::fs::create_dir_all(target.join("debug/deps")).unwrap();
    std::fs::write(root.join("kt/src/lib.rs"), "pub fn value() {}\n").unwrap();
    args.out_dir = Some(target.join("debug/deps"));
    args.source_file = Some(alias.join("kt/src/lib.rs"));
    let vars = manifest_vars(&alias.join("kt"));
    let cwd = std::fs::canonicalize(&root).unwrap();
    let roots = workspace_roots_in(&args, &vars, &cwd).unwrap();
    assert_eq!(roots.root, alias);
    assert_eq!(roots.canonical_root, std::fs::canonicalize(&root).unwrap());
    assert_eq!(roots.cwd, "");
    let closure = DepInfo {
        source_files: vec![alias.join("kt/src/lib.rs")],
        env_deps: vec![],
    };
    assert!(workspace_portable_prediction(&closure, &roots, Some("tree")).is_some());
}

#[test]
fn only_linker_paths_under_the_root_are_made_neutral() {
    let roots = workspace_test_roots();
    let args = |args: &[&str]| args.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
    let some = |arg: &str| Some(arg.to_string());
    assert_eq!(
        workspace_neutral_link_args(
            &args(&[
                "-C",
                "linker=/w/build/cargo-linker",
                "-Clinker=/private/w/l",
                "--codegen=linker=/w/l",
                "--codegen",
                "linker=/w/m",
            ]),
            &roots
        ),
        vec![
            None,
            some("linker=kache-workspace:/build/cargo-linker"),
            some("-Clinker=kache-workspace:/l"),
            some("--codegen=linker=kache-workspace:/l"),
            None,
            some("linker=kache-workspace:/m"),
        ]
    );
    let kept = args(&[
        "-C",
        "linker=/usr/bin/cc",
        "-C",
        "opt-level=3",
        "-Clinker=/w2/l",
        "--extern",
        "x=/w/libx.rlib",
        "-L",
        "native=/w/lib",
        "-L/w/dir",
        "-C",
        "linker=/w/../outside",
        "linker=/w/l",
    ]);
    assert!(
        workspace_neutral_link_args(&kept, &roots)
            .iter()
            .all(Option::is_none)
    );
}

#[test]
fn a_workspace_identity_is_the_same_in_every_checkout_and_per_unit() {
    let dir = tempfile::tempdir().unwrap();
    let identity = |name: &str, crate_name: &str| {
        let (root, args) = workspace_invocation(dir.path(), name, crate_name);
        let vars = manifest_vars(&root.join("kt"));
        let roots = workspace_roots_in(&args, &vars, &root).unwrap();
        workspace_prediction_identity(&args, vars, &roots).unwrap()
    };
    let a = identity("a", "kt");
    assert!(a.starts_with(WORKSPACE_PREDICTION_PREFIX), "{a}");
    assert_eq!(a, identity("b", "kt"), "another checkout of the same unit");
    assert_ne!(a, identity("c", "other"), "another unit");
}

#[test]
fn a_remote_row_is_kept_only_once_it_checks_out() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    let hasher = FileHasher::persistent(&db);
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "kt".to_string(),
        "src/lib.rs".to_string(),
    ])
    .unwrap();
    let record = InputPrediction {
        schema: PREDICTION_SCHEMA,
        sources: vec![PathBuf::from("/r/i/kt-1.0.0/src/lib.rs")],
        env_deps: vec![],
        tree: None,
    };
    let dep_info = DepInfo {
        source_files: record.sources.clone(),
        env_deps: vec![],
    };
    keep_remote_plain_row(&hasher, "refused", &args, &record, &Err(Rejection::Missing));
    assert_eq!(hasher.input_prediction("refused"), None);
    keep_remote_plain_row(&hasher, "kept", &args, &record, &Ok(dep_info));
    assert_eq!(
        hasher.input_prediction("kept").map(|kept| kept.sources),
        Some(record.sources.clone())
    );
}

#[test]
fn a_workspace_value_is_relocated_refused_or_kept() {
    let roots = workspace_test_roots();
    let value = |value: &str| workspace_portable_value(std::ffi::OsStr::new(value), &roots);
    assert_eq!(
        value("/w/target/debug/build/kt-1/out/gen.rs"),
        Some(Portable::OutDir("/gen.rs".to_string()))
    );
    assert_eq!(
        value("/w/target/debug/deps/libx.rlib"),
        None,
        "another unit's output"
    );
    assert_eq!(value("/private/w/target/debug/deps/libx.rlib"), None);
    assert_eq!(
        value("/w/kt/src/lib.rs"),
        Some(Portable::Workspace("/kt/src/lib.rs".to_string()))
    );
    assert_eq!(
        value("/private/w/assets/a.txt"),
        Some(Portable::Workspace("/assets/a.txt".to_string()))
    );
    assert_eq!(value("/w"), Some(Portable::Workspace(String::new())));
    assert_eq!(
        value("/w2/x"),
        Some(Portable::Literal("/w2/x".to_string())),
        "a sibling that merely starts the same is not the workspace"
    );
    assert_eq!(value("kt"), Some(Portable::Literal("kt".to_string())));
}

#[test]
fn a_relative_source_must_stay_in_the_workspace() {
    let mut roots = workspace_test_roots();
    let source = |spelled: &str, roots: &WorkspaceRoots| {
        workspace_relative_source(Path::new(spelled), roots)
    };
    let kept = |spelled: &str| Some(Portable::Literal(spelled.to_string()));
    assert_eq!(source("kt/src/lib.rs", &roots), kept("kt/src/lib.rs"));
    assert_eq!(
        source("kt/src/../../assets/a.txt", &roots),
        kept("kt/src/../../assets/a.txt")
    );
    assert_eq!(source("../outside.txt", &roots), None);
    assert_eq!(source("kt//lib.rs", &roots), None);
    assert_eq!(
        source("kt\\..\\..\\outside.txt", &roots),
        None,
        "a Windows walk that leaves, which a `/` split alone would miss"
    );
    roots.cwd = "/kt".to_string();
    assert_eq!(source("../assets/a.txt", &roots), kept("../assets/a.txt"));
    assert_eq!(source("../../outside.txt", &roots), None);
}

#[test]
fn a_workspace_record_needs_the_guard_and_every_source_inside() {
    let roots = workspace_test_roots();
    let dep_info = |sources: &[&str]| DepInfo {
        source_files: sources.iter().map(PathBuf::from).collect(),
        env_deps: vec![("CARGO_MANIFEST_DIR".to_string(), "/w/kt".to_string())],
    };
    let inside = dep_info(&["kt/src/lib.rs", "/w/target/debug/build/kt-1/out/gen.rs"]);
    assert_eq!(
        workspace_portable_prediction(&inside, &roots, Some("tree-1")),
        Some(PortablePrediction {
            schema: PORTABLE_PREDICTION_SCHEMA,
            sources: vec![
                Portable::Literal("kt/src/lib.rs".to_string()),
                Portable::OutDir("/gen.rs".to_string()),
            ],
            env_deps: vec![(
                "CARGO_MANIFEST_DIR".to_string(),
                Portable::Workspace("/kt".to_string())
            )],
            tree: "tree-1".to_string(),
        })
    );
    assert_eq!(workspace_portable_prediction(&inside, &roots, None), None);
    for outside in ["/elsewhere/x.rs", "../x.rs", "/w/target/debug/deps/x.rs"] {
        let closure = dep_info(&["kt/src/lib.rs", outside]);
        assert_eq!(
            workspace_portable_prediction(&closure, &roots, Some("t")),
            None,
            "{outside}"
        );
    }
    let mut env_in_target = dep_info(&["kt/src/lib.rs"]);
    env_in_target.env_deps = vec![("X".to_string(), "/w/target/debug/x".to_string())];
    assert_eq!(
        workspace_portable_prediction(&env_in_target, &roots, Some("t")),
        None
    );
}

/// What Cargo writes into a target directory it creates.
const CARGO_BUILD_TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
     # This file is a cache directory tag created by cargo.\n";

fn write_file(path: &Path, content: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, content).unwrap();
}

/// The guard sees a file only where its walk goes: not through a symlinked
/// directory, nor into a directory Cargo tagged as its build directory,
/// except below `OUT_DIR`, which the walk reads whole.
#[test]
fn the_guard_sees_only_the_files_its_walk_reaches() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let out = dir.path().join("out");
    for file in ["kt/src/lib.rs", "assets/a.txt", "stale/x.rs"] {
        write_file(&root.join(file), "");
    }
    write_file(&root.join("stale/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    write_file(&out.join("gen.rs"), "");
    write_file(&out.join("nested/y.rs"), "");
    write_file(&out.join("nested/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    write_file(&dir.path().join("outside/o.txt"), "");
    let canonical_root = root.canonicalize().unwrap();
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_target: canonical_root.join("target"),
        canonical_root: canonical_root.clone(),
        target: root.join("target"),
        out_dir: Some(out.clone()),
        vendored_package: None,
    };
    let covers = |sources: &[PathBuf]| guard_covers(sources, &roots);
    let relative = PathBuf::from;
    assert!(covers(&[
        relative("kt/src/lib.rs"),
        relative("kt/src/../../assets/a.txt"),
        root.join("assets/a.txt"),
        canonical_root.join("assets/a.txt"),
        out.join("gen.rs"),
        out.join("nested/y.rs"),
    ]));
    for (source, why) in [
        (relative("../outside/o.txt"), "relative, leaving the root"),
        (dir.path().join("outside/o.txt"), "outside the workspace"),
        (
            root.join("target/debug/deps/libx.rlib"),
            "the target directory",
        ),
        (root.join("stale/x.rs"), "a Cargo build directory"),
        (
            relative("stale/x.rs"),
            "relative, into a Cargo build directory",
        ),
        (root.join("kt/missing/x.rs"), "no such directory"),
    ] {
        assert!(!covers(&[relative("kt/src/lib.rs"), source]), "{why}");
    }
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(dir.path().join("outside"), root.join("linked")).unwrap();
        assert!(
            !covers(&[root.join("linked/o.txt")]),
            "through a symlinked directory"
        );
    }
    let mut entered = HashMap::new();
    assert!(walk_reaches(&root, "/top.txt", true, &mut entered));
    assert!(walk_reaches(
        &root,
        "/kt/src/../src/lib.rs",
        true,
        &mut entered
    ));
    assert!(!walk_reaches(
        &root,
        "/../w/kt/src/lib.rs",
        true,
        &mut entered
    ));
}

/// A record for another checkout is only made when the guard sees every file
/// the closure names.
#[test]
fn a_workspace_record_needs_every_source_where_the_guard_walks() {
    let mut lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let base = lock.enter();
    let (root, args) = workspace_invocation(&base, "w", "kt");
    std::env::set_current_dir(&root).unwrap();
    write_file(&root.join("kt/src/lib.rs"), "");
    write_file(&root.join("stale/x.rs"), "");
    write_file(&root.join("stale/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    let manifest_dir = root.join("kt");
    let _manifest = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(manifest_dir.as_os_str()),
    );
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", None);
    let closure = |sources: &[&str]| DepInfo {
        source_files: sources.iter().map(PathBuf::from).collect(),
        env_deps: Vec::new(),
    };
    assert!(workspace_record(&args, &closure(&["kt/src/lib.rs"]), Some("tree")).is_some());
    assert!(
        workspace_record(
            &args,
            &closure(&["kt/src/lib.rs", "stale/x.rs"]),
            Some("tree")
        )
        .is_none()
    );
}

#[test]
fn a_workspace_entry_resolves_only_where_this_invocation_has_a_workspace() {
    let record = PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![Portable::Workspace("/kt/src/lib.rs".to_string())],
        env_deps: vec![],
        tree: "t".to_string(),
    };
    let places = |out_dir, workspace| Places {
        out_dir,
        workspace,
        registry: None,
    };
    assert_eq!(record.resolve(&places(Some("/o"), None)), None);
    assert_eq!(
        record
            .resolve(&places(None, Some("/v")))
            .map(|resolved| resolved.sources),
        Some(vec![PathBuf::from("/v/kt/src/lib.rs")])
    );
    assert_eq!(
        portable_test_record().resolve(&places(None, Some("/v"))),
        None,
        "an OUT_DIR entry needs an OUT_DIR"
    );
}

#[test]
fn the_workspace_guard_covers_everything_but_target_and_git() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let write = |path: &str, content: &str| {
        let path = root.join(path);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, content).unwrap();
    };
    write("Cargo.toml", "[workspace]\n");
    write("kt/src/lib.rs", "pub fn a() {}\n");
    write("assets/a.txt", "a\n");
    write("target/debug/build/kt-1/out/gen.rs", "// gen\n");
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.canonicalize().unwrap(),
        target: root.join("target"),
        canonical_target: root.join("target").canonicalize().unwrap(),
        out_dir: Some(root.join("target/debug/build/kt-1/out")),
        vendored_package: None,
    };
    let hasher = FileHasher::new();
    let digest = || workspace_tree_digest(&roots, &hasher).unwrap();
    let baseline = digest();

    write("target/debug/deps/libx.rlib", "x");
    write(".git/HEAD", "ref");
    assert_eq!(
        digest(),
        baseline,
        "target and .git are not what a macro reads"
    );

    write("docs/new.md", "new");
    assert_ne!(digest(), baseline, "a new file anywhere in the workspace");
    std::fs::remove_file(root.join("docs/new.md")).unwrap();
    std::fs::remove_dir(root.join("docs")).unwrap();
    assert_eq!(digest(), baseline);

    write("assets/a.txt", "changed");
    assert_ne!(digest(), baseline, "content");
    write("assets/a.txt", "a\n");
    write("target/debug/build/kt-1/out/gen.rs", "// other\n");
    assert_ne!(digest(), baseline, "OUT_DIR, though it lies under target");
}

/// A directory Cargo tagged as its build directory, such as a stale `target`
/// left in the tree while the build writes elsewhere, counts by its tag
/// alone: its output neither changes the guard nor fills the budget.
/// `OUT_DIR` and a registry package are read whole.
#[test]
fn a_cargo_build_dir_in_the_workspace_counts_by_its_tag() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let out = dir.path().join("out");
    for file in [
        "Cargo.toml",
        "kt/src/lib.rs",
        "stale/debug/a",
        "stale/debug/b",
    ] {
        write_file(&root.join(file), "");
    }
    write_file(&root.join("stale/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    write_file(&out.join("gen.rs"), "");
    write_file(&out.join("nested/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.clone(),
        target: dir.path().join("target"),
        canonical_target: dir.path().join("target"),
        out_dir: Some(out.clone()),
        vendored_package: None,
    };
    let hasher = FileHasher::new();
    let digest = |budget| workspace_tree_digest_within(&roots, &hasher, budget);
    // `Cargo.toml`, `kt`, `kt/src`, `kt/src/lib.rs`, `stale` and its tag,
    // then `gen.rs`, `nested` and its tag.
    let baseline = digest(9).unwrap();
    assert_eq!(digest(8), None);
    write_file(&root.join("stale/debug/c"), "");
    assert_eq!(digest(9).as_ref(), Some(&baseline), "build output");
    write_file(&out.join("nested/x"), "");
    assert_eq!(digest(9), None, "OUT_DIR is read whole");
    assert!(digest(10).is_some_and(|changed| changed != baseline));

    let package = dir.path().join("registry/src/index-1/kt-1.0.0");
    write_file(&package.join("src/lib.rs"), "");
    write_file(&package.join("stale/CACHEDIR.TAG"), CARGO_BUILD_TAG);
    let registry = || crate_tree_digest_in(package.clone(), None, &hasher).unwrap();
    let before = registry();
    write_file(&package.join("stale/debug/a"), "");
    assert_ne!(registry(), before, "a registry package is read whole");
}

#[test]
fn a_vendored_package_is_guarded_by_itself_not_the_workspace() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let write = |path: &str, content: &str| {
        let path = root.join(path);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, content).unwrap();
    };
    write("Cargo.toml", "[workspace]\n");
    write("third_party/rust/foo/.cargo-checksum.json", "{}");
    write("third_party/rust/foo/src/lib.rs", "pub fn a() {}\n");
    write("target/debug/build/foo-1/out/gen.rs", "// gen\n");
    let mut roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.canonicalize().unwrap(),
        target: root.join("target"),
        canonical_target: root.join("target").canonicalize().unwrap(),
        out_dir: Some(root.join("target/debug/build/foo-1/out")),
        vendored_package: Some(root.join("third_party/rust/foo")),
    };
    let hasher = FileHasher::new();
    let digest = |roots: &WorkspaceRoots| workspace_tree_digest(roots, &hasher).unwrap();
    let baseline = digest(&roots);

    write("docs/new.md", "new");
    write("third_party/rust/bar/src/lib.rs", "other package");
    assert_eq!(
        digest(&roots),
        baseline,
        "sibling packages and the rest of the tree do not count"
    );
    write(".git", "gitdir: /elsewhere/.git/worktrees/w");
    assert_eq!(
        digest(&roots),
        baseline,
        "a worktree's .git file differs between checkouts"
    );
    std::fs::remove_file(root.join(".git")).unwrap();
    for found_on_the_way_up in [".env", ".sqlx/query.json", "third_party/.config/x"] {
        write(found_on_the_way_up, "x");
        assert_ne!(digest(&roots), baseline, "{found_on_the_way_up}");
        std::fs::remove_file(root.join(found_on_the_way_up)).unwrap();
    }
    std::fs::remove_dir_all(root.join(".sqlx")).unwrap();
    std::fs::remove_dir_all(root.join("third_party/.config")).unwrap();
    assert_eq!(digest(&roots), baseline);
    #[cfg(unix)]
    {
        write("elsewhere/env", "A=1");
        std::os::unix::fs::symlink(root.join("elsewhere/env"), root.join(".env")).unwrap();
        let linked = digest(&roots);
        assert_ne!(linked, baseline);
        write("elsewhere/env", "A=2");
        assert_ne!(digest(&roots), linked, "what a read through the link finds");
        std::fs::remove_file(root.join(".env")).unwrap();
        assert_eq!(digest(&roots), baseline);
    }
    write("third_party/rust/foo/src/lib.rs", "pub fn b() {}\n");
    assert_ne!(digest(&roots), baseline, "the package's content");
    write("third_party/rust/foo/src/lib.rs", "pub fn a() {}\n");
    assert_eq!(digest(&roots), baseline);
    write("target/debug/build/foo-1/out/gen.rs", "// other\n");
    assert_ne!(digest(&roots), baseline, "OUT_DIR");

    let vendored = digest(&roots);
    roots.vendored_package = None;
    assert_ne!(digest(&roots), vendored, "not the workspace digest");
}

/// A vendored unit's guard walks the files at the top of each directory
/// between the package and the workspace root, which its digest reads, and
/// each such directory's own times, but not what the directories beside the
/// package hold.
#[test]
fn a_vendored_guard_moves_with_a_file_at_the_top_of_an_ancestor() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    write_file(&root.join("Cargo.toml"), "[workspace]\n");
    write_file(&root.join(".env"), "A=1");
    write_file(&root.join("docs/a.md"), "");
    write_file(
        &root.join("third_party/rust/foo/.cargo-checksum.json"),
        "{}",
    );
    write_file(&root.join("third_party/rust/foo/src/lib.rs"), "");
    write_file(&root.join("third_party/rust/bar/src/lib.rs"), "");
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.canonicalize().unwrap(),
        target: root.join("target"),
        canonical_target: root.join("target"),
        out_dir: None,
        vendored_package: Some(root.join("third_party/rust/foo")),
    };
    // Old times, so a name added beside the package moves them on any clock.
    let old = filetime::FileTime::from_unix_time(1_000_000_000, 0);
    for directory in [
        root.clone(),
        root.join("third_party"),
        root.join("third_party/rust"),
    ] {
        filetime::set_file_mtime(directory, old).unwrap();
    }
    let hasher = FileHasher::new();
    let taken = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher)).unwrap();
    assert!(taken.held());
    write_file(&root.join("docs/b.md"), "");
    write_file(&root.join("third_party/rust/bar/src/more.rs"), "");
    assert!(taken.held(), "the rest of the tree");
    write_file(&root.join(".env"), "A=12");
    assert!(!taken.held(), "a file at the top of the workspace");
    let taken = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher)).unwrap();
    write_file(&root.join("third_party/rust/baz/src/lib.rs"), "");
    assert!(
        !taken.held(),
        "a directory added beside the package while the unit compiles"
    );
}

/// A workspace at `root` with `third_party/rust/foo` vendored into it, and
/// the roots of a unit of that package.
fn vendored_workspace(root: &Path) -> WorkspaceRoots {
    write_file(&root.join("Cargo.toml"), "[workspace]\n");
    write_file(
        &root.join("third_party/rust/foo/.cargo-checksum.json"),
        "{}",
    );
    write_file(&root.join("third_party/rust/foo/src/lib.rs"), "");
    WorkspaceRoots {
        root: root.to_path_buf(),
        cwd: String::new(),
        canonical_root: root.canonicalize().unwrap(),
        target: root.join("target"),
        canonical_target: root.join("target"),
        out_dir: None,
        vendored_package: Some(root.join("third_party/rust/foo")),
    }
}

/// A vendored unit's guard reads the dot-directories at the top of each
/// ancestor, but not Kache's own cache there: it changes while units build.
#[test]
fn a_vendored_guard_leaves_out_kaches_cache_at_an_ancestor() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let roots = vendored_workspace(&root);
    let cache = root.join(".kache");
    write_file(&cache.join("index.db"), "a");
    let hasher = FileHasher::new().with_own_dirs([cache.clone()]);
    let taken = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher)).unwrap();
    write_file(&cache.join("index.db"), "ab");
    assert!(taken.held(), "the store moved");
    let again = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher)).unwrap();
    assert_eq!(again.digest, taken.digest);
    let counted = FileHasher::new();
    let before = workspace_tree_digest(&roots, &counted).unwrap();
    write_file(&cache.join("index.db"), "abc");
    assert_ne!(
        workspace_tree_digest(&roots, &counted).unwrap(),
        before,
        "another dot-directory there counts"
    );
}

/// A file or dot-directory that came and went at the top of an ancestor
/// while the unit compiled leaves the digest as it was, so a record could
/// pair that digest with output a macro made from it. The ancestor's own
/// times show it.
#[test]
fn a_vendored_guard_moves_with_a_name_that_came_and_went_at_an_ancestor() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let roots = vendored_workspace(&root);
    let hasher = FileHasher::new();
    let old = filetime::FileTime::from_unix_time(1_000_000_000, 0);
    for (name, directory) in [(".env", None), (".sqlx/query.json", Some(".sqlx"))] {
        filetime::set_file_mtime(&root, old).unwrap();
        let taken = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher)).unwrap();
        write_file(&root.join(name), "x");
        std::fs::remove_file(root.join(name)).unwrap();
        if let Some(directory) = directory {
            std::fs::remove_dir(root.join(directory)).unwrap();
        }
        assert_eq!(
            workspace_tree_digest(&roots, &hasher).as_deref(),
            Some(taken.digest.as_str()),
            "{name} left nothing to digest"
        );
        assert!(!taken.held(), "{name} came and went");
    }
}

/// A vendored guard lists the top of an ancestor after stamping it. Listed
/// before, a name that appeared between the two would be in the stamp and
/// not in the digest, and once it was gone the digest would match again.
#[test]
fn a_vendored_guard_digests_what_its_ancestor_stamp_saw() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    let roots = vendored_workspace(&root);
    let hasher = FileHasher::new();
    let ancestor = root.clone();
    let mut pending = true;
    set_before_stamp(Some(Box::new(move |path: &Path| {
        if pending && path == ancestor {
            pending = false;
            std::fs::write(ancestor.join(".env"), "A=1").unwrap();
        }
    })));
    let taken = tree_guard_of(&hasher, || workspace_tree_digest(&roots, &hasher));
    set_before_stamp(None);
    let taken = taken.unwrap();
    assert!(
        root.join(".env").exists(),
        "the name appeared before the stamp"
    );
    assert!(taken.held());
    assert_eq!(
        workspace_tree_digest(&roots, &hasher).as_deref(),
        Some(taken.digest.as_str()),
        "the digest holds the name its stamp saw"
    );
}

/// A file at the top of an ancestor that the build cannot read counts as
/// unreadable in a vendored unit's guard, as it does in the workspace guard.
#[cfg(unix)]
#[test]
fn a_vendored_guard_counts_an_unreadable_ancestor_file_as_unreadable() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    write_file(&root.join("Cargo.toml"), "[workspace]\n");
    write_file(&root.join(".env"), "A=1");
    write_file(
        &root.join("third_party/rust/foo/.cargo-checksum.json"),
        "{}",
    );
    write_file(&root.join("third_party/rust/foo/src/lib.rs"), "");
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.canonicalize().unwrap(),
        target: root.join("target"),
        canonical_target: root.join("target"),
        out_dir: None,
        vendored_package: Some(root.join("third_party/rust/foo")),
    };
    let hasher = FileHasher::new();
    let readable = workspace_tree_digest(&roots, &hasher).unwrap();
    let env = root.join(".env");
    struct Readable(PathBuf);
    impl Drop for Readable {
        fn drop(&mut self) {
            let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o644));
        }
    }
    let _env = Readable(env.clone());
    std::fs::set_permissions(&env, std::fs::Permissions::from_mode(0o000)).unwrap();
    if std::fs::read(&env).is_ok() {
        eprintln!("skipped: this user reads past permissions");
        return;
    }
    let unreadable = workspace_tree_digest(&roots, &hasher).expect("a file it cannot read");
    assert_ne!(unreadable, readable);
}

#[test]
fn same_dir_is_equal_spelling_or_one_place() {
    let dir = tempfile::tempdir().unwrap();
    let missing = dir.path().join("missing");
    assert!(
        same_dir(&missing, &missing),
        "spelled the same, even if absent"
    );
    assert!(!same_dir(&missing, &dir.path().join("other")));
    let real = dir.path().join("real");
    std::fs::create_dir(&real).unwrap();
    #[cfg(unix)]
    {
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        assert!(same_dir(&link, &real), "the same place by another spelling");
    }
}

#[test]
fn a_vendored_source_is_what_cargo_says_it_is() {
    let dir = tempfile::tempdir().unwrap();
    let (root, relative) = workspace_invocation(dir.path(), "a", "kt");
    let package = root.join("kt");
    let vars = manifest_vars(&package);
    std::fs::write(package.join(".cargo-checksum.json"), "{}").unwrap();
    // How Cargo invokes rustc for a vendored package: an absolute source,
    // run from the package, lints capped.
    let mut vendored = relative.clone();
    vendored.source_file = Some(package.join("src/lib.rs"));
    vendored.outcome_lint_flags = vec!["--cap-lints".into(), "allow".into()];
    let vendored_package = |args: &RustcArgs, cwd: &Path| {
        workspace_roots_in(args, &vars, cwd)
            .unwrap()
            .vendored_package
    };
    assert_eq!(vendored_package(&vendored, &package), Some(package.clone()));

    let mut member = vendored.clone();
    member.source_file = relative.source_file.clone();
    assert_eq!(
        vendored_package(&member, &root),
        None,
        "a path package inside the workspace, however its lints are capped"
    );
    assert_eq!(
        vendored_package(&vendored, &root),
        None,
        "run from the workspace root"
    );
    let mut uncapped = vendored.clone();
    uncapped.outcome_lint_flags = vec!["--cap-lints".into(), "warn".into()];
    assert_eq!(
        vendored_package(&uncapped, &package),
        None,
        "not capped by Cargo"
    );
    let mut escaping = vendored.clone();
    escaping.source_file = Some(dir.path().join("elsewhere/lib.rs"));
    assert_eq!(
        vendored_package(&escaping, &package),
        None,
        "a source outside the package, as a `[lib] path` can name"
    );
    std::fs::remove_file(package.join(".cargo-checksum.json")).unwrap();
    assert_eq!(
        vendored_package(&vendored, &package),
        None,
        "no checksum file"
    );
}

#[test]
fn the_workspace_guard_gives_up_past_its_entry_budget() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("w");
    std::fs::create_dir_all(root.join("target")).unwrap();
    for name in ["a", "b", "c"] {
        std::fs::write(root.join(name), name).unwrap();
    }
    let roots = WorkspaceRoots {
        root: root.clone(),
        cwd: String::new(),
        canonical_root: root.clone(),
        target: root.join("target"),
        canonical_target: root.join("target"),
        out_dir: None,
        vendored_package: None,
    };
    let hasher = FileHasher::new();
    // Three files; `target` is skipped before it is counted.
    assert!(workspace_tree_digest_within(&roots, &hasher, 3).is_some());
    assert!(workspace_tree_digest_within(&roots, &hasher, 2).is_none());
}

#[test]
fn a_portable_record_relocates_out_dir_and_keeps_registry_paths() {
    let dep_info = DepInfo {
        source_files: vec![
            PathBuf::from("/h/registry/src/index-1/kt-1.0.0/src/lib.rs"),
            PathBuf::from("/t/debug/build/kt-1/out\\version.expr"),
            PathBuf::from("/t/debug/build/kt-1/out/gen.rs"),
        ],
        env_deps: vec![
            ("OUT_DIR".to_string(), "/t/debug/build/kt-1/out".to_string()),
            ("CARGO_PKG_NAME".to_string(), "kt".to_string()),
        ],
    };
    assert_eq!(
        portable_prediction(&dep_info, &portable_roots_for_test(), Some("tree-1")),
        Some(portable_test_record())
    );
}

#[test]
fn a_portable_record_refuses_anything_that_could_name_another_file() {
    let roots = portable_roots_for_test();
    let lib = "/h/registry/src/index-1/kt-1.0.0/src/lib.rs";
    let generated = "/t/debug/build/kt-1/out/gen.rs";
    let portable = |sources: &[&str], env: &[(&str, &str)], tree: Option<&str>| {
        let dep_info = DepInfo {
            source_files: sources.iter().map(PathBuf::from).collect(),
            env_deps: env
                .iter()
                .map(|(name, value)| (name.to_string(), value.to_string()))
                .collect(),
        };
        portable_prediction(&dep_info, &roots, tree)
    };
    assert!(portable(&[lib, generated], &[], Some("tree")).is_some());
    for (source, why) in [
        ("/t/debug/build/other-2/out/x.rs", "another unit's output"),
        (
            "/private/t/debug/build/kt-1/out/gen.rs",
            "a canonical spelling of the target",
        ),
        ("/w/src/lib.rs", "a checkout path"),
        ("src/lib.rs", "a relative path"),
        (
            "/t/debug/build/kt-1/out/../../other-2/out/x.rs",
            "a parent component that leaves OUT_DIR",
        ),
        (
            "/h/registry/src/../x.rs",
            "a parent component under the registry",
        ),
    ] {
        assert_eq!(
            portable(&[lib, generated, source], &[], Some("tree")),
            None,
            "{why}"
        );
    }
    assert_eq!(portable(&[lib, generated], &[], None), None, "no guard");
    assert_eq!(
        portable(&[lib], &[], Some("tree")),
        None,
        "nothing to relocate"
    );
    for value in ["/t/debug/deps", "/private/t/debug/build/kt-1/out"] {
        assert_eq!(
            portable(&[lib, generated], &[("X", value)], Some("tree")),
            None,
            "{value} spells the target"
        );
    }
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        let dep_info = DepInfo {
            source_files: vec![
                PathBuf::from(generated),
                PathBuf::from(std::ffi::OsStr::from_bytes(b"/h/registry/src/i/\xff.rs")),
            ],
            env_deps: Vec::new(),
        };
        assert_eq!(
            portable_prediction(&dep_info, &roots, Some("tree")),
            None,
            "a literal that is not UTF-8"
        );
    }
}

/// The relocated row follows the shared row's rule: a `..` inside the
/// package stays a literal, one inside `OUT_DIR` is relocated as spelled,
/// and one that leaves either refuses the row.
#[test]
fn a_portable_record_keeps_a_parent_path_inside_out_dir_or_the_package() {
    let roots = portable_roots_for_test();
    let readme = "/h/registry/src/index-1/kt-1.0.0/src/../README.md";
    let generated = "/t/debug/build/kt-1/out/sub/../gen.rs";
    let portable = |sources: &[&str]| {
        let dep_info = DepInfo {
            source_files: sources.iter().map(PathBuf::from).collect(),
            env_deps: Vec::new(),
        };
        portable_prediction(&dep_info, &roots, Some("tree"))
    };
    assert_eq!(
        portable(&[readme, generated]).map(|record| record.sources),
        Some(vec![
            Portable::Literal(readme.to_string()),
            Portable::OutDir("/sub/../gen.rs".to_string()),
        ])
    );
    for (source, why) in [
        (
            "/h/registry/src/index-1/kt-1.0.0/src/../../other-1.0/lib.rs",
            "leaves the package",
        ),
        ("/t/debug/build/kt-1/out/../out/gen.rs", "leaves OUT_DIR"),
    ] {
        assert_eq!(portable(&[generated, source]), None, "{why}");
    }
}

#[test]
fn a_portable_record_resolves_to_this_out_dir_byte_for_byte() {
    assert_eq!(
        portable_test_record().resolve(&Places {
            out_dir: Some("/u/debug/build/kt-1/out"),
            workspace: None,
            registry: None,
        }),
        Some(InputPrediction {
            schema: PREDICTION_SCHEMA,
            sources: vec![
                PathBuf::from("/h/registry/src/index-1/kt-1.0.0/src/lib.rs"),
                PathBuf::from("/u/debug/build/kt-1/out\\version.expr"),
                PathBuf::from("/u/debug/build/kt-1/out/gen.rs"),
            ],
            env_deps: vec![
                ("OUT_DIR".to_string(), "/u/debug/build/kt-1/out".to_string()),
                ("CARGO_PKG_NAME".to_string(), "kt".to_string()),
            ],
            tree: Some("tree-1".to_string()),
        })
    );
}

/// Relocation replaces the prefix only; the raw env value still has to
/// agree, and the guard has to be the one the row was made with.
#[test]
fn a_relocated_record_is_checked_against_this_out_dir_and_guard() {
    let file = tempfile::NamedTempFile::new().unwrap();
    let record = PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![Portable::OutDir("/gen.rs".to_string())],
        env_deps: vec![("OUT_DIR".to_string(), Portable::OutDir(String::new()))],
        tree: "tree-1".to_string(),
    };
    let check = |guard: &str, env_out_dir: &str| {
        validate_portable_prediction(
            &record,
            guard,
            &Places {
                out_dir: Some("/u/out"),
                workspace: None,
                registry: None,
            },
            |_| std::fs::metadata(file.path()).ok(),
            |_| false,
            |var| (var == "OUT_DIR").then(|| env_out_dir.to_string()),
        )
    };
    assert_eq!(
        check("tree-1", "/u/out"),
        Ok(DepInfo {
            source_files: vec![PathBuf::from("/u/out/gen.rs")],
            env_deps: vec![("OUT_DIR".to_string(), "/u/out".to_string())],
        })
    );
    assert_eq!(check("tree-1", "/v/out"), Err(Rejection::EnvChanged));
    assert_eq!(check("tree-2", "/u/out"), Err(Rejection::TreeChanged));
}

#[test]
fn mentions_root_finds_raw_canonical_and_escaped_spellings() {
    let raw = Path::new("/t/target");
    let canonical = Path::new("/private/t/target");
    assert!(mentions_root(b"// built in /t/target/debug\n", &[raw]));
    assert!(
        mentions_root(
            b"x /private/t/target/y",
            &[Path::new("/nowhere"), canonical]
        ),
        "any root"
    );
    assert!(!mentions_root(b"pub fn generated() {}", &[raw, canonical]));
    let windows = Path::new("C:\\t\\target");
    assert!(mentions_root(b"C:\\t\\target\\x", &[windows]), "as-is");
    assert!(
        mentions_root(b"\"C:\\\\t\\\\target\\\\x.rs\"", &[windows]),
        "escaped in a string literal"
    );
    assert!(!mentions_root(b"C:/t/target", &[windows]));
}

#[test]
fn an_out_dir_is_relocatable_only_when_no_file_names_the_target() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("target");
    let out = target.join("debug/build/kt-1/out");
    std::fs::create_dir_all(out.join("nested")).unwrap();
    std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    std::fs::write(out.join("nested/more.rs"), "pub fn h() {}\n").unwrap();
    let roots = [target.as_path()];
    assert!(out_dir_spells_no_root(&out, &roots));
    std::fs::write(
        out.join("nested/more.rs"),
        format!("// {}\n", target.display()),
    )
    .unwrap();
    assert!(!out_dir_spells_no_root(&out, &roots), "a nested file");
    std::fs::write(out.join("nested/more.rs"), "pub fn h() {}\n").unwrap();
    #[cfg(unix)]
    {
        let link = out.join("link.rs");
        std::os::unix::fs::symlink(target.join("elsewhere.rs"), &link).unwrap();
        assert!(!out_dir_spells_no_root(&out, &roots), "a symlink's text");
        std::fs::remove_file(link).unwrap();
    }
    assert!(out_dir_spells_no_root(&out, &roots));
    assert!(
        !out_dir_spells_no_root(&dir.path().join("absent"), &roots),
        "a directory that cannot be read"
    );
    // 3 entries so far; the cap counts every entry.
    for index in 3..OUT_DIR_TREE_MAX_ENTRIES {
        std::fs::write(out.join(format!("f{index}")), "x").unwrap();
    }
    assert!(out_dir_spells_no_root(&out, &roots), "exactly at the cap");
    std::fs::write(out.join("one-more"), "x").unwrap();
    assert!(!out_dir_spells_no_root(&out, &roots), "past the cap");
}

#[test]
fn the_out_dir_guard_follows_content_and_stops_at_its_cap() {
    let dir = tempfile::tempdir().unwrap();
    let hasher = FileHasher::new();
    let a = dir.path().join("a/out");
    let b = dir.path().join("b/out");
    for out in [&a, &b] {
        std::fs::create_dir_all(out).unwrap();
        std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    }
    let guard = out_dir_tree_digest(&a, &hasher).unwrap();
    assert_eq!(
        out_dir_tree_digest(&b, &hasher).as_deref(),
        Some(guard.as_str())
    );
    std::fs::write(b.join("extra.rs"), "").unwrap();
    assert_ne!(
        out_dir_tree_digest(&b, &hasher).unwrap(),
        guard,
        "a new file"
    );
    for index in 2..OUT_DIR_TREE_MAX_ENTRIES {
        std::fs::write(b.join(format!("f{index}")), "x").unwrap();
    }
    assert!(
        out_dir_tree_digest(&b, &hasher).is_some(),
        "exactly at the cap"
    );
    std::fs::write(b.join("one-more"), "x").unwrap();
    assert_eq!(out_dir_tree_digest(&b, &hasher), None, "past the cap");
}

/// A build script can put anything in `OUT_DIR`, a nested `target` or a
/// git checkout included, and a macro scanning `OUT_DIR` reads it all.
/// Both guards that cover `OUT_DIR` digest it all; only the crate
/// directory skips those names.
#[test]
fn the_out_dir_guards_cover_target_and_git_under_out_dir() {
    let dir = tempfile::tempdir().unwrap();
    let hasher = FileHasher::new();
    let package = dir.path().join("registry/src/index/kt-1.0.0");
    let out = dir.path().join("out");
    for directory in [&package, &out] {
        std::fs::create_dir_all(directory).unwrap();
        std::fs::write(directory.join("lib.rs"), "pub fn g() {}\n").unwrap();
    }
    let guards = || {
        (
            out_dir_tree_digest(&out, &hasher).unwrap(),
            crate_tree_digest_in(package.clone(), Some(out.clone()), &hasher).unwrap(),
        )
    };
    let before = guards();
    for name in ["target", ".git"] {
        std::fs::create_dir_all(package.join(name)).unwrap();
        std::fs::write(package.join(name).join("x"), "x").unwrap();
    }
    assert_eq!(guards().1, before.1, "the crate directory skips them");
    for name in ["target", ".git"] {
        let nested = out.join(name);
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(nested.join("x"), "x").unwrap();
        let after = guards();
        assert_ne!(after.0, before.0, "{name} under OUT_DIR, OUT_DIR guard");
        assert_ne!(after.1, before.1, "{name} under OUT_DIR, crate tree guard");
        std::fs::remove_dir_all(nested).unwrap();
    }
    assert_eq!(guards(), before);
}

/// A relocated row round-trips, and neither decoder accepts the other's
/// schema, whatever identity it is looked up under.
#[test]
fn a_portable_prediction_round_trips_and_no_other_decoder_reads_it() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("index.db");
    let hasher = FileHasher::persistent(&db);
    let record = portable_test_record();
    assert_eq!(hasher.portable_prediction("unit"), None);
    hasher.record_portable_prediction("unit", Some("kt"), &record);
    assert_eq!(
        FileHasher::persistent(&db).portable_prediction("unit"),
        Some(record)
    );
    assert_eq!(hasher.input_prediction("unit"), None);
    hasher.record_input_prediction(
        "plain",
        Some("kt"),
        &DepInfo {
            source_files: vec![PathBuf::from("/w/src/lib.rs")],
            env_deps: Vec::new(),
        },
        Some("tree".to_string()),
    );
    assert_eq!(hasher.portable_prediction("plain"), None);
    let cache = hasher.cache.as_ref().unwrap();
    cache
        .put_input_prediction("corrupt", PORTABLE_PREDICTION_SCHEMA, None, "not json")
        .unwrap();
    assert_eq!(hasher.portable_prediction("corrupt"), None);
    let stale = serde_json::to_string(&PortablePrediction {
        schema: PREDICTION_SCHEMA,
        ..portable_test_record()
    })
    .unwrap();
    cache
        .put_input_prediction("mismatched", PORTABLE_PREDICTION_SCHEMA, None, &stale)
        .unwrap();
    assert_eq!(hasher.portable_prediction("mismatched"), None);

    let no_db = FileHasher::new();
    no_db.record_portable_prediction("unit", None, &portable_test_record());
    assert_eq!(no_db.portable_prediction("unit"), None);
}

/// A tree the recorder wrote the relocated row from, in a temporary
/// registry: the package, and target `a` with its OUT_DIR.
fn relocatable_fixture() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    let package = dir.path().join("home/registry/src/index-1/kt-1.0.0");
    std::fs::create_dir_all(package.join("src")).unwrap();
    std::fs::write(package.join("src/lib.rs"), "include!(\"x\");\n").unwrap();
    let target = dir.path().join("a/target");
    let out = target.join("debug/build/kt-1/out");
    std::fs::create_dir_all(&out).unwrap();
    std::fs::create_dir_all(target.join("debug/deps")).unwrap();
    std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    (dir, package, target, out)
}

fn unit_args_in(package: &Path, target: &Path) -> RustcArgs {
    RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "kt".to_string(),
        package.join("src/lib.rs").display().to_string(),
        "--out-dir".to_string(),
        target.join("debug/deps").display().to_string(),
    ])
    .unwrap()
}

#[test]
fn a_relocatable_record_needs_a_registry_unit_and_a_clean_out_dir() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let (dir, package, target, out) = relocatable_fixture();
    let args = unit_args_in(&package, &target);
    let vars = |manifest_dir: &Path| {
        vec![
            ("CARGO_MANIFEST_DIR".into(), manifest_dir.into()),
            ("OUT_DIR".into(), out.clone().into()),
        ]
    };
    let dep_info = DepInfo {
        source_files: vec![package.join("src/lib.rs"), out.join("gen.rs")],
        env_deps: Vec::new(),
    };
    let (identity, record) =
        relocatable_record_in(&args, &dep_info, Some("tree"), vars(&package)).unwrap();
    assert_eq!(
        Some(identity),
        relocatable_prediction_identity(&args, vars(&package))
    );
    assert_eq!(
        record.sources,
        vec![
            Portable::Literal(package.join("src/lib.rs").display().to_string()),
            Portable::OutDir(format!("{}gen.rs", std::path::MAIN_SEPARATOR)),
        ]
    );
    assert_eq!(
        relocatable_record_in(
            &args,
            &dep_info,
            Some("tree"),
            vars(&dir.path().join("w/kt"))
        ),
        None,
        "a workspace unit"
    );
    let canonical = std::fs::canonicalize(&target).unwrap();
    for spelled in [&target, &canonical] {
        std::fs::write(out.join("gen.rs"), format!("// {}\n", spelled.display())).unwrap();
        assert_eq!(
            relocatable_record_in(&args, &dep_info, Some("tree"), vars(&package)),
            None,
            "{} is spelled in OUT_DIR",
            spelled.display()
        );
    }
}

/// Through a symlink, the canonical target shares nothing with the raw
/// spelling, so the scan has to look for it on its own.
#[cfg(unix)]
#[test]
fn an_out_dir_naming_only_the_canonical_target_is_not_relocated() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let (dir, package, _, _) = relocatable_fixture();
    let real = std::fs::canonicalize(dir.path()).unwrap().join("real");
    std::fs::create_dir_all(real.join("debug/build/kt-1/out")).unwrap();
    std::fs::create_dir_all(real.join("debug/deps")).unwrap();
    let target = dir.path().join("b/target");
    std::fs::create_dir_all(target.parent().unwrap()).unwrap();
    std::os::unix::fs::symlink(&real, &target).unwrap();
    let out = target.join("debug/build/kt-1/out");
    let args = unit_args_in(&package, &target);
    let vars = || {
        vec![
            ("CARGO_MANIFEST_DIR".into(), package.clone().into()),
            ("OUT_DIR".into(), out.clone().into()),
        ]
    };
    let dep_info = DepInfo {
        source_files: vec![package.join("src/lib.rs"), out.join("gen.rs")],
        env_deps: Vec::new(),
    };
    std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    assert!(relocatable_record_in(&args, &dep_info, Some("tree"), vars()).is_some());

    let content = format!("// {}\n", real.display());
    assert!(!mentions_root(content.as_bytes(), &[&target]));
    std::fs::write(out.join("gen.rs"), content).unwrap();
    assert_eq!(
        relocatable_record_in(&args, &dep_info, Some("tree"), vars()),
        None
    );
}

/// A workspace unit never reads a relocated row, even one filed under the
/// identity it would have: its package is not the same files in another
/// checkout.
#[test]
fn a_workspace_unit_never_reads_a_relocated_record() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let package = dir.path().join("w/kt");
    std::fs::create_dir_all(package.join("src")).unwrap();
    std::fs::write(package.join("src/lib.rs"), "include!(\"x\");\n").unwrap();
    // A path package built from its own directory, as Cargo builds one.
    std::fs::write(package.join("Cargo.toml"), "[package]\n").unwrap();
    std::env::set_current_dir(&package).unwrap();
    let target = dir.path().join("b/target");
    let out = target.join("debug/build/kt-1/out");
    std::fs::create_dir_all(&out).unwrap();
    std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    let _manifest =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(package.as_os_str()));
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", Some(out.as_os_str()));
    let args = unit_args_in(&package, &target);
    let hasher = FileHasher::persistent(&dir.path().join("index.db")).with_input_predictions(true);
    let shared = rustc_shared_prediction_identity(&args).unwrap();
    let would_be = format!(
        "{RELOCATABLE_PREDICTION_PREFIX}{}",
        shared.strip_prefix(SHARED_PREDICTION_PREFIX).unwrap()
    );
    let record = PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![
            Portable::Literal(package.join("src/lib.rs").display().to_string()),
            Portable::OutDir("/gen.rs".to_string()),
        ],
        env_deps: vec![("OUT_DIR".to_string(), Portable::OutDir(String::new()))],
        tree: out_dir_tree_digest(&out, &hasher).unwrap(),
    };
    hasher.record_portable_prediction(&would_be, Some("kt"), &record);
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut None),
        Err(Rejection::NoRecord)
    );
}

/// After this checkout's row and the shared one miss, a registry unit
/// reads the relocated row under its OUT_DIR guard, and reports that guard
/// before the lookup so the record it makes carries it.
#[test]
fn a_registry_unit_reads_a_relocated_record_under_its_out_dir_guard() {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let (dir, package, _, _) = relocatable_fixture();
    let target = dir.path().join("b/target");
    let out = target.join("debug/build/kt-1/out");
    std::fs::create_dir_all(&out).unwrap();
    std::fs::write(out.join("gen.rs"), "pub fn g() {}\n").unwrap();
    let _manifest =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(package.as_os_str()));
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", Some(out.as_os_str()));
    let args = unit_args_in(&package, &target);
    let hasher = FileHasher::persistent(&dir.path().join("index.db")).with_input_predictions(true);
    let guard = out_dir_tree_digest(&out, &hasher).unwrap();

    let mut tree = None;
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut tree),
        Err(Rejection::NoRecord)
    );
    assert_eq!(
        tree.map(|guard| guard.digest).as_deref(),
        Some(guard.as_str()),
        "a cold build records the guard it saw before compiling"
    );

    let identity = relocatable_prediction_identity(&args, std::env::vars_os().collect()).unwrap();
    let record = PortablePrediction {
        schema: PORTABLE_PREDICTION_SCHEMA,
        sources: vec![
            Portable::Literal(package.join("src/lib.rs").display().to_string()),
            Portable::OutDir("/gen.rs".to_string()),
        ],
        env_deps: vec![("OUT_DIR".to_string(), Portable::OutDir(String::new()))],
        tree: guard.clone(),
    };
    hasher.record_portable_prediction(&identity, Some("kt"), &record);
    let mut tree = None;
    let dep_info = predicted_key_inputs(&args, &hasher, &mut tree).unwrap();
    assert_eq!(
        dep_info.source_files,
        vec![package.join("src/lib.rs"), out.join("gen.rs")]
    );
    assert_eq!(
        dep_info.env_deps,
        vec![("OUT_DIR".to_string(), out.display().to_string())]
    );
    assert_eq!(tree.map(|guard| guard.digest), Some(guard));

    std::fs::write(out.join("extra.rs"), "").unwrap();
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut None),
        Err(Rejection::TreeChanged),
        "a file added under OUT_DIR changes the guard"
    );
}

/// An aliased `OUT_DIR` (see `out_dir_alias`) is one path outside every
/// target directory, so the shared identity keeps it as it is. Two target
/// directories that alias the unit read one shared row, and a build with
/// its own `OUT_DIR` never reads that row.
///
/// With `macro_dep` the unit links a proc macro, so the row is read under
/// the crate tree guard, and the guard digests the alias as the unit's
/// `OUT_DIR`.
fn an_aliased_out_dir_takes_the_shared_row(macro_dep: bool) {
    let _lock = key_test_lock();
    if get_rustc_version(Path::new("rustc")).is_err() {
        return;
    }
    let (dir, package, target_a, _) = relocatable_fixture();
    let target_b = dir.path().join("b/target");
    let own_out_dir = target_b.join("debug/build/kt-1/out");
    std::fs::create_dir_all(&own_out_dir).unwrap();
    std::fs::create_dir_all(target_b.join("debug/deps")).unwrap();
    let alias = dir
        .path()
        .join("cache/out-dirs/v1/d/kt-0123456789abcdef/out");
    std::fs::create_dir_all(&alias).unwrap();
    let vars = |out_dir: &Path| {
        vec![
            ("CARGO_MANIFEST_DIR".into(), package.clone().into()),
            ("OUT_DIR".into(), out_dir.into()),
        ]
    };
    let args_in = |target: &Path| {
        let deps = target.join("debug/deps");
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "kt".to_string(),
            package.join("src/lib.rs").display().to_string(),
            "--out-dir".to_string(),
            deps.display().to_string(),
        ];
        if macro_dep {
            argv.push("--extern".to_string());
            argv.push(format!("pm={}", deps.join("libpm-1.so").display()));
        }
        RustcArgs::parse(&argv).unwrap()
    };
    let args_a = args_in(&target_a);
    let args_b = args_in(&target_b);
    assert_eq!(has_dylib_extern(&args_a.externs), macro_dep);
    let shared = |args: &RustcArgs, out_dir: &Path| {
        rustc_shared_prediction_identity_in(args, vars(out_dir)).unwrap()
    };
    assert_eq!(shared(&args_a, &alias), shared(&args_b, &alias));
    assert_ne!(shared(&args_b, &alias), shared(&args_b, &own_out_dir));

    let debug_dir = alias.join("debug");
    let dep_info = DepInfo {
        source_files: vec![package.join("src/lib.rs")],
        env_deps: vec![
            ("OUT_DIR".to_string(), alias.display().to_string()),
            (
                "DEBUG_OUTPUT_DIR".to_string(),
                debug_dir.display().to_string(),
            ),
        ],
    };
    for args in [&args_a, &args_b] {
        assert!(shared_prediction_can_record_in(
            args,
            &dep_info,
            Some(&package)
        ));
    }

    let _manifest =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(package.as_os_str()));
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", Some(alias.as_os_str()));
    let _debug =
        crate::config::tests::set_env_for_test("DEBUG_OUTPUT_DIR", Some(debug_dir.as_os_str()));
    let hasher = FileHasher::persistent(&dir.path().join("index.db")).with_input_predictions(true);
    let tree = macro_dep.then(|| crate_tree_digest(&hasher).unwrap());
    let identity = rustc_shared_prediction_identity(&args_a).unwrap();
    hasher.record_input_prediction(&identity, Some("kt"), &dep_info, tree);
    assert_eq!(
        predicted_key_inputs(&args_b, &hasher, &mut None),
        Ok(dep_info)
    );

    if macro_dep {
        std::fs::write(alias.join("stray.rs"), "").unwrap();
        assert_eq!(
            predicted_key_inputs(&args_b, &hasher, &mut None),
            Err(Rejection::TreeChanged),
            "the tree guard reads the alias as OUT_DIR"
        );
        std::fs::remove_file(alias.join("stray.rs")).unwrap();
    }

    let _own = crate::config::tests::set_env_for_test("OUT_DIR", Some(own_out_dir.as_os_str()));
    assert_eq!(
        predicted_key_inputs(&args_b, &hasher, &mut None),
        Err(Rejection::NoRecord),
        "a build with its own OUT_DIR has another identity"
    );
}

#[test]
fn an_aliased_out_dir_takes_the_shared_row_without_a_macro_dependency() {
    an_aliased_out_dir_takes_the_shared_row(false);
}

#[test]
fn an_aliased_out_dir_takes_the_shared_row_under_the_tree_guard() {
    an_aliased_out_dir_takes_the_shared_row(true);
}

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

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

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

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

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

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

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

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

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

#[test]
fn emitted_closure_keeps_the_precompile_tree_guard() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let package = dir.path().join("registry/src/index/guarded-1.0.0");
    std::fs::create_dir_all(package.join("src")).unwrap();
    let source = package.join("src/lib.rs");
    std::fs::write(&source, "pub fn v() {}\n").unwrap();
    let macro_path = dir.path().join("libmacro.so");
    std::fs::write(&macro_path, "macro artifact").unwrap();
    let out = dir.path().join("target/debug/deps");
    std::fs::create_dir_all(&out).unwrap();
    let _manifest =
        crate::config::tests::set_env_for_test("CARGO_MANIFEST_DIR", Some(package.as_os_str()));
    let _out = crate::config::tests::set_env_for_test("OUT_DIR", None);
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "guarded".to_string(),
        "--crate-type=lib".to_string(),
        "--emit=dep-info,metadata".to_string(),
        source.display().to_string(),
        "--out-dir".to_string(),
        out.display().to_string(),
        "--extern".to_string(),
        format!("my_macro={}", macro_path.display()),
    ])
    .unwrap();
    let db = dir.path().join("index.db");
    rusqlite::Connection::open(&db)
        .unwrap()
        .execute_batch(
            "CREATE TABLE entries (cache_key TEXT PRIMARY KEY, crate_name TEXT NOT NULL);",
        )
        .unwrap();
    let hasher = FileHasher::persistent(&db)
        .with_input_predictions(true)
        .with_prediction_flights(Some(dir.path().join("cache")));
    let original_tree = crate_tree_digest(&hasher).unwrap();
    set_defer_discovery(true);
    let (deferred, deferred_outputs) = compute_cache_key_with_outputs(
        &args,
        &hasher,
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    );
    set_defer_discovery(false);
    assert!(deferred.unwrap_err().is::<DeferredDiscovery>());
    // Let a broken handoff reach the pre-pass and fail, not self-deadlock.
    drop(hasher.take_discovery_flight());

    let closure = DepInfo {
        source_files: vec![source],
        env_deps: Vec::new(),
    };
    // A macro input changed during compilation. Recording the newer tree
    // would make the old emitted closure appear valid for those new files.
    std::fs::write(package.join("macro-input.txt"), "changed").unwrap();
    provide_dep_info(closure.clone(), deferred_outputs.tree_guard);
    let (key, outputs) = compute_cache_key_with_outputs(
        &args,
        &hasher,
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    );
    key.unwrap();
    let tree = outputs.tree_guard.map(|guard| guard.digest);
    assert_eq!(tree.as_deref(), Some(original_tree.as_str()));
    let identity = rustc_prediction_identity(&args).unwrap();
    hasher.record_input_prediction(&identity, Some("guarded"), &closure, tree);
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut None),
        Err(Rejection::TreeChanged)
    );
    std::fs::remove_file(package.join("macro-input.txt")).unwrap();
    assert_eq!(
        predicted_key_inputs(&args, &hasher, &mut None).unwrap(),
        closure
    );
    // An emitted closure without a prior guarded discovery must not
    // inherit the preceding invocation's tree.
    provide_dep_info(closure, None);
    let (key, outputs) = compute_cache_key_with_outputs(
        &args,
        &hasher,
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    );
    key.unwrap();
    assert!(outputs.tree_guard.is_none());
}

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

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

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

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

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

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

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

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

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

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

/// The compiler a target is recorded as built by is what `rustc -vV` says,
/// and nothing when the compiler cannot be run.
#[cfg(unix)]
#[test]
fn rustc_version_text_is_the_compilers_own_description() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let rustc = dir.path().join("rustc");
    kache_fs::testutil::write_executable(
        &rustc,
        "#!/bin/sh\nprintf 'rustc 1.98.0 (fake 2026-09-01)\\nhost: test\\n'\n",
    );
    let text = rustc_version_text(&rustc).expect("a runnable compiler");
    assert!(text.starts_with("rustc 1.98.0 (fake 2026-09-01)"), "{text}");
    assert!(text.contains("host: test"), "{text}");
    assert_eq!(rustc_version_text(&dir.path().join("missing")), None);
}

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

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

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

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

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

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

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

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

/// Cargo passes a bare `rustc` when the toolchain's `bin` directory is on
/// PATH without rustup's proxy. It must find the same cache file as the
/// file a spawn runs; before, it found none and every call spawned
/// `rustc -vV`.
#[cfg(unix)]
#[test]
fn a_bare_compiler_name_finds_its_version_cache_on_path() {
    let _lock = key_test_lock();
    let shadow = tempfile::tempdir().unwrap();
    let dir = tempfile::tempdir().unwrap();
    let empty = tempfile::tempdir().unwrap();
    // Earlier on PATH but not executable: a spawn skips it, and so must we.
    std::fs::write(shadow.path().join("kache-test-rustc"), b"not runnable").unwrap();
    let binary = dir.path().join("kache-test-rustc");
    kache_fs::testutil::write_executable(&binary, "#!/bin/sh\n");
    let path_var = std::env::join_paths([empty.path(), shadow.path(), dir.path()]).unwrap();
    let bare = Path::new("kache-test-rustc");

    assert_eq!(
        program_path(bare, Some(&path_var)).as_deref(),
        Some(binary.as_path()),
        "a bare name resolves to the file a spawn runs"
    );
    let resolved = tool_version_cache_path_in(bare, "rustc-ver", Some(&path_var));
    assert!(resolved.is_some(), "a bare name on PATH has a cache file");
    assert_eq!(
        resolved,
        tool_version_cache_path_in(&binary, "rustc-ver", Some(&path_var))
    );
    assert_eq!(
        tool_version_cache_path_in(bare, "rustc-ver", Some(empty.path().as_os_str())),
        None,
        "a bare name absent from PATH has none"
    );
    // A name with a directory is not searched for.
    let relative = Path::new("bin").join("kache-test-rustc");
    assert_eq!(
        program_path(&relative, Some(&path_var)).as_deref(),
        Some(relative.as_path())
    );
}

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

    assert_eq!(rustup_home(), Some(expected_home));
}

/// #1406: `rustup update nightly` swaps the toolchain behind an unchanged
/// shim and an unchanged selection. The version probe must see the new
/// compiler, or its old `rustc -vV` keys entries the new one cannot read.
#[cfg(unix)]
#[test]
#[ignore = "spawned by the toolchain update regression"]
fn rustc_version_after_toolchain_update_fixture() {
    let home = std::env::var_os("RUSTUP_HOME")
        .map(PathBuf::from)
        .expect("fixture requires an isolated RUSTUP_HOME");
    let toolchain_rustc = home.join("toolchains/nightly-test/bin/rustc");
    let shim = home.join("shim/rustc");
    for file in [&toolchain_rustc, &shim] {
        std::fs::create_dir_all(file.parent().unwrap()).unwrap();
    }
    let install = |commit: &str, mtime: i64| {
        kache_fs::testutil::write_executable(
            &toolchain_rustc,
            format!("#!/bin/sh\necho 'rustc 1.101.0-nightly ({commit})'\n"),
        );
        filetime::set_file_mtime(
            &toolchain_rustc,
            filetime::FileTime::from_unix_time(mtime, 0),
        )
        .unwrap();
    };
    // The shim stays put, like `~/.cargo/bin/rustc` or Homebrew's wrapper.
    kache_fs::testutil::write_executable(
        &shim,
        format!("#!/bin/sh\nexec '{}' \"$@\"\n", toolchain_rustc.display()),
    );

    install("c1070d693", 1_790_000_000);
    assert_eq!(
        get_rustc_version(&shim).unwrap(),
        "rustc 1.101.0-nightly (c1070d693)"
    );
    install("21b707e3f", 1_790_200_000);
    assert_eq!(
        get_rustc_version(&shim).unwrap(),
        "rustc 1.101.0-nightly (21b707e3f)"
    );
}

#[cfg(unix)]
#[test]
fn rustc_version_follows_a_toolchain_update_behind_its_shim() {
    let cache_dir = crate::config::default_cache_dir();
    if std::fs::create_dir_all(&cache_dir).is_err() || tempfile::tempfile_in(&cache_dir).is_err() {
        eprintln!("skipping: {} is not writable", cache_dir.display());
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let output = std::process::Command::new(
        std::env::current_exe().expect("resolve cache-key test executable"),
    )
    .args([
        "--ignored",
        "--exact",
        "cache_key::tests::rustc_version_after_toolchain_update_fixture",
        "--test-threads=1",
    ])
    .env("RUSTUP_HOME", dir.path())
    .env_remove("RUSTUP_TOOLCHAIN")
    .output()
    .expect("spawn isolated toolchain update fixture");

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

/// What the fingerprint must notice, and what it must not depend on.
#[test]
fn installed_toolchains_fingerprint_tracks_installed_compilers() {
    let dir = tempfile::tempdir().unwrap();
    let toolchains = dir.path().join("toolchains");
    assert_eq!(installed_toolchains_fingerprint(None), "");
    assert_eq!(installed_toolchains_fingerprint(Some(&toolchains)), "");

    let rustc = format!("rustc{}", std::env::consts::EXE_SUFFIX);
    let install = |name: &str, content: &str, mtime: i64| {
        let path = toolchains.join(name).join("bin").join(&rustc);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, content).unwrap();
        filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(mtime, 0)).unwrap();
    };
    install("stable", "stable", 1_000);
    install("nightly", "old", 2_000);
    let base = installed_toolchains_fingerprint(Some(&toolchains));
    assert_eq!(base, installed_toolchains_fingerprint(Some(&toolchains)));

    // An update with the same size still moves the mtime.
    install("nightly", "new", 3_000);
    let updated = installed_toolchains_fingerprint(Some(&toolchains));
    assert_ne!(updated, base);
    // A rebuild that keeps the mtime still changes the size.
    install("nightly", "newer", 3_000);
    let rebuilt = installed_toolchains_fingerprint(Some(&toolchains));
    assert_ne!(rebuilt, updated);
    // Installing a toolchain, even one with no compiler yet, moves it.
    std::fs::create_dir_all(toolchains.join("beta")).unwrap();
    assert_ne!(installed_toolchains_fingerprint(Some(&toolchains)), rebuilt);
}

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

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

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

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

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

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

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

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

#[test]
fn source_scanner_detects_runtime_env_use_and_skips_literals() {
    use super::SourceEnvDepUse::{IncludeLocator, RuntimeValue, Unused};
    use super::source_env_dep_use as scan;

    // A bare runtime env! use is a real dependency.
    assert_eq!(
        scan(r#"const X: &str = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let v = option_env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"const N: usize = env!("MYVAR").len();"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"const P: usize = env!("MYVAR").len() % 2;"#, "MYVAR"),
        RuntimeValue
    );
    // A different var name doesn't match, and proves nothing.
    assert_eq!(scan(r#"env!("OTHER")"#, "MYVAR"), Unused);
    assert_eq!(
        scan(r#"include!(concat!(env!("OTHER"), "/gen.rs"));"#, "MYVAR"),
        Unused
    );
    assert_eq!(scan("pub fn f() {}", "MYVAR"), Unused);

    // env! nested inside include!(concat!(...)) is a compile-time include,
    // not a runtime value, and is the positive proof normalization needs.
    assert_eq!(
        scan(r#"include!(concat!(env!("MYVAR"), "/gen.rs"));"#, "MYVAR"),
        IncludeLocator
    );
    assert_eq!(
        scan(r#"include_bytes![env!("MYVAR")];"#, "MYVAR"),
        IncludeLocator
    );
    assert_eq!(
        scan(r#"include_str! { env! { "MYVAR" } }"#, "MYVAR"),
        IncludeLocator
    );
    // The include context ends at the include's own closing delimiter.
    assert_eq!(
        scan(
            r#"include!{ concat!(env!("MYVAR"), "/gen.rs") } const X: &str = env!("MYVAR");"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"f(include!(env!("MYVAR"))); [env!("MYVAR")];"#, "MYVAR"),
        RuntimeValue
    );

    // A name the scanner cannot read counts against every var outside an
    // include, and proves nothing inside one.
    assert_eq!(
        scan(r#"const S: &str = env!(concat!("MY", "VAR"));"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"const S: &str = env!(concat!("OT", "HER"));"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(
            r#"macro_rules! e { ($v:literal) => { env!($v) } } const X: &str = e!("MYVAR");"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    assert_eq!(scan(r#"env!("MY\x56AR")"#, "MYVAR"), RuntimeValue);
    assert_eq!(scan(r##"env!(r#"MYVAR"#)"##, "MYVAR"), RuntimeValue);
    assert_eq!(scan(r#"env!("MYVAR"#, "MYVAR"), RuntimeValue);
    assert_eq!(scan("env!(", "MYVAR"), RuntimeValue);
    assert_eq!(
        scan(
            r#"include!(concat!(env!(concat!("MY", "VAR")), "/gen.rs"));"#,
            "MYVAR"
        ),
        Unused
    );

    // Whitespace and comments between the macro tokens do not hide a use.
    assert_eq!(
        scan(
            r#"env /* c */ ! // c
            ( "MYVAR" )"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    // `!` that is not a macro bang opens no macro group.
    assert_eq!(
        scan(r#"if a != (b) { include!(env!("MYVAR")); }"#, "MYVAR"),
        IncludeLocator
    );

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

    // Nested block comments end at the matching `*/` only.
    assert_eq!(
        scan(
            r#"/* /* */ include!( */ const X: &str = env!("MYVAR");"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    assert_eq!(scan(r#"/*/ env!("MYVAR") */"#, "MYVAR"), Unused);

    // A char literal earlier in the line must not derail scanning of a real
    // use that follows it.
    assert_eq!(
        scan(r#"let c = '"'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = '\''; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    // An escape longer than one character, and a char literal whose
    // closing quote is the byte before another quote: both decide where
    // the literal ends, and ending it in the wrong place swallows the
    // code after it.
    assert_eq!(
        scan(r#"let c = '\u{41}'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = '\x41'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let v = ['\n','"']; env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = b'\\'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = 'é'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = '"'; let s = "env!(\"MYVAR\")";"#, "MYVAR"),
        Unused
    );
    // A lifetime or label is not a char literal: skipping to the next quote
    // would hide the use.
    assert_eq!(
        scan(
            r#"fn f(_: &'static str) -> usize { env!("MYVAR").len() }"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    assert_eq!(
        scan(
            r#"fn f<'a>(_: &'a str) { 'outer: loop { env!("MYVAR"); } }"#,
            "MYVAR"
        ),
        RuntimeValue
    );
    assert_eq!(scan("'", "MYVAR"), Unused);
    // A real use after a raw string is still found (exercises skip_raw_string).
    assert_eq!(
        scan(r###"let r = r#"noise"#; env!("MYVAR")"###, "MYVAR"),
        RuntimeValue
    );
    // A raw C string ending in a backslash has no escape to swallow the
    // closing quote.
    assert_eq!(
        scan(
            r#"let c = cr"\"; let x = env!("MYVAR"); let t = "";"#,
            "MYVAR"
        ),
        RuntimeValue
    );
}

#[test]
fn source_scanner_tokenizes_operators_numbers_and_idents_like_rustc() {
    use super::SourceEnvDepUse::{IncludeLocator, RuntimeValue, Unused};
    use super::source_env_dep_use as scan;

    // A division is not a comment.
    assert_eq!(
        scan(r#"let q = a / b; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    // Nor between macro tokens: `env / 2 */ !(..)` is no macro call.
    assert_eq!(scan(r#"let q = env / 2 */ !("MYVAR");"#, "MYVAR"), Unused);
    // An identifier that merely starts like a raw string prefix.
    assert_eq!(scan(r#"rinclude!(env!("MYVAR"))"#, "MYVAR"), RuntimeValue);
    // A variable named `env` compared with `!=` opens no macro.
    assert_eq!(scan("fn f(env: u8) -> bool { env != 0 }", "MYVAR"), Unused);
    // Plain groups inside an include keep the include context open.
    assert_eq!(
        scan(r#"include!(concat!(("a"), ("b"), env!("MYVAR")))"#, "MYVAR"),
        IncludeLocator
    );
    assert_eq!(
        scan(r#"include!(m!('a'('b')), env!("MYVAR"))"#, "MYVAR"),
        IncludeLocator
    );
    // Closing an include leaves its context; nested includes count down.
    assert_eq!(
        scan(r#"include!(()) const X: &str = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"include!(include!("a"), env!("MYVAR"))"#, "MYVAR"),
        IncludeLocator
    );

    // Char literals: escaped quote, non-ASCII, and a lone quote at EOF.
    assert_eq!(
        scan(r#"let c = '\"'; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(
        scan(r#"let c = ['é','"']; let x = env!("MYVAR");"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(scan("let s = '", "MYVAR"), Unused);

    // A number's suffix cannot start a raw string.
    assert_eq!(
        scan(
            r##"m!{ 1r#"x" } const P: &str = env!("MYVAR"); // "#"##,
            "MYVAR"
        ),
        RuntimeValue
    );
    // Non-ASCII identifier bytes belong to the identifier.
    assert_eq!(scan(r#"éinclude!(env!("MYVAR"))"#, "MYVAR"), RuntimeValue);
    assert_eq!(scan(r#"include!(envé!("MYVAR"))"#, "MYVAR"), Unused);
    // Rust whitespace beyond ASCII space separates tokens.
    for space in [
        "\x0B", "\x0C", "\u{85}", "\u{200E}", "\u{200F}", "\u{2028}", "\u{2029}",
    ] {
        assert_eq!(
            scan(&format!("env{space}!{space}(\"MYVAR\")"), "MYVAR"),
            RuntimeValue,
            "{space:?}"
        );
        assert_eq!(
            scan(&format!("{space}env!(\"MYVAR\")"), "MYVAR"),
            RuntimeValue,
            "leading {space:?}"
        );
    }
    // U+00A9 shares U+0085's lead byte but is not whitespace.
    assert_eq!(scan("env\u{A9}!(\"MYVAR\")", "MYVAR"), Unused);
    // A byte-order mark does not glue to the identifier after it.
    assert_eq!(scan("\u{FEFF}env!(\"MYVAR\")", "MYVAR"), RuntimeValue);

    // A file that ends inside an identifier or a number has no byte after
    // it, and a skipped token never hides the use that follows it.
    assert_eq!(scan("let n = 1", "MYVAR"), Unused);
    assert_eq!(
        scan(r#"const X: &str = env!("MYVAR"); mod tail"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(scan(r#"let s = "x"; env!("MYVAR")"#, "MYVAR"), RuntimeValue);
    assert_eq!(
        scan(r#"let s = "a\"b"; env!("MYVAR")"#, "MYVAR"),
        RuntimeValue
    );
    assert_eq!(scan("// c\nenv!(\"MYVAR\")", "MYVAR"), RuntimeValue);
    assert_eq!(scan("/* c */ env!(\"MYVAR\")", "MYVAR"), RuntimeValue);
    assert_eq!(scan("/* /* c */ */ env!(\"MYVAR\")", "MYVAR"), RuntimeValue);
    assert_eq!(
        scan(r###"let r = r##"x"##; env!("MYVAR")"###, "MYVAR"),
        RuntimeValue
    );

    // Identifiers and numbers are consumed from their first byte, so a
    // one-byte token keeps its boundary.
    assert_eq!(scan(r#"m!(env!("MYVAR"))"#, "MYVAR"), RuntimeValue);
    assert_eq!(scan(r#"e!("MYVAR")"#, "MYVAR"), Unused);
    assert_eq!(scan(r#"let n = 1; env!("MYVAR");"#, "MYVAR"), RuntimeValue);
    assert_eq!(
        scan(r#"include!(1, env!("MYVAR"))"#, "MYVAR"),
        IncludeLocator
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

/// [`key_of_flags`], returning what the key computation learned.
fn outputs_of_flags(args: &[String]) -> KeyOutputs {
    let fh = FileHasher::new();
    let pn = PathNormalizer::empty();
    let mut parsed = RustcArgs::parse(args).unwrap();
    parsed.source_file = None;
    let (key, outputs) = compute_cache_key_with_outputs(&parsed, &fh, &pn, &KeyEnv::default());
    key.unwrap();
    outputs
}

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

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

#[test]
fn static_lib_spec_models_kind_modifiers_and_rename() {
    let archive = |files: &[&str], bundle, whole_archive| StaticLibSpec::Archive {
        files: files.iter().map(|file| file.to_string()).collect(),
        bundle,
        whole_archive,
    };
    let plain = || archive(&["libfoo.a", "foo.lib"], true, false);
    let whole = || archive(&["libfoo.a", "foo.lib"], true, true);
    assert_eq!(static_lib_spec("static=foo"), plain());
    // Modifiers that change how the archive links, not which file it is.
    assert_eq!(static_lib_spec("static:+whole-archive=foo"), whole());
    // The last `±whole-archive` wins.
    assert_eq!(
        static_lib_spec("static:+whole-archive,-whole-archive=foo"),
        plain()
    );
    assert_eq!(
        static_lib_spec("static:-bundle=foo"),
        archive(&["libfoo.a", "foo.lib"], false, false)
    );
    assert_eq!(static_lib_spec("static:+bundle,-as-needed=foo"), plain());
    // The last `±bundle` wins.
    assert_eq!(static_lib_spec("static:-bundle,+bundle=foo"), plain());
    // `+verbatim` names the file exactly; a later `-verbatim` undoes it.
    assert_eq!(
        static_lib_spec("static:+whole-archive,+verbatim=foo.a"),
        archive(&["foo.a"], true, true)
    );
    assert_eq!(static_lib_spec("static:+verbatim,-verbatim=foo"), plain());
    // Rename, unknown modifiers and an empty name are not modelled.
    assert_eq!(
        static_lib_spec("static=foo:bar"),
        StaticLibSpec::Unmodeled("static=foo:bar")
    );
    assert_eq!(
        static_lib_spec("static:+link-arg=foo"),
        StaticLibSpec::Unmodeled("static:+link-arg=foo")
    );
    assert_eq!(
        static_lib_spec("static="),
        StaticLibSpec::Unmodeled("static=")
    );
    // Other kinds are referenced, not bundled.
    assert_eq!(static_lib_spec("dylib=foo"), StaticLibSpec::NotStatic);
    assert_eq!(
        static_lib_spec("dylib:+verbatim=foo"),
        StaticLibSpec::NotStatic
    );
    assert_eq!(static_lib_spec("foo"), StaticLibSpec::NotStatic);
    // A kindless or `dylib` rename can retarget an attribute's static
    // library, so it is refused like a static one. Frameworks cannot.
    assert_eq!(
        static_lib_spec("foo:bar"),
        StaticLibSpec::Unmodeled("foo:bar")
    );
    assert_eq!(
        static_lib_spec("dylib=foo:bar"),
        StaticLibSpec::Unmodeled("dylib=foo:bar")
    );
    assert_eq!(
        static_lib_spec("framework=Foo:Bar"),
        StaticLibSpec::NotStatic
    );
}

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

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

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

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

    // `dylib=`/bare are referenced not bundled → never content-hashed, and
    // a missing lib does not resolve.
    assert!(
        resolve_native_static_lib("dylib=foo", &dirs, &fh, false, |_| StaticLibUse::Bundled)
            .unwrap()
            .is_none()
    );
    assert!(
        resolve_native_static_lib("foo", &dirs, &fh, false, |_| StaticLibUse::Bundled)
            .unwrap()
            .is_none()
    );
    assert!(
        resolve_native_static_lib("static=absent", &dirs, &fh, false, |_| {
            StaticLibUse::Bundled
        })
        .unwrap()
        .is_none()
    );

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

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

/// For an MSVC target `cc` hard-links or copies each `lib<name>.a` it
/// builds to `<name>.lib`. Candidates with the same bytes are one archive,
/// keyed through the first one found; a candidate with other bytes anywhere
/// keeps the choice ambiguous.
#[test]
fn resolve_native_static_lib_accepts_copies_with_the_same_bytes() {
    let fh = FileHasher::new();
    let resolve = |dirs: &[&Path]| {
        let dirs: Vec<PathBuf> = dirs.iter().map(|dir| dir.to_path_buf()).collect();
        resolve_native_static_lib("static=foo", &dirs, &fh, false, |_| StaticLibUse::Bundled)
    };
    let dir = tempfile::tempdir().unwrap();
    let gnu = dir.path().join("libfoo.a");
    std::fs::write(&gnu, b"archive bytes").unwrap();
    let single = resolve(&[dir.path()]).unwrap().unwrap();
    assert_eq!(single.0, gnu);
    assert!(
        !single.1.contains("copies="),
        "one candidate keys as before"
    );

    // `cc` links or copies `libfoo.a` to `foo.lib` for an MSVC target: the
    // same bytes, so not ambiguous. Which name rustc takes is target-specific
    // and lands in a bundling output, so the copies are part of the key.
    let msvc = dir.path().join("foo.lib");
    std::fs::hard_link(&gnu, &msvc).unwrap();
    let linked = resolve(&[dir.path()]).unwrap().unwrap();
    assert_eq!(linked.0, gnu, "the first one found is hashed");
    assert_ne!(linked.1, single.1, "a new copy changes the key");
    assert!(linked.1.starts_with(&single.1), "{linked:?}");
    std::fs::remove_file(&msvc).unwrap();
    std::fs::write(&msvc, b"archive bytes").unwrap();
    assert_eq!(
        resolve(&[dir.path()]).unwrap().unwrap(),
        linked,
        "a hard link and a copy are the same candidates"
    );

    let copy = tempfile::tempdir().unwrap();
    std::fs::write(copy.path().join("libfoo.a"), b"archive bytes").unwrap();
    let both = resolve(&[dir.path(), copy.path()]).unwrap().unwrap();
    assert_eq!(both.0, gnu);
    assert_ne!(
        both.1, linked.1,
        "a copy in another dir is another candidate"
    );
    // A dir listed twice is the same candidates.
    assert_eq!(
        resolve(&[dir.path(), copy.path(), dir.path()])
            .unwrap()
            .unwrap(),
        both
    );
    assert_eq!(
        resolve(&[copy.path(), dir.path()]).unwrap().unwrap().0,
        copy.path().join("libfoo.a"),
        "search order picks the copy"
    );

    let other = tempfile::tempdir().unwrap();
    std::fs::write(other.path().join("foo.lib"), b"other bytes").unwrap();
    for dirs in [
        [dir.path(), other.path(), copy.path()],
        [dir.path(), copy.path(), other.path()],
    ] {
        let error = resolve(&dirs).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("ambiguous native static library"),
            "{error:#}"
        );
    }
}

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

    // `cargo:rustc-link-lib=static:+whole-archive=foo` bundles libfoo.a
    // just like `static=foo`, so a rebuilt archive must change the hash.
    let hash_of = |spec| {
        resolve_native_static_lib(spec, &dirs, &fh, false, |_| StaticLibUse::Bundled)
            .unwrap()
            .expect("modifier spec must resolve its archive")
    };
    let (path, h1) = hash_of("static:+whole-archive=foo");
    assert_eq!(path, lib);
    std::fs::write(&lib, b"v2 different bytes").unwrap();
    let (_, h2) = hash_of("static:+whole-archive=foo");
    assert_ne!(h1, h2, "rebuilt whole-archive lib must change the hash");

    // `+verbatim` resolves the exact file name and nothing else.
    std::fs::write(dir.path().join("foo.a"), b"verbatim bytes").unwrap();
    let (verbatim, _) = hash_of("static:+verbatim=foo.a");
    assert_eq!(verbatim, dir.path().join("foo.a"));

    // A rename is refused rather than keyed by its name.
    assert!(
        resolve_native_static_lib("static=foo:bar", &dirs, &fh, false, |_| {
            StaticLibUse::Bundled
        })
        .is_err()
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#[test]
fn hash_static_lib_gnu_longname_archive_is_checkout_independent() {
    // Every `cc` archive on Linux has a `//` table whose header GNU `ar`
    // leaves blank apart from name and size. Two checkouts that build the
    // same members must get the same structural digest, not a path-bound one.
    let bytes = crate::native_archive::gnu_crs_longname_archive_for_tests(b"payload");
    let fh = FileHasher::new();
    let mut digests = Vec::new();
    for checkout in ["checkout-a", "checkout-b"] {
        let dir = tempfile::tempdir().unwrap();
        let lib = dir.path().join(checkout).join("libprobe.a");
        std::fs::create_dir_all(lib.parent().unwrap()).unwrap();
        std::fs::write(&lib, &bytes).unwrap();
        for usage in [StaticLibUse::Bundled, StaticLibUse::Linked] {
            let digest = fh.hash_static_lib_for(&lib, usage).unwrap();
            assert!(digest.starts_with("gnu-ar-v2:"), "{usage:?}: {digest}");
            digests.push(digest);
        }
    }
    assert!(digests.windows(2).all(|pair| pair[0] == pair[1]));
}

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

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

    cache
        .put(&legacy_v7_key, "legacy-path-bound-bsd-elf-sentinel")
        .unwrap();

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

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

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

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

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

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

/// A link through Cargo's `OUT_DIR` symlink into a sealed hermetic
/// directory keys the archive by content; anything else stays resolved.
#[cfg(unix)]
#[test]
fn an_archive_linked_through_a_sealed_out_dir_counts_as_under_the_root() {
    let dir = tempfile::tempdir().unwrap();
    let profile = dir.path().join("w/target/debug");
    let sealed = dir.path().join("cache/out-dirs/v2").join("ef".repeat(16));
    let shared = sealed.join("debug/build/z-1/out");
    std::fs::create_dir_all(&shared).unwrap();
    std::fs::write(shared.join("libz.a"), b"!<arch>\n").unwrap();
    std::fs::create_dir_all(profile.join("build/z-1")).unwrap();
    let out = profile.join("build/z-1/out");
    std::os::unix::fs::symlink(&shared, &out).unwrap();
    let archive = out.join("libz.a");
    let resolved = resolved_path(&archive);

    assert!(
        !hermetic_archive_under(&archive, &resolved, &profile),
        "not sealed"
    );
    std::fs::write(sealed.join(".kache-sealed"), b"{}").unwrap();
    assert!(hermetic_archive_under(&archive, &resolved, &profile));
    assert!(
        !hermetic_archive_under(&archive, &resolved, &dir.path().join("elsewhere")),
        "spelled outside the root"
    );
    let plain = profile.join("deps/libq.a");
    std::fs::create_dir_all(plain.parent().unwrap()).unwrap();
    std::fs::write(&plain, b"!<arch>\n").unwrap();
    assert!(
        !hermetic_archive_under(&plain, &resolved_path(&plain), &resolved_path(&profile)),
        "an archive that resolves under the root needs no exception"
    );

    let bin = RustcArgs::parse(&[
        "rustc".to_string(),
        "src/main.rs".to_string(),
        "--crate-type".to_string(),
        "bin".to_string(),
    ])
    .unwrap();
    let root = resolved_path(&profile);
    assert_eq!(
        oso_archive_use(&bin, &archive, &profile, &root),
        StaticLibUse::Bundled
    );
    assert_eq!(
        oso_archive_use(&bin, &resolved, &profile, &root),
        StaticLibUse::Linked,
        "named by the sealed path itself, the link keeps that path"
    );
    assert_eq!(
        oso_archive_use(&bin, &plain, &profile, &root),
        StaticLibUse::Bundled
    );
    assert_eq!(
        oso_archive_use(&bin, Path::new("/opt/lib/libz.a"), &profile, &root),
        StaticLibUse::Linked
    );
}

/// A unit that does not link bundles the archive. A link reads it by path
/// unless the injected `-oso_prefix` root covers it.
#[test]
fn linked_archive_use_follows_output_and_oso_root() {
    let root = Path::new("/w/target/debug");
    let under = Path::new("/w/target/debug/build/s-1/out/libfoo.a");
    let outside = Path::new("/opt/lib/libfoo.a");
    let use_of = |crate_type: &str, test: bool, archive: &Path, oso_root: Option<&Path>| {
        let mut argv = vec![
            "rustc".to_string(),
            "src/lib.rs".to_string(),
            "--crate-type".to_string(),
            crate_type.to_string(),
        ];
        if test {
            argv.push("--test".to_string());
        }
        linked_archive_use(&RustcArgs::parse(&argv).unwrap(), archive, oso_root)
    };
    for crate_type in ["lib", "rlib", "staticlib"] {
        assert_eq!(
            use_of(crate_type, false, outside, None),
            StaticLibUse::Bundled,
            "{crate_type}"
        );
    }
    for crate_type in ["bin", "cdylib", "proc-macro"] {
        assert_eq!(
            use_of(crate_type, false, outside, None),
            StaticLibUse::Linked,
            "{crate_type}"
        );
    }
    assert_eq!(use_of("lib", true, outside, None), StaticLibUse::Linked);
    assert_eq!(
        use_of("bin", false, under, Some(root)),
        StaticLibUse::Bundled,
        "the injected prefix strips an archive under its root"
    );
    assert_eq!(
        use_of("bin", false, outside, Some(root)),
        StaticLibUse::Linked
    );
    assert_eq!(use_of("bin", false, under, None), StaticLibUse::Linked);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Argv for an rlib, where a build-script archive does its damage: rustc
/// copies the archive into the rlib and every later link reads that copy.
fn rlib_base(source: &Path, extra: &[&str]) -> Vec<String> {
    let mut args: Vec<String> = ["rustc", "--crate-name", "mylib", "--crate-type", "lib"]
        .map(String::from)
        .into();
    args.push(source.to_string_lossy().into_owned());
    args.extend(extra.iter().map(|s| s.to_string()));
    args
}

/// A build script can name its archive with link modifiers:
/// `static:+whole-archive=foo` still reads `libfoo.a`, and
/// `static:+verbatim=foo.a` reads `foo.a`. Either is bundled like a plain
/// `static=foo`, so rebuilding the archive in place must change the key.
#[test]
fn native_static_lib_named_with_modifiers_is_content_keyed() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let libdir = dir.path().join("out");
    std::fs::create_dir_all(&libdir).unwrap();
    let search = format!("native={}", libdir.display());

    for (spec, file) in [
        ("static:+whole-archive=foo", "libfoo.a"),
        ("static:+verbatim=foo.a", "foo.a"),
    ] {
        let lib = libdir.join(file);
        let flags = ["-L", search.as_str(), "-l", spec];
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let k1 = key_of(&rlib_base(&source, &flags));
        std::fs::write(&lib, b"v2 archive bytes - DIFFERENT").unwrap();
        let k2 = key_of(&rlib_base(&source, &flags));
        assert_ne!(k1, k2, "{spec}: a rebuilt archive must change the key");
        std::fs::write(&lib, b"v1 archive bytes").unwrap();
        let k3 = key_of(&rlib_base(&source, &flags));
        assert_eq!(k1, k3, "{spec}: identical bytes must reproduce the key");
        std::fs::remove_file(&lib).unwrap();
    }
}

/// `static=foo:bar` makes rustc link `bar` wherever a `#[link]` attribute
/// names `foo`. Which archive that reads is not modelled, and keying it by
/// name could restore an rlib bundling an older archive, so the key fails.
#[test]
fn renamed_native_static_lib_is_not_cacheable() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let libdir = dir.path().join("out");
    std::fs::create_dir_all(&libdir).unwrap();
    std::fs::write(libdir.join("libfoo.a"), b"archive bytes").unwrap();
    std::fs::write(libdir.join("libbar.a"), b"archive bytes").unwrap();
    let search = format!("native={}", libdir.display());
    let flags = ["-L", search.as_str(), "-l", "static=foo:bar"];

    let parsed = RustcArgs::parse(&rlib_base(&source, &flags)).unwrap();
    let error = compute_cache_key(
        &parsed,
        &FileHasher::new(),
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    )
    .unwrap_err();
    assert!(
        format!("{error:#}").contains("is not cacheable"),
        "a renamed static lib must fail the key: {error:#}"
    );
}

/// A `dylib` lib is referenced, not copied into the rlib, so its bytes
/// stay out of the key while `static` specs with modifiers are hashed.
/// `+verbatim` names the file itself, so a `dylib` wrongly taken for a
/// `static` would be found and hashed.
#[test]
fn native_dylib_stays_name_only_for_an_rlib() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let libdir = dir.path().join("out");
    std::fs::create_dir_all(&libdir).unwrap();
    let lib = libdir.join("libfoo.so");
    let search = format!("native={}", libdir.display());

    for spec in ["dylib=foo", "dylib:+verbatim=libfoo.so"] {
        let flags = ["-L", search.as_str(), "-l", spec];
        std::fs::write(&lib, b"so v1").unwrap();
        let k1 = key_of(&rlib_base(&source, &flags));
        std::fs::write(&lib, b"so v2 changed").unwrap();
        let k2 = key_of(&rlib_base(&source, &flags));
        assert_eq!(
            k1, k2,
            "{spec}: a dynamic lib's content must not key the rlib"
        );
    }
}

/// A Cargo build tree: `<tmp>/target/debug/deps` for outputs and a build
/// script's `<tmp>/target/debug/build/s-1/out`, plus a dir outside it.
struct NativeTree {
    _tmp: tempfile::TempDir,
    target: PathBuf,
    deps: PathBuf,
    out: PathBuf,
    elsewhere: PathBuf,
}

fn native_tree() -> NativeTree {
    let tmp = tempfile::tempdir().unwrap();
    let target = tmp.path().join("target");
    let deps = target.join("debug/deps");
    let out = target.join("debug/build/s-1/out");
    let elsewhere = tmp.path().join("elsewhere/lib");
    for dir in [&deps, &out, &elsewhere] {
        std::fs::create_dir_all(dir).unwrap();
    }
    NativeTree {
        _tmp: tmp,
        target,
        deps,
        out,
        elsewhere,
    }
}

/// Argv for a `crate_type` unit (`test` for a `--test` harness) writing
/// into `out_dir`. Keyed with [`key_of_flags`], so no source is read.
fn unit_args(crate_type: &str, out_dir: &Path, extra: &[&str]) -> Vec<String> {
    let mut args: Vec<String> = ["rustc", "--crate-name", "mylib", "src/lib.rs"]
        .map(String::from)
        .into();
    args.push("--out-dir".to_string());
    args.push(out_dir.display().to_string());
    if crate_type == "test" {
        args.push("--test".to_string());
    } else {
        args.push(format!("--crate-type={crate_type}"));
    }
    args.extend(extra.iter().map(|s| s.to_string()));
    args
}

/// [`key_of_flags`] for a key that may fail.
#[cfg(not(windows))]
fn try_key_of_flags(args: &[String]) -> Result<String> {
    let mut parsed = RustcArgs::parse(args).unwrap();
    parsed.source_file = None;
    compute_cache_key(
        &parsed,
        &FileHasher::new(),
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    )
}

/// Key `argv`, rewrite `file` with new bytes, and key it again.
#[cfg(not(windows))]
fn keys_around_rewrite(argv: &[String], file: &Path) -> (String, String) {
    std::fs::write(file, b"v1 native bytes").unwrap();
    let before = key_of_flags(argv);
    std::fs::write(file, b"v2 native bytes, different").unwrap();
    (before, key_of_flags(argv))
}

/// A Unix link context for `target` with no default dirs, no OUT_DIR, no
/// build tree, no system library dirs and no path rules.
fn unix_context<'a>(target: &'a str, normalizer: &'a PathNormalizer) -> NativeLinkContext<'a> {
    NativeLinkContext {
        native_windows_msvc: false,
        target,
        default_dirs: Vec::new(),
        out_dir: None,
        build_tree: Vec::new(),
        system_dirs: Vec::new(),
        path_normalizer: normalizer,
    }
}

/// [`fold_native_link_inputs`] for `argv` with explicit search dirs and
/// context: the fold's digest and what it reports.
fn fold_inputs(
    argv: &[String],
    native: &[PathBuf],
    framework: &[PathBuf],
    context: &NativeLinkContext<'_>,
) -> Result<(String, KeyedNativeArchives)> {
    let args = RustcArgs::parse(argv).unwrap();
    let mut hasher = blake3::Hasher::new();
    let keyed = fold_native_link_inputs(
        &mut hasher,
        &args,
        &NativeSearchDirs { native, framework },
        context,
        &FileHasher::new(),
    )?;
    Ok((hasher.finalize().to_hex().to_string(), keyed))
}

#[test]
fn apple_dynamic_install_names_bind_link_keys() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let stub = tree.out.join("libfoo.tbd");
    for crate_type in ["bin", "test", "dylib", "cdylib", "proc-macro"] {
        // Downstream argv can omit -l: the dependency's rlib carries it.
        for extra in [
            vec![],
            vec!["-lfoo"],
            vec!["-ldylib=foo"],
            vec!["-ldylib=foo", "-Ctarget-feature=+crt-static"],
        ] {
            let argv = unit_args(crate_type, &tree.deps, &extra);
            std::fs::write(
                &stub,
                "--- !tapi-tbd\ninstall-name: '/target/one/libfoo.dylib'\n...\n",
            )
            .unwrap();
            let before = fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
                .unwrap()
                .0;
            std::fs::write(
                &stub,
                "--- !tapi-tbd\ninstall-name: '/target/two/libfoo.dylib'\n...\n",
            )
            .unwrap();
            let after = fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
                .unwrap()
                .0;
            assert_ne!(
                before, after,
                "{crate_type} {extra:?}: install names reach the linked output"
            );
        }
    }
}

#[test]
fn apple_dylib_and_framework_install_names_bind_link_keys() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let bundle = tree.out.join("Foo.framework");
    std::fs::create_dir(&bundle).unwrap();
    for file in [tree.out.join("libfoo.dylib"), bundle.join("Foo")] {
        let framework = file.parent() == Some(bundle.as_path());
        let native = if framework {
            vec![]
        } else {
            vec![tree.out.clone()]
        };
        let frameworks = if framework {
            vec![tree.out.clone()]
        } else {
            vec![]
        };
        let argv = unit_args("bin", &tree.deps, &[]);
        let fold = || {
            fold_inputs(&argv, &native, &frameworks, &context)
                .unwrap()
                .0
        };
        std::fs::write(
            &file,
            apple_install_name::tests::dylib("/target/one/libfoo.dylib", false, true),
        )
        .unwrap();
        let before = fold();
        std::fs::write(
            &file,
            apple_install_name::tests::dylib("/target/two/libfoo.dylib", false, true),
        )
        .unwrap();
        assert_ne!(before, fold(), "{}", file.display());
        std::fs::remove_file(file).unwrap();
    }
}

#[test]
fn apple_dynamic_scan_ignores_non_library_entries() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let argv = unit_args("bin", &tree.deps, &[]);
    let fold = || {
        fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
            .unwrap()
            .0
    };
    let before = fold();
    std::fs::write(tree.out.join("README.txt"), "native library build notes").unwrap();
    assert_eq!(before, fold());
    std::fs::create_dir(tree.out.join("generated.dylib")).unwrap();
    assert_eq!(before, fold());
}

#[test]
fn apple_dynamic_scan_preserves_system_and_nonlinking_units() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let stub = tree.out.join("libfoo.tbd");
    std::fs::write(stub, "unsupported stub").unwrap();
    for crate_type in ["rlib", "staticlib"] {
        let argv = unit_args(crate_type, &tree.deps, &[]);
        assert!(fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context).is_ok());
    }
    let system = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.out)],
        ..unix_context("aarch64-apple-darwin", &normalizer)
    };
    let argv = unit_args("bin", &tree.deps, &[]);
    assert!(fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &system).is_ok());
    assert!(fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context).is_err());
}

#[test]
fn apple_relative_install_names_share_across_directories() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let argv = unit_args("bin", &tree.deps, &[]);
    for name in [
        "@rpath/libfoo.dylib",
        "@loader_path/libfoo.dylib",
        "@executable_path/libfoo.dylib",
    ] {
        let stub = format!("--- !tapi-tbd\ninstall-name: '{name}'\n...\n");
        std::fs::write(tree.out.join("libfoo.tbd"), &stub).unwrap();
        std::fs::write(tree.elsewhere.join("libfoo.tbd"), &stub).unwrap();
        assert_eq!(
            fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
                .unwrap()
                .0,
            fold_inputs(&argv, std::slice::from_ref(&tree.elsewhere), &[], &context)
                .unwrap()
                .0
        );
    }
}

#[test]
fn apple_verbatim_extensionless_dylib_install_name_is_keyed() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("aarch64-apple-darwin", &normalizer);
    let path = tree.out.join("foo");
    for flag in ["-ldylib:+verbatim=foo", "-Clink-arg=-l:foo"] {
        let argv = unit_args("bin", &tree.deps, &[flag]);
        std::fs::write(
            &path,
            apple_install_name::tests::dylib("/target/one/foo", false, true),
        )
        .unwrap();
        let before = fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
            .unwrap()
            .0;
        std::fs::write(
            &path,
            apple_install_name::tests::dylib("/target/two/foo", false, true),
        )
        .unwrap();
        assert_ne!(
            before,
            fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
                .unwrap()
                .0
        );
    }
}

#[test]
fn apple_verbatim_system_dylib_install_name_is_not_keyed() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.out)],
        ..unix_context("aarch64-apple-darwin", &normalizer)
    };
    let path = tree.out.join("foo");
    for flag in ["-ldylib:+verbatim=foo", "-Clink-arg=-l:foo"] {
        let argv = unit_args("bin", &tree.deps, &[flag]);
        let fold = || {
            fold_inputs(&argv, std::slice::from_ref(&tree.out), &[], &context)
                .unwrap()
                .0
        };
        std::fs::write(
            &path,
            apple_install_name::tests::dylib("/system/one/foo", false, true),
        )
        .unwrap();
        let before = fold();
        std::fs::write(
            &path,
            apple_install_name::tests::dylib("/system/two/foo", false, true),
        )
        .unwrap();
        assert_eq!(before, fold(), "{flag}");
    }
}

#[cfg(not(windows))]
#[test]
fn linux_embedded_rpath_is_keyed_raw() {
    let _lock = key_test_lock();
    let key = |root: &str| {
        let normalizer = PathNormalizer::empty().with_target_dir(Some(Path::new(root)));
        let path = format!("{root}/native");
        assert_eq!(normalizer.normalize(&path), "<TARGET>/native");
        let mut args = RustcArgs::parse(&unit_args(
            "bin",
            Path::new("/out"),
            &[
                "--target=x86_64-unknown-linux-gnu",
                &format!("-Clink-arg=-Wl,-rpath,{path}"),
            ],
        ))
        .unwrap();
        args.source_file = None;
        compute_cache_key(&args, &FileHasher::new(), &normalizer, &KeyEnv::default()).unwrap()
    };
    assert_ne!(key("/one"), key("/two"));
}

/// Whether rewriting `file` with new `ar` bytes changes the fold.
fn fold_rewrites(file: &Path, fold: impl Fn() -> Result<(String, KeyedNativeArchives)>) -> bool {
    std::fs::write(file, b"!<arch>\nv1 native bytes").unwrap();
    let before = fold().unwrap().0;
    std::fs::write(file, b"!<arch>\nv2 native bytes, different").unwrap();
    before != fold().unwrap().0
}

/// Cargo passes a build script's `-L` to every dependent, so a binary two
/// crates above a sys crate sees its OUT_DIR with no `-l`. The archive
/// there reaches the binary through the sys crate's rlib, whose bytes the
/// binary's `--extern`s do not cover.
#[cfg(not(windows))]
#[test]
fn linked_output_keys_build_tree_archives_without_link_spec() {
    let _lock = key_test_lock();
    let tree = native_tree();
    let search = format!("native={}", tree.out.display());
    for crate_type in ["bin", "test", "cdylib", "staticlib"] {
        let argv = unit_args(crate_type, &tree.deps, &["-L", &search]);
        let (before, after) = keys_around_rewrite(&argv, &tree.out.join("libfoo.a"));
        assert_ne!(before, after, "{crate_type}: a rebuilt archive must re-key");
    }
}

/// Every archive in a `-L` dir away from the system library dirs keys a
/// linked output, inside the build tree or not: a monorepo's native build
/// above the workspace, a path dependency beside it, or `OPENSSL_DIR`.
/// Cargo hands a build script's `-L` to every dependent, and a
/// dependency's rlib can carry those archives with no `-l` of this unit
/// naming them. The same holds for a link-argument `-L` and for a static
/// framework in a `framework=` dir.
#[cfg(not(windows))]
#[test]
fn linked_output_scans_dirs_in_and_outside_the_workspace() {
    let _lock = key_test_lock();
    let tree = native_tree();
    let in_tree = tree.target.join("native");
    std::fs::create_dir_all(&in_tree).unwrap();
    for dir in [&in_tree, &tree.elsewhere] {
        let shown = dir.display();
        let archive = dir.join("libssl.a");
        let search = format!("native={shown}");
        for crate_type in ["bin", "test", "cdylib", "staticlib"] {
            let argv = unit_args(crate_type, &tree.deps, &["-L", &search]);
            let (before, after) = keys_around_rewrite(&argv, &archive);
            assert_ne!(before, after, "{shown}: {crate_type}");
        }
        let link_search = format!("-Clink-arg=-L{shown}");
        let (before, after) =
            keys_around_rewrite(&unit_args("bin", &tree.deps, &[&link_search]), &archive);
        assert_ne!(before, after, "{shown}: a link-argument -L dir");

        let bundle = dir.join("Foo.framework");
        std::fs::create_dir_all(&bundle).unwrap();
        let frameworks = format!("framework={shown}");
        let bin = unit_args("bin", &tree.deps, &["-L", &frameworks]);
        std::fs::write(bundle.join("Foo"), b"!<arch>\nv1 framework").unwrap();
        let before = key_of_flags(&bin);
        std::fs::write(bundle.join("Foo"), b"!<arch>\nv2 framework").unwrap();
        assert_ne!(before, key_of_flags(&bin), "{shown}: a static framework");
    }
}

/// A system library dir outside the build tree (`/opt/homebrew/lib`) is
/// not scanned: rewriting an archive there that no `-l` names leaves a
/// linked output's fold alone, and rewriting one an `-l` resolves to
/// re-keys it, in each spelling of `-l`. A `-L` in the link arguments
/// follows the same rule.
#[test]
fn system_dir_archives_key_only_by_name() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.elsewhere)],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    std::fs::write(tree.elsewhere.join("libssl.a"), b"!<arch>\nssl").unwrap();
    let archive = tree.elsewhere.join("libz.a");
    let rewrites = |crate_type: &str, native: &[PathBuf], extra: &[&str]| {
        let argv = unit_args(crate_type, &tree.deps, extra);
        fold_rewrites(&archive, || fold_inputs(&argv, native, &[], &context))
    };
    let native = [tree.elsewhere.clone()];
    for crate_type in ["bin", "test", "cdylib", "staticlib"] {
        assert!(!rewrites(crate_type, &native, &[]), "{crate_type}: no -l");
        assert!(
            rewrites(crate_type, &native, &["-l", "static=z"]),
            "{crate_type}: a static spec"
        );
    }
    for spec in ["z", "dylib=z"] {
        assert!(rewrites("bin", &native, &["-l", spec]), "{spec}");
    }

    let link_search = format!("-Clink-arg=-L{}", tree.elsewhere.display());
    assert!(!rewrites("bin", &[], &[&link_search]), "a link-argument -L");
    for link_arg in [
        "-Clink-arg=-lz",
        "-Clink-arg=-Wl,-hidden-lz",
        "-Clink-arg=-Wl,-force-lz",
    ] {
        assert!(
            rewrites("bin", &[], &[&link_search, link_arg]),
            "{link_arg}"
        );
    }
}

/// A thin archive or an unreadable dir under a system library dir refuses
/// a link only when an `-l` resolves to it; anywhere else the scan reads
/// it and refuses.
#[test]
fn system_dir_thin_archive_refuses_only_a_link_that_names_it() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let system = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.elsewhere)],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    let elsewhere = unix_context("x86_64-unknown-linux-gnu", &normalizer);
    std::fs::write(tree.elsewhere.join("libthin.a"), b"!<thin>\n").unwrap();
    let fold = |context: &NativeLinkContext<'_>, dir: &Path, extra: &[&str]| {
        let argv = unit_args("bin", &tree.deps, extra);
        fold_inputs(&argv, &[dir.to_path_buf()], &[], context)
    };
    let unreadable = tree.elsewhere.join("libthin.a");
    assert!(fold(&system, &tree.elsewhere, &[]).is_ok());
    assert!(fold(&system, &tree.elsewhere, &["-l", "static=thin"]).is_err());
    assert!(fold(&system, &unreadable, &[]).is_ok());
    assert!(fold(&elsewhere, &tree.elsewhere, &[]).is_err());
    assert!(fold(&elsewhere, &unreadable, &[]).is_err());
}

/// A dir under a system library dir is still scanned inside the build
/// tree. Each is compared resolved: a dir is judged by where it leads,
/// and a build tree spelled through a symlink (macOS reaches `/var` as
/// `/private/var`) still holds the build script's OUT_DIR.
#[cfg(unix)]
#[test]
fn system_dirs_and_the_build_tree_are_compared_resolved() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let system = tree.target.with_file_name("system");
    std::fs::create_dir_all(&system).unwrap();
    let leads_out = system.join("out");
    std::os::unix::fs::symlink(&tree.out, &leads_out).unwrap();
    let alias = tree.target.with_file_name("alias");
    std::os::unix::fs::symlink(&tree.target, &alias).unwrap();
    let bin = unit_args("bin", &tree.deps, &[]);
    let rewrites = |dir: &Path, system_dirs: &[&Path], build_tree: &[&Path]| {
        let context = NativeLinkContext {
            system_dirs: system_dirs.iter().map(|dir| resolved_path(dir)).collect(),
            build_tree: build_tree.iter().map(|root| root.to_path_buf()).collect(),
            ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
        };
        let dirs = [dir.to_path_buf()];
        fold_rewrites(&tree.out.join("libfoo.a"), || {
            fold_inputs(&bin, &dirs, &[], &context)
        })
    };
    let target: &Path = &tree.target;
    assert!(rewrites(&leads_out, &[&system], &[]), "leads out of it");
    let leads_in = alias.join("debug/build/s-1/out");
    assert!(!rewrites(&leads_in, &[target], &[]), "leads into it");
    assert!(rewrites(&tree.out, &[target], &[&alias]), "an aliased tree");
    assert!(!rewrites(&tree.out, &[target], &[&tree.elsewhere]));
}

/// The scan keys linked outputs only, only archives, and no system
/// library dir outside the build tree.
#[test]
fn archive_scan_leaves_other_units_and_files_alone() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("x86_64-unknown-linux-gnu", &normalizer);
    let dirs = [tree.out.clone()];
    let rewrites = |argv: Vec<String>, file: &Path| {
        fold_rewrites(file, || fold_inputs(&argv, &dirs, &[], &context))
    };
    let archive = tree.out.join("libfoo.a");
    assert!(!rewrites(unit_args("rlib", &tree.deps, &[]), &archive));
    assert!(!rewrites(
        unit_args("bin", &tree.deps, &["--emit=metadata"]),
        &archive
    ));
    let bin = unit_args("bin", &tree.deps, &[]);
    assert!(rewrites(bin.clone(), &archive));
    assert!(!rewrites(bin.clone(), &tree.out.join("libfoo.so")));
    assert!(!rewrites(bin.clone(), &tree.out.join("foo.o")));

    let system = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.target)],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    assert!(!fold_rewrites(&archive, || fold_inputs(
        &bin,
        &dirs,
        &[],
        &system
    )));
}

/// A `#[link(kind = "static")]` attribute bundles an archive into an rlib
/// with no `-l` on argv. The archives under the unit's own OUT_DIR key its
/// rlib, so the audit need not refuse it; dirs elsewhere do not.
#[test]
fn rlib_keys_archives_under_its_own_out_dir() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let unit_out = tree.out.clone();
    let own = tree.out.join("x64");
    std::fs::create_dir_all(&own).unwrap();
    let dirs = [own.clone(), tree.elsewhere.clone()];
    let rlib = unit_args("rlib", &tree.deps, &[]);
    let fold_with = |argv: &[String], out_dir: Option<&Path>| {
        let context = NativeLinkContext {
            out_dir,
            ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
        };
        fold_inputs(argv, &dirs, &[], &context)
    };
    let archive = own.join("libWebView2LoaderStatic.a");
    assert!(fold_rewrites(&archive, || fold_with(
        &rlib,
        Some(&unit_out)
    )));
    assert_eq!(
        fold_with(&rlib, Some(&unit_out)).unwrap().1.archives,
        std::slice::from_ref(&archive)
    );
    assert!(!fold_rewrites(&tree.elsewhere.join("libdep.a"), || {
        fold_with(&rlib, Some(&unit_out))
    }));
    assert!(!fold_rewrites(&archive, || fold_with(&rlib, None)));
    let metadata = unit_args("rlib", &tree.deps, &["--emit=metadata"]);
    assert!(!fold_rewrites(&archive, || fold_with(
        &metadata,
        Some(&unit_out)
    )));

    // Cargo's OUT_DIR and the build script's `-L` may spell the same dir
    // differently.
    #[cfg(unix)]
    {
        let alias = tree.elsewhere.join("alias");
        std::os::unix::fs::symlink(&unit_out, &alias).unwrap();
        assert!(fold_rewrites(&archive, || fold_with(&rlib, Some(&alias))));
    }
}

#[test]
fn native_scan_dirs_follow_the_unit_and_skip_cargo_packages() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let unit_out = tree.out.parent().unwrap().to_path_buf();
    let context = NativeLinkContext {
        out_dir: Some(&unit_out),
        system_dirs: vec![resolved_path(&tree.elsewhere)],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    let native = tree.target.join("native");
    std::fs::create_dir_all(&native).unwrap();
    let dirs = [
        tree.out.clone(),
        tree.elsewhere.clone(),
        native.clone(),
        tree.out.clone(),
    ];
    let scan = |crate_type: &str| {
        let args = RustcArgs::parse(&unit_args(crate_type, &tree.deps, &[])).unwrap();
        native_scan_dirs(&args, &dirs, &context)
    };
    assert_eq!(scan("bin"), [tree.out.clone(), native.clone()]);
    assert_eq!(scan("rlib"), std::slice::from_ref(&tree.out));
    assert_eq!(scan("rlib,staticlib"), scan("bin"));
    assert_eq!(context.scanned_dirs(&dirs), scan("bin"));

    let package = PathBuf::from("/home/u/.cargo/registry/src/index-1/windows_x-0.52.6/lib");
    let dirs = [package.clone(), tree.elsewhere.clone()];
    let kept: Vec<&PathBuf> =
        dirs_outside_packages(&dirs, |dir| dir.replace("/home/u/.cargo", "<CARGO_HOME>")).collect();
    assert_eq!(kept, [&tree.elsewhere]);
}

#[test]
fn cargo_package_dirs_are_registry_sources_and_git_checkouts() {
    assert!(is_cargo_package_dir(
        "<CARGO_HOME>/registry/src/index.crates.io-1/foo-1.0.0/lib"
    ));
    assert!(is_cargo_package_dir(
        "<CARGO_HOME>\\registry\\src\\index.crates.io-1\\foo-1.0.0\\lib"
    ));
    assert!(is_cargo_package_dir(
        "<CARGO_HOME>/git/checkouts/foo-1a2b/3c4d/lib"
    ));
    assert!(!is_cargo_package_dir("<CARGO_HOME>/registry/cache/x"));
    assert!(!is_cargo_package_dir("<CARGO_HOME>/git/db/x"));
    assert!(!is_cargo_package_dir("<CARGO_HOME>/src/registry"));
    assert!(!is_cargo_package_dir("/w/registry/src/index/foo-1.0.0/lib"));
    assert!(!is_cargo_package_dir("<WORKSPACE>/registry/src/x"));
}

#[test]
fn dirs_under_compare_resolved_paths() {
    let tree = native_tree();
    let root = tree.out.parent().unwrap();
    let dirs = [tree.out.clone(), tree.elsewhere.clone()];
    assert_eq!(dirs_under(&dirs, root), std::slice::from_ref(&tree.out));
    assert!(dirs_under(&dirs, &tree.deps).is_empty());
    assert!(dirs_under(&[], root).is_empty());
    assert_eq!(
        unique_dirs(&[tree.out.clone(), tree.elsewhere.clone(), tree.out.clone()]),
        [tree.out.clone(), tree.elsewhere.clone()]
    );

    // A root or a dir spelled through a symlink is compared by its target.
    #[cfg(unix)]
    {
        let alias = tree.target.with_file_name("alias");
        std::os::unix::fs::symlink(&tree.target, &alias).unwrap();
        assert_eq!(dirs_under(&dirs, &alias), std::slice::from_ref(&tree.out));
        let aliased = [alias.join("debug/build/s-1/out"), tree.elsewhere.clone()];
        assert_eq!(
            dirs_under(&aliased, &tree.target),
            std::slice::from_ref(&aliased[0])
        );
    }
}

#[test]
fn build_tree_roots_are_the_target_dir_and_the_workspace() {
    let deps = Path::new("/w/target/debug/deps");
    let workspace = Path::new("/w");
    assert_eq!(
        build_tree_roots_of(Some(deps), None, Some(workspace)),
        [PathBuf::from("/w/target"), PathBuf::from("/w")]
    );
    assert_eq!(
        build_tree_roots_of(Some(Path::new("/w/target/debug/build/s-1")), None, None),
        [PathBuf::from("/w/target")]
    );
    assert_eq!(
        build_tree_roots_of(
            Some(Path::new("/w/target/debug/build/s/0123456789abcdef/out")),
            None,
            None
        ),
        [PathBuf::from("/w/target")],
        "Cargo 1.100's per-unit layout"
    );
    assert_eq!(
        build_tree_roots_of(Some(Path::new("/tmp/out")), None, Some(workspace)),
        [PathBuf::from("/w")],
        "an --out-dir outside Cargo's layout"
    );
    assert!(build_tree_roots_of(None, None, None).is_empty());

    let triple = "x86_64-unknown-linux-gnu";
    let cross = Path::new("/w/target/x86_64-unknown-linux-gnu/debug");
    assert_eq!(
        cargo_target_dir(cross, Some(triple)),
        Path::new("/w/target")
    );
    assert_eq!(
        cargo_target_dir(Path::new("/w/target/spec/debug"), Some("targets/spec.json")),
        Path::new("/w/target"),
        "a target spec file names its dir by its stem"
    );
    assert_eq!(
        cargo_target_dir(cross, None),
        Path::new("/w/target/x86_64-unknown-linux-gnu")
    );
    assert_eq!(
        cargo_target_dir(Path::new("/w/target/debug"), Some(triple)),
        Path::new("/w/target"),
        "a host unit of a cross build"
    );
    assert_eq!(
        cargo_target_dir(Path::new("/debug"), Some("debug")),
        Path::new("/")
    );
    assert_eq!(cargo_target_dir(Path::new("/"), None), Path::new("/"));
}

#[test]
fn build_tree_roots_read_the_unit_out_dir_and_target() {
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "src/main.rs".to_string(),
        "--out-dir".to_string(),
        "/w/target/x86_64-unknown-linux-gnu/debug/deps".to_string(),
        "--target".to_string(),
        "x86_64-unknown-linux-gnu".to_string(),
    ])
    .unwrap();
    assert_eq!(
        build_tree_roots(&args).first(),
        Some(&PathBuf::from("/w/target")),
        "the target dir comes from --out-dir and --target"
    );
}
#[test]
fn native_dir_archives_list_regular_archives_in_order() {
    let dir = tempfile::tempdir().unwrap();
    for name in [
        "libz.a",
        "foo.LIB",
        "liba.A",
        "libfoo.so",
        "foo.o",
        "notes.txt",
    ] {
        std::fs::write(dir.path().join(name), b"x").unwrap();
    }
    std::fs::create_dir(dir.path().join("sub.a")).unwrap();
    assert_eq!(
        native_dir_archives(dir.path()).unwrap(),
        ["foo.LIB", "liba.A", "libz.a"].map(|name| dir.path().join(name))
    );
    assert!(
        native_dir_archives(&dir.path().join("absent"))
            .unwrap()
            .is_empty(),
        "a missing dir holds no archives"
    );
    // Windows reports a file read as a dir as a missing path.
    #[cfg(unix)]
    assert!(
        native_dir_archives(&dir.path().join("libz.a")).is_err(),
        "a dir that cannot be read is an error"
    );
    assert!(is_native_archive_name("libfoo.a"));
    assert!(is_native_archive_name("FOO.Lib"));
    assert!(!is_native_archive_name("libfoo.rlib.bak"));
    assert!(!is_native_archive_name("libfoo.so"));
}

/// ld64 links a static framework's binary into the output like an
/// archive; a dynamic framework, or a dir that is no framework, is not
/// one.
#[test]
fn native_dir_static_frameworks_list_archive_binaries() {
    let dir = tempfile::tempdir().unwrap();
    for (framework, bytes) in [
        ("Static", &b"!<arch>\nmembers"[..]),
        ("Dynamic", b"\xcf\xfa\xed\xfe dylib"),
    ] {
        let bundle = dir.path().join(format!("{framework}.framework"));
        std::fs::create_dir_all(&bundle).unwrap();
        std::fs::write(bundle.join(framework), bytes).unwrap();
    }
    std::fs::create_dir_all(dir.path().join("Empty.framework")).unwrap();
    std::fs::create_dir_all(dir.path().join("Other")).unwrap();
    std::fs::write(dir.path().join("Other/Other"), b"!<arch>\nx").unwrap();
    assert_eq!(
        native_dir_static_frameworks(dir.path()).unwrap(),
        [dir.path().join("Static.framework/Static")]
    );
    assert!(
        native_dir_static_frameworks(&dir.path().join("absent"))
            .unwrap()
            .is_empty()
    );
}

/// A linking unit hashes the static frameworks in its `framework=` dirs,
/// and under a system library dir the one a `framework` spec names; an
/// rlib does not link them.
#[test]
fn linking_unit_keys_static_frameworks() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.elsewhere)],
        ..unix_context("aarch64-apple-darwin", &normalizer)
    };
    let rewrites = |dir: &Path, crate_type: &str, extra: &[&str]| {
        let bundle = dir.join("Foo.framework");
        std::fs::create_dir_all(&bundle).unwrap();
        let argv = unit_args(crate_type, &tree.deps, extra);
        let frameworks = [dir.to_path_buf()];
        fold_rewrites(&bundle.join("Foo"), || {
            fold_inputs(&argv, &[], &frameworks, &context)
        })
    };
    assert!(rewrites(&tree.out, "bin", &[]));
    assert!(!rewrites(&tree.out, "rlib", &[]));
    assert!(!rewrites(&tree.elsewhere, "bin", &[]));
    assert!(rewrites(&tree.elsewhere, "bin", &["-l", "framework=Foo"]));
    assert!(!rewrites(&tree.elsewhere, "rlib", &["-l", "framework=Foo"]));
}

/// A dir under a system library dir is scanned only inside the build
/// tree; every other dir is scanned, once.
#[test]
fn scanned_dirs_skip_system_dirs_outside_the_build_tree() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let scanned = |system: &Path, build_tree: &[&Path]| {
        let context = NativeLinkContext {
            system_dirs: vec![resolved_path(system)],
            build_tree: build_tree.iter().map(|root| root.to_path_buf()).collect(),
            ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
        };
        context.scanned_dirs(&[tree.out.clone(), tree.elsewhere.clone(), tree.out.clone()])
    };
    let tmp = tree.target.parent().unwrap();
    let target: &Path = &tree.target;
    assert_eq!(scanned(tmp, &[target]), std::slice::from_ref(&tree.out));
    assert!(scanned(tmp, &[]).is_empty());
    assert_eq!(
        scanned(&tree.elsewhere, &[]),
        std::slice::from_ref(&tree.out)
    );
    assert_eq!(
        scanned(&tree.deps, &[]),
        [tree.out.clone(), tree.elsewhere.clone()]
    );
}

#[test]
fn system_library_dirs_hold_os_and_package_manager_prefixes() {
    let dirs = system_library_dirs();
    for dir in ["/usr/lib", "/usr/local/lib", "/opt/homebrew", "/nix/store"] {
        assert!(dirs.contains(&PathBuf::from(dir)), "{dir}");
    }
    for local in [
        "/home/u/mono/build/lib",
        "/usr/src/app/build",
        "/opt/app/lib",
    ] {
        assert!(!is_under_any(Path::new(local), &dirs), "{local}");
    }
}

#[test]
fn is_under_any_compares_whole_components() {
    let roots = [PathBuf::from("/x"), PathBuf::from("/a")];
    assert!(is_under_any(Path::new("/a/b"), &roots));
    assert!(is_under_any(Path::new("/a"), &roots));
    assert!(!is_under_any(Path::new("/ab"), &roots));
    assert!(!is_under_any(Path::new("/a"), &[]));
}

/// The bundle audit reads an rlib's scanned `-L` dirs, so a system
/// library dir outside the build tree cannot refuse every rlib that sees
/// it. Other units report none.
#[test]
fn audit_dirs_are_an_rlibs_scanned_dirs() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = NativeLinkContext {
        system_dirs: vec![resolved_path(&tree.elsewhere)],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    let dirs = [tree.out.clone(), tree.elsewhere.clone(), tree.out.clone()];
    let audit_dirs = |crate_type: &str| {
        let argv = unit_args(crate_type, &tree.deps, &[]);
        fold_inputs(&argv, &dirs, &[], &context).unwrap().1.dirs
    };
    assert_eq!(audit_dirs("rlib"), std::slice::from_ref(&tree.out));
    assert!(audit_dirs("bin").is_empty());
}

/// rustc hands the value of a `link-arg` `-l` spec to the linker as is,
/// so a linking unit with one is refused; an rlib only records it.
#[test]
fn link_arg_lib_spec_refuses_a_link() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("x86_64-unknown-linux-gnu", &normalizer);
    let fold = |crate_type: &str, spec: &str| {
        let argv = unit_args(crate_type, &tree.deps, &["-l", spec]);
        fold_inputs(&argv, &[], &[], &context)
    };
    assert!(fold("bin", "link-arg=-lfoo").is_err());
    assert!(fold("cdylib", "link-arg:+verbatim=-Wl,-hidden-lfoo").is_err());
    assert!(fold("rlib", "link-arg=-lfoo").is_ok());
    assert!(fold("bin", "dylib=foo").is_ok());

    assert!(is_link_arg_spec("link-arg=-lfoo"));
    assert!(is_link_arg_spec("link-arg:+verbatim=-lfoo"));
    assert!(!is_link_arg_spec("static=link-arg"));
    assert!(!is_link_arg_spec("link-arg"));
    assert!(!is_link_arg_spec("dylib=foo"));
}

#[test]
fn framework_request_reads_framework_specs() {
    assert_eq!(framework_request("framework=Foo"), Some("Foo"));
    assert_eq!(framework_request("framework:-as-needed=Foo"), Some("Foo"));
    assert_eq!(framework_request("framework=Foo:Bar"), Some("Bar"));
    assert_eq!(framework_request("framework="), None);
    assert_eq!(framework_request("dylib=Foo"), None);
    assert_eq!(framework_request("Foo"), None);
}

/// ld64 takes the first `Foo.framework/Foo` in its `-F` dirs; only an
/// `ar` archive there is static.
#[test]
fn resolve_static_framework_takes_the_first_bundle() {
    let first = tempfile::tempdir().unwrap();
    let second = tempfile::tempdir().unwrap();
    let dirs = [first.path().to_path_buf(), second.path().to_path_buf()];
    let bundle = |dir: &Path, bytes: &[u8]| {
        let bundle = dir.join("Foo.framework");
        std::fs::create_dir_all(&bundle).unwrap();
        std::fs::write(bundle.join("Foo"), bytes).unwrap();
        bundle.join("Foo")
    };
    assert_eq!(resolve_static_framework("Foo", &dirs).unwrap(), None);
    std::fs::create_dir_all(first.path().join("Foo.framework")).unwrap();
    let later = bundle(second.path(), b"!<arch>\nstatic");
    assert_eq!(
        resolve_static_framework("Foo", &dirs).unwrap(),
        Some(later),
        "a bundle with no binary is skipped"
    );
    bundle(first.path(), b"\xcf\xfa\xed\xfe dylib");
    assert_eq!(
        resolve_static_framework("Foo", &dirs).unwrap(),
        None,
        "a dynamic framework first hides a later static one"
    );
    let static_first = bundle(first.path(), b"!<arch>\nstatic");
    assert_eq!(
        resolve_static_framework("Foo", &dirs).unwrap(),
        Some(static_first)
    );
}

/// Each scanned archive folds under its dir index and its path in the
/// dir; a thin archive, whose members live elsewhere, refuses the key.
#[test]
fn fold_native_dir_archives_names_dir_index_and_file() {
    let first = tempfile::tempdir().unwrap();
    let second = tempfile::tempdir().unwrap();
    std::fs::write(first.path().join("liba.a"), b"a").unwrap();
    std::fs::write(second.path().join("libb.a"), b"b").unwrap();
    let dirs = [first.path().to_path_buf(), second.path().to_path_buf()];
    let fold = |dirs: &[PathBuf]| {
        let mut hasher = blake3::Hasher::new();
        let hashed = fold_native_dir_archives(&mut hasher, dirs, native_dir_archives, |path| {
            Ok(std::fs::read_to_string(path)?)
        })
        .unwrap();
        (hasher.finalize(), hashed)
    };
    let mut expected = blake3::Hasher::new();
    fold_field(&mut expected, b"native_dir_archive.v1:", b"0/liba.a=a");
    fold_field(&mut expected, b"native_dir_archive.v1:", b"1/libb.a=b");
    let (digest, hashed) = fold(&dirs);
    assert_eq!(digest, expected.finalize());
    assert_eq!(
        hashed,
        [first.path().join("liba.a"), second.path().join("libb.a")]
    );
    assert_eq!(fold(&[]).0, blake3::Hasher::new().finalize());

    // A framework binary names its bundle too.
    let bundle = first.path().join("Foo.framework");
    std::fs::create_dir_all(&bundle).unwrap();
    std::fs::write(bundle.join("Foo"), b"!<arch>\nf").unwrap();
    let mut hasher = blake3::Hasher::new();
    fold_native_dir_archives(
        &mut hasher,
        &dirs[..1],
        native_dir_static_frameworks,
        |_| Ok("d".to_string()),
    )
    .unwrap();
    let mut expected = blake3::Hasher::new();
    let binary = Path::new("Foo.framework").join("Foo");
    fold_field(
        &mut expected,
        b"native_dir_archive.v1:",
        format!("0/{}=d", binary.display()).as_bytes(),
    );
    assert_eq!(hasher.finalize(), expected.finalize());

    std::fs::write(first.path().join("libthin.a"), b"!<thin>\n").unwrap();
    let mut hasher = blake3::Hasher::new();
    let thin = fold_native_dir_archives(&mut hasher, &dirs, native_dir_archives, |path| {
        FileHasher::new().hash_static_lib(path)
    });
    assert!(thin.is_err(), "a thin archive refuses the key");
}

/// An rlib or staticlib leaves a `-bundle` archive out of its output, so
/// the archive must not key it by its spec; the unit that links it later
/// does.
#[test]
fn unbundled_static_lib_keys_only_the_unit_that_links_it() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("x86_64-unknown-linux-gnu", &normalizer);
    let dirs = [tree.elsewhere.clone()];
    let archive = tree.elsewhere.join("libfoo.a");
    let rewrites = |crate_type: &str, spec: &str| {
        let argv = unit_args(crate_type, &tree.deps, &["-l", spec]);
        fold_rewrites(&archive, || fold_inputs(&argv, &dirs, &[], &context))
    };
    assert!(!rewrites("rlib", "static:-bundle=foo"));
    assert!(rewrites("rlib", "static:-bundle,+bundle=foo"));
    assert!(rewrites("bin", "static:-bundle=foo"));
}

/// A Unix linker looks for `-l foo` or `-l dylib=foo` in the `-L` dirs,
/// then in its default dirs (`/usr/local/lib`, ...), and takes
/// `libfoo.a` when the first dir that has the name holds no shared
/// library, or always under `+crt-static`.
#[test]
fn unix_link_keys_a_library_only_a_default_dir_holds() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let archive = tree.elsewhere.join("libfoo.a");
    let fold_with = |crate_type: &str, spec: &str, extra: &[&str], target: &str| {
        let mut flags = vec!["-l", spec];
        flags.extend_from_slice(extra);
        let argv = unit_args(crate_type, &tree.deps, &flags);
        let context = NativeLinkContext {
            default_dirs: vec![tree.elsewhere.clone()],
            ..unix_context(target, &normalizer)
        };
        let native = [tree.out.clone()];
        fold_rewrites(&archive, || fold_inputs(&argv, &native, &[], &context))
    };
    let gnu = "x86_64-unknown-linux-gnu";
    assert!(fold_with("bin", "foo", &[], gnu));
    assert!(fold_with("bin", "dylib=foo", &[], gnu));
    assert!(!fold_with("rlib", "foo", &[], gnu), "an rlib does not link");

    std::fs::write(tree.elsewhere.join("libfoo.so"), b"shared").unwrap();
    assert!(
        !fold_with("bin", "foo", &[], gnu),
        "the shared library wins in its dir"
    );
    assert!(fold_with(
        "bin",
        "foo",
        &["-Ctarget-feature=+crt-static"],
        gnu
    ));
    assert!(
        fold_with("bin", "foo", &[], "x86_64-unknown-linux-musl"),
        "musl links statically by default"
    );
    std::fs::remove_file(tree.elsewhere.join("libfoo.so")).unwrap();

    // A shared library in a `-L` dir comes first.
    std::fs::write(tree.out.join("libfoo.so"), b"shared").unwrap();
    assert!(!fold_with("bin", "foo", &[], gnu));
}

/// A library a link argument names is looked up like `-l`, and its
/// first archive counts even beside a shared library, since the link
/// arguments may say `-Bstatic`.
#[test]
fn unix_link_keys_libraries_named_in_link_arguments() {
    let tree = native_tree();
    let normalizer = PathNormalizer::empty();
    let context = NativeLinkContext {
        default_dirs: vec![tree.elsewhere.clone()],
        ..unix_context("x86_64-unknown-linux-gnu", &normalizer)
    };
    std::fs::write(tree.elsewhere.join("libfoo.so"), b"shared").unwrap();
    let rewrites = |crate_type: &str, flag: &str, file: &Path| {
        let argv = unit_args(crate_type, &tree.deps, &[flag]);
        fold_rewrites(file, || fold_inputs(&argv, &[], &[], &context))
    };
    let archive = tree.elsewhere.join("libfoo.a");
    assert!(rewrites(
        "bin",
        "-Clink-arg=-Wl,-Bstatic,-lfoo,-Bdynamic",
        &archive
    ));
    assert!(rewrites("bin", "-Clink-arg=-l:libfoo.a", &archive));
    assert!(!rewrites("rlib", "-Clink-arg=-lfoo", &archive));
    assert!(!rewrites(
        "bin",
        "-Clink-arg=-lbar",
        &tree.elsewhere.join("libbaz.a")
    ));
}

#[test]
fn resolve_unix_library_follows_the_first_dir_with_a_candidate() {
    let first = PathBuf::from("/one");
    let second = PathBuf::from("/two");
    let dirs = [first.clone(), second.clone()];
    let all = ["so", "dylib", "tbd"];
    let resolve = |present: &[&str], name: &str, verbatim: bool, prefer_static: bool| {
        resolve_unix_library(name, verbatim, &dirs, prefer_static, &all, |path| {
            present.iter().any(|file| path == Path::new(file))
        })
    };
    let archive_in = |dir: &Path| Some(dir.join("libfoo.a"));

    assert_eq!(
        resolve(&["/two/libfoo.a"], "foo", false, false),
        archive_in(&second)
    );
    assert_eq!(
        resolve(&["/one/libfoo.a", "/two/libfoo.a"], "foo", false, false),
        archive_in(&first)
    );
    assert_eq!(resolve(&[], "foo", false, false), None);
    for shared in ["/one/libfoo.so", "/one/libfoo.dylib", "/one/libfoo.tbd"] {
        assert_eq!(
            resolve(&[shared, "/one/libfoo.a"], "foo", false, false),
            None,
            "{shared}"
        );
        assert_eq!(
            resolve(&[shared, "/one/libfoo.a"], "foo", false, true),
            archive_in(&first),
            "{shared} under a static link"
        );
    }
    // A shared library alone in the first dir hides a later archive,
    // except from a static link, which only looks for archives.
    let hidden = ["/one/libfoo.so", "/two/libfoo.a"];
    assert_eq!(resolve(&hidden, "foo", false, false), None);
    assert_eq!(resolve(&hidden, "foo", false, true), archive_in(&second));

    assert_eq!(
        resolve(&["/two/foo.a"], "foo.a", true, false),
        Some(second.join("foo.a"))
    );
    assert_eq!(resolve(&["/one/libfoo.so"], "libfoo.so", true, false), None);

    // An ELF linker does not read a stray `.dylib` beside the archive.
    let elf = resolve_unix_library(
        "foo",
        false,
        &dirs,
        false,
        shared_library_extensions("x86_64-unknown-linux-gnu"),
        |path| path == Path::new("/one/libfoo.dylib") || path == Path::new("/one/libfoo.a"),
    );
    assert_eq!(elf, archive_in(&first));
}

#[test]
fn shared_library_extensions_follow_the_object_format() {
    assert_eq!(
        shared_library_extensions("aarch64-apple-darwin"),
        ["tbd", "dylib", "so"]
    );
    assert_eq!(
        shared_library_extensions("x86_64-unknown-linux-gnu"),
        ["so"]
    );
}

#[test]
fn static_link_preference_follows_crt_static() {
    let gnu = "x86_64-unknown-linux-gnu";
    let musl = "x86_64-unknown-linux-musl";
    assert!(!prefers_static_libraries(&[], gnu));
    assert!(prefers_static_libraries(&["+crt-static"], gnu));
    assert!(prefers_static_libraries(&["+sse2, +crt-static"], gnu));
    assert!(!prefers_static_libraries(
        &["+crt-static", "-crt-static"],
        gnu
    ));
    assert!(prefers_static_libraries(&[], musl));
    assert!(!prefers_static_libraries(&["-crt-static"], musl));
    assert!(prefers_static_libraries(&["+sse2"], musl));
}

/// With no `--target`, a link is for the wrapped rustc's host, as `rustc
/// -vV` reports it, not for whatever kache was built for: a musl host
/// links statically by default.
#[test]
fn link_target_defaults_to_the_wrapped_rustc_host() {
    let version = "rustc 1.98.0\nhost: x86_64-unknown-linux-musl\nrelease: 1.98.0\n";
    let host = rustc_host_triple(version);
    assert_eq!(link_target(None, host), "x86_64-unknown-linux-musl");
    assert!(prefers_static_libraries(&[], link_target(None, host)));
    assert_eq!(
        link_target(Some("aarch64-unknown-linux-gnu"), host),
        "aarch64-unknown-linux-gnu"
    );
    assert_eq!(link_target(None, None), "unknown");
}

/// A host-native Unix link searches `LIBRARY_PATH` and then the system
/// and local install dirs; a cross link and other targets search none of
/// them.
#[test]
fn default_library_dirs_follow_a_host_native_unix_target() {
    let linux = "x86_64-unknown-linux-gnu";
    let dirs = |target: &str, host: &str, library_path: Option<&str>| {
        default_library_dirs(target, Some(host), library_path.map(std::ffi::OsStr::new))
    };
    let expected: Vec<PathBuf> = [
        "/usr/local/lib/x86_64-linux-gnu",
        "/lib/x86_64-linux-gnu",
        "/usr/lib/x86_64-linux-gnu",
        "/usr/local/lib64",
        "/lib64",
        "/usr/lib64",
        "/usr/local/lib",
        "/lib",
        "/usr/lib",
    ]
    .map(PathBuf::from)
    .into();
    assert_eq!(dirs(linux, linux, None), expected);
    #[cfg(unix)]
    {
        let mut with_path = vec![PathBuf::from("/opt/a"), PathBuf::from("/opt/b")];
        with_path.extend(expected.clone());
        assert_eq!(dirs(linux, linux, Some("/opt/a::/opt/b")), with_path);
    }
    let apple = "aarch64-apple-darwin";
    assert_eq!(
        dirs(apple, apple, None),
        [PathBuf::from("/usr/lib"), PathBuf::from("/usr/local/lib")]
    );
    assert!(dirs("aarch64-unknown-linux-gnu", linux, None).is_empty());
    assert!(default_library_dirs(linux, None, None).is_empty());
    let windows = "x86_64-pc-windows-gnu";
    assert!(dirs(windows, windows, Some("/opt/a")).is_empty());
    assert_eq!(
        multiarch_name("aarch64-unknown-linux-gnu"),
        "aarch64-linux-gnu"
    );
    assert_eq!(
        multiarch_name("x86_64-linux-android"),
        "x86_64-linux-android"
    );
}

#[test]
fn unix_library_request_reads_kindless_and_dylib_specs() {
    assert_eq!(unix_library_request("foo"), Some(("foo", false)));
    assert_eq!(unix_library_request("dylib=foo"), Some(("foo", false)));
    assert_eq!(
        unix_library_request("dylib:-as-needed=foo"),
        Some(("foo", false))
    );
    assert_eq!(
        unix_library_request("dylib:+verbatim=libfoo.so"),
        Some(("libfoo.so", true))
    );
    assert_eq!(
        unix_library_request("dylib:+verbatim,-verbatim=foo"),
        Some(("foo", false))
    );
    assert_eq!(unix_library_request("static=foo"), None);
    assert_eq!(unix_library_request("framework=Foo"), None);
    assert_eq!(unix_library_request("dylib="), None);
}

/// Files a link argument names are linker inputs: rebuilding one in place
/// must re-key the binary.
#[cfg(not(windows))]
#[test]
fn unix_link_keys_files_named_in_link_arguments() {
    let _lock = key_test_lock();
    let tree = native_tree();
    let archive = tree.elsewhere.join("libfoo.a");
    let object = tree.elsewhere.join("extra.o");
    let a = archive.display().to_string();
    let o = object.display().to_string();
    for (flag, file) in [
        (format!("-Clink-arg={a}"), &archive),
        (format!("-Clink-arg=-Wl,--whole-archive,{a}"), &archive),
        (format!("-Clink-args=-force_load {a}"), &archive),
        (format!("-Clink-arg={o}"), &object),
    ] {
        let bin = unit_args("bin", &tree.deps, &[&flag]);
        let (before, after) = keys_around_rewrite(&bin, file);
        assert_ne!(before, after, "{flag}");
        let rlib = unit_args("rlib", &tree.deps, &[&flag]);
        let (before, after) = keys_around_rewrite(&rlib, file);
        assert_eq!(before, after, "an rlib does not link: {flag}");
    }

    // An archive is hashed as one, so a thin archive refuses the key; any
    // other input is hashed as a file, whatever its bytes.
    std::fs::write(tree.elsewhere.join("libthin.a"), b"!<thin>\n").unwrap();
    std::fs::write(tree.elsewhere.join("thin.o"), b"!<thin>\n").unwrap();
    let thin_object = format!("-Clink-arg={}", tree.elsewhere.join("thin.o").display());
    assert!(try_key_of_flags(&unit_args("bin", &tree.deps, &[&thin_object])).is_ok());

    for flag in [
        format!("-Clink-arg={}", tree.elsewhere.join("absent.a").display()),
        "-Clink-arg=relative/libfoo.a".to_string(),
        format!("-Clink-arg={}", tree.elsewhere.join("libthin.a").display()),
    ] {
        assert!(
            try_key_of_flags(&unit_args("bin", &tree.deps, &[&flag])).is_err(),
            "{flag}"
        );
    }
}

/// A linking unit's `static` lib that no `-L` dir holds may come from a
/// system dir the key never sees. A `-L` in the link arguments counts.
#[cfg(not(windows))]
#[test]
fn unresolved_static_lib_refuses_a_linking_unit() {
    let _lock = key_test_lock();
    let tree = native_tree();
    let error =
        try_key_of_flags(&unit_args("bin", &tree.deps, &["-l", "static=nope"])).unwrap_err();
    assert!(
        format!("{error:#}").contains("is in no -L directory"),
        "{error:#}"
    );
    assert!(try_key_of_flags(&unit_args("rlib", &tree.deps, &["-l", "static=nope"])).is_ok());

    let link_search = format!("-Clink-arg=-L{}", tree.elsewhere.display());
    let bin = unit_args("bin", &tree.deps, &[&link_search, "-l", "static=nope"]);
    let (before, after) = keys_around_rewrite(&bin, &tree.elsewhere.join("libnope.a"));
    assert_ne!(before, after, "found through the link argument and keyed");
}

#[test]
fn unresolved_static_lib_is_an_error_only_for_non_msvc_links() {
    assert!(unresolved_static_lib_is_error(true, false));
    assert!(!unresolved_static_lib_is_error(true, true));
    assert!(!unresolved_static_lib_is_error(false, false));
}

#[test]
fn packed_bundled_libs_flag_is_read_in_either_spelling() {
    let flags = |items: &[&str]| {
        items
            .iter()
            .map(|flag| flag.to_string())
            .collect::<Vec<_>>()
    };
    assert!(packs_bundled_libs(&flags(&["packed-bundled-libs"])));
    assert!(packs_bundled_libs(&flags(&[
        "share-generics",
        "packed_bundled_libs=yes"
    ])));
    assert!(!packs_bundled_libs(&flags(&[
        "share-generics=packed-bundled-libs"
    ])));
    assert!(!packs_bundled_libs(&[]));
}

/// An rlib carries a `static` spec's archive unless `-bundle`; it packs
/// one under `+whole-archive` or `-Z packed-bundled-libs`.
#[test]
fn rlib_bundle_follows_bundle_and_packing() {
    let spec = static_lib_spec;
    assert_eq!(rlib_bundle(&spec("static=foo"), true, false), Some(false));
    assert_eq!(
        rlib_bundle(&spec("static:+whole-archive=foo"), true, false),
        Some(true)
    );
    assert_eq!(rlib_bundle(&spec("static=foo"), true, true), Some(true));
    assert_eq!(rlib_bundle(&spec("static:-bundle=foo"), true, false), None);
    assert_eq!(rlib_bundle(&spec("static=foo"), false, false), None);
    assert_eq!(rlib_bundle(&spec("foo"), true, false), None);
}

#[test]
fn rlib_bundle_uses_one_effective_spec_per_library() {
    let tree = native_tree();
    let archive = tree.elsewhere.join("libfoo.a");
    std::fs::write(&archive, b"archive").unwrap();
    let normalizer = PathNormalizer::empty();
    let context = unix_context("x86_64-unknown-linux-gnu", &normalizer);
    let dirs = [tree.elsewhere.clone()];
    for (specs, packed) in [
        (vec!["static=foo"], Some(false)),
        (vec!["static=foo", "static=foo"], Some(false)),
        (vec!["static=foo", "dylib=foo"], None),
        (vec!["dylib=foo", "static=foo"], Some(false)),
        (vec!["static=foo", "foo"], Some(false)),
        (vec!["static=foo", "static:-bundle=foo"], None),
        (
            vec!["static:-bundle=foo", "static:+bundle=foo"],
            Some(false),
        ),
        (vec!["static=foo", "static:+whole-archive=foo"], Some(true)),
    ] {
        let extra: Vec<&str> = specs.iter().flat_map(|spec| ["-l", *spec]).collect();
        let (_, native) =
            fold_inputs(&unit_args("rlib", &tree.deps, &extra), &dirs, &[], &context).unwrap();
        let expected: Vec<BundledArchive> = packed
            .map(|packed| BundledArchive {
                path: archive.clone(),
                packed,
            })
            .into_iter()
            .collect();
        assert_eq!(native.bundled, expected, "{specs:?}");
    }
}

/// The bundle-audit marker keys rlibs with a native dir apart from
/// entries stored without the audit, and the outputs report what the key
/// hashed and what the rlib carries.
///
/// A dir outside the workspace counts like one inside it (see
/// [`audit_dirs_are_an_rlibs_scanned_dirs`] for system library dirs).
#[test]
fn native_bundle_audit_marks_rlibs_with_a_native_dir() {
    let _lock = key_test_lock();
    let tree = native_tree();
    std::fs::write(tree.out.join("libfoo.a"), b"archive").unwrap();
    std::fs::write(tree.elsewhere.join("libbar.a"), b"archive").unwrap();
    let search = format!("native={}", tree.out.display());
    let outside = format!("native={}", tree.elsewhere.display());
    let marked = |crate_type: &str, extra: &[&str]| {
        outputs_of_flags(&unit_args(crate_type, &tree.deps, extra))
            .fields
            .unwrap()
            .contains_key("native_bundle_audit")
    };
    assert!(marked("rlib", &["-L", &search]));
    assert!(!marked("rlib", &[]));
    assert!(marked("rlib", &["-L", &outside]));
    assert!(!marked("rlib", &["-L", &search, "--emit=metadata"]));
    #[cfg(not(windows))]
    assert!(!marked("bin", &["-L", &search]));

    let outputs = outputs_of_flags(&unit_args(
        "rlib",
        &tree.deps,
        &[
            "-L",
            &search,
            "-L",
            &outside,
            "-L",
            &search,
            "-l",
            "static:+whole-archive=foo",
            "-l",
            "static=bar",
        ],
    ));
    assert_eq!(
        outputs.native_archives,
        Some(KeyedNativeArchives {
            archives: vec![tree.out.join("libfoo.a"), tree.elsewhere.join("libbar.a")],
            bundled: vec![
                BundledArchive {
                    path: tree.out.join("libfoo.a"),
                    packed: true,
                },
                BundledArchive {
                    path: tree.elsewhere.join("libbar.a"),
                    packed: false,
                },
            ],
            dirs: vec![tree.out.clone(), tree.elsewhere.clone()],
        })
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// With Cargo's new build-dir layout, a `-sys` crate's
/// `cargo:rustc-link-search=native=$OUT_DIR` reaches every dependent as
/// `<target>/<profile>/build/<pkg>/<hash>/out`. The target directory
/// derived from the dependent's own `--out-dir` must cover it, or the
/// checkout path stays in the key and the dependent misses in every other
/// checkout. The unit is an rlib, as such dependents usually are: a linked
/// output would run the native Windows MSVC link probe, which fails closed
/// on the made-up search directories.
#[test]
fn link_search_into_new_layout_out_dir_is_the_same_in_every_checkout() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();

    let key_in = |checkout: &str| {
        let target = checkout_target(checkout);
        let out_dir = format!("{target}/debug/build/mylib/0123456789abcdef/out");
        let native = format!("native={target}/debug/build/foo-sys/fedcba9876543210/out");
        let argv: Vec<String> = [
            "rustc",
            "--crate-name",
            "mylib",
            &source.to_string_lossy(),
            "--crate-type",
            "lib",
            "--out-dir",
            &out_dir,
            "-L",
            &native,
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let args = RustcArgs::parse(&argv).unwrap();
        let pn = PathNormalizer::empty().with_target_dir(args.target_dir().as_deref());
        compute_cache_key(&args, &FileHasher::new(), &pn, &KeyEnv::default()).unwrap()
    };

    assert_eq!(key_in("checkout-a"), key_in("checkout-b"));
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// A trusted codegen backend dylib is keyed by content: a rebuild in place
/// changes the key, the same bytes at another checkout's path do not.
/// A toolchain backend name stays keyed as written.
#[test]
fn codegen_backend_dylib_is_keyed_by_content_not_path() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let clone_a = dir.path().join("a/librustc_codegen_x.so");
    let clone_b = dir.path().join("b/librustc_codegen_x.so");
    for backend in [&clone_a, &clone_b] {
        std::fs::create_dir_all(backend.parent().unwrap()).unwrap();
        std::fs::write(backend, b"backend-v1").unwrap();
    }
    let flag = |backend: &Path| format!("-Zcodegen-backend={}", backend.display());

    let a = key_of_flags(&flag_base(&source, &[&flag(&clone_a)]));
    let b = key_of_flags(&flag_base(&source, &[&flag(&clone_b)]));
    assert_eq!(a, b, "identical backends at different paths share a key");

    std::fs::write(&clone_a, b"backend-v2").unwrap();
    let rebuilt = key_of_flags(&flag_base(&source, &[&flag(&clone_a)]));
    assert_ne!(a, rebuilt, "a rebuilt backend must change the key");

    let sysroot = dir.path().join("sysroot");
    let backends = sysroot_codegen_backends(&sysroot);
    for name in ["cranelift", "gcc"] {
        std::fs::write(backends.join(backend_library(name, "")), b"same bytes").unwrap();
    }
    let named = |name: &str| {
        key_of_flags(&flag_base(
            &source,
            &[
                "--sysroot",
                &sysroot.to_string_lossy(),
                &format!("-Zcodegen-backend={name}"),
            ],
        ))
    };
    let cranelift = named("cranelift");
    assert_ne!(
        cranelift,
        named("gcc"),
        "toolchain backend names stay keyed"
    );
    assert_ne!(cranelift, a);

    let missing = dir.path().join("missing.so");
    let mut parsed = RustcArgs::parse(&flag_base(&source, &[&flag(&missing)])).unwrap();
    parsed.source_file = None;
    assert!(
        compute_cache_key(
            &parsed,
            &FileHasher::new(),
            &PathNormalizer::empty(),
            &KeyEnv::default()
        )
        .is_err(),
        "an unreadable backend must not produce a key"
    );
}

/// `<sysroot>/lib/rustlib/<host>/codegen-backends`, created, for the rustc
/// the key tests run.
fn sysroot_codegen_backends(sysroot: &Path) -> PathBuf {
    let version = get_rustc_version(Path::new("rustc")).unwrap();
    let backends = sysroot
        .join("lib")
        .join("rustlib")
        .join(rustc_host_triple(&version).unwrap())
        .join("codegen-backends");
    std::fs::create_dir_all(&backends).unwrap();
    backends
}

/// The file name rustc loads for backend `name`, with `release` appended.
fn backend_library(name: &str, release: &str) -> String {
    format!(
        "{}rustc_codegen_{name}{release}{}",
        std::env::consts::DLL_PREFIX,
        std::env::consts::DLL_SUFFIX
    )
}

/// A backend selected by name is keyed by the library rustc loads for it,
/// so a toolchain whose backend is rebuilt in place, with the same
/// `rustc -vV`, does not serve outputs of the old backend.
#[test]
fn named_codegen_backend_is_keyed_by_its_library() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let sysroot = dir.path().join("sysroot");
    let backends = sysroot_codegen_backends(&sysroot);
    let key = |name: &str| {
        let mut parsed = RustcArgs::parse(&flag_base(
            &source,
            &[
                "--sysroot",
                &sysroot.to_string_lossy(),
                &format!("-Zcodegen-backend={name}"),
            ],
        ))
        .unwrap();
        parsed.source_file = None;
        compute_cache_key(
            &parsed,
            &FileHasher::new(),
            &PathNormalizer::empty(),
            &KeyEnv::default(),
        )
    };

    assert!(
        key("kachetest").is_err(),
        "a backend that is not installed must not produce a key"
    );
    std::fs::write(backends.join(backend_library("kachetest", "")), b"v1").unwrap();
    let first = key("kachetest").unwrap();
    std::fs::write(
        backends.join(backend_library("kachetest", "")),
        b"v2 rebuilt",
    )
    .unwrap();
    let rebuilt = key("kachetest").unwrap();
    assert_ne!(first, rebuilt, "a rebuilt backend must change the key");

    // Other files in the directory are not this backend.
    std::fs::write(backends.join(backend_library("kachetest_other", "")), b"x").unwrap();
    std::fs::write(backends.join("librustc_codegen_kachetest.a"), b"x").unwrap();
    assert_eq!(rebuilt, key("kachetest").unwrap());

    std::fs::write(
        backends.join(backend_library("kachetest", "-1.99.0-nightly")),
        b"release",
    )
    .unwrap();
    assert_ne!(
        rebuilt,
        key("kachetest").unwrap(),
        "the release-suffixed library is one rustc loads too"
    );
}

/// Every sysroot rustc may search contributes its backend libraries; a
/// sysroot without a `codegen-backends` directory contributes none.
#[test]
fn codegen_backend_libraries_span_every_sysroot() {
    let dir = tempfile::tempdir().unwrap();
    let host = "aarch64-apple-darwin";
    let sysroot = |name: &str| dir.path().join(name);
    for (name, content) in [
        ("explicit", b"explicit".as_slice()),
        ("default", b"default"),
    ] {
        let backends = sysroot(name)
            .join("lib")
            .join("rustlib")
            .join(host)
            .join("codegen-backends");
        std::fs::create_dir_all(&backends).unwrap();
        std::fs::write(backends.join(backend_library("gcc", "")), content).unwrap();
    }
    let hasher = FileHasher::new();
    let libraries = |sysroots: &[&str]| {
        codegen_backend_libraries(
            sysroots.iter().map(|name| sysroot(name)),
            host,
            "gcc",
            &hasher,
        )
        .unwrap()
    };

    let both = libraries(&["missing", "explicit", "default"]);
    assert_eq!(both.len(), 2);
    assert!(
        both.iter()
            .all(|(file, _)| *file == backend_library("gcc", ""))
    );
    assert_ne!(both[0].1, both[1].1);
    assert!(libraries(&["missing"]).is_empty());

    // A directory that exists but cannot be listed is not a missing one.
    let unlistable = sysroot("unlistable").join("lib").join("rustlib").join(host);
    std::fs::create_dir_all(&unlistable).unwrap();
    std::fs::write(unlistable.join("codegen-backends"), b"not a directory").unwrap();
    assert!(codegen_backend_libraries([sysroot("unlistable")], host, "gcc", &hasher).is_err());
}

/// An explicit `--sysroot` wins; otherwise the toolchain reports its own.
#[test]
fn rustc_sysroot_prefers_the_explicit_one() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    let explicit = dir.path().join("sysroot");
    let args = |extra: &[&str]| RustcArgs::parse(&flag_base(&source, extra)).unwrap();
    assert_eq!(
        get_rustc_sysroot(&args(&["--sysroot", &explicit.to_string_lossy()])),
        Some(explicit)
    );
    let own = get_rustc_sysroot(&args(&[])).unwrap();
    assert!(
        own.join("lib").join("rustlib").is_dir(),
        "{}",
        own.display()
    );
}

/// rustc looks for a linker named without a directory in the tool directory
/// of an explicit `--sysroot`, then in that of its own sysroot. Behind a
/// workspace wrapper, the sysroot is the inner rustc's.
#[test]
fn rustc_tool_dirs_follow_rustcs_sysroot_order() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    let explicit = dir.path().join("sysroot");
    let host = "x86_64-pc-windows-msvc";
    let tools = |sysroot: &Path| sysroot.join("lib").join("rustlib").join(host).join("bin");
    let args = |extra: &[&str]| RustcArgs::parse(&flag_base(&source, extra)).unwrap();
    let own = get_rustc_sysroot(&args(&[])).unwrap();

    assert_eq!(rustc_tool_dirs(&args(&[]), host).unwrap(), [tools(&own)]);
    assert_eq!(
        rustc_tool_dirs(&args(&["--sysroot", &explicit.to_string_lossy()]), host).unwrap(),
        [tools(&explicit), tools(&own)]
    );

    let mut wrapped = args(&[]);
    wrapped.inner_rustc = Some(wrapped.rustc.clone());
    wrapped.rustc = dir.path().join("workspace-wrapper");
    assert_eq!(rustc_tool_dirs(&wrapped, host).unwrap(), [tools(&own)]);

    // Without rustc's own sysroot the lookup could find another linker.
    wrapped.inner_rustc = Some(dir.path().join("missing-rustc"));
    let explicit_only = format!("--sysroot={}", explicit.display());
    let mut with_explicit =
        RustcArgs::parse(&flag_base(&source, &[explicit_only.as_str()])).unwrap();
    with_explicit.inner_rustc = wrapped.inner_rustc.clone();
    for args in [&wrapped, &with_explicit] {
        let error = rustc_tool_dirs(args, host).unwrap_err();
        assert!(error.to_string().contains("sysroot"), "{error:#}");
    }
}

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

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

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

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

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

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

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

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

    assert_ne!(key1, key2);
}

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

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

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

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

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

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

/// [`path_is_only_used_for_includes`] with both sides in probe form, as the
/// key computation calls it.
fn locates_includes(value: &str, source_files: &[PathBuf]) -> bool {
    let paths = EnvDepPaths::new(None, source_files);
    path_is_only_used_for_includes(EnvDepValue::new(value).probe(), paths.source_probes())
}

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

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

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

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

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

#[test]
fn out_dir_probe_needs_an_absolute_out_dir() {
    assert_eq!(out_dir_probe(None), None);
    assert_eq!(out_dir_probe(Some(OsStr::new(""))), None);
    assert_eq!(
        out_dir_probe(Some(OsStr::new("kache-no-such-dir/out"))),
        None
    );
    let dir = tempfile::tempdir().unwrap();
    let canonical = dir.path().canonicalize().unwrap();
    assert_eq!(
        out_dir_probe(Some(dir.path().as_os_str())),
        Some(canonical.clone())
    );
    // An absolute OUT_DIR that does not exist anchors in its raw form.
    let missing = canonical.join("missing/out");
    assert_eq!(out_dir_probe(Some(missing.as_os_str())), Some(missing));
}

#[test]
fn out_dir_suffix_is_relative_to_out_dir_by_components() {
    let out = Path::new("/o/out");
    let suffix = |value: &str| out_dir_relative_suffix(Path::new(value), out);
    assert_eq!(suffix("/o/out"), Some(String::new()));
    assert_eq!(suffix("/o/out/gen/x.rs"), Some("gen/x.rs".to_string()));
    assert_eq!(suffix("/o/out2/x.rs"), None);
    assert_eq!(suffix("/o"), None);
    // A backslash separates on Windows and is part of a name on Unix; the
    // suffix spells it `/` either way.
    assert_eq!(suffix("/o/out/gen\\x.rs"), Some("gen/x.rs".to_string()));
}

#[test]
fn env_dep_paths_anchor_only_on_a_usable_out_dir() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().canonicalize().unwrap().join("pkg-1/out");
    std::fs::create_dir_all(&out).unwrap();
    let generated = out.join("consts.rs");
    std::fs::write(&generated, b"").unwrap();
    let generated = generated.to_str().unwrap();
    let suffix = |out_dir: Option<&OsStr>, value: &str| {
        EnvDepPaths::new(out_dir, &[]).out_dir_suffix(&EnvDepValue::new(value))
    };

    let out_dir = Some(out.as_os_str());
    assert_eq!(suffix(out_dir, generated), Some("consts.rs".to_string()));
    assert_eq!(suffix(out_dir, out.to_str().unwrap()), Some(String::new()));
    assert_eq!(suffix(None, generated), None);
    assert_eq!(suffix(Some(OsStr::new("pkg-1/out")), generated), None);
    // A value that does not exist compares in its raw form.
    let gone = out.join("gone.rs");
    assert_eq!(
        suffix(out_dir, gone.to_str().unwrap()),
        Some("gone.rs".to_string())
    );

    assert_eq!(out_dir_unit(out_dir), "pkg-1");
    assert_eq!(out_dir_unit(Some(OsStr::new("out"))), "");
    assert_eq!(out_dir_unit(None), "");
}

#[cfg(unix)]
#[test]
fn env_dep_paths_see_through_a_symlinked_out_dir() {
    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().canonicalize().unwrap().join("real");
    let out = real.join("pkg-1/out");
    std::fs::create_dir_all(&out).unwrap();
    let generated = out.join("consts.rs");
    std::fs::write(&generated, b"").unwrap();
    let link = dir.path().join("link");
    std::os::unix::fs::symlink(&real, &link).unwrap();
    let linked_out = link.join("pkg-1/out");
    let linked_generated = linked_out.join("consts.rs");

    // OUT_DIR through the link and the value real, then the reverse.
    let via_link = EnvDepPaths::new(Some(linked_out.as_os_str()), &[]);
    assert_eq!(
        via_link.out_dir_suffix(&EnvDepValue::new(generated.to_str().unwrap())),
        Some("consts.rs".to_string())
    );
    let direct = EnvDepPaths::new(Some(out.as_os_str()), &[]);
    assert_eq!(
        direct.out_dir_suffix(&EnvDepValue::new(linked_generated.to_str().unwrap())),
        Some("consts.rs".to_string())
    );
    // The unit name comes from OUT_DIR as given.
    assert_eq!(out_dir_unit(via_link.out_dir), "pkg-1");

    // Source files resolve through the link too.
    assert!(locates_includes(out.to_str().unwrap(), &[linked_generated]));
    assert!(locates_includes(linked_out.to_str().unwrap(), &[generated]));
}

#[test]
fn source_probes_fall_back_to_the_raw_path() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().canonicalize().unwrap();
    let out = root.join("out");
    std::fs::create_dir_all(&out).unwrap();
    let sources = [root.join("src/lib.rs"), out.join("gone.rs")];

    let paths = EnvDepPaths::new(None, &sources);
    assert_eq!(paths.source_probes(), &sources);
    let out = out.to_str().unwrap();
    assert!(locates_includes(out, &sources));
    assert!(!locates_includes(out, &sources[..1]));
}

/// A value that does not exist but resolves lexically to a path under
/// OUT_DIR is compared in its resolved form, not as written.
#[cfg(unix)]
#[test]
fn a_missing_value_compares_in_its_resolved_form() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().canonicalize().unwrap().join("pkg-1/out");
    std::fs::create_dir_all(&out).unwrap();
    let value = format!("{}/sub/../gen.rs", out.display());
    let pn = PathNormalizer::empty().with_path_only_env_vars(vec!["c:GEN".to_string()]);

    let dep = normalize_env_dep_value_in("c", "GEN", &value, &[], &pn, Some(out.as_os_str()));
    assert_eq!(dep.decision, EnvDepNormalizationDecision::ForcedPathOnly);
    assert_eq!(dep.value, "<OUT_DIR:pkg-1>/gen.rs");
}

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

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

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

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

#[test]
fn env_dep_normalization_decision_trace_labels_are_stable() {
    for (decision, expected) in [
        (EnvDepNormalizationDecision::Unchanged, "unchanged"),
        (
            EnvDepNormalizationDecision::NormalizedPathOnly,
            "normalized path-only",
        ),
        (
            EnvDepNormalizationDecision::KeptAbsoluteNotPathOnly,
            "kept absolute: not a path-only var",
        ),
        (
            EnvDepNormalizationDecision::KeptAbsoluteManifestDir,
            "kept absolute: CARGO_MANIFEST_DIR is never path-only",
        ),
        (
            EnvDepNormalizationDecision::KeptAbsoluteNoIncludeProof,
            "kept absolute: no include proof",
        ),
        (
            EnvDepNormalizationDecision::KeptAbsoluteRuntimeUse,
            "kept absolute: value use in source",
        ),
        (
            EnvDepNormalizationDecision::KeptAbsoluteScanError,
            "kept absolute: source scan failed",
        ),
        (
            EnvDepNormalizationDecision::ForcedPathOnly,
            "forced path-only (user-asserted)",
        ),
        (
            EnvDepNormalizationDecision::AliasedOutDir,
            "aliased OUT_DIR",
        ),
    ] {
        assert_eq!(decision.as_str(), expected);
    }
}

/// The same unit in two checkouts gets two OUT_DIRs. Pointed at one
/// shared alias, both its OUT_DIR and a `rustc-env` var under it key the
/// same, and never through a sentinel.
#[test]
fn aliased_out_dir_values_key_the_same_in_every_checkout() {
    let alias = Path::new("/cache/out-dirs/v1/d/dmac-0123456789abcdef/out");
    // A rule over the cache dir must not turn the alias into a sentinel.
    let pn = PathNormalizer::empty().with_base_dirs(&["/cache".to_string()]);
    assert_ne!(
        pn.normalize(alias.to_str().unwrap()),
        alias.to_str().unwrap()
    );
    let keyed = |checkout: &str| {
        let real = PathBuf::from(format!(
            "/{checkout}/target/debug/build/dmac-0123456789abcdef/out"
        ));
        let env = vec![
            ("OUT_DIR".into(), real.clone().into_os_string()),
            ("DEBUG_OUTPUT_DIR".into(), real.clone().into_os_string()),
        ];
        let rewrites = crate::out_dir_alias::env_rewrites(&env, &[], &[&real], alias)
            .expect("nothing else mentions OUT_DIR");
        rewrites
            .iter()
            .map(|(var, value)| {
                normalize_env_dep_value_with_hasher(
                    "dmac",
                    var.to_str().unwrap(),
                    &EnvDepValue::new(value.to_str().unwrap()),
                    &EnvDepPaths::new(None, &[]),
                    &FileHasher::new(),
                    &pn,
                    Some(alias),
                )
            })
            .collect::<Vec<_>>()
    };
    let a = keyed("a");
    let b = keyed("b");
    assert_eq!(a, b);
    assert_eq!(a.len(), 2);
    for dep in &a {
        assert_eq!(dep.decision, EnvDepNormalizationDecision::AliasedOutDir);
        assert_eq!(dep.value, alias.to_str().unwrap());
    }
}

#[test]
fn only_values_at_or_under_the_alias_take_the_aliased_decision() {
    let alias = Path::new("/c/d/out");
    let pn = PathNormalizer::empty();
    let decide = |value: &str, aliased: Option<&Path>| {
        normalize_env_dep_value_with_hasher(
            "dmac",
            "V",
            &EnvDepValue::new(value),
            &EnvDepPaths::new(None, &[]),
            &FileHasher::new(),
            &pn,
            aliased,
        )
        .decision
    };
    assert_eq!(
        decide("/c/d/out/gen.rs", Some(alias)),
        EnvDepNormalizationDecision::AliasedOutDir
    );
    assert_ne!(
        decide("/c/d/out2", Some(alias)),
        EnvDepNormalizationDecision::AliasedOutDir
    );
    assert_ne!(
        decide("/c/d/out", None),
        EnvDepNormalizationDecision::AliasedOutDir
    );
    assert!(value_at_or_under("/c/d/out", alias));
    assert!(value_at_or_under("/c/d/out/", alias));
    assert!(!value_at_or_under("/c/d", alias));
    assert!(!value_at_or_under("x/c/d/out", alias));
}

#[test]
fn env_dep_bakes_out_dir_when_an_out_dir_path_stays_literal() {
    use EnvDepNormalizationDecision as D;
    let literal = [
        D::Unchanged,
        D::KeptAbsoluteNotPathOnly,
        D::KeptAbsoluteManifestDir,
        D::KeptAbsoluteNoIncludeProof,
        D::KeptAbsoluteRuntimeUse,
        D::KeptAbsoluteScanError,
        D::AliasedOutDir,
    ];
    for decision in literal {
        assert!(decision.keeps_literal_value(), "{decision:?}");
        assert!(env_dep_bakes_out_dir("OUT_DIR", decision, || false));
        assert!(env_dep_bakes_out_dir("GEN", decision, || true));
        assert!(!env_dep_bakes_out_dir("GEN", decision, || false));
    }
    for decision in [D::NormalizedPathOnly, D::ForcedPathOnly] {
        assert!(!decision.keeps_literal_value(), "{decision:?}");
        assert!(!env_dep_bakes_out_dir("OUT_DIR", decision, || true));
    }
}

/// The key says whether it kept an OUT_DIR path, and a later key that
/// did not starts clean.
#[test]
fn key_computation_reports_whether_it_bakes_out_dir() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, "pub fn f() {}").unwrap();
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "helper".to_string(),
        source.to_str().unwrap().to_string(),
    ])
    .unwrap();
    let bakes = |args: &RustcArgs| {
        let (key, outputs) = compute_cache_key_with_outputs(
            args,
            &FileHasher::new(),
            &PathNormalizer::empty(),
            &KeyEnv::default(),
        );
        key.unwrap();
        outputs.bakes_out_dir
    };
    let key_with = |env_deps: Vec<(String, String)>| {
        provide_dep_info(
            DepInfo {
                source_files: vec![source.clone()],
                env_deps,
            },
            None,
        );
        bakes(&args)
    };

    assert!(key_with(vec![("OUT_DIR".into(), "/nowhere/out".into())]));
    assert!(!key_with(vec![("CARGO_PKG_NAME".into(), "helper".into())]));

    // Any one baking value is enough, however many there are.
    assert!(key_with(vec![
        ("OUT_DIR".into(), "/nowhere/out".into()),
        ("OUT_DIR".into(), "/nowhere/out".into()),
    ]));

    assert!(key_with(vec![("OUT_DIR".into(), "/nowhere/out".into())]));
    let mut no_source = args.clone();
    no_source.source_file = None;
    assert!(!bakes(&no_source), "a key with no closure bakes nothing");
}

/// The unit's OUT_DIR comes from the snapshot: a value under it is baked
/// only when the snapshot names that OUT_DIR.
#[test]
fn key_reads_out_dir_from_the_snapshot() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, "pub fn f() {}").unwrap();
    let args = RustcArgs::parse(&[
        "rustc".to_string(),
        "--crate-name".to_string(),
        "helper".to_string(),
        source.to_str().unwrap().to_string(),
    ])
    .unwrap();
    // Absent directories, so both sides compare as given; absolute on
    // every platform, or OUT_DIR anchors nothing.
    let out_dir = dir.path().join("absent-out");
    let generated = out_dir.join("gen.rs").to_str().unwrap().to_string();
    let bakes = |env: &KeyEnv| {
        provide_dep_info(
            DepInfo {
                source_files: vec![source.clone()],
                env_deps: vec![("GEN".into(), generated.clone())],
            },
            None,
        );
        let (key, outputs) = compute_cache_key_with_outputs(
            &args,
            &FileHasher::new(),
            &PathNormalizer::empty(),
            env,
        );
        key.unwrap();
        outputs.bakes_out_dir
    };
    let out_env = |path: &Path| KeyEnv::from_parts([("OUT_DIR", path)], None);
    assert!(bakes(&out_env(&out_dir)));
    assert!(!bakes(&KeyEnv::default()));
    assert!(!bakes(&out_env(&dir.path().join("elsewhere"))));
}

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

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

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

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

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

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

/// The OUT_DIR decision for a crate whose root source is `lib_source` and
/// whose dep-info lists a generated include under OUT_DIR, the shape that
/// makes OUT_DIR a normalization candidate at all.
fn out_dir_decision_for(
    lib_source: &str,
    file_hasher: &FileHasher<'_>,
) -> EnvDepNormalizationDecision {
    out_dir_decision_for_files(&[("src/lib.rs", Some(lib_source))], file_hasher)
}

/// Like [`out_dir_decision_for`], with every workspace-relative file in
/// `files` listed in dep-info. A `None` body is listed but never written.
fn out_dir_decision_for_files(
    files: &[(&str, Option<&str>)],
    file_hasher: &FileHasher<'_>,
) -> EnvDepNormalizationDecision {
    let dir = tempfile::tempdir().unwrap();
    let workspace = dir.path().join("workspace");
    let out_dir = workspace.join("target/debug/build/pkg/out");
    std::fs::create_dir_all(&out_dir).unwrap();
    let mut source_files = Vec::new();
    for (relative, body) in files {
        let path = workspace.join(relative);
        if let Some(body) = body {
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, body).unwrap();
        }
        source_files.push(path);
    }
    let included = out_dir.join("generated.rs");
    std::fs::write(&included, b"pub fn generated() -> u8 { 1 }").unwrap();
    source_files.push(included);
    let out_dir_value = out_dir
        .canonicalize()
        .unwrap()
        .to_string_lossy()
        .to_string();
    normalize_env_dep_value_with_hasher(
        "test_crate",
        "OUT_DIR",
        &EnvDepValue::new(&out_dir_value),
        &EnvDepPaths::new(None, &source_files),
        file_hasher,
        &PathNormalizer::from_env(Some(&workspace)),
        None,
    )
    .decision
}

#[test]
fn env_dep_policy_keeps_out_dir_absolute_for_uses_the_scanner_cannot_prove() {
    // Every source below includes a generated file through OUT_DIR, so
    // dep-info alone would allow normalization, and every one also derives
    // something from the absolute OUT_DIR that ends up in the artifact. A
    // normalized key would restore one checkout's artifact in another.
    const INCLUDE: &str = r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#;
    let value_uses: &[(&str, String)] = &[
        (
            "value length",
            format!(r#"{INCLUDE} pub const N: usize = env!("OUT_DIR").len();"#),
        ),
        (
            "value arithmetic",
            format!(r#"{INCLUDE} pub const P: usize = env!("OUT_DIR").len() % 2;"#),
        ),
        (
            "computed name",
            format!(r#"{INCLUDE} pub const S: &str = env!(concat!("OUT", "_DIR"));"#),
        ),
        (
            "computed name, option_env",
            format!(
                r#"{INCLUDE} pub const S: Option<&str> = option_env!(concat!("OUT", "_DIR"));"#
            ),
        ),
        (
            "forwarding macro",
            format!(
                r#"{INCLUDE}
macro_rules! e {{ ($v:literal) => {{ env!($v) }} }}
pub const X: &str = e!("OUT_DIR");"#
            ),
        ),
        (
            "brace delimiter",
            format!(r#"{INCLUDE} pub const S: &str = env!{{"OUT_DIR"}};"#),
        ),
        (
            "bracket delimiter",
            format!(r#"{INCLUDE} pub const S: &str = env!["OUT_DIR"];"#),
        ),
        (
            "escaped name",
            format!(r#"{INCLUDE} pub const S: &str = env!("OUT\x5FDIR");"#),
        ),
        (
            "raw string name",
            format!(r##"{INCLUDE} pub const S: &str = env!(r#"OUT_DIR"#);"##),
        ),
        (
            "comment before the bang",
            format!(r#"{INCLUDE} pub const S: &str = env /* x */ !("OUT_DIR");"#),
        ),
        (
            "non-ASCII whitespace before the bang",
            format!("{INCLUDE} pub const S: &str = env\u{200E}!(\"OUT_DIR\");"),
        ),
        (
            "vertical tab before the bang",
            format!("{INCLUDE} pub const S: &str = env\x0B!(\"OUT_DIR\");"),
        ),
        (
            "lifetime before the use",
            format!(r#"{INCLUDE} pub fn f(_: &'static str) -> usize {{ env!("OUT_DIR").len() }}"#),
        ),
        (
            "nested block comment",
            format!(
                r#"{INCLUDE} /* /* */ include!( */ pub const N: usize = env!("OUT_DIR").len();"#
            ),
        ),
        (
            "raw C string ending in a backslash",
            format!(
                r#"{INCLUDE} pub const C: &core::ffi::CStr = cr"\"; pub const N: usize = env!("OUT_DIR").len(); pub const T: &str = "";"#
            ),
        ),
        (
            "number suffix before a raw-string look-alike",
            format!(r##"{INCLUDE} m!{{ 1r#"x" }} pub const P: &str = env!("OUT_DIR"); // "#"##),
        ),
        (
            "non-ASCII prefix on an include look-alike",
            format!(
                r#"{INCLUDE}
macro_rules! éinclude {{ ($e:expr) => {{ pub const P: &str = $e; }} }}
éinclude!(env!("OUT_DIR"));"#
            ),
        ),
    ];
    // No visible include use: the env dep may come from another crate's
    // macro that bakes the value.
    let unproven: &[(&str, String)] = &[
        (
            "no env! in the crate",
            "pub fn f() -> &'static str { some_dep::out_dir!() }".to_string(),
        ),
        (
            "only a computed name inside include",
            r#"include!(concat!(env!(concat!("OUT", "_DIR")), "/generated.rs"));"#.to_string(),
        ),
    ];
    let hasher = FileHasher::new();
    let wrong: Vec<(&str, EnvDepNormalizationDecision)> = value_uses
        .iter()
        .map(|case| (case, EnvDepNormalizationDecision::KeptAbsoluteRuntimeUse))
        .chain(unproven.iter().map(|case| {
            (
                case,
                EnvDepNormalizationDecision::KeptAbsoluteNoIncludeProof,
            )
        }))
        .filter_map(|((label, source), expected)| {
            let decision = out_dir_decision_for(source, &hasher);
            (decision != expected).then_some((*label, decision))
        })
        .collect();
    assert!(wrong.is_empty(), "unexpected OUT_DIR decisions: {wrong:?}");
}

#[test]
fn env_dep_policy_takes_include_proof_only_from_rust_sources() {
    // `#![doc = include_str!("../README.md")]` puts the README in dep-info.
    // A code block in it that shows the include pattern is not code.
    let readme = r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#;
    let lib = r#"#![doc = include_str!("../README.md")] some_dep::out_dir!();"#;
    let hasher = FileHasher::new();
    assert_eq!(
        out_dir_decision_for_files(
            &[("src/lib.rs", Some(lib)), ("README.md", Some(readme))],
            &hasher
        ),
        EnvDepNormalizationDecision::KeptAbsoluteNoIncludeProof
    );
    // The same text in a Rust file is proof.
    assert_eq!(
        out_dir_decision_for_files(
            &[("src/lib.rs", Some(lib)), ("src/gen.rs", Some(readme))],
            &hasher
        ),
        EnvDepNormalizationDecision::NormalizedPathOnly
    );
    // A value use in any file still counts.
    assert_eq!(
        out_dir_decision_for_files(
            &[
                ("src/lib.rs", Some(readme)),
                (
                    "README.md",
                    Some(r#"const N: usize = env!("OUT_DIR").len();"#)
                ),
            ],
            &hasher
        ),
        EnvDepNormalizationDecision::KeptAbsoluteRuntimeUse
    );
}

#[test]
fn env_dep_policy_keeps_out_dir_absolute_when_a_source_cannot_be_scanned() {
    let include = r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#;
    assert_eq!(
        out_dir_decision_for_files(
            &[("src/lib.rs", Some(include)), ("src/missing.rs", None)],
            &FileHasher::new()
        ),
        EnvDepNormalizationDecision::KeptAbsoluteScanError
    );
}

#[test]
fn env_dep_policy_normalizes_out_dir_proven_include_locators() {
    let cases: &[(&str, &str)] = &[
        (
            "include concat",
            r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#,
        ),
        (
            "include in a local macro",
            r#"macro_rules! generated { ($f:literal) => { include!(concat!(env!("OUT_DIR"), "/", $f)); } }
generated!("generated.rs");"#,
        ),
        (
            "brace-delimited include",
            r#"include!{ concat!(env!("OUT_DIR"), "/generated.rs") }"#,
        ),
        (
            "lifetime and char literals around the include",
            r#"pub fn f<'a>(x: &'a str) -> char { let _ = x; 'x' }
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
pub fn g(_: &'static str) {}"#,
        ),
    ];
    let hasher = FileHasher::new();
    let kept: Vec<&str> = cases
        .iter()
        .filter(|(_, source)| {
            out_dir_decision_for(source, &hasher) != EnvDepNormalizationDecision::NormalizedPathOnly
        })
        .map(|(label, _)| *label)
        .collect();
    assert!(kept.is_empty(), "OUT_DIR must normalize for: {kept:?}");
}

#[test]
fn env_dep_policy_ignores_env_use_memo_rows_from_the_old_scanner() {
    // Before the scanner learned computed names, it recorded "no runtime
    // use" for this source. That row is keyed by content hash only, so an
    // upgraded wrapper would reuse it for the unchanged file unless the
    // memo is versioned.
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let source = concat!(
        r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));"#,
        r#" pub const S: &str = env!(concat!("OUT", "_DIR"));"#
    );
    let content_hash = blake3::hash(source.as_bytes()).to_hex().to_string();
    drop(FileHasher::persistent(&db));
    let conn = rusqlite::Connection::open(&db).unwrap();
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS source_env_runtime_uses (
                content_hash    TEXT NOT NULL,
                env_var         TEXT NOT NULL,
                has_runtime_use INTEGER NOT NULL,
                updated_at      TEXT NOT NULL DEFAULT (datetime('now')),
                PRIMARY KEY (content_hash, env_var)
            );",
    )
    .unwrap();
    conn.execute(
        "INSERT OR REPLACE INTO source_env_runtime_uses
             (content_hash, env_var, has_runtime_use) VALUES (?1, 'OUT_DIR', 0)",
        rusqlite::params![content_hash],
    )
    .unwrap();
    drop(conn);

    let hasher = FileHasher::persistent(&db);
    assert_eq!(
        out_dir_decision_for(source, &hasher),
        EnvDepNormalizationDecision::KeptAbsoluteRuntimeUse
    );
}

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

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

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

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

    let under = normalize_env_dep_value_in(
        "test_crate",
        "GEN_BUILD_CONSTS",
        &value,
        &source_files,
        &path_normalizer,
        Some(out_dir.as_os_str()),
    );
    // With OUT_DIR unset there is no anchor, so the same var must stay
    // absolute — proves the gate is the under-OUT_DIR test, not the var name.
    let no_anchor = normalize_env_dep_value(
        "test_crate",
        "GEN_BUILD_CONSTS",
        &value,
        &source_files,
        &path_normalizer,
    );

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

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

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

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

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

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

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

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

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

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

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

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

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

#[test]
fn env_dep_policy_refuses_manifest_dir_in_every_allowlist_form() {
    // A crate's own sources live under CARGO_MANIFEST_DIR, so the include
    // proof is trivially satisfied and only the refusal keeps #167 shut.
    let dir = tempfile::tempdir().unwrap();
    let workspace = dir.path().join("workspace");
    let manifest_dir = workspace.join("helper");
    let src = manifest_dir.join("src");
    std::fs::create_dir_all(&src).unwrap();
    let lib = src.join("lib.rs");
    std::fs::write(
        &lib,
        br#"include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/gen.rs"));"#,
    )
    .unwrap();

    let source_files = vec![lib];
    let manifest_dir_value = manifest_dir
        .canonicalize()
        .unwrap()
        .to_string_lossy()
        .to_string();
    for (entry, var) in [
        ("test_crate:CARGO_MANIFEST_DIR", "CARGO_MANIFEST_DIR"),
        ("CARGO_MANIFEST_DIR", "CARGO_MANIFEST_DIR"),
        // Windows resolves env names case-insensitively, so dep-info can
        // carry any spelling of the same variable.
        ("cargo_manifest_dir", "cargo_manifest_dir"),
    ] {
        let path_normalizer = PathNormalizer::from_env(Some(&workspace))
            .with_path_only_env_vars(vec![entry.to_string()]);
        let env_dep = normalize_env_dep_value(
            "test_crate",
            var,
            &manifest_dir_value,
            &source_files,
            &path_normalizer,
        );

        assert_eq!(
            env_dep.decision,
            EnvDepNormalizationDecision::KeptAbsoluteManifestDir,
            "CARGO_MANIFEST_DIR must stay absolute, listed as `{entry}`"
        );
        assert_eq!(env_dep.value, manifest_dir_value);
    }
}

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

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

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

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

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

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

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

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

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

    assert_ne!(key1, key2);
}

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

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

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

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

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

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

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

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

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

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

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

    assert!(parsed_coverage.has_coverage_instrumentation());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// --- FileHasher tests ---

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

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

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

    let hasher = FileHasher::persistent(&db);
    let content_hash = hasher.hash(&source).unwrap();
    let answers = [
        ("OUT_DIR", SourceEnvDepUse::RuntimeValue),
        ("GEN", SourceEnvDepUse::IncludeLocator),
        ("OTHER_DIR", SourceEnvDepUse::Unused),
    ];
    for (var, expected) in answers {
        assert_eq!(hasher.env_dep_use(&source, var).unwrap(), expected, "{var}");
    }
    drop(hasher);

    // A fresh wrapper can answer every decision from SQLite using the
    // content hash it already obtained while building the cache key. The
    // source is gone, so any attempted reread would fail this test.
    std::fs::remove_file(&source).unwrap();
    let fresh = FileHasher::persistent(&db);
    for (var, expected) in answers {
        assert_eq!(
            fresh
                .env_dep_use_for_hash(&source, var, &content_hash)
                .unwrap(),
            expected,
            "{var}"
        );
    }
}

#[test]
fn env_dep_use_memo_rescans_rows_from_other_scanner_versions() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let source = dir.path().join("lib.rs");
    std::fs::write(
        &source,
        br#"pub const S: &str = env!(concat!("OUT", "_DIR"));"#,
    )
    .unwrap();
    let content_hash = hash_file(&source).unwrap();

    let cache = FileHashCache::open(&db).unwrap();
    let unused = SourceEnvDepUse::Unused.memo_code();
    cache
        .put_source_env_dep_use(
            &content_hash,
            "OUT_DIR",
            SOURCE_ENV_DEP_SCANNER_VERSION - 1,
            unused,
        )
        .unwrap();
    cache
        .put_source_env_dep_use(&content_hash, "OTHER", SOURCE_ENV_DEP_SCANNER_VERSION, 7)
        .unwrap();
    drop(cache);

    let hasher = FileHasher::persistent(&db);
    assert_eq!(
        hasher
            .env_dep_use_for_hash(&source, "OUT_DIR", &content_hash)
            .unwrap(),
        SourceEnvDepUse::RuntimeValue,
        "an older scanner's answer must not be reused"
    );
    assert_eq!(
        hasher
            .env_dep_use_for_hash(&source, "OTHER", &content_hash)
            .unwrap(),
        SourceEnvDepUse::RuntimeValue,
        "an unknown stored code must be rescanned"
    );
    drop(hasher);

    let cache = FileHashCache::open(&db).unwrap();
    for var in ["OUT_DIR", "OTHER"] {
        assert_eq!(
            cache
                .get_source_env_dep_use(&content_hash, var, SOURCE_ENV_DEP_SCANNER_VERSION)
                .unwrap(),
            Some(SourceEnvDepUse::RuntimeValue.memo_code()),
            "the rescan replaces the stale row for {var}"
        );
    }
}

#[test]
fn env_dep_use_memo_codes_round_trip() {
    for answer in [
        SourceEnvDepUse::Unused,
        SourceEnvDepUse::IncludeLocator,
        SourceEnvDepUse::RuntimeValue,
    ] {
        assert_eq!(
            SourceEnvDepUse::from_memo_code(answer.memo_code()),
            Some(answer)
        );
    }
    assert_eq!(
        [
            SourceEnvDepUse::Unused.memo_code(),
            SourceEnvDepUse::IncludeLocator.memo_code(),
            SourceEnvDepUse::RuntimeValue.memo_code(),
        ],
        [0, 1, 2]
    );
    assert_eq!(SourceEnvDepUse::from_memo_code(3), None);
    assert_eq!(SourceEnvDepUse::from_memo_code(-1), None);
}

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

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

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

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

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

/// The mapped hash is memoised by raw content and map set: a second unit
/// that reads the same bytes, at any path, takes the memo instead of
/// reading and rewriting the file; another map set or an empty key does
/// not; a memo error or a missing store still computes.
#[test]
fn mapped_hashes_are_memoised_by_content_and_map_set() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let header = dir.path().join("header.h");
    let copy = dir.path().join("copy.h");
    let other = dir.path().join("other.h");
    // Above MIN_PERSISTED_HASH_BYTES so the raw hash itself is memoised.
    let body = "#define VALUE 1\n".repeat(64);
    std::fs::write(&header, &body).unwrap();
    std::fs::write(&copy, &body).unwrap();
    std::fs::write(&other, format!("{body}#define OTHER 2\n")).unwrap();
    let reads = std::cell::Cell::new(0usize);
    let counting = |path: &Path| -> Option<CcContentHashes> {
        reads.set(reads.get() + 1);
        let bytes = std::fs::read(path).ok()?;
        Some(content_hashes(
            &bytes,
            &[b"mapped:".as_slice(), &bytes].concat(),
        ))
    };
    let name = |path: &Path| (path.to_string_lossy().into_owned(), path.to_path_buf());

    let hasher = FileHasher::persistent(&db);
    let first = hasher
        .cc_preprocess_fingerprints(&[name(&header)], "maps-a", &counting)
        .unwrap();
    assert_eq!(reads.get(), 1);
    let second = hasher
        .cc_preprocess_fingerprints(&[name(&copy), name(&other)], "maps-a", &counting)
        .unwrap();
    assert_eq!(
        reads.get(),
        2,
        "the copy took the memo, the other file did not"
    );
    let by_name: std::collections::HashMap<_, _> =
        second.iter().map(|i| (i.name.as_str(), i)).collect();
    assert_eq!(by_name[name(&copy).0.as_str()].mapped, first[0].mapped);
    assert_ne!(by_name[name(&other).0.as_str()].mapped, first[0].mapped);

    // A fresh process (new hasher on the same index) still has the memo.
    let later = FileHasher::persistent(&db);
    later
        .cc_preprocess_fingerprints(&[name(&header)], "maps-a", &counting)
        .unwrap();
    assert_eq!(reads.get(), 2, "the memo survives the process");
    // Another map set rewrites bytes differently and computes again.
    later
        .cc_preprocess_fingerprints(&[name(&header)], "maps-b", &counting)
        .unwrap();
    assert_eq!(reads.get(), 3);
    // An empty key never memoises.
    later
        .cc_preprocess_fingerprints(&[name(&header)], "", &counting)
        .unwrap();
    later
        .cc_preprocess_fingerprints(&[name(&header)], "", &counting)
        .unwrap();
    assert_eq!(reads.get(), 5);
    // Without a store, every unit computes.
    let bare = FileHasher::new();
    bare.cc_preprocess_fingerprints(&[name(&header)], "maps-a", &counting)
        .unwrap();
    assert_eq!(reads.get(), 6);
}

/// The assembler scan runs once per distinct content and its verdict is
/// memoised across processes; an unreadable file is skipped and not
/// recorded.
#[test]
fn assembler_scans_are_memoised_by_content() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let clean = dir.path().join("clean.h");
    let twin = dir.path().join("twin.h");
    let pasted = dir.path().join("pasted.h");
    let body = "#define VALUE 1\n".repeat(64);
    std::fs::write(&clean, &body).unwrap();
    std::fs::write(&twin, &body).unwrap();
    std::fs::write(
        &pasted,
        format!("{body}__asm__(\".incbin \\\"blob\\\"\");\n"),
    )
    .unwrap();
    let scans = std::cell::Cell::new(0usize);
    let scan = |path: &Path| -> Option<(String, Option<&'static str>)> {
        scans.set(scans.get() + 1);
        let text = std::fs::read_to_string(path).ok()?;
        Some((
            blake3::hash(text.as_bytes()).to_hex().to_string(),
            text.contains(".incbin").then_some(".incbin"),
        ))
    };
    let name = |path: &Path| (path.to_string_lossy().into_owned(), path.to_path_buf());
    let hasher = FileHasher::persistent(&db);
    let inputs = hasher
        .cc_preprocess_fingerprints(&[name(&clean), name(&twin)], "", &no_mapping)
        .unwrap();
    assert_eq!(hasher.cc_inputs_hide_assembler_input(&inputs, &scan), None);
    assert_eq!(scans.get(), 1, "twins share one scan");
    let later = FileHasher::persistent(&db);
    let inputs = later
        .cc_preprocess_fingerprints(&[name(&clean), name(&pasted)], "", &no_mapping)
        .unwrap();
    assert_eq!(
        later
            .cc_inputs_hide_assembler_input(&inputs, &scan)
            .as_deref(),
        Some(".incbin")
    );
    assert_eq!(
        scans.get(),
        2,
        "the clean verdict survived the process; only the new file was scanned"
    );
    assert_eq!(
        later
            .cc_inputs_hide_assembler_input(&inputs, &scan)
            .as_deref(),
        Some(".incbin"),
        "the construct verdict is memoised too"
    );
    assert_eq!(scans.get(), 2);
    // An unreadable file is skipped and left for the next run.
    let mut gone = inputs.clone();
    gone[0].fingerprint.path = dir.path().join("absent.h").to_string_lossy().into_owned();
    gone[0].content = "c".repeat(64);
    assert_eq!(
        later.cc_inputs_hide_assembler_input(&gone[..1], &scan),
        None
    );
    assert_eq!(
        later.cc_inputs_hide_assembler_input(&gone[..1], &scan),
        None
    );
    assert_eq!(
        scans.get(),
        4,
        "an unreadable file is scanned again next time"
    );
}

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

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

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

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

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

/// Tests that do not exercise prefix maps hash contents as they are.
fn no_mapping(path: &Path) -> Option<CcContentHashes> {
    let bytes = std::fs::read(path).ok()?;
    Some(content_hashes(&bytes, &bytes))
}

/// What `mapped_content` returns for one read of `bytes` that the maps
/// rewrote to `mapped`.
fn content_hashes(bytes: &[u8], mapped: &[u8]) -> CcContentHashes {
    CcContentHashes {
        raw: blake3::hash(bytes).to_hex().to_string(),
        mapped: blake3::hash(mapped).to_hex().to_string(),
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

    // Rewrite identical bytes with different metadata. Filesystems can
    // reuse the inode and timestamp on an immediate rewrite, so set the
    // mtime explicitly to exercise content-based memo validation.
    for (path, bytes) in [(&source, source_bytes), (&header, header_bytes)] {
        std::fs::remove_file(path).unwrap();
        std::fs::write(path, bytes).unwrap();
        filetime::set_file_mtime(path, filetime::FileTime::from_unix_time(1, 0)).unwrap();
    }
    let rewritten = FileFingerprint::from_path(&header).unwrap();
    assert_ne!(
        rewritten, inputs[0].fingerprint,
        "the rewrite must actually change the metadata this test is about"
    );

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

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

/// A stamp taken less than the settle window after its file changed can
/// survive a second write in the same timestamp tick. The memo does not
/// record it, so a lookup reads that input instead of trusting metadata;
/// the same stamp observed once settled is trusted.
#[test]
fn a_stamp_observed_before_it_settled_never_answers_a_lookup() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let digest = "e".repeat(64);
    let record = |file: &str, observed_later_ns: i64| {
        let path = dir.path().join(file);
        std::fs::write(&path, "#define H 1\n").unwrap();
        let hasher = FileHasher::persistent(&db);
        let mut inputs = hasher
            .cc_preprocess_fingerprints(
                &[(path.to_string_lossy().into_owned(), path.clone())],
                "",
                &no_mapping,
            )
            .unwrap();
        inputs[0].observed_ns += observed_later_ns;
        hasher.cc_preprocess_memo_record_if_unchanged(file, &digest, &inputs, &no_mapping);
        let recorded = hasher
            .cache
            .as_ref()
            .unwrap()
            .get_cc_preprocess_memo(file)
            .unwrap()
            .expect("the memo is recorded either way");
        (inputs.remove(0), recorded.inputs[0].fingerprint.clone())
    };
    let reads_on_lookup = |file: &str| {
        let hasher = FileHasher::persistent(&db);
        let hit = hasher
            .cc_preprocess_memo_lookup(file, no_remap, &no_mapping)
            .map(|(hash, _)| hash);
        assert_eq!(hit.as_deref(), Some(digest.as_str()), "{file}");
        hasher.stats().cache_misses
    };

    let (fresh, stored) = record("fresh.h", 0);
    assert!(!fresh.stamp_settled(), "the file was just written");
    assert_ne!(stored, fresh.fingerprint, "the stamp is not recorded");
    assert_eq!(reads_on_lookup("fresh.h"), 1, "the content is compared");

    let (settled, stored) = record("settled.h", HASH_SETTLE_NS);
    assert!(settled.stamp_settled());
    assert_eq!(stored, settled.fingerprint);
    assert_eq!(
        reads_on_lookup("settled.h"),
        0,
        "matching metadata needs no read"
    );
}

/// A memo hit proves an input by its settled stamp without hashing it. A
/// key-first compile's check still covers that input: it reads it again
/// when the invocation started before the stamp settled, and flags it once
/// it is rewritten.
#[test]
fn an_input_a_memo_hit_proved_by_stamp_is_rechecked() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let header = dir.path().join("h.h");
    std::fs::write(&header, "#define H 1\n").unwrap();
    let names = [(header.to_string_lossy().into_owned(), header.clone())];
    let recorder = FileHasher::persistent(&db);
    let mut inputs = recorder
        .cc_preprocess_fingerprints(&names, "", &no_mapping)
        .unwrap();
    inputs[0].observed_ns += HASH_SETTLE_NS;
    recorder.cc_preprocess_memo_record_if_unchanged(
        "memo-key",
        &"f".repeat(64),
        &inputs,
        &no_mapping,
    );
    let mut hasher = FileHasher::persistent(&db);
    // After the write, past the window that counts it as one made during
    // the build, but before its stamp settled: a peer recorded the memo
    // while this invocation was still keying.
    hasher.arm_too_new_guard(past_the_write(&inputs[0].fingerprint), 0);
    assert!(
        hasher
            .cc_preprocess_memo_lookup("memo-key", no_remap, &no_mapping)
            .is_some()
    );
    assert_eq!(hasher.stats().cache_misses, 0, "proved by its stamp");
    assert!(
        !hasher.inputs_changed_since_keyed(),
        "read again, it holds the bytes the memo proved"
    );
    std::fs::write(&header, "#define H 22\n").unwrap();
    assert!(hasher.inputs_changed_since_keyed());
}

/// A stamp that had not settled when the invocation started can survive a
/// second write in the same timestamp tick, so a key-first check reads
/// that input again instead of trusting its stat. A row memoised for the
/// stamp with other bytes' hash stands in for such a write here. A settled
/// stamp is trusted without a read.
///
/// The modification time is an hour ahead of the clock, so neither start
/// counts the file as written during the build, whatever grain the
/// filesystem keeps its times in. A file written just before the start
/// would not do where times are whole seconds: its write window there is
/// longer than the settle window, so no start leaves it outside the one and
/// inside the other.
#[test]
fn a_key_first_check_reads_again_only_an_input_fresh_at_the_start() {
    let dir = tempfile::tempdir().unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let header = dir.path().join("big.h");
    std::fs::write(&header, "x".repeat(MIN_PERSISTED_HASH_BYTES as usize)).unwrap();
    let ahead = std::time::SystemTime::now() + std::time::Duration::from_secs(3600);
    filetime::set_file_mtime(&header, filetime::FileTime::from_system_time(ahead)).unwrap();
    let stamp = FileFingerprint::from_path(&header).unwrap();
    let stale = "0".repeat(64);
    FileHashCache::Borrowed(&db).put(&stamp, &stale).unwrap();
    let checked = |start_ns: i64| {
        let mut hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        hasher.arm_too_new_guard(start_ns, 0);
        assert_eq!(hasher.hash(&header).unwrap(), stale, "the key's hash");
        assert!(
            !hasher.too_new.saw_write_since_start.get(),
            "not written during the build"
        );
        hasher.inputs_changed_since_keyed()
    };

    // Past the change time's own window: only the modification time is
    // fresh at this start.
    let fresh = stamp.ctime_ns + stamp_window_ns(stamp.ctime_ns) + 1;
    assert!(checked(fresh), "a fresh input is read again");
    assert!(
        !checked(stamp.mtime_ns + HASH_SETTLE_NS),
        "a settled stamp is trusted without a read"
    );
}

/// A write between the preprocessor's read and the key's own leaves a
/// stat after the compile matching what the key saw; only its stamp, from
/// after the invocation started, shows it. A stamp ahead of the clock when
/// the key read the file was not made during the build by this host's
/// clock, so it refuses nothing while the file holds the bytes the key
/// hashed.
#[test]
fn a_key_first_check_refuses_a_stamp_from_the_build_but_not_one_ahead_of_the_clock() {
    let dir = tempfile::tempdir().unwrap();
    let header = dir.path().join("h.h");
    std::fs::write(&header, "#define H 1\n").unwrap();
    let checked = |start_ns: i64| {
        let mut hasher = FileHasher::new();
        hasher.arm_too_new_guard(start_ns, 0);
        hasher.hash(&header).unwrap();
        (hasher.too_new(), hasher.inputs_changed_since_keyed())
    };

    let written = FileFingerprint::from_path(&header).unwrap();
    assert_eq!(
        checked(written.mtime_ns.min(written.ctime_ns)),
        (true, true),
        "written after the invocation started"
    );
    // File clocks can trail the start, so a stamp just below it may be
    // from a write made after it.
    assert_eq!(
        checked(written.mtime_ns.max(written.ctime_ns) + 1),
        (true, true),
        "stamped just before the invocation started"
    );

    let ahead = std::time::SystemTime::now() + std::time::Duration::from_secs(3600);
    filetime::set_file_mtime(&header, filetime::FileTime::from_system_time(ahead)).unwrap();
    let skewed = FileFingerprint::from_path(&header).unwrap();
    // Changed before the invocation started, modified an hour from now.
    let start = skewed.ctime_ns + stamp_window_ns(skewed.ctime_ns) + 1;
    assert_eq!(checked(start), (true, false));
}

/// The earliest start a write with `stamp` counts as made before
/// ([`stamp_written_since`]).
fn past_the_write(stamp: &FileFingerprint) -> i64 {
    [stamp.mtime_ns, stamp.ctime_ns]
        .into_iter()
        .map(|stamp| stamp + stamp_window_ns(stamp))
        .max()
        .unwrap()
        + 1
}

/// The mapped hash comes from a second read of the file. A save landing
/// between the content hash and that read must not pair the old content
/// with the new bytes' mapping: the capture fails and nothing is learned.
#[test]
fn a_mapped_hash_of_other_bytes_is_never_learned() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let header = dir.path().join("h.h");
    std::fs::write(&header, "#define H 1\n").unwrap();
    let names = [(header.to_string_lossy().into_owned(), header.clone())];
    let old = blake3::hash(b"#define H 1\n").to_hex().to_string();
    let new = blake3::hash(b"#define H 22\n").to_hex().to_string();
    let saved_in_between = |path: &Path| {
        std::fs::write(path, "#define H 22\n").unwrap();
        no_mapping(path)
    };

    let hasher = FileHasher::persistent(&db);
    assert_eq!(
        hasher.cc_preprocess_fingerprints(&names, "maps", &saved_in_between),
        None
    );
    let learned = |hasher: &FileHasher<'_>| {
        hasher
            .cache
            .as_ref()
            .unwrap()
            .get_cc_mapped_hashes("maps", &[&old, &new])
            .unwrap()
    };
    assert!(learned(&hasher).is_empty(), "{:?}", learned(&hasher));

    // One read that matches the content hash is learned.
    let later = FileHasher::persistent(&db);
    let inputs = later
        .cc_preprocess_fingerprints(&names, "maps", &no_mapping)
        .unwrap();
    assert_eq!(inputs[0].content, new);
    assert_eq!(
        learned(&later),
        HashMap::from([(new.clone(), inputs[0].mapped.clone())])
    );
}

/// The assembler scan reads the file again too. A verdict on bytes saved
/// since the fingerprint is not recorded, and it does not clear the inputs.
#[test]
fn an_assembler_verdict_on_other_bytes_is_never_learned() {
    let dir = tempfile::tempdir().unwrap();
    let db = dir.path().join("idx.sqlite");
    let header = dir.path().join("h.h");
    std::fs::write(&header, "#define H 1\n").unwrap();
    let names = [(header.to_string_lossy().into_owned(), header.clone())];
    let hasher = FileHasher::persistent(&db);
    let inputs = hasher
        .cc_preprocess_fingerprints(&names, "", &no_mapping)
        .unwrap();
    let scanned_after_a_save = |path: &Path| {
        std::fs::write(path, "#define H 22\n").unwrap();
        let bytes = std::fs::read(path).ok()?;
        Some((blake3::hash(&bytes).to_hex().to_string(), None))
    };

    assert_eq!(
        hasher
            .cc_inputs_hide_assembler_input(&inputs, &scanned_after_a_save)
            .as_deref(),
        Some(CC_INPUT_CHANGED_WHILE_SCANNED)
    );
    assert!(
        hasher
            .cache
            .as_ref()
            .unwrap()
            .get_cc_asm_scans(&[&inputs[0].content])
            .unwrap()
            .is_empty()
    );
}

/// A key taken before the compile hashed its inputs. One rewritten or
/// removed before the check is flagged; untouched ones are not.
#[test]
fn a_key_first_check_flags_an_input_written_since_it_was_hashed() {
    let dir = tempfile::tempdir().unwrap();
    let kept = dir.path().join("kept.h");
    let rewritten = dir.path().join("rewritten.h");
    let removed = dir.path().join("removed.h");
    for path in [&kept, &rewritten, &removed] {
        std::fs::write(path, "#define H 1\n").unwrap();
    }
    let checked = |paths: &[&PathBuf], after_hashing: &dyn Fn()| {
        let mut hasher = FileHasher::new();
        // Armed, but no stamp is new enough to trip it by the clock.
        hasher.arm_too_new_guard(i64::MAX, 0);
        for path in paths {
            hasher.hash(path).unwrap();
        }
        after_hashing();
        hasher.inputs_changed_since_keyed()
    };

    assert!(!checked(&[&kept, &rewritten], &|| {}));
    assert!(checked(&[&kept, &rewritten], &|| {
        std::fs::write(&rewritten, "#define H 22\n").unwrap();
    }));
    assert!(checked(&[&kept, &removed], &|| {
        std::fs::remove_file(&removed).unwrap();
    }));
}

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

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

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

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

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

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

/// A write after the start can carry a stamp below it, so the guard counts
/// from one stamp window early, and the margin moves that start earlier
/// still.
#[test]
fn the_too_new_guard_allows_for_coarse_file_clocks_and_keeps_its_margin() {
    // Off any 10 ms boundary, so every stamp below gets the fine window.
    let start = 1_700_000_000_250_000_007_i64;
    let flagged = |margin_ns: i64, stamp_ns: i64| {
        let mut hasher = FileHasher::new();
        hasher.arm_too_new_guard(start, margin_ns);
        hasher.note_too_new(&FileFingerprint {
            path: "/src/lib.rs".to_string(),
            size: 1,
            mtime_ns: stamp_ns,
            ctime_ns: stamp_ns,
            inode: 1,
        });
        hasher.too_new()
    };
    let edge = start - FINE_STAMP_WINDOW_NS;
    assert!(flagged(0, edge));
    assert!(!flagged(0, edge - 1));
    assert!(
        flagged(0, 1_699_999_999_000_000_000),
        "a whole-second stamp 1.25 s before the start"
    );
    let margin = 5_000_000_000;
    assert!(flagged(margin, edge - margin));
    assert!(!flagged(margin, edge - margin - 1));
}

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

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

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

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

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

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

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

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

/// A file rewritten after the hasher's stat and before its read may have
/// been read as either version. With the guard armed, every read path stats
/// the file again: the input counts as too new, the later fingerprint is the
/// one reported, so a barrier sees the write, and the earlier one stays among
/// the guarded inputs, so no excuse accepts the input. Nothing is memoised.
#[test]
fn a_file_rewritten_between_the_stat_and_the_read_counts_as_written() {
    let small = 16;
    let large = usize::try_from(MIN_PERSISTED_HASH_BYTES).unwrap() + 16;
    // (store-backed, header capture, size)
    for (store_backed, header, size) in [
        (false, false, small),
        (true, false, small),
        (true, false, large),
        (true, true, small),
    ] {
        let case = format!("store_backed={store_backed} header={header} size={size}");
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("input.h");
        std::fs::write(&file, vec![b'a'; size]).unwrap();
        let first = FileFingerprint::from_path(&file).unwrap();
        // Past every window of the first write's stamps.
        let start = [first.mtime_ns, first.ctime_ns]
            .into_iter()
            .map(|stamp| stamp + stamp_window_ns(stamp))
            .max()
            .unwrap()
            + 1;
        let db = rusqlite::Connection::open_in_memory().unwrap();
        ensure_file_hash_cache_schema(&db).unwrap();
        let mut hasher = if store_backed {
            FileHasher::from_cache(FileHashCache::Borrowed(&db))
        } else {
            FileHasher::new()
        };
        hasher.arm_too_new_guard(start, 0);
        set_before_read(Some(Box::new(move |path: &Path| {
            while wall_clock_ns() <= start + 30_000_000 {
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            std::fs::write(path, vec![b'b'; size + 1]).unwrap();
        })));
        let hash = if header {
            let headers = vec![("input.h".to_string(), file.clone())];
            hasher
                .cc_preprocess_fingerprints(&headers, "maps", &no_mapping)
                .map(|inputs| inputs[0].content.clone())
        } else {
            hasher.hash(&file).ok()
        };
        set_before_read(None);

        let second = FileFingerprint::from_path(&file).unwrap();
        assert_eq!(hash, Some(hash_file(&file).unwrap()), "{case}");
        assert!(hasher.too_new(), "{case}");
        assert!(!stamp_written_since(&first, start), "{case}");
        assert!(stamp_written_since(&second, start), "{case}");
        let guarded = hasher.take_guarded_inputs();
        let kept: Vec<_> = guarded.iter().map(|input| &input.fingerprint).collect();
        assert!(kept.contains(&&second), "{case}: {guarded:?}");
        assert!(kept.contains(&&first), "{case}: {guarded:?}");
        assert!(
            !FileHasher::guarded_inputs_unchanged_since_hash(&guarded),
            "{case}"
        );
        assert!(hasher.pending_memo.borrow().is_empty(), "{case}");
        hasher.flush_memo_as_if_settled();
        let memo = FileHashCache::Borrowed(&db);
        assert_eq!(memo.get(&first).unwrap(), None, "{case}");
        assert_eq!(memo.get(&second).unwrap(), None, "{case}");
    }
}

/// A file gone by the second stat counts as too new; the stamp from before
/// the read is reported and fails any later check.
#[test]
fn a_file_removed_after_its_read_counts_as_too_new() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("input.rs");
    std::fs::write(&file, b"pub fn x() {}").unwrap();
    let mut hasher = FileHasher::new();
    hasher.arm_too_new_guard(1, 0);
    let before = ObservedFingerprint::from_path(&file).unwrap();
    assert!(!hasher.too_new());
    std::fs::remove_file(&file).unwrap();
    let (reported, unchanged) = hasher.restat_after_read(&file, before.clone(), true);
    assert!(!unchanged);
    assert!(hasher.too_new());
    assert_eq!(reported, before);
    assert!(!FileHasher::guarded_inputs_unchanged_since_hash(
        std::slice::from_ref(&reported)
    ));
}

/// A file that is no key input, such as one a tree guard reads, is stat'ed
/// again after its read like a key input, but a write or removal between the
/// two stats only costs its memo row: the too-new guard stays quiet and no
/// guarded input is kept.
#[test]
fn an_unkeyed_file_moved_while_it_is_read_trips_nothing_and_leaves_no_row() {
    let small = 16;
    let large = usize::try_from(MIN_PERSISTED_HASH_BYTES).unwrap() + 16;
    for size in [small, large] {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("asset.txt");
        std::fs::write(&file, vec![b'a'; size]).unwrap();
        let first = FileFingerprint::from_path(&file).unwrap();
        let db = rusqlite::Connection::open_in_memory().unwrap();
        ensure_file_hash_cache_schema(&db).unwrap();
        let mut hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        hasher.arm_too_new_guard(1, 0);
        set_before_read(Some(Box::new(move |path: &Path| {
            std::fs::write(path, vec![b'b'; size + 1]).unwrap();
        })));
        let hash = hasher.hash_unkeyed(&file).unwrap();
        set_before_read(None);

        assert_eq!(hash, hash_file(&file).unwrap(), "size={size}");
        assert!(!hasher.too_new(), "size={size}");
        assert!(hasher.take_guarded_inputs().is_empty(), "size={size}");
        assert!(hasher.pending_memo.borrow().is_empty(), "size={size}");
        hasher.flush_memo_as_if_settled();
        let second = FileFingerprint::from_path(&file).unwrap();
        let memo = FileHashCache::Borrowed(&db);
        assert_eq!(memo.get(&first).unwrap(), None, "size={size}");
        assert_eq!(memo.get(&second).unwrap(), None, "size={size}");
    }

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("asset.txt");
    std::fs::write(&file, b"a").unwrap();
    let mut hasher = FileHasher::new();
    hasher.arm_too_new_guard(1, 0);
    let before = ObservedFingerprint::from_path(&file).unwrap();
    std::fs::remove_file(&file).unwrap();
    assert_eq!(
        hasher.restat_after_read(&file, before.clone(), false),
        (before, false)
    );
    assert!(!hasher.too_new());
    assert!(hasher.take_guarded_inputs().is_empty());
}

/// Each guarded input keeps the wall clock read before its stat, so a later
/// check can ask whether its stamp had settled by then.
#[test]
fn guarded_inputs_keep_when_they_were_observed() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("input.rs");
    std::fs::write(&file, b"pub fn x() {}").unwrap();
    let db = dir.path().join("index.db");
    for mut hasher in [FileHasher::new(), FileHasher::persistent(&db)] {
        hasher.arm_too_new_guard(1, 0);
        let before = wall_clock_ns();
        hasher.hash(&file).unwrap();
        let after = wall_clock_ns();
        let [input] = hasher.take_guarded_inputs().try_into().unwrap();
        assert!((before..=after).contains(&input.observed_ns), "{input:?}");
        assert_eq!(
            input.fingerprint,
            FileFingerprint::from_path(&file).unwrap()
        );
        assert!(!input.settled(), "written a moment ago");
    }
}

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

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

/// A root past the entry budget withholds the digest without reading a
/// file, and is remembered so the next unit does not walk it; a stale memo
/// counts the tree again.
#[test]
fn an_oversized_tree_is_counted_not_hashed_and_remembered() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let tree = dir.path().join("tree");
    std::fs::create_dir_all(tree.join("sub")).unwrap();
    for i in 0..4 {
        std::fs::write(tree.join("sub").join(format!("f{i}")), b"x").unwrap();
    }
    // Five entries: `sub` and its four files.
    let roots = || vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
    let now = std::time::SystemTime::now();
    let hasher = FileHasher::new();

    assert!(tree_digest_memoised(roots(), &hasher, 4, &memo, now).is_none());
    assert_eq!(hasher.stats().bytes_hashed, 0, "no file is read");
    assert!(oversized_tree_marker(&memo, &tree, 4).exists());
    assert!(
        tree_digest_memoised(roots(), &hasher, 5, &memo, now).is_some(),
        "the marker is per budget"
    );

    std::fs::remove_file(tree.join("sub").join("f3")).unwrap();
    assert!(
        tree_digest_memoised(roots(), &hasher, 4, &memo, now).is_none(),
        "remembered while fresh"
    );
    let half_an_hour = now + std::time::Duration::from_secs(30 * 60);
    assert!(
        tree_digest_memoised(roots(), &hasher, 4, &memo, half_an_hour).is_none(),
        "still remembered half an hour on"
    );
    let marked = std::fs::metadata(oversized_tree_marker(&memo, &tree, 4))
        .and_then(|metadata| metadata.modified())
        .unwrap();
    assert!(
        tree_digest_memoised(roots(), &hasher, 4, &memo, marked + OVERSIZED_TREE_TTL).is_some(),
        "a marker exactly its lifetime old has expired"
    );
    let later = now + OVERSIZED_TREE_TTL + std::time::Duration::from_secs(1);
    assert_eq!(
        tree_digest_memoised(roots(), &hasher, 4, &memo, later),
        tree_digest_memoised(roots(), &hasher, 5, &memo, later),
        "a stale memo counts the tree again, and the digest does not depend on the budget"
    );
}

/// Roots that each fit but together run past the budget withhold the digest
/// without marking either, and are remembered together, so the next unit
/// does not walk them again. An excluded directory does not count.
#[test]
fn tree_budgets_add_up_across_roots_and_skip_exclusions() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let (first, second) = (dir.path().join("a"), dir.path().join("b"));
    for root in [&first, &second] {
        std::fs::create_dir_all(root).unwrap();
        for i in 0..3 {
            std::fs::write(root.join(format!("f{i}")), b"x").unwrap();
        }
    }
    std::fs::create_dir_all(first.join("target")).unwrap();
    for i in 0..10 {
        std::fs::write(first.join("target").join(format!("t{i}")), b"x").unwrap();
    }
    let hasher = FileHasher::new();
    let now = std::time::SystemTime::now();
    let skipped: &[&str] = &["target"];
    let roots = || {
        vec![
            TreeRoot::new(first.clone(), b"workspace", skipped),
            TreeRoot::new(second.clone(), b"out_dir", &[]),
        ]
    };
    assert!(tree_digest_memoised(roots(), &hasher, 5, &memo, now).is_none());
    assert!(!oversized_tree_marker(&memo, &first, 5).exists());
    assert!(!oversized_tree_marker(&memo, &second, 5).exists());
    assert!(tree_digest_memoised(roots(), &hasher, 6, &memo, now).is_some());

    std::fs::remove_file(second.join("f2")).unwrap();
    assert!(
        tree_digest_memoised(roots(), &hasher, 5, &memo, now).is_none(),
        "remembered together while fresh"
    );
    let first_alone = vec![TreeRoot::new(first.clone(), b"workspace", skipped)];
    assert!(
        tree_digest_memoised(first_alone, &hasher, 5, &memo, now).is_some(),
        "the first root alone is not remembered"
    );
    let later = now + OVERSIZED_TREE_TTL + std::time::Duration::from_secs(1);
    assert!(
        tree_digest_memoised(roots(), &hasher, 5, &memo, later).is_some(),
        "a stale marker counts the roots again"
    );
}

/// Kache's cache and runtime directories inside a guarded tree, as GitLab CI
/// requires of cached paths, are left out: the build writes to them while a
/// unit compiles, and a large store would run the walk past its budget. A
/// directory given through another spelling is found by its resolved path.
#[test]
fn kaches_own_directories_are_left_out_of_a_guarded_tree() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let root = dir.path().join("w");
    let cache = root.join(".cache/kache");
    let runtime = root.join("run");
    write_file(&root.join("kt/src/lib.rs"), "");
    write_file(&cache.join("index.db"), "a");
    write_file(&runtime.join("events.jsonl"), "");
    let roots = || vec![TreeRoot::new(root.clone(), b"workspace", &[])];
    let now = std::time::SystemTime::now();
    let guard_with = |hasher: &FileHasher<'_>| {
        tree_guard_of(hasher, || {
            // `kt`, `kt/src`, `kt/src/lib.rs` and `.cache`.
            tree_digest_memoised(roots(), hasher, 4, &memo, now)
        })
    };
    let hasher = FileHasher::new().with_own_dirs([cache.clone(), runtime.clone()]);
    let taken = guard_with(&hasher).expect("the cache does not count toward the budget");
    write_file(&cache.join("index.db"), "ab");
    write_file(&cache.join("blobs/x"), "x");
    write_file(&runtime.join("events.jsonl"), "{}\n");
    assert!(taken.held(), "the store and the event log moved");
    assert_eq!(
        guard_with(&hasher).map(|guard| guard.digest),
        Some(taken.digest.clone())
    );
    #[cfg(unix)]
    {
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&root, &link).unwrap();
        let linked = FileHasher::new().with_own_dirs(crate::build_script_inputs::excluded_roots(
            None,
            [
                link.join(".cache/kache").as_path(),
                link.join("run").as_path(),
            ],
        ));
        assert_eq!(
            guard_with(&linked).map(|guard| guard.digest),
            Some(taken.digest.clone()),
            "the directories given through a link"
        );
    }
    write_file(&root.join("kt/src/lib.rs"), "pub fn a() {}\n");
    assert!(!taken.held(), "the workspace itself still counts");
    assert!(
        guard_with(&FileHasher::new()).is_none(),
        "counted, the cache runs the walk past its budget"
    );
}

/// A settled tree's digest is memoised under its stamp, and the next unit
/// reads no file. A tree written just now is not memoised, a changed tree is
/// read again, and a memo that does not hold a digest is ignored.
#[test]
fn a_settled_tree_digest_is_memoised_under_its_stamp() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let tree = dir.path().join("tree");
    write_file(&tree.join("src/lib.rs"), "pub fn a() {}\n");
    #[cfg(unix)]
    std::os::unix::fs::symlink("src/lib.rs", tree.join("lib.rs")).unwrap();
    let roots = || vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    // The digest, and how many files were read for it.
    let digest_at = |now: std::time::SystemTime| {
        let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        let digest = tree_digest_memoised(roots(), &hasher, 10, &memo, now);
        (digest, hasher.stats().cache_misses)
    };
    let now = std::time::SystemTime::now();
    let settled = now + crate::tree_stamp::TreeStamp::SETTLE;

    let (fresh, read) = digest_at(now);
    let fresh = fresh.expect("a symlink counts by its text");
    assert_eq!(read, 1);
    let file = tree_digest_memo(&memo, &roots()[0]);
    assert!(!file.exists(), "a tree written just now is not memoised");
    assert_eq!(digest_at(settled), (Some(fresh.clone()), 1));
    assert_eq!(
        digest_at(settled),
        (Some(fresh.clone()), 0),
        "the memo answers"
    );

    let recorded = std::fs::read_to_string(&file).unwrap();
    let (stamp, _) = recorded.split_once('\n').unwrap();
    for (digest, why) in [("g".repeat(64), "not hex"), ("a".repeat(63), "too short")] {
        std::fs::write(&file, format!("{stamp}\n{digest}")).unwrap();
        assert_eq!(digest_at(settled), (Some(fresh.clone()), 1), "{why}");
    }
    let trusted = "a".repeat(64);
    std::fs::write(&file, format!("{stamp}\n{trusted}")).unwrap();
    assert_eq!(
        digest_at(settled),
        (Some(trusted), 0),
        "trusted under its stamp"
    );

    write_file(&tree.join("src/new.rs"), "");
    let (changed, read) = digest_at(settled + crate::tree_stamp::TreeStamp::SETTLE);
    assert!(changed.is_some_and(|changed| changed != fresh));
    assert_eq!(read, 2);
}

/// Each root is memoised alone. Once the workspace is, a unit with an
/// `OUT_DIR` reads only that `OUT_DIR`, and an `OUT_DIR` written again in a new
/// target directory is read again alone. The guard walks both roots.
#[test]
fn each_root_of_a_tree_digest_is_memoised_alone() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let (workspace, out) = (dir.path().join("w"), dir.path().join("out"));
    write_file(&workspace.join("Cargo.toml"), "[workspace]\n");
    write_file(&workspace.join("kt/src/lib.rs"), "pub fn a() {}\n");
    write_file(&out.join("gen.rs"), "// gen\n");
    // Recreating a file can reuse its inode and coarse times. Give the two
    // identical files distinct mtimes so the OUT_DIR entry stamp must move.
    filetime::set_file_mtime(
        out.join("gen.rs"),
        filetime::FileTime::from_unix_time(1_000_000_000, 0),
    )
    .unwrap();
    let roots = |with_out: bool| {
        let mut roots = vec![TreeRoot::new(workspace.clone(), b"workspace", &[])];
        if with_out {
            roots.push(TreeRoot::new(out.clone(), b"out_dir", &[]));
        }
        roots
    };
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    // The guard, and how many files were read for it.
    let guard = |with_out| {
        let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        let settled = std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE;
        let guard = tree_guard_of(&hasher, || {
            tree_digest_memoised(roots(with_out), &hasher, 10, &memo, settled)
        })
        .unwrap();
        (guard, hasher.stats().cache_misses)
    };
    let (alone, read) = guard(false);
    assert_eq!(read, 2);
    let (taken, read) = guard(true);
    assert_eq!(read, 1, "the OUT_DIR alone");
    assert_ne!(taken.digest, alone.digest);

    std::fs::remove_dir_all(&out).unwrap();
    write_file(&out.join("gen.rs"), "// gen\n");
    filetime::set_file_mtime(
        out.join("gen.rs"),
        filetime::FileTime::from_unix_time(1_000_000_010, 0),
    )
    .unwrap();
    let (again, read) = guard(true);
    assert_eq!((again.digest.as_str(), read), (taken.digest.as_str(), 1));
    assert_eq!(guard(true).1, 0);
    assert!(!taken.held(), "the OUT_DIR moved");
    assert!(again.held());
    write_file(&workspace.join("kt/src/lib.rs"), "pub fn b() {}\n");
    assert!(!again.held(), "the workspace moved");
}

/// On Unix a memo answers while every entry has the stamp it was recorded
/// under. A new target directory moves only the root's own times, and
/// changes nothing the digest reads; a guard taken before still sees it.
#[cfg(unix)]
#[test]
fn a_tree_memo_outlives_a_new_target_directory() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let root = dir.path().join("w");
    write_file(&root.join("kt/src/lib.rs"), "");
    write_file(&root.join("target/debug/a"), "");
    filetime::set_file_mtime(&root, filetime::FileTime::from_unix_time(1_000_000_000, 0)).unwrap();
    let skipped: &[&str] = &["target"];
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    // The guard, and how many files were read for it.
    let guard = || {
        let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        let settled = std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE;
        let roots = vec![TreeRoot::new(root.clone(), b"workspace", skipped)];
        let guard = tree_guard_of(&hasher, || {
            tree_digest_memoised(roots, &hasher, 10, &memo, settled)
        })
        .unwrap();
        (guard, hasher.stats().cache_misses)
    };
    let (taken, read) = guard();
    assert_eq!(read, 1);
    std::fs::remove_dir_all(root.join("target")).unwrap();
    write_file(&root.join("target/debug/b"), "");
    let (again, read) = guard();
    assert_eq!((again.digest.as_str(), read), (taken.digest.as_str(), 0));
    assert!(!taken.held(), "the root's own times moved");
    assert!(again.held());
}

/// A file directly under the root, put back with other bytes of the same
/// size and its old times, is read again. Where an entry's stamp has no inode
/// or change time, only the root's own times show it: NTFS gives a name
/// recreated within 15 s its old creation time.
#[test]
fn a_file_put_back_under_the_root_with_its_old_times_is_read_again() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let root = dir.path().join("w");
    let file = root.join("schema.sql");
    write_file(&file, "a");
    let old = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000);
    filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old)).unwrap();
    filetime::set_file_mtime(&root, filetime::FileTime::from_system_time(old)).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    // The digest, and how many files were read for it.
    let digest = || {
        let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        let settled = std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE;
        let roots = vec![TreeRoot::new(root.clone(), b"workspace", &[])];
        let digest = tree_digest_memoised(roots, &hasher, 10, &memo, settled).unwrap();
        (digest, hasher.stats().cache_misses)
    };
    let (taken, read) = digest();
    assert_eq!(read, 1);
    assert_eq!(digest(), (taken.clone(), 0), "the memo answers");

    #[cfg(windows)]
    let created = std::fs::metadata(&file).unwrap().created().unwrap();
    // Past any timestamp tick, so the file put back gets a new change time.
    std::thread::sleep(std::time::Duration::from_millis(50));
    std::fs::remove_file(&file).unwrap();
    write_file(&file, "b");
    let times = std::fs::FileTimes::new().set_modified(old);
    // The creation time NTFS gives back within 15 s.
    #[cfg(windows)]
    let times = std::os::windows::fs::FileTimesExt::set_created(times, created);
    std::fs::File::options()
        .write(true)
        .open(&file)
        .and_then(|file| file.set_times(times))
        .unwrap();
    let (again, read) = digest();
    assert_eq!(read, 1);
    assert_ne!(again, taken);
}

/// One root's digest is the one 1.0 records, so 1.0 records of such units
/// still match. The digest of several roots folds the digest of each, so that
/// each root can be memoised alone.
#[test]
fn a_tree_digest_of_several_roots_folds_the_digest_of_each() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let (package, out) = (dir.path().join("p"), dir.path().join("out"));
    write_file(&package.join("lib.rs"), "pub fn a() {}\n");
    write_file(&out.join("gen.rs"), "");
    let hasher = FileHasher::new();
    let now = std::time::SystemTime::now();
    let digest = |roots| tree_digest_memoised(roots, &hasher, 10, &memo, now).unwrap();
    let fold = |version: &[u8], fields: &[(&[u8], &[u8])]| {
        let mut hasher = blake3::Hasher::new();
        hasher.update(version);
        for (label, value) in fields {
            fold_field(&mut hasher, label, value);
        }
        hasher.finalize().to_hex().to_string()
    };
    let package_root = || TreeRoot::new(package.clone(), b"manifest_dir", &[]);
    let out_root = || TreeRoot::new(out.clone(), b"out_dir", &[]);

    let package_digest = digest(vec![package_root()]);
    let content = blake3::hash(b"pub fn a() {}\n").to_hex();
    let fields: [(&[u8], &[u8]); 3] = [
        (b"root:", b"manifest_dir"),
        (b"path:", b"lib.rs"),
        (b"file:", content.as_bytes()),
    ];
    assert_eq!(package_digest, fold(b"kache-crate-tree-v1\n", &fields));
    let out_digest = digest(vec![out_root()]);
    let fields: [(&[u8], &[u8]); 2] = [
        (b"digest:", package_digest.as_bytes()),
        (b"digest:", out_digest.as_bytes()),
    ];
    assert_eq!(
        digest(vec![package_root(), out_root()]),
        fold(b"kache-crate-tree-roots-v1\n", &fields)
    );
}

/// A root read after the stamps may spend only what the other roots leave of
/// the budget, so one that grew in the meantime gives no digest.
#[test]
fn a_root_read_after_the_stamps_spends_what_the_others_leave() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let (first, second) = (dir.path().join("a"), dir.path().join("b"));
    write_file(&first.join("f"), "");
    write_file(&second.join("g"), "");
    let roots = || {
        vec![
            TreeRoot::new(first.clone(), b"workspace", &[]),
            TreeRoot::new(second.clone(), b"out_dir", &[]),
        ]
    };
    let hasher = FileHasher::new();
    let settled = std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE;
    // `first` is walked again before its digest is memoised, after both
    // stamps and before `second` is read: `second` grows then.
    let (watched, grown) = (first.clone(), second.join("h"));
    let mut walks = 0;
    set_before_stamp(Some(Box::new(move |path: &Path| {
        if path == watched {
            walks += 1;
            if walks == 2 {
                std::fs::write(&grown, "").unwrap();
            }
        }
    })));
    let digest = tree_digest_memoised(roots(), &hasher, 2, &memo, settled);
    set_before_stamp(None);
    assert_eq!(digest, None);
    assert!(tree_digest_memoised(roots(), &hasher, 3, &memo, settled).is_some());
}

/// What the tree guard cannot read counts as unreadable instead of
/// withholding the digest: a proc macro the build starts cannot read it
/// either. A file it cannot read keeps the digest out of the memo, since only
/// a change time would show the file becoming readable.
#[cfg(unix)]
#[test]
fn what_the_tree_guard_cannot_read_counts_as_unreadable() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let tree = dir.path().join("tree");
    write_file(&tree.join("src/lib.rs"), "");
    write_file(&tree.join("pgdata/PG_VERSION"), "16");
    write_file(&tree.join("secret.env"), "A=1");
    struct Mode(PathBuf, u32);
    impl Drop for Mode {
        fn drop(&mut self) {
            let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(self.1));
        }
    }
    let _pgdata = Mode(tree.join("pgdata"), 0o755);
    let _secret = Mode(tree.join("secret.env"), 0o644);
    let mode = |path: &str, mode| {
        std::fs::set_permissions(tree.join(path), std::fs::Permissions::from_mode(mode)).unwrap();
    };
    let roots = || vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
    let hasher = FileHasher::new();
    let settled = || std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE * 2;
    let digest = || tree_digest_memoised(roots(), &hasher, 10, &memo, settled());
    let readable = digest().unwrap();

    mode("pgdata", 0o000);
    if std::fs::read_dir(tree.join("pgdata")).is_ok() {
        eprintln!("skipped: this user reads past permissions");
        return;
    }
    let unlisted = digest().expect("a directory it cannot list");
    assert_ne!(unlisted, readable);
    mode("pgdata", 0o755);
    assert_eq!(digest().as_ref(), Some(&readable));

    mode("secret.env", 0o000);
    let file = tree_digest_memo(&memo, &roots()[0]);
    let _ = std::fs::remove_file(&file);
    let unread = digest().expect("a file it cannot read");
    assert_ne!(unread, readable);
    assert!(!file.exists(), "not memoised");
    mode("secret.env", 0o644);
    assert_eq!(digest(), Some(readable));
}

/// Below the root, a directory the fold cannot list counts as unreadable.
/// A root it cannot list gives no digest: nothing of the tree was read. The
/// stamp walk refuses such a root first, so the fold meets one only when
/// the root goes away between the two.
#[test]
fn a_root_the_tree_fold_cannot_list_gives_no_digest() {
    let dir = tempfile::tempdir().unwrap();
    let gone = dir.path().join("gone");
    let hasher = FileHasher::new();
    let fold = |root: &Path| {
        let mut budget = 10;
        let mut digest = blake3::Hasher::new();
        crate_tree_fold(
            root,
            &gone,
            &[],
            false,
            &GuardFileHashes {
                hasher: &hasher,
                memoised: HashMap::new(),
            },
            &mut digest,
            &mut budget,
        )
    };
    assert_eq!(fold(dir.path()), Some(true), "a directory below the root");
    assert_eq!(fold(&gone), None, "the root");
}

/// A digest is memoised only while the tree still has the stamp it had
/// before its files were read. A name that came and went directly under the
/// root meanwhile leaves every entry as it was, and moves the root's times.
#[test]
fn a_tree_that_moved_while_it_was_read_is_not_memoised() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let tree = dir.path().join("tree");
    write_file(&tree.join("a.txt"), "a");
    let old = filetime::FileTime::from_unix_time(1_000_000_000, 0);
    filetime::set_file_mtime(tree.join("a.txt"), old).unwrap();
    filetime::set_file_mtime(&tree, old).unwrap();
    let root = TreeRoot::new(tree.clone(), b"workspace", &[]);
    let file = tree_digest_memo(&memo, &root);
    let walked = |root: &TreeRoot<'_>| {
        let walked = root.walked();
        let stamp = stamp_root(&walked, 10).unwrap();
        let walk = GuardWalk {
            root: walked,
            max_entries: 10,
            stamp: stamp.digest.clone(),
        };
        (walk, stamp)
    };
    let digest = "d".repeat(64);
    let now = std::time::SystemTime::now();

    let (walk, stamp) = walked(&root);
    write_file(&tree.join("transient.txt"), "t");
    std::fs::remove_file(tree.join("transient.txt")).unwrap();
    memoise_tree_digest(&file, &walk, &stamp, &digest, now);
    assert!(
        !file.exists(),
        "a name came and went while the files were read"
    );

    let (walk, stamp) = walked(&root);
    let settled = std::time::SystemTime::now() + crate::tree_stamp::TreeStamp::SETTLE;
    memoise_tree_digest(&file, &walk, &stamp, &digest, settled);
    assert_eq!(
        crate::tree_stamp::memoised_digest(&file, stamp.memo_key()),
        Some(digest)
    );
}

/// A guard holds while the trees it read keep their stamps. A file removed
/// and put back with the same bytes and times leaves the digest as it was,
/// not the stamp: the file has a new inode and change time.
#[test]
fn a_tree_guard_holds_until_its_tree_moves() {
    let dir = tempfile::tempdir().unwrap();
    let memo = dir.path().join("memo");
    let tree = dir.path().join("tree");
    let file = tree.join("a.txt");
    write_file(&file, "a");
    let old = filetime::FileTime::from_unix_time(1_000_000_000, 0);
    filetime::set_file_mtime(&file, old).unwrap();
    // Past any timestamp tick, so the file put back below gets a new one.
    std::thread::sleep(std::time::Duration::from_millis(50));
    let hasher = FileHasher::new();
    let guard = || {
        tree_guard_of(&hasher, || {
            let roots = vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
            tree_digest_memoised(roots, &hasher, 10, &memo, std::time::SystemTime::now())
        })
        .unwrap()
    };
    let taken = guard();
    assert!(taken.held());
    write_file(&dir.path().join("elsewhere.txt"), "");
    assert!(taken.held(), "outside the tree");

    std::fs::remove_file(&file).unwrap();
    assert!(!taken.held(), "a file removed");
    write_file(&file, "a");
    filetime::set_file_mtime(&file, old).unwrap();
    assert_eq!(guard().digest, taken.digest, "the same bytes");
    #[cfg(unix)]
    assert!(!taken.held(), "put back with the same bytes and times");
    assert!(guard().held());
    let unwalked = TreeGuard {
        digest: taken.digest,
        walks: Vec::new(),
    };
    assert!(!unwalked.held(), "nothing to walk again");
}

/// A file a tree guard reads is not a key input: a save anywhere in the
/// workspace while a unit builds must not keep that unit out of the store.
#[test]
fn a_tree_file_never_trips_the_too_new_guard() {
    let dir = tempfile::tempdir().unwrap();
    let tree = dir.path().join("tree");
    let file = tree.join("f");
    write_file(&file, "x");
    filetime::set_file_mtime(&file, filetime::FileTime::from_unix_time(2_000_000_000, 0)).unwrap();
    let now_ns = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos() as i64;
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    for cached in [false, true] {
        let mut hasher = if cached {
            FileHasher::from_cache(FileHashCache::Borrowed(&db))
        } else {
            FileHasher::new()
        };
        hasher.arm_too_new_guard(now_ns, 0);
        let roots = vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
        let memo = dir.path().join("memo");
        let now = std::time::SystemTime::now();
        assert!(tree_digest_memoised(roots, &hasher, 10, &memo, now).is_some());
        assert!(!hasher.too_new(), "cached={cached}");
        assert!(hasher.take_guarded_inputs().is_empty(), "cached={cached}");
        hasher.hash(&file).unwrap();
        assert!(
            hasher.too_new(),
            "a key input still trips it, cached={cached}"
        );
    }
}

#[test]
fn guard_stamp_collection_respects_kinds_exclusions_and_build_tags() {
    let dir = tempfile::tempdir().unwrap();
    write_file(&dir.path().join("small.txt"), "kept");
    write_file(&dir.path().join("excluded/hidden.txt"), "excluded");
    write_file(&dir.path().join("build/hidden.txt"), "build output");
    write_file(
        &dir.path().join("build/CACHEDIR.TAG"),
        "Signature: 8a477f597d28d172789f06886806bc55\n# This file is a cache directory tag created by cargo.\n",
    );
    std::fs::write(dir.path().join("large.txt"), vec![0; 64 << 10]).unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink("small.txt", dir.path().join("link.txt")).unwrap();
    let root = TreeRoot::new(dir.path().to_path_buf(), b"workspace", &["excluded"])
        .skipping_build_dirs()
        .walked();
    let stamped = stamp_roots(std::slice::from_ref(&root), 20, true)
        .unwrap()
        .pop()
        .unwrap();
    let mut collected: Vec<_> = stamped
        .small_files
        .iter()
        .map(|fp| {
            Path::new(&fp.path)
                .strip_prefix(dir.path())
                .unwrap()
                .to_path_buf()
        })
        .collect();
    collected.sort();
    if cfg!(unix) {
        assert_eq!(
            collected,
            [
                PathBuf::from("build/CACHEDIR.TAG"),
                PathBuf::from("small.txt")
            ]
        );
    } else {
        assert!(collected.is_empty());
    }
    let default = stamp_roots(std::slice::from_ref(&root), 20, false)
        .unwrap()
        .pop()
        .unwrap();
    assert!(default.small_files.is_empty());
    assert_eq!(stamped.stamp.digest, default.stamp.digest);
    assert_eq!(stamped.entries, default.entries);
    assert!(matches!(
        stamp_roots(&[root], 1, true),
        Err(StampRefusal::TooLarge(0))
    ));
}

#[cfg(unix)]
#[test]
fn guard_files_without_a_cache_do_not_queue_memo_rows() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "input");
    let hasher = FileHasher::new();
    assert_eq!(
        hasher.guard_file_hash(&path, &HashMap::new()).unwrap(),
        hash_file(&path).unwrap()
    );
    assert!(hasher.pending_memo.borrow().is_empty());
}

#[cfg(target_os = "linux")]
#[test]
fn guard_file_memos_do_not_merge_lossy_path_spellings() {
    use std::os::unix::ffi::OsStringExt;
    let dir = tempfile::tempdir().unwrap();
    let paths: Vec<_> = [0xfe, 0xff]
        .into_iter()
        .map(|byte| dir.path().join(std::ffi::OsString::from_vec(vec![byte])))
        .collect();
    write_file(&paths[0], "first");
    write_file(&paths[1], "other");
    let roots = [TreeRoot::new(dir.path().to_path_buf(), b"workspace", &[]).walked()];
    assert!(
        stamp_roots(&roots, 10, true).unwrap()[0]
            .small_files
            .is_empty()
    );
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    for path in &paths {
        let poisoned = HashMap::from([(
            FileFingerprint::from_path(path).unwrap(),
            "wrong hash".to_string(),
        )]);
        assert_eq!(
            hasher.guard_file_hash(path, &poisoned).unwrap(),
            hash_file(path).unwrap()
        );
    }
    assert!(hasher.pending_memo.borrow().is_empty());
}

#[cfg(unix)]
#[test]
fn small_guard_file_memos_reuse_absolute_rows_from_relative_roots() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir_in(".").unwrap();
    let tree = PathBuf::from(dir.path().file_name().unwrap());
    write_file(&tree.join("input.txt"), "input");
    let memo_dir = tempfile::tempdir().unwrap();
    let memo = memo_dir.path().join("memo");
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let digest = |root, hasher: &FileHasher<'_>| {
        tree_digest_memoised(
            vec![TreeRoot::new(root, b"workspace", &[])],
            hasher,
            10,
            &memo,
            std::time::UNIX_EPOCH,
        )
        .unwrap()
    };
    let first = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let cold = digest(absolute_path(&tree), &first);
    assert_eq!(first.stats().cache_misses, 1);
    first.flush_memo_as_if_settled();
    let second = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    assert_eq!(digest(tree, &second), cold);
    assert_eq!(second.stats().cache_hits, 1);
    assert_eq!(second.stats().cache_misses, 0);
    assert_eq!(second.stats().bytes_hashed, 0);
}

#[cfg(unix)]
#[test]
fn a_guard_leaf_changed_after_its_metadata_leaves_no_memo_row() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "before");
    filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(1_000_000_000, 0)).unwrap();
    let metadata = std::fs::symlink_metadata(&path).unwrap();
    let before = FileFingerprint::from_path(&path).unwrap();
    // Model a same-size save after the content walk's stat and before its
    // read. Even a settled observation must not publish that read's bytes
    // under the earlier fingerprint.
    write_file(&path, "after!");
    filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(2_000_000_000, 0)).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let hash = hasher
        .guard_file_hash_from_metadata(&path, &metadata, i64::MAX, &HashMap::new())
        .unwrap();
    assert_eq!(hash, hash_file(&path).unwrap());
    assert_eq!(hasher.stats().cache_hits, 0);
    assert_eq!(hasher.stats().cache_misses, 1);
    assert!(hasher.pending_memo.borrow().is_empty());
    hasher.flush_memo();
    let cache = FileHashCache::Borrowed(&db);
    assert_eq!(cache.get(&before).unwrap(), None);
    assert_eq!(
        cache
            .get(&FileFingerprint::from_path(&path).unwrap())
            .unwrap(),
        None
    );
}

#[cfg(unix)]
#[test]
fn a_guard_leaf_settles_against_the_content_walk_observation() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "input");
    filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(4_000_000_000, 0)).unwrap();
    let metadata = std::fs::symlink_metadata(&path).unwrap();
    let fingerprint = FileFingerprint::from_path(&path).unwrap();
    let changed_ns = fingerprint.mtime_ns.max(fingerprint.ctime_ns);
    let hash = hash_file(&path).unwrap();
    // A supplied clock models the two sides of the settle boundary without
    // waiting. Reading a later clock inside the hash must not replace it.
    for (observed_ns, settled) in [
        (changed_ns + HASH_SETTLE_NS - 1, false),
        (changed_ns + HASH_SETTLE_NS, true),
    ] {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        ensure_file_hash_cache_schema(&db).unwrap();
        let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        assert_eq!(
            hasher
                .guard_file_hash_from_metadata(&path, &metadata, observed_ns, &HashMap::new())
                .unwrap(),
            hash
        );
        hasher.flush_memo();
        assert_eq!(
            FileHashCache::Borrowed(&db).get(&fingerprint).unwrap(),
            settled.then(|| hash.clone())
        );
    }
}

#[cfg(unix)]
#[test]
fn small_guard_files_reuse_hashes_when_the_tree_memo_cannot_settle() {
    let dir = tempfile::tempdir().unwrap();
    let tree = dir.path().join("tree");
    let files: Vec<PathBuf> = (0..300)
        .map(|i| {
            let path = tree.join(format!("part{}/f{i}.txt", i % 3));
            write_file(&path, &format!("value {i}\n"));
            path
        })
        .collect();
    let roots = || vec![TreeRoot::new(tree.clone(), b"workspace", &[])];
    let memo = dir.path().join("memo");
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    // Force a content walk on every pass, even though individual files can
    // settle. Three hundred files also span more than one SQL lookup chunk.
    let digest = |hasher: &FileHasher<'_>| {
        tree_digest_memoised(roots(), hasher, 500, &memo, std::time::UNIX_EPOCH).unwrap()
    };
    let mut first = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    first.arm_too_new_guard(1, 0);
    let cold = digest(&first);
    assert_eq!(first.stats().cache_misses, 300);
    assert_eq!(first.stats().cache_hits, 0);
    first.flush_memo_as_if_settled();
    assert!(!tree_digest_memo(&memo, &roots()[0]).exists());

    let mut second = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    second.arm_too_new_guard(1, 0);
    assert_eq!(digest(&second), cold);
    assert_eq!(second.stats().cache_hits, 300);
    assert_eq!(second.stats().cache_misses, 0);
    assert_eq!(second.stats().bytes_hashed, 0);
    assert!(!second.too_new());
    assert!(second.take_guarded_inputs().is_empty());
    assert!(second.recent_hashes.borrow().is_empty());

    write_file(&files[0], "changed content\n");
    let third = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let changed = digest(&third);
    assert_ne!(changed, cold);
    assert_eq!(third.stats().cache_hits, 299);
    assert_eq!(third.stats().cache_misses, 1);
    assert_eq!(
        changed,
        digest(&FileHasher::new()),
        "same digest without memo"
    );
}

#[test]
fn a_weak_guard_identity_cannot_reuse_a_row_from_before_replacement() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "before");
    let mtime = filetime::FileTime::from_last_modification_time(&std::fs::metadata(&path).unwrap());
    let mut observed = ObservedFingerprint::from_path(&path).unwrap();
    observed.fingerprint.inode = 0;
    assert!(!guard_file_memo_eligible(observed.fingerprint.size, 0));
    assert!(!guard_file_memo_eligible(64 << 10, 1));
    let old_hash = hash_file(&path).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    // Model a row left by an earlier memo user on a platform whose identity
    // can survive a same-size replacement with the old modification time.
    hasher
        .pending_memo
        .borrow_mut()
        .push((observed.clone(), old_hash.clone()));
    hasher.flush_memo_as_if_settled();
    let rows = hasher.memoised_hashes(std::iter::once(&observed.fingerprint));
    assert_eq!(rows.get(&observed.fingerprint.path), Some(&old_hash));
    let memoised = HashMap::from([(observed.fingerprint.clone(), old_hash.clone())]);
    std::fs::remove_file(&path).unwrap();
    write_file(&path, "after!");
    filetime::set_file_mtime(&path, mtime).unwrap();
    assert_eq!(std::fs::metadata(&path).unwrap().len(), 6);
    assert_eq!(
        filetime::FileTime::from_last_modification_time(&std::fs::metadata(&path).unwrap()),
        mtime
    );
    // Keep the old weak fingerprint to model the aliased creation time too.
    let hash = hasher
        .guard_file_hash_observed(&path, observed, &memoised)
        .unwrap();
    assert_eq!(hash, hash_file(&path).unwrap());
    assert_ne!(hash, old_hash);
    assert_eq!(hasher.stats().cache_hits, 0);
    assert_eq!(hasher.stats().cache_misses, 1);
    assert!(hasher.pending_memo.borrow().is_empty());
}

#[cfg(windows)]
#[test]
fn windows_guard_files_stay_fresh_reads_without_queued_memo_rows() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "before");
    let metadata = std::fs::metadata(&path).unwrap();
    let mtime = filetime::FileTime::from_last_modification_time(&metadata);
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let old_hash = hasher.guard_file_hash(&path, &HashMap::new()).unwrap();
    assert!(hasher.pending_memo.borrow().is_empty());
    hasher.flush_memo_as_if_settled();
    write_file(&path, "after!");
    filetime::set_file_mtime(&path, mtime).unwrap();
    let hash = hasher.guard_file_hash(&path, &HashMap::new()).unwrap();
    assert_eq!(hash, hash_file(&path).unwrap());
    assert_ne!(hash, old_hash);
    assert_eq!(hasher.stats().cache_misses, 2);
    assert!(hasher.pending_memo.borrow().is_empty());
    assert_eq!(
        FileHashCache::Borrowed(&db)
            .get(&FileFingerprint::from_path(&path).unwrap())
            .unwrap(),
        None
    );
}

#[test]
fn a_guard_batch_row_must_match_the_fresh_leaf_fingerprint() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "before");
    let queried = FileFingerprint::from_path(&path).unwrap();
    let memoised = HashMap::from([(queried, hash_file(&path).unwrap())]);
    write_file(&path, "after!");
    // Keep size equal but make the timestamp change visible on coarse clocks.
    filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(2_000_000_000, 0)).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let mut hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    hasher.arm_too_new_guard(1, 0);
    assert_eq!(
        hasher.guard_file_hash(&path, &memoised).unwrap(),
        hash_file(&path).unwrap()
    );
    assert_eq!(hasher.stats().cache_hits, 0);
    assert_eq!(hasher.stats().cache_misses, 1);
    assert!(!hasher.too_new());
    assert!(hasher.take_guarded_inputs().is_empty());
}

#[test]
fn a_guard_file_changed_during_its_read_leaves_no_memo_row() {
    for armed in [false, true] {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("input.txt");
        write_file(&path, "before");
        let before = FileFingerprint::from_path(&path).unwrap();
        let db = rusqlite::Connection::open_in_memory().unwrap();
        ensure_file_hash_cache_schema(&db).unwrap();
        let mut hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
        if armed {
            hasher.arm_too_new_guard(1, 0);
        }
        set_before_read(Some(Box::new(|path| {
            write_file(path, "changed while read")
        })));
        let hash = hasher.guard_file_hash(&path, &HashMap::new()).unwrap();
        set_before_read(None);
        assert_eq!(hash, hash_file(&path).unwrap());
        assert!(!hasher.too_new());
        assert!(hasher.take_guarded_inputs().is_empty());
        assert!(hasher.recent_hashes.borrow().is_empty());
        assert!(hasher.pending_memo.borrow().is_empty());
        hasher.flush_memo_as_if_settled();
        let cache = FileHashCache::Borrowed(&db);
        assert_eq!(cache.get(&before).unwrap(), None);
        assert_eq!(
            cache
                .get(&FileFingerprint::from_path(&path).unwrap())
                .unwrap(),
            None
        );
    }
}

#[cfg(unix)]
#[test]
fn a_guard_file_observed_before_settling_is_not_memoised() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("input.txt");
    write_file(&path, "fresh");
    filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(4_000_000_000, 0)).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    assert_eq!(
        hasher.guard_file_hash(&path, &HashMap::new()).unwrap(),
        hash_file(&path).unwrap()
    );
    assert_eq!(hasher.pending_memo.borrow().len(), 1);
    assert!(!hasher.pending_memo.borrow()[0].0.settled());
    hasher.flush_memo();
    assert_eq!(
        FileHashCache::Borrowed(&db)
            .get(&FileFingerprint::from_path(&path).unwrap())
            .unwrap(),
        None
    );
}

#[test]
fn a_units_headers_come_from_one_memo_lookup_once_settled() {
    let dir = tempfile::tempdir().unwrap();
    // Small on purpose: `hash` never memoises these, the capture does.
    let headers: Vec<(String, PathBuf)> = (0..5)
        .map(|i| {
            let path = dir.path().join(format!("h{i}.h"));
            std::fs::write(&path, format!("#define H{i} {i}\n")).unwrap();
            (format!("h{i}.h"), path)
        })
        .collect();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let mapped = no_mapping;

    let mut first = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    first.arm_too_new_guard(1, 0);
    let cold = first
        .cc_preprocess_fingerprints(&headers, "maps", &mapped)
        .unwrap();
    assert_eq!(first.stats().cache_misses, 5);
    assert_eq!(first.stats().cache_hits, 0);
    // Every header is registered for the post-compile revalidation and
    // remembered for later users in this process.
    assert_eq!(first.guard_inputs.borrow().len(), 5);
    for (_, path) in &headers {
        assert!(
            first
                .recent_hashes
                .borrow()
                .contains_key(&absolute_path(path))
        );
    }
    first.flush_memo_as_if_settled();

    let second = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let warm = second
        .cc_preprocess_fingerprints(&headers, "maps", &mapped)
        .unwrap();
    assert_eq!(second.stats().cache_hits, 5, "all five from the memo");
    assert_eq!(second.stats().cache_misses, 0);
    assert_eq!(second.stats().bytes_hashed, 0);
    let hashes = |inputs: &[CcPreprocessMemoInput]| {
        inputs.iter().map(|i| i.content.clone()).collect::<Vec<_>>()
    };
    assert_eq!(hashes(&warm), hashes(&cold));

    // A header rewritten since then is hashed again, not served stale.
    std::fs::write(&headers[0].1, "#define H0 changed\n").unwrap();
    let third = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let after = third
        .cc_preprocess_fingerprints(&headers, "maps", &mapped)
        .unwrap();
    assert_eq!(third.stats().cache_misses, 1);
    assert_ne!(hashes(&after)[0], hashes(&cold)[0]);
}

#[test]
fn an_unarmed_guard_keeps_no_headers_for_revalidation() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("h.h");
    std::fs::write(&path, "#define H 1\n").unwrap();
    let headers = vec![("h.h".to_string(), path)];
    let mapped = no_mapping;

    let hasher = FileHasher::new();
    hasher
        .cc_preprocess_fingerprints(&headers, "maps", &mapped)
        .unwrap();
    assert!(hasher.take_guarded_inputs().is_empty());
}

/// A row's fate is fixed when its file is observed. Both rows here are
/// flushed decades after their stamp from the epoch; only the one observed
/// a full settle window after it is written.
#[test]
fn a_row_observed_inside_the_settle_window_is_never_memoised_however_late_the_flush() {
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let stamp = |path: &str| FileFingerprint {
        path: path.to_string(),
        size: 12,
        mtime_ns: 1,
        ctime_ns: 1,
        inode: 7,
    };
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    for (path, observed_ns) in [
        ("/early.h", HASH_SETTLE_NS),
        ("/settled.h", 1 + HASH_SETTLE_NS),
    ] {
        hasher.pending_memo.borrow_mut().push((
            ObservedFingerprint {
                fingerprint: stamp(path),
                observed_ns,
            },
            format!("hash of {path}"),
        ));
    }
    hasher.flush_memo();

    let reader = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    let memo = reader.memoised_hashes([stamp("/early.h"), stamp("/settled.h")].iter());
    assert_eq!(
        memo.get("/early.h"),
        None,
        "observed one nanosecond inside the window"
    );
    assert_eq!(
        memo.get("/settled.h").map(String::as_str),
        Some("hash of /settled.h")
    );
}

#[test]
fn a_file_changed_within_the_settle_window_is_hashed_but_not_memoised() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("fresh.h");
    std::fs::write(&file, vec![1u8; 70 * 1024]).unwrap();
    let db = rusqlite::Connection::open_in_memory().unwrap();
    ensure_file_hash_cache_schema(&db).unwrap();
    let hasher = FileHasher::from_cache(FileHashCache::Borrowed(&db));
    assert_eq!(hasher.hash(&file).unwrap(), hash_file(&file).unwrap());
    hasher.flush_memo();
    let stamp = FileFingerprint::from_path(&file).unwrap();
    assert_eq!(
        FileHashCache::Borrowed(&db).get(&stamp).unwrap(),
        None,
        "a second write in this timestamp tick could reuse this stamp"
    );
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// The deleted-cwd panic, as rustc 1.98 prints it: the panic, a backtrace,
/// then the generic banner. Only the panic's message names the cause.
#[test]
fn first_rustc_error_line_prefers_a_compiler_panic_message() {
    let stderr = "\nthread 'main' (21712) panicked at compiler/rustc_span/src/source_map.rs:221:14:\n\
                  expecting a current working directory to exist: Os { code: 2 }\n\
                  stack backtrace:\n\
                  error: the compiler unexpectedly panicked. This is a bug\n";
    assert_eq!(
        first_rustc_error_line(stderr),
        Some("expecting a current working directory to exist: Os { code: 2 }")
    );
    // Older toolchains print no thread id.
    let stderr = "thread 'rustc' panicked at src/lib.rs:1:1:\n\nboom\n";
    assert_eq!(first_rustc_error_line(stderr), Some("boom"));
}

#[test]
fn first_rustc_error_line_keeps_a_panic_header_with_no_message() {
    let stderr = "thread 'rustc' panicked at src/lib.rs:1:1:\n  \n";
    assert_eq!(
        first_rustc_error_line(stderr),
        Some("thread 'rustc' panicked at src/lib.rs:1:1:")
    );
    // A panic header needs both the thread prefix and "panicked at".
    for stderr in [
        "note: a thread panicked at startup\nwarning: noise\nerror: real cause\n",
        "thread 'x' started\nwarning: noise\nerror: real cause\n",
    ] {
        assert_eq!(first_rustc_error_line(stderr), Some("error: real cause"));
    }
}

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

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

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

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

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

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

    let fh = FileHasher::new();
    let pn = PathNormalizer::empty();

    let parsed1 = RustcArgs::parse(&args_vec).unwrap();
    let key1 = compute_cache_key(&parsed1, &fh, &pn, &KeyEnv::default()).unwrap();

    // Modify the module file (NOT lib.rs)
    std::fs::write(
        src.join("utils.rs"),
        b"pub fn helper() { println!(\"changed\"); }",
    )
    .unwrap();

    let parsed2 = RustcArgs::parse(&args_vec).unwrap();
    let key2 = compute_cache_key(&parsed2, &fh, &pn, &KeyEnv::default()).unwrap();

    assert_ne!(
        key1, key2,
        "cache key must change when a module file changes"
    );
}

// --- cache key determinism with multiple source files ---

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

    std::fs::write(src.join("lib.rs"), b"mod a;\nmod b;\npub fn lib_fn() {}").unwrap();
    std::fs::write(src.join("a.rs"), b"pub fn a_fn() {}").unwrap();
    std::fs::write(src.join("b.rs"), b"pub fn b_fn() {}").unwrap();

    let args_vec: Vec<String> = vec![
        "rustc".to_string(),
        "--crate-name".to_string(),
        "testcrate".to_string(),
        src.join("lib.rs").to_string_lossy().to_string(),
        "--crate-type".to_string(),
        "lib".to_string(),
        "--edition=2021".to_string(),
    ];

    let fh = FileHasher::new();
    let pn = PathNormalizer::empty();

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

    let key1 = compute_cache_key(&parsed1, &fh, &pn, &KeyEnv::default()).unwrap();
    let key2 = compute_cache_key(&parsed2, &fh, &pn, &KeyEnv::default()).unwrap();

    assert_eq!(
        key1, key2,
        "cache key must be deterministic with multiple source files"
    );
}

// ────────────────────────────────────────────────────────────────
// rustc cache-key correctness matrix
//
// Property under test: the key must react to every input that
// changes rustc's *output artifact*, and must NOT react to inputs
// that only affect diagnostics. A missed input is a miscache (a
// false hit serving the wrong artifact); a spurious change is
// over-keying (a missed hit, wasted work).
//
// The testable seam is `compute_cache_key` itself: it forks rustc
// (`get_rustc_version`, the `--emit=dep-info` pre-pass) and reads
// source files, so each case builds a real temp `.rs` file plus a
// `RustcArgs` and compares two keys. Cases that depend on env vars
// (`RUSTFLAGS`) mutate the process environment and are isolated
// onto a serial mutex so parallel test threads can't interleave.
// ────────────────────────────────────────────────────────────────

/// Serializes every test that computes a cache key through the shared
/// process-state lock also used by argument-parser tests.
///
/// `compute_cache_key` reads process-wide env (`RUSTFLAGS`,
/// `CARGO_ENCODED_RUSTFLAGS`, `CARGO_CFG_*`); the env-mutating
/// matrix case below temporarily changes `RUSTFLAGS`. `cargo test`
/// runs tests as parallel threads of one process, so without a
/// shared lock any test's two key computations can straddle that
/// mutation and observe a spurious key difference — that is exactly
/// how the `assert_eq` tests `test_cache_key_deterministic` and
/// `test_coverage_keys_consistent_across_remap_forms` flaked on CI.
///
/// The lock is therefore NOT matrix-scoped: every test that calls
/// `compute_cache_key` — matrix or not — holds it for its full
/// duration. New key tests must do the same; that is the price of
/// `compute_cache_key` reading process-global env directly.
/// Keep the local name used throughout this large test module while the
/// underlying lock remains shared with other process-state observers.
fn key_test_lock() -> crate::test_support::ProcessStateTestGuard {
    process_state_test_lock()
}

/// Key computation returns this compile's unit identity and its per-extern
/// producer ids (kunobi-ninja/kache#627).
#[test]
fn key_computation_returns_unit_identity() {
    let _lock = key_test_lock();
    let args: Vec<String> = [
        "rustc",
        "--crate-name",
        "app",
        "src/lib.rs",
        "-C",
        "extra-filename=-843f02d6a46ebef1",
        "--extern",
        "foo_old=/w/target/debug/deps/libfoo-0532daf0ee3516f0.rlib",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let mut parsed = RustcArgs::parse(&args).unwrap();
    // Skip the dep-info pre-pass: this is about what the externs loop
    // records, not source discovery.
    parsed.source_file = None;

    let (key, outputs) = compute_cache_key_with_outputs(
        &parsed,
        &FileHasher::new(),
        &PathNormalizer::empty(),
        &KeyEnv::default(),
    );
    key.unwrap();

    assert_eq!(
        outputs.unit_id.as_deref(),
        Some("843f02d6a46ebef1"),
        "the compile's own `-C extra-filename`"
    );

    let units = outputs.extern_units.expect("recorded with the digests");
    assert_eq!(
        units.get("foo_old").map(String::as_str),
        // Keyed by the alias the consumer used; the value is the producer's
        // identity, recovered from the artifact filename even though that
        // file does not exist here.
        Some("0532daf0ee3516f0")
    );
    assert!(
        outputs.externs.is_some(),
        "digests ride with their identities"
    );
    assert!(outputs.fields.is_some(), "per-group digests too");
}

/// True if a bare `rustc` is invocable. `compute_cache_key` forks
/// rustc for the version probe and dep-info pre-pass; without it
/// the key still computes (the pre-pass falls back) but the
/// matrix's intent is to exercise the real path. Guard-skip when
/// absent, consistent with other compiler-forking tests.
fn rustc_available() -> bool {
    std::process::Command::new("rustc")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

#[cfg(unix)]
fn rustc_exe_name() -> &'static str {
    "rustc"
}

#[cfg(unix)]
fn rustc_path_on_path() -> Option<PathBuf> {
    let path_var = std::env::var_os("PATH")?;
    std::env::split_paths(&path_var)
        .map(|dir| dir.join(rustc_exe_name()))
        .find(|path| path.is_file())
}

#[cfg(unix)]
fn shell_single_quote(path: &Path) -> String {
    format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
}

#[cfg(unix)]
fn write_rustc_version_wrapper(root: &Path, subdir: &str, version: &str) -> PathBuf {
    let real_rustc = rustc_path_on_path().expect("rustc should be on PATH");
    let dir = root.join(subdir);
    std::fs::create_dir_all(&dir).unwrap();
    let wrapper = dir.join("rustc");
    let script = format!(
        "#!/bin/sh\n\
if [ \"$1\" = \"--version\" ] && [ \"$2\" = \"--verbose\" ]; then\n\
cat <<'KACHE_RUSTC_VERSION'\n\
{version}\n\
KACHE_RUSTC_VERSION\n\
exit 0\n\
fi\n\
exec {} \"$@\"\n",
        shell_single_quote(&real_rustc)
    );
    kache_fs::testutil::write_executable(&wrapper, script);
    wrapper
}

/// Build a minimal lib-crate arg vector around a temp source file.
/// Callers push the dimension-under-test onto the returned vec.
fn base_args(source: &Path) -> Vec<String> {
    vec![
        "rustc".to_string(),
        "--crate-name".to_string(),
        "mxcrate".to_string(),
        source.to_string_lossy().to_string(),
        "--crate-type".to_string(),
        "lib".to_string(),
        "--edition=2021".to_string(),
    ]
}

/// Compute a key for an arg vector. The source file path is
/// already embedded in `args` (positional) — `RustcArgs::parse`
/// picks it up — so no separate source argument is needed.
fn key_for(args: &[String]) -> String {
    key_with(args, &KeyEnv::capture())
}

/// [`key_for`] with the environment `env`.
fn key_with(args: &[String], env: &KeyEnv) -> String {
    let parsed = RustcArgs::parse(args).unwrap();
    let fh = FileHasher::new();
    let pn = PathNormalizer::empty();
    compute_cache_key(&parsed, &fh, &pn, env).unwrap()
}

/// A snapshot holding only `name=value`.
fn env_with(name: &str, value: &str) -> KeyEnv {
    KeyEnv::from_parts([(name, value)], None)
}

fn restore_env_var(key: &str, old: Option<std::ffi::OsString>) {
    match old {
        Some(value) => unsafe { std::env::set_var(key, value) },
        None => unsafe { std::env::remove_var(key) },
    }
}

/// `KACHE_RUSTC_PATH_NORMALIZE=0` bakes real machine-local paths into DWARF
/// (no `--remap-path-prefix`), so the opt-out key MUST be path-local:
/// otherwise two checkouts at different paths compute the same key and a
/// shared cache serves one checkout's real-path artifact to another
/// (kunobi-ninja/kache#480). This pins the exact regression — two builds
/// that differ ONLY in cwd (the DWARF `comp_dir`) must get different opt-out
/// keys, while the default (remapped) build stays cwd-portable.
#[test]
fn opt_out_key_is_path_local_but_default_stays_portable() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
    let old_cwd = std::env::current_dir().unwrap();

    // Two identical crates at DIFFERENT paths; source arg is relative
    // ("lib.rs") so cwd is the only thing that varies — exactly what cargo
    // passes and what makes `comp_dir` the discriminator.
    let dir_a = crate::test_support::cwd_dir();
    let dir_b = crate::test_support::cwd_dir();
    std::fs::write(dir_a.join("lib.rs"), "pub fn f() {}\n").unwrap();
    std::fs::write(dir_b.join("lib.rs"), "pub fn f() {}\n").unwrap();
    let args = base_args(Path::new("lib.rs"));

    // SAFETY: env access is serialized by the process-state test lock; restored below.
    unsafe { std::env::set_var("KACHE_RUSTC_PATH_NORMALIZE", "0") };
    std::env::set_current_dir(&dir_a).unwrap();
    let optout_a = key_for(&args);
    std::env::set_current_dir(&dir_b).unwrap();
    let optout_b = key_for(&args);

    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);
    std::env::set_current_dir(&dir_a).unwrap();
    let default_a = key_for(&args);
    std::env::set_current_dir(&dir_b).unwrap();
    let default_b = key_for(&args);

    std::env::set_current_dir(&old_cwd).unwrap();
    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);

    assert_ne!(
        optout_a, optout_b,
        "opt-out builds bake real paths, so keys must be cwd-local"
    );
    assert_eq!(
        default_a, default_b,
        "default (remapped) builds must stay cwd-portable"
    );
    assert_ne!(
        optout_a, default_a,
        "opt-out must be a separate namespace from remapped builds"
    );
}

/// The opt-out fold must cover EVERY prefix the normalizer would have
/// remapped — not just cwd/$HOME. A build-script `OUT_DIR` lives under
/// `$CARGO_TARGET_DIR`, which the default key normalizes to `<TARGET>`; if
/// the opt-out fold missed that prefix, two builds under different target
/// dirs (each baking a different real `OUT_DIR` path into DWARF) would
/// collide on one opt-out key. Folding the normalizer's own `raw_prefixes`
/// closes that gap by construction. Pins it: changing only
/// `$CARGO_TARGET_DIR` changes the opt-out key but not the (portable)
/// default key.
#[test]
fn opt_out_key_folds_all_normalizer_prefixes_not_just_home() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
    let old_target = std::env::var_os("CARGO_TARGET_DIR");

    let ws = tempfile::tempdir().unwrap();
    let src = ws.path().join("lib.rs");
    std::fs::write(&src, "pub fn f() {}\n").unwrap();
    let target_a = tempfile::tempdir().unwrap();
    let target_b = tempfile::tempdir().unwrap();
    // Absolute source (same for both variants) so the pre-pass finds it
    // regardless of cwd; $CARGO_TARGET_DIR is then the only thing that varies.
    let args = base_args(&src);

    // Build the normalizer AFTER setting CARGO_TARGET_DIR so its `<TARGET>`
    // rule reflects the current target dir (from_env reads the env).
    let key = || {
        let parsed = RustcArgs::parse(&args).unwrap();
        let fh = FileHasher::new();
        let pn = PathNormalizer::from_env(Some(ws.path()));
        compute_cache_key(&parsed, &fh, &pn, &KeyEnv::default()).unwrap()
    };

    // SAFETY: env access is serialized by the process-state test lock; restored below.
    unsafe { std::env::set_var("KACHE_RUSTC_PATH_NORMALIZE", "0") };
    unsafe { std::env::set_var("CARGO_TARGET_DIR", target_a.path()) };
    let optout_a = key();
    unsafe { std::env::set_var("CARGO_TARGET_DIR", target_b.path()) };
    let optout_b = key();

    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);
    unsafe { std::env::set_var("CARGO_TARGET_DIR", target_a.path()) };
    let default_a = key();
    unsafe { std::env::set_var("CARGO_TARGET_DIR", target_b.path()) };
    let default_b = key();

    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);
    restore_env_var("CARGO_TARGET_DIR", old_target);

    assert_ne!(
        optout_a, optout_b,
        "opt-out key must fold the raw $CARGO_TARGET_DIR prefix (OUT_DIR lives under it)"
    );
    assert_eq!(
        default_a, default_b,
        "default build normalizes $CARGO_TARGET_DIR to <TARGET>, so it stays portable"
    );
}

/// Coverage builds skip remap injection too (llvm-cov / tarpaulin need real
/// paths in the profraw), so they bake real machine-local paths into DWARF
/// exactly like the `KACHE_RUSTC_PATH_NORMALIZE=0` opt-out. Their `remap:none`
/// key must therefore be path-local as well, or a shared cache serves one
/// checkout's real-path coverage artifact to another (the coverage analog of
/// kunobi-ninja/kache#480). Pins it: two coverage builds differing only in
/// cwd must get different keys.
#[test]
fn coverage_key_is_path_local() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let old_cwd = std::env::current_dir().unwrap();
    // Force the opt-out OFF so this test exercises the COVERAGE `remap:none`
    // path specifically. If `KACHE_RUSTC_PATH_NORMALIZE=0` were set in the
    // ambient env, `path_normalize_disabled` would be true and the fold
    // would fire via the opt-out — passing even if coverage regressed to the
    // old opt-out-only condition. Removing it pins the coverage path.
    let old_var = std::env::var_os("KACHE_RUSTC_PATH_NORMALIZE");
    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", None);

    let dir_a = crate::test_support::cwd_dir();
    let dir_b = crate::test_support::cwd_dir();
    std::fs::write(dir_a.join("lib.rs"), "pub fn f() {}\n").unwrap();
    std::fs::write(dir_b.join("lib.rs"), "pub fn f() {}\n").unwrap();
    let mut args = base_args(Path::new("lib.rs"));
    args.push("-Cinstrument-coverage".to_string());

    // Sanity-check the fixture is the coverage path, not the opt-out path.
    let parsed = RustcArgs::parse(&args).unwrap();
    assert!(parsed.has_coverage_instrumentation());
    assert!(
        !parsed.path_normalize_disabled,
        "test must exercise the coverage remap:none path, not the opt-out path"
    );

    std::env::set_current_dir(&dir_a).unwrap();
    let cov_a = key_for(&args);
    std::env::set_current_dir(&dir_b).unwrap();
    let cov_b = key_for(&args);

    std::env::set_current_dir(&old_cwd).unwrap();
    restore_env_var("KACHE_RUSTC_PATH_NORMALIZE", old_var);

    assert_ne!(
        cov_a, cov_b,
        "coverage builds bake real paths, so their keys must be cwd-local"
    );
}

#[test]
fn key_rustc_bootstrap_presence_changes_key_but_empty_is_identity() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("lib.rs");
    std::fs::write(&src, "pub fn f() {}\n").unwrap();
    let args = base_args(&src);

    let key_unset = key_with(&args, &KeyEnv::default());
    // Empty must hash identically to unset: that is what keeps existing
    // caches valid (no CACHE_KEY_VERSION bump for the common case).
    let key_empty = key_with(&args, &env_with("RUSTC_BOOTSTRAP", ""));
    let key_set = key_with(&args, &env_with("RUSTC_BOOTSTRAP", "1"));
    let key_other = key_with(&args, &env_with("RUSTC_BOOTSTRAP", "some_crate"));

    assert_eq!(
        key_unset, key_empty,
        "empty RUSTC_BOOTSTRAP must equal unset"
    );
    assert_ne!(key_unset, key_set, "RUSTC_BOOTSTRAP=1 must change the key");
    assert_ne!(
        key_set, key_other,
        "different RUSTC_BOOTSTRAP values must differ"
    );
}

#[test]
fn key_cargo_encoded_rustflags_changes_key() {
    // cargo passes flags via CARGO_ENCODED_RUSTFLAGS (\x1f-separated); they
    // affect codegen, so they must be folded into the key.
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("lib.rs");
    std::fs::write(&src, "pub fn f() {}\n").unwrap();
    let args = base_args(&src);

    let key_unset = key_with(&args, &KeyEnv::default());
    let flags = |value| env_with("CARGO_ENCODED_RUSTFLAGS", value);
    let key_set = key_with(&args, &flags("-C\x1ftarget-cpu=native"));
    let key_other = key_with(&args, &flags("-C\x1ftarget-cpu=x86-64-v3"));

    assert_ne!(
        key_unset, key_set,
        "setting CARGO_ENCODED_RUSTFLAGS must change the key"
    );
    assert_ne!(
        key_set, key_other,
        "different encoded rustflags must diverge the key"
    );
}

#[test]
fn key_cargo_cfg_env_changes_key() {
    // CARGO_CFG_* vars (cargo's reflection of `--cfg`) are folded into the
    // key so a build-script cfg change diverges it.
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }
    let var = "CARGO_CFG_KACHE_TEST_FLAG";
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("lib.rs");
    std::fs::write(&src, "pub fn f() {}\n").unwrap();
    let args = base_args(&src);

    let key_unset = key_with(&args, &KeyEnv::default());
    let key_set = key_with(&args, &env_with(var, "1"));
    let key_other = key_with(&args, &env_with(var, "2"));

    assert_ne!(key_unset, key_set, "a CARGO_CFG_* var must change the key");
    assert_ne!(
        key_set, key_other,
        "a different CARGO_CFG_* value must diverge the key"
    );
}

// ── "should change" cases — varying a codegen-affecting input ──

#[cfg(unix)]
#[test]
fn key_matrix_rustc_version_changes_key() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }

    let dir = tempfile::tempdir().unwrap();
    let rustc_a = write_rustc_version_wrapper(
        dir.path(),
        "toolchain-a",
        "rustc 1.95.0-test-a\nbinary: test-a\ncommit-hash: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    );
    let rustc_b = write_rustc_version_wrapper(
        dir.path(),
        "toolchain-b",
        "rustc 1.95.0-test-b\nbinary: test-b\ncommit-hash: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    );

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

    let mut args_a = base_args(&source);
    args_a[0] = rustc_a.to_string_lossy().into_owned();
    let mut args_b = base_args(&source);
    args_b[0] = rustc_b.to_string_lossy().into_owned();

    assert_ne!(
        key_for(&args_a),
        key_for(&args_b),
        "`rustc --version --verbose` output must affect the cache key"
    );
}

#[test]
fn key_matrix_manifest_dir_runtime_env_path_changes_key_across_workspaces() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }

    let old_manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
    let dir = tempfile::tempdir().unwrap();
    let workspace_a = dir.path().join("checkout-a");
    let workspace_b = dir.path().join("checkout-b");

    fn write_helper(workspace: &Path) -> PathBuf {
        let src = workspace.join("helper/src");
        std::fs::create_dir_all(&src).unwrap();
        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            r#"pub fn manifest_dir() -> &'static str {
    env!("CARGO_MANIFEST_DIR")
}
"#,
        )
        .unwrap();
        lib
    }

    let source_a = write_helper(&workspace_a);
    let source_b = write_helper(&workspace_b);
    let fh = FileHasher::new();

    let manifest_a = workspace_a.join("helper").canonicalize().unwrap();
    unsafe {
        std::env::set_var("CARGO_MANIFEST_DIR", manifest_a);
    }
    let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
    let pn_a = PathNormalizer::from_env(Some(&workspace_a));
    let key_a = compute_cache_key(&parsed_a, &fh, &pn_a, &KeyEnv::capture()).unwrap();

    let manifest_b = workspace_b.join("helper").canonicalize().unwrap();
    unsafe {
        std::env::set_var("CARGO_MANIFEST_DIR", manifest_b);
    }
    let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
    let pn_b = PathNormalizer::from_env(Some(&workspace_b));
    let key_b = compute_cache_key(&parsed_b, &fh, &pn_b, &KeyEnv::capture()).unwrap();

    restore_env_var("CARGO_MANIFEST_DIR", old_manifest_dir);

    assert_ne!(
        key_a, key_b,
        "CARGO_MANIFEST_DIR is a runtime env! value and must stay checkout-specific"
    );
}

#[test]
fn key_matrix_out_dir_include_pattern_stays_stable_across_workspaces() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }

    let old_out_dir = std::env::var_os("OUT_DIR");
    let old_manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
    let dir = tempfile::tempdir().unwrap();
    let workspace_a = dir.path().join("checkout-a");
    let workspace_b = dir.path().join("checkout-b");

    fn write_generated_include_crate(workspace: &Path) -> (PathBuf, PathBuf) {
        let src = workspace.join("src");
        let out_dir = workspace.join("target/debug/build/include-crate/out");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&out_dir).unwrap();

        let generated = out_dir.join("generated.rs");
        std::fs::write(&generated, b"pub fn generated() -> u8 { 7 }\n").unwrap();

        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));

pub fn value() -> u8 {
    generated()
}
"#,
        )
        .unwrap();
        (lib, out_dir)
    }

    let (source_a, out_a) = write_generated_include_crate(&workspace_a);
    let (source_b, out_b) = write_generated_include_crate(&workspace_b);
    let fh = FileHasher::new();

    let out_a = out_a.canonicalize().unwrap();
    unsafe {
        std::env::set_var("OUT_DIR", &out_a);
        std::env::set_var("CARGO_MANIFEST_DIR", &workspace_a);
    }
    let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
    let pn_a = PathNormalizer::from_env(Some(&workspace_a));
    let key_a = compute_cache_key(&parsed_a, &fh, &pn_a, &KeyEnv::capture()).unwrap();

    let out_b = out_b.canonicalize().unwrap();
    unsafe {
        std::env::set_var("OUT_DIR", &out_b);
        std::env::set_var("CARGO_MANIFEST_DIR", &workspace_b);
    }
    let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
    let pn_b = PathNormalizer::from_env(Some(&workspace_b));
    let key_b = compute_cache_key(&parsed_b, &fh, &pn_b, &KeyEnv::capture()).unwrap();

    restore_env_var("OUT_DIR", old_out_dir);
    restore_env_var("CARGO_MANIFEST_DIR", old_manifest_dir);

    assert_eq!(
        key_a, key_b,
        "OUT_DIR include!() paths should stay portable across workspaces"
    );
}

#[test]
fn key_matrix_out_dir_dual_pattern_diverges_across_workspaces() {
    let _lock = key_test_lock();
    if !rustc_available() {
        return;
    }

    let old_out_dir = std::env::var_os("OUT_DIR");
    let dir = tempfile::tempdir().unwrap();
    let workspace_a = dir.path().join("checkout-a");
    let workspace_b = dir.path().join("checkout-b");

    fn write_dual_pattern_crate(workspace: &Path) -> (PathBuf, PathBuf) {
        let src = workspace.join("src");
        let out_dir = workspace.join("target/debug/build/dual-crate/out");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&out_dir).unwrap();

        let generated = out_dir.join("generated.rs");
        std::fs::write(&generated, b"pub fn generated() -> u8 { 7 }\n").unwrap();

        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            r#"include!(concat!(env!("OUT_DIR"), "/generated.rs"));

pub const OUT_DIR_AT_COMPILE_TIME: &str = env!("OUT_DIR");

pub fn value() -> (&'static str, u8) {
    (OUT_DIR_AT_COMPILE_TIME, generated())
}
"#,
        )
        .unwrap();
        (lib, out_dir)
    }

    let (source_a, out_a) = write_dual_pattern_crate(&workspace_a);
    let (source_b, out_b) = write_dual_pattern_crate(&workspace_b);
    let fh = FileHasher::new();

    let out_a = out_a.canonicalize().unwrap();
    unsafe {
        std::env::set_var("OUT_DIR", &out_a);
    }
    let parsed_a = RustcArgs::parse(&base_args(&source_a)).unwrap();
    let pn_a = PathNormalizer::from_env(Some(&workspace_a));
    let key_a = compute_cache_key(&parsed_a, &fh, &pn_a, &KeyEnv::capture()).unwrap();

    let out_b = out_b.canonicalize().unwrap();
    unsafe {
        std::env::set_var("OUT_DIR", &out_b);
    }
    let parsed_b = RustcArgs::parse(&base_args(&source_b)).unwrap();
    let pn_b = PathNormalizer::from_env(Some(&workspace_b));
    let key_b = compute_cache_key(&parsed_b, &fh, &pn_b, &KeyEnv::capture()).unwrap();

    restore_env_var("OUT_DIR", old_out_dir);

    assert_ne!(
        key_a, key_b,
        "OUT_DIR dual pattern must stay checkout-specific: include!() alone is path-only, \
             but env!(\"OUT_DIR\") as a runtime value bakes the absolute path into the artifact"
    );
}

#[test]
fn key_matrix_emit_changes_key() {
    // `cargo check` runs rustc --emit=metadata (-> .rmeta);
    // `cargo build` runs --emit=link (-> .rlib). Same crate, same
    // everything else the key hashes => without hashing `emit` the
    // two collide and a check entry could be served to a build.
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();

    let mut metadata = base_args(&source);
    metadata.push("--emit=metadata".to_string());
    let mut link = base_args(&source);
    link.push("--emit=link".to_string());

    assert_ne!(
        key_for(&metadata),
        key_for(&link),
        "`--emit=metadata` vs `--emit=link` must produce different keys"
    );
}

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

    let mut o0 = base_args(&source);
    o0.extend(["-C".to_string(), "opt-level=0".to_string()]);
    let mut o3 = base_args(&source);
    o3.extend(["-C".to_string(), "opt-level=3".to_string()]);

    assert_ne!(
        key_for(&o0),
        key_for(&o3),
        "`-C opt-level` must affect the key"
    );
}

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

    let mut on = base_args(&source);
    on.extend(["-C".to_string(), "debug-assertions=on".to_string()]);
    let mut off = base_args(&source);
    off.extend(["-C".to_string(), "debug-assertions=off".to_string()]);

    assert_ne!(
        key_for(&on),
        key_for(&off),
        "`-C debug-assertions` must affect the key"
    );
}

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

    let base = base_args(&source);
    let mut with_cfg = base_args(&source);
    with_cfg.extend(["--cfg".to_string(), "extra_feature".to_string()]);

    assert_ne!(
        key_for(&base),
        key_for(&with_cfg),
        "a `--cfg` value must affect the key"
    );
}

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

    let mut std_feat = base_args(&source);
    std_feat.extend(["--cfg".to_string(), "feature=\"std\"".to_string()]);
    let mut both = std_feat.clone();
    both.extend(["--cfg".to_string(), "feature=\"derive\"".to_string()]);

    assert_ne!(
        key_for(&std_feat),
        key_for(&both),
        "adding a feature must affect the key"
    );
}

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

    let mut e2018 = base_args(&source);
    e2018.retain(|a| a != "--edition=2021");
    e2018.push("--edition=2018".to_string());
    let e2021 = base_args(&source); // already --edition=2021

    assert_ne!(
        key_for(&e2018),
        key_for(&e2021),
        "`--edition` must affect the key"
    );
}

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

    // Two distinct triples — neither needs to be installed; the
    // key hashes the `--target` string, it does not invoke a
    // cross-compile.
    let mut t1 = base_args(&source);
    t1.push("--target=x86_64-unknown-linux-gnu".to_string());
    let mut t2 = base_args(&source);
    t2.push("--target=aarch64-apple-darwin".to_string());

    assert_ne!(
        key_of_flags(&t1),
        key_of_flags(&t2),
        "`--target` must affect the key"
    );
}

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

    let rlib = base_args(&source); // --crate-type lib
    let mut staticlib = base_args(&source);
    for a in staticlib.iter_mut() {
        if a == "lib" {
            *a = "staticlib".to_string();
        }
    }

    assert_ne!(
        key_for(&rlib),
        key_for(&staticlib),
        "`--crate-type` must affect the key"
    );
}

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

    let key_none = key_with(&args, &KeyEnv::default());
    let key_set = key_with(&args, &env_with("RUSTFLAGS", "-C target-cpu=native"));

    assert_ne!(key_none, key_set, "`RUSTFLAGS` env var must affect the key");
}

/// Direct test of the `normalize_rustflags` helper.
#[test]
fn normalize_rustflags_collapses_whitespace() {
    assert_eq!(normalize_rustflags("-C a -C b"), "-C a -C b");
    // Multiple spaces between tokens → single space.
    assert_eq!(normalize_rustflags("-C a    -C b"), "-C a -C b");
    // Leading / trailing whitespace stripped.
    assert_eq!(normalize_rustflags("  -C a   -C b  "), "-C a -C b");
    // Mixed whitespace (tabs, newlines) treated as whitespace.
    assert_eq!(normalize_rustflags("-C a\t\t-C b"), "-C a -C b");
    // Order is preserved (rustc resolves later flags over earlier ones).
    assert_eq!(normalize_rustflags("-Cfoo=b   -Cfoo=a"), "-Cfoo=b -Cfoo=a");
    assert_ne!(
        normalize_rustflags("-Cfoo=a -Cfoo=b"),
        normalize_rustflags("-Cfoo=b -Cfoo=a")
    );
}

/// Direct test of the `scrub_remap_from_prefixes` helper.
#[test]
fn scrub_remap_from_prefixes_collapses_from_keeps_to() {
    let scrub = |s: &str| scrub_remap_from_prefixes(s.split_whitespace()).join(" ");

    // The core case: two checkouts converge, TO preserved.
    assert_eq!(
        scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
        "--remap-path-prefix=<REMAP_FROM>=/topsrcdir/"
    );
    assert_eq!(
        scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
        scrub("--remap-path-prefix=/abs/clone-b/=/topsrcdir/"),
        "different checkout `from` paths must collapse identically"
    );

    // Space-separated form: value is the next token.
    assert_eq!(
        scrub("--remap-path-prefix /abs/clone-a/=/topsrcdir/"),
        "--remap-path-prefix <REMAP_FROM>=/topsrcdir/"
    );

    // The clang `-f*-prefix-map` family (equals form).
    for flag in [
        "-ffile-prefix-map",
        "-fdebug-prefix-map",
        "-fmacro-prefix-map",
    ] {
        assert_eq!(
            scrub(&format!("{flag}=/abs/clone-a/=/virt/")),
            format!("{flag}=<REMAP_FROM>=/virt/")
        );
    }

    // Split on the LAST `=` (FROM may contain `=`), matching rustc/clang.
    assert_eq!(
        scrub("--remap-path-prefix=/a=b/clone-a/=/topsrcdir/"),
        "--remap-path-prefix=<REMAP_FROM>=/topsrcdir/"
    );

    // Changing TO must NOT be scrubbed away — it stays in the result.
    assert_ne!(
        scrub("--remap-path-prefix=/abs/clone-a/=/topsrcdir/"),
        scrub("--remap-path-prefix=/abs/clone-a/=/other/")
    );

    // Non-remap flags pass through verbatim.
    assert_eq!(
        scrub("-C opt-level=2 -C debuginfo=2"),
        "-C opt-level=2 -C debuginfo=2"
    );
    // A remap value with no `=` is malformed and left untouched.
    assert_eq!(
        scrub("--remap-path-prefix=garbage"),
        "--remap-path-prefix=garbage"
    );
}

#[test]
fn normalize_direct_remap_normalizes_known_from_but_keeps_to() {
    let dir = tempfile::tempdir().unwrap();
    let workspace = dir.path().join("workspace");
    std::fs::create_dir_all(&workspace).unwrap();
    let workspace = PathBuf::from(crate::path_normalizer::canonical_string(&workspace).unwrap());
    let normalizer = PathNormalizer::from_env(Some(&workspace));
    let from = workspace.join("dir=with=equals");
    let to = workspace.join("literal-to");
    let value = format!("{}={}", from.display(), to.display());

    assert_eq!(
        normalize_direct_remap_value(&value, &normalizer),
        format!(
            "{}={}",
            Path::new("<WORKSPACE>").join("dir=with=equals").display(),
            to.display()
        ),
        "only FROM is normalized; TO remains verbatim"
    );
    assert_eq!(
        normalize_direct_remap_value("malformed", &normalizer),
        "malformed"
    );
}

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

    let none = key_of_flags(&flag_base(&source, &[]));
    let separated = key_of_flags(&flag_base(
        &source,
        &["--remap-path-prefix", "/work/clone-a=/virtual/src"],
    ));
    let attached = key_of_flags(&flag_base(
        &source,
        &["--remap-path-prefix=/work/clone-a=/virtual/src"],
    ));
    let unrelated_from = key_of_flags(&flag_base(
        &source,
        &["--remap-path-prefix=/work/clone-b=/virtual/src"],
    ));
    let other_target = key_of_flags(&flag_base(
        &source,
        &["--remap-path-prefix=/work/clone-a=/virtual/other"],
    ));
    let remap_root = format!("--remap-path-prefix={}=/virtual/root", dir.path().display());
    let remap_source = format!("--remap-path-prefix={}=/virtual/source", source.display());
    let order_ab = key_of_flags(&flag_base(&source, &[&remap_root, &remap_source]));
    let order_ba = key_of_flags(&flag_base(&source, &[&remap_source, &remap_root]));

    assert_ne!(none, separated, "adding a direct remap must change the key");
    assert_eq!(separated, attached, "both rustc spellings are equivalent");
    assert_ne!(
        separated, unrelated_from,
        "without a matching normalization rule, FROM remains semantic"
    );
    assert_ne!(
        separated, other_target,
        "the remap target is embedded in artifacts and must remain key-visible"
    );
    assert_ne!(order_ab, order_ba, "overlapping remap order is semantic");

    let clone_a = dir.path().join("clone-a");
    let clone_b = dir.path().join("clone-b");
    std::fs::create_dir_all(&clone_a).unwrap();
    std::fs::create_dir_all(&clone_b).unwrap();
    let portable_key = |workspace: &Path| {
        let workspace = workspace.canonicalize().unwrap();
        let remap = format!("--remap-path-prefix={}=/virtual/src", workspace.display());
        let mut parsed = RustcArgs::parse(&flag_base(&source, &[&remap])).unwrap();
        parsed.source_file = None;
        compute_cache_key(
            &parsed,
            &FileHasher::new(),
            &PathNormalizer::from_env(Some(&workspace)),
            &KeyEnv::default(),
        )
        .unwrap()
    };
    assert_eq!(
        portable_key(&clone_a),
        portable_key(&clone_b),
        "known workspace prefixes normalize portably across checkouts"
    );
}

/// The cross-checkout fix (v14): a build system's own `--remap-path-prefix`
/// (Firefox `--enable-path-remapping`) carries the checkout path on its
/// `from` side, so two clones at different paths must still hash identically
/// — and changing the stable `to` target must still diverge the key.
#[test]
fn key_matrix_rustflags_remap_path_prefix_stable_across_checkouts() {
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let args = base_args(&source);

    let key = |flags| key_with(&args, &env_with("RUSTFLAGS", flags));
    let key_a = key("--remap-path-prefix=/work/clone-a/=/topsrcdir/");
    let key_b = key("--remap-path-prefix=/work/clone-b/=/topsrcdir/");
    // Same flag, different stable target → must diverge.
    let key_other_to = key("--remap-path-prefix=/work/clone-a/=/elsewhere/");

    assert_eq!(
        key_a, key_b,
        "different checkout paths under the same remap target must not change the key"
    );
    assert_ne!(
        key_a, key_other_to,
        "changing the remap target (`to`) must still change the key"
    );
}

/// Cosmetic whitespace differences between cargo / mach assemblies
/// of the same logical RUSTFLAGS must not change the cache key.
/// Firefox bench surfaced this as the dominant source of leaf
/// cache-key divergence; this test pins the fix.
#[test]
fn key_matrix_rustflags_whitespace_does_not_change_key() {
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();
    let args = base_args(&source);

    let key = |flags| key_with(&args, &env_with("RUSTFLAGS", flags));
    let key_tight = key("-C debuginfo=2 -C codegen-units=1");
    // Same flags, cosmetically different whitespace.
    let key_loose = key("-C debuginfo=2    -C codegen-units=1");
    // Same flags, leading whitespace.
    let key_padded = key("  -C debuginfo=2 -C codegen-units=1  ");

    assert_eq!(
        key_tight, key_loose,
        "RUSTFLAGS extra-whitespace must not change the key"
    );
    assert_eq!(
        key_tight, key_padded,
        "RUSTFLAGS leading/trailing whitespace must not change the key"
    );
}

// ── "should NOT change" cases — diagnostics-only inputs ──
//
// These flags steer only what rustc *prints*, never the emitted
// artifact bytes. If the key changes for one of them, that is
// over-keying (a missed hit) — the test will fail and surface it
// rather than silently weakening the key.
//
// All lint configuration is deliberately absent from this section: it
// cannot change successful artifact bytes, but it can change whether the
// compile FAILS, and a hit replays success. See the tests below.

#[test]
fn key_matrix_outcome_lint_configuration_changes_key() {
    // `-D warnings` promotes warnings to hard errors: two builds
    // differing only here can disagree about whether the compile
    // succeeded while emitting byte-identical objects on success.
    // Since a hit replays success, the key MUST move (review
    // finding #2) — otherwise an entry stored without the gate
    // serves green to a build the gate should have failed.
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();

    let base = base_args(&source);
    let mut with_lint = base_args(&source);
    with_lint.extend(["-D".to_string(), "warnings".to_string()]);
    let mut with_forbid = base_args(&source);
    with_forbid.extend(["--forbid".to_string(), "warnings".to_string()]);
    let mut with_cap = base_args(&source);
    with_cap.extend(["--cap-lints".to_string(), "allow".to_string()]);
    let mut with_attached = base_args(&source);
    with_attached.push("-Dwarnings".to_string());
    let mut with_warn = base_args(&source);
    with_warn.extend(["-W".to_string(), "unused".to_string()]);
    let mut with_allow = base_args(&source);
    with_allow.extend(["-A".to_string(), "dead_code".to_string()]);
    let mut with_check_cfg = base_args(&source);
    with_check_cfg.extend(["--check-cfg".to_string(), "cfg(foo)".to_string()]);
    let mut with_other_check_cfg = base_args(&source);
    with_other_check_cfg.push("--check-cfg=cfg(bar)".to_string());

    assert_ne!(
        key_for(&base),
        key_for(&with_lint),
        "an outcome-affecting lint gate (`-D warnings`) changes whether \
             the compile fails and MUST change the key"
    );
    assert_ne!(
        key_for(&base),
        key_for(&with_forbid),
        "`--forbid` is outcome-affecting and must change the key"
    );
    assert_ne!(
        key_for(&base),
        key_for(&with_cap),
        "`--cap-lints` re-levels every lint and must change the key"
    );
    assert_ne!(
        key_for(&with_lint),
        key_for(&with_attached),
        "separated (`-D warnings`) and attached (`-Dwarnings`) spellings \
             carry different tokens; each keys distinctly by design"
    );
    assert_ne!(
        key_for(&base),
        key_for(&with_warn),
        "-W can activate a lint that a deny group makes fatal"
    );
    assert_ne!(
        key_for(&base),
        key_for(&with_allow),
        "-A can relax an otherwise fatal lint"
    );
    assert_ne!(
        key_for(&base),
        key_for(&with_check_cfg),
        "--check-cfg controls the unexpected_cfgs outcome"
    );
    assert_ne!(
        key_for(&with_check_cfg),
        key_for(&with_other_check_cfg),
        "different accepted cfg sets must not share a key"
    );
}

#[test]
fn check_cfg_values_are_not_path_normalized() {
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let root = tempfile::tempdir().unwrap();
    let key_at = |workspace: &Path, with_check_cfg: bool| {
        std::fs::create_dir_all(workspace).unwrap();
        let source = workspace.join("lib.rs");
        std::fs::write(&source, b"pub fn hello() {}").unwrap();
        let mut args = base_args(&source);
        if with_check_cfg {
            let semantic_path = workspace
                .join("generated")
                .to_string_lossy()
                .replace('\\', "/");
            args.extend([
                "--check-cfg".to_string(),
                format!("cfg(build_path, values(\"{semantic_path}\"))"),
            ]);
        }
        let parsed = RustcArgs::parse(&args).unwrap();
        compute_cache_key(
            &parsed,
            &FileHasher::new(),
            &PathNormalizer::from_env(Some(workspace)),
            &KeyEnv::default(),
        )
        .unwrap()
    };

    let workspace_a = root.path().join("checkout-a");
    let workspace_b = root.path().join("checkout-b");
    assert_eq!(
        key_at(&workspace_a, false),
        key_at(&workspace_b, false),
        "the control must prove ordinary workspace paths normalize portably"
    );
    assert_ne!(
        key_at(&workspace_a, true),
        key_at(&workspace_b, true),
        "path-looking check-cfg values are semantic strings and must stay raw"
    );
}

#[test]
fn key_matrix_outcome_lint_gates_key_by_pairing_not_multiset() {
    // The gates are captured as a flat token stream, so folding them
    // sorted would collapse permutations that mean different things:
    // `-D unsafe_code -F warnings` denies unsafe_code (a `#[allow]` in
    // the crate can still re-allow it) and forbids warnings, while the
    // swap forbids unsafe_code (no `#[allow]` escape) and denies
    // warnings. Same token multiset, different outcomes — so the key
    // must distinguish them.
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();

    let gated = |gates: &[&str]| {
        let mut args = base_args(&source);
        args.extend(gates.iter().map(|s| s.to_string()));
        key_for(&args)
    };

    assert_ne!(
        gated(&["-D", "unsafe_code", "-F", "warnings"]),
        gated(&["-F", "unsafe_code", "-D", "warnings"]),
        "swapping which lint is denied and which is forbidden changes \
             the outcome and MUST change the key"
    );
    // (`--force-warn` takes a single lint, never a group, so both sides
    // name concrete lints.)
    assert_ne!(
        gated(&["-D", "unused_mut", "--force-warn", "deprecated"]),
        gated(&["-D", "deprecated", "--force-warn", "unused_mut"]),
        "swapping the deny and force-warn targets changes the outcome \
             and MUST change the key"
    );
    // Argv order is kept as the conservative choice: rustc resolves
    // repeated levels for the same lint last-wins, so a reordered gate
    // list can be a different build. A given build config emits a stable
    // order, so preserving it costs no hits.
    assert_ne!(
        gated(&["-D", "warnings", "-A", "unused", "-D", "unused"]),
        gated(&["-D", "unused", "-A", "unused", "-D", "warnings"]),
        "gate order is preserved in the key"
    );
}

#[test]
fn key_matrix_error_format_does_not_change_key() {
    // `--error-format=json` changes how diagnostics are rendered
    // (cargo always passes it) — never the artifact. The key must
    // not move.
    if !rustc_available() {
        return;
    }
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, b"pub fn hello() {}").unwrap();

    let base = base_args(&source);
    let mut with_fmt = base_args(&source);
    with_fmt.push("--error-format=json".to_string());

    assert_eq!(
        key_for(&base),
        key_for(&with_fmt),
        "`--error-format` is diagnostics-only and must NOT change \
             the key — a change here is over-keying"
    );
}

/// A handed-over closure is visible until the next key takes it, so that key
/// knows to arm the too-new guard.
#[test]
fn a_provided_closure_is_pending_until_a_key_takes_it() {
    let _lock = key_test_lock();
    assert!(!dep_info_provided());
    provide_dep_info(
        DepInfo {
            source_files: vec![PathBuf::from("src/lib.rs")],
            env_deps: Vec::new(),
        },
        None,
    );
    assert!(dep_info_provided());
    let taken = PROVIDED_DEP_INFO.with(|cell| cell.borrow_mut().take());
    assert!(taken.is_some());
    assert!(!dep_info_provided());
}

#[test]
fn a_deferred_discovery_says_so_when_displayed() {
    let text = DeferredDiscovery { miss_certain: true }.to_string();
    assert!(text.contains("deferred"), "{text}");
    let error: anyhow::Error = DeferredDiscovery { miss_certain: true }.into();
    assert!(error.downcast_ref::<DeferredDiscovery>().is_some());
}

#[test]
fn a_shared_identity_needs_an_absolute_target_and_a_predictable_unit() {
    let _lock = key_test_lock();
    let _workspace = crate::config::tests::set_env_for_test(
        "CARGO_MANIFEST_DIR",
        Some(std::ffi::OsStr::new("/w/kt")),
    );
    let parse = |argv: &[&str]| {
        RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
    };
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("debug").join("deps");
    std::fs::create_dir_all(&out).unwrap();
    let out_str = out.to_str().unwrap();
    let eligible = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        "src/lib.rs",
        "--out-dir",
        out_str,
    ]);
    assert!(rustc_shared_prediction_identity(&eligible).is_some());
    let relative = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        "src/lib.rs",
        "--out-dir",
        "target/debug/deps",
    ]);
    assert!(
        rustc_shared_prediction_identity(&relative).is_none(),
        "a relative target directory is not shareable"
    );
    let with_macro = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        "src/lib.rs",
        "--out-dir",
        out_str,
        "--extern",
        "my_macro=/t/debug/deps/libmy_macro-3.so",
    ]);
    assert!(
        rustc_shared_prediction_identity(&with_macro).is_none(),
        "a proc-macro dependency outside the registry is not predictable by closure alone"
    );
}

#[test]
fn a_discovery_identity_is_the_shared_one_when_predictions_are_on() {
    let _lock = key_test_lock();
    let parse = |argv: &[&str]| {
        RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
    };
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("debug").join("deps");
    std::fs::create_dir_all(&out).unwrap();
    let out_str = out.to_str().unwrap();
    let eligible = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        "src/lib.rs",
        "--out-dir",
        out_str,
    ]);
    let with_macro = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        "src/lib.rs",
        "--out-dir",
        out_str,
        "--extern",
        "my_macro=/t/debug/deps/libmy_macro-3.so",
    ]);
    let db = dir.path().join("index.db");
    let off = FileHasher::persistent(&db);
    assert_eq!(prediction_discovery_identity(&eligible, &off), None);
    let on = FileHasher::persistent(&db).with_input_predictions(true);
    let identity = prediction_discovery_identity(&eligible, &on).unwrap();
    assert_eq!(
        Some(identity.clone()),
        rustc_shared_prediction_identity(&eligible),
        "the shared spelling comes first"
    );
    assert!(!identity.is_empty());
    assert_eq!(
        prediction_discovery_identity(&with_macro, &on),
        None,
        "not shareable and not predictable: no flight"
    );
}

/// A record for a unit under the tree guard is usable only while the
/// crate tree it was made from is unchanged; a record without a tree
/// digest is not usable at all for such a unit.
#[test]
fn a_guarded_record_is_refused_when_the_tree_changed() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let package = dir
        .path()
        .join("registry")
        .join("src")
        .join("index-1")
        .join("kt-1.0.0");
    std::fs::create_dir_all(package.join("src")).unwrap();
    std::fs::write(package.join("src/lib.rs"), "pub fn v() {}\n").unwrap();
    let parse = |argv: &[&str]| {
        RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
    };
    let out = dir.path().join("debug").join("deps");
    std::fs::create_dir_all(&out).unwrap();
    let with_macro = parse(&[
        "rustc",
        "--crate-name",
        "kt",
        package.join("src/lib.rs").to_str().unwrap(),
        "--out-dir",
        out.to_str().unwrap(),
        "--extern",
        "my_macro=/t/debug/deps/libmy_macro-3.so",
    ]);
    let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR");
    // SAFETY: the key test lock serialises environment edits.
    unsafe {
        std::env::set_var("CARGO_MANIFEST_DIR", &package);
        std::env::remove_var("OUT_DIR");
    }
    let on = FileHasher::persistent(&dir.path().join("index.db")).with_input_predictions(true);
    let tree = crate_tree_digest(&on).expect("a registry package has a tree digest");
    let identity = rustc_prediction_identity(&with_macro).unwrap();
    let closure = DepInfo {
        source_files: vec![package.join("src/lib.rs")],
        env_deps: Vec::new(),
    };

    on.record_input_prediction(&identity, Some("kt"), &closure, None);
    assert_eq!(
        predicted_key_inputs(&with_macro, &on, &mut None),
        Err(Rejection::NoRecord),
        "a record without a tree digest cannot guard a proc-macro unit"
    );

    on.record_input_prediction(&identity, Some("kt"), &closure, Some("stale".to_string()));
    assert_eq!(
        predicted_key_inputs(&with_macro, &on, &mut None),
        Err(Rejection::TreeChanged)
    );

    on.record_input_prediction(&identity, Some("kt"), &closure, Some(tree.clone()));
    let mut current_tree = None;
    let current = predicted_key_inputs(&with_macro, &on, &mut current_tree);
    assert_ne!(current, Err(Rejection::TreeChanged), "{current:?}");
    assert_ne!(current, Err(Rejection::NoRecord), "{current:?}");
    assert_eq!(current_tree.map(|guard| guard.digest), Some(tree));

    std::fs::write(package.join("extra.txt"), "read by the macro").unwrap();
    assert_eq!(
        predicted_key_inputs(&with_macro, &on, &mut None),
        Err(Rejection::TreeChanged),
        "a file added under the package changes the tree"
    );
    unsafe {
        match manifest_dir {
            Some(value) => std::env::set_var("CARGO_MANIFEST_DIR", value),
            None => std::env::remove_var("CARGO_MANIFEST_DIR"),
        }
    }
}

#[cfg(unix)]
#[test]
fn clippy_identity_reads_the_snapshot() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let driver = dir.path().join("clippy-driver");
    kache_fs::testutil::write_executable(
        &driver,
        "#!/bin/sh\necho 'clippy 0.1.98 (abc 2026-09-01)'\n",
    );
    let member = dir.path().join("member");
    std::fs::create_dir_all(&member).unwrap();
    std::fs::write(member.join("clippy.toml"), "msrv = \"1.70\"\n").unwrap();

    let from_manifest = clippy_identity(
        &driver,
        &KeyEnv::from_parts(
            [
                ("CARGO_MANIFEST_DIR", member.as_os_str()),
                ("CLIPPY_ARGS", OsStr::new("-Dwarnings")),
            ],
            None,
        ),
    )
    .unwrap();
    assert!(
        from_manifest.starts_with("clippy 0.1.98"),
        "{from_manifest}"
    );
    assert!(
        from_manifest.contains("config:clippy.toml:"),
        "{from_manifest}"
    );
    assert!(
        from_manifest.contains("CLIPPY_ARGS=-Dwarnings"),
        "{from_manifest}"
    );

    // With no manifest dir, the search starts at the working directory.
    let from_cwd = clippy_identity(
        &driver,
        &KeyEnv::from_parts([] as [(&str, &str); 0], Some(member.clone())),
    )
    .unwrap();
    assert!(from_cwd.contains("config:clippy.toml:"), "{from_cwd}");
    assert!(from_cwd.contains("CLIPPY_ARGS unset"), "{from_cwd}");
}

#[cfg(target_os = "linux")]
#[test]
fn the_linux_libc_signature_names_the_running_libc() {
    let family = if cfg!(target_env = "musl") {
        LinuxLibcFamily::Musl
    } else {
        LinuxLibcFamily::Gnu
    };
    let signature = probe_linux_libc_signature(family).unwrap();
    assert!(!signature.is_empty());
    assert!(
        signature.chars().any(|c| c.is_ascii_digit()),
        "a version, not a label: {signature}"
    );
}

#[cfg(unix)]
#[test]
fn linker_identity_is_the_first_version_line_of_the_configured_linker() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    // SAFETY: the key test lock serialises environment edits.
    unsafe { std::env::set_var("KACHE_CACHE_DIR", dir.path()) };
    let linker = dir.path().join("my-ld");
    kache_fs::testutil::write_executable(
        &linker,
        "#!/bin/sh\necho 'my-ld 9.9'\necho 'second line'\n",
    );
    let parse = |argv: &[&str]| {
        RustcArgs::parse(&argv.iter().map(|a| (*a).to_string()).collect::<Vec<_>>()).unwrap()
    };
    let args = parse(&[
        "rustc",
        "src/lib.rs",
        "-C",
        &format!("linker={}", linker.display()),
    ]);
    let identity = get_linker_identity(&args);
    let missing = get_linker_identity(&parse(&[
        "rustc",
        "src/lib.rs",
        "-C",
        &format!("linker={}", dir.path().join("absent").display()),
    ]));
    unsafe { std::env::remove_var("KACHE_CACHE_DIR") };
    assert_eq!(identity.as_deref(), Some("my-ld 9.9"));
    assert_eq!(missing, None, "a linker that cannot run has no identity");
}

#[test]
fn a_key_that_read_an_undeclared_variable_is_refused() {
    let env = crate::key_env::KeyEnv::from_parts([("RUSTFLAGS", "-a")], None);
    assert_eq!(complete_key(&env, "k".into()).unwrap(), "k");
    let _ = env.var_os("PATH");
    let err = complete_key(&env, "k".into()).unwrap_err();
    assert!(err.to_string().contains("KEY_ENV_VARS"), "{err}");
}

/// Property tests for the key's two false-hit guards: every keyed input moves
/// the key, and what the key must ignore does not. Each case writes a small
/// crate (a root, module files, an OUT_DIR `include!`, two externs) and hands
/// its closure in through [`provide_dep_info`], so no rustc pre-pass runs.
mod properties {
    use super::*;
    use proptest::prelude::*;

    /// Codegen options, each with two non-default values.
    const CODEGEN: [(&str, [&str; 2]); 3] = [
        ("opt-level", ["1", "3"]),
        ("debuginfo", ["1", "2"]),
        ("codegen-units", ["3", "5"]),
    ];
    const CFGS: [&str; 3] = ["alpha", "beta", "gamma"];
    const FEATURES: [&str; 3] = ["std", "derive", "serde"];
    const RUSTFLAGS: [&str; 3] = ["--cfg=rf_a", "-Cdebug-assertions=on", "-Aunused"];
    const CARGO_CFGS: [&str; 2] = ["CARGO_CFG_PROP_A", "CARGO_CFG_PROP_B"];
    const ENV_DEPS: [&str; 2] = ["PROP_ENV_A", "PROP_ENV_B"];
    const EXTERNS: [&str; 2] = ["dep_a", "dep_b"];

    #[derive(Debug, Clone, PartialEq)]
    struct Unit {
        codegen: [Option<usize>; 3],
        cfgs: [bool; 3],
        features: [bool; 3],
        /// `sources[0]` is the crate root's text; the rest are module files.
        sources: Vec<String>,
        generated: String,
        out_dir_unit: String,
        rustflags: [bool; 3],
        cargo_cfgs: [Option<String>; 2],
        env_deps: [String; 2],
        externs: [Option<String>; 2],
    }

    fn text() -> impl Strategy<Value = String> {
        "[a-z0-9 ]{0,12}"
    }

    fn unit() -> impl Strategy<Value = Unit> {
        (
            prop::array::uniform3(prop::option::of(0..2usize)),
            prop::array::uniform3(any::<bool>()),
            prop::array::uniform3(any::<bool>()),
            prop::collection::vec(text(), 1..4),
            text(),
            "[a-f0-9]{4}",
            prop::array::uniform3(any::<bool>()),
            prop::array::uniform2(prop::option::of("[a-z0-9,]{0,6}")),
            prop::array::uniform2("[a-z0-9./]{0,6}"),
            prop::array::uniform2(prop::option::of(text())),
        )
            .prop_map(
                |(
                    codegen,
                    cfgs,
                    features,
                    sources,
                    generated,
                    out_dir_unit,
                    rustflags,
                    cargo_cfgs,
                    env_deps,
                    externs,
                )| Unit {
                    codegen,
                    cfgs,
                    features,
                    sources,
                    generated,
                    out_dir_unit,
                    rustflags,
                    cargo_cfgs,
                    env_deps,
                    externs,
                },
            )
    }

    /// One edit to one key-relevant input.
    #[derive(Debug, Clone)]
    enum Change {
        Codegen(usize),
        Cfg(usize),
        Feature(usize),
        Source(usize, String),
        Generated(String),
        OutDirUnit(String),
        Rustflag(usize),
        CargoCfg(usize, String),
        EnvDep(usize, String),
        Extern(usize, String),
    }

    fn change() -> impl Strategy<Value = Change> {
        prop_oneof![
            (0..3usize).prop_map(Change::Codegen),
            (0..3usize).prop_map(Change::Cfg),
            (0..3usize).prop_map(Change::Feature),
            (0..4usize, text()).prop_map(|(i, t)| Change::Source(i, t)),
            text().prop_map(Change::Generated),
            "[a-f0-9]{4}".prop_map(Change::OutDirUnit),
            (0..3usize).prop_map(Change::Rustflag),
            (0..2usize, "[a-z0-9,]{0,6}").prop_map(|(i, v)| Change::CargoCfg(i, v)),
            (0..2usize, "[a-z0-9./]{0,6}").prop_map(|(i, v)| Change::EnvDep(i, v)),
            (0..2usize, text()).prop_map(|(i, t)| Change::Extern(i, t)),
        ]
    }

    /// `unit` with `change` applied, or `None` when the edit is a no-op.
    fn apply(unit: &Unit, change: &Change) -> Option<Unit> {
        let mut next = unit.clone();
        match change {
            // Absent -> first value -> second value -> absent.
            Change::Codegen(i) => {
                next.codegen[*i] = match unit.codegen[*i] {
                    None => Some(0),
                    Some(0) => Some(1),
                    Some(_) => None,
                }
            }
            Change::Cfg(i) => next.cfgs[*i] = !unit.cfgs[*i],
            Change::Feature(i) => next.features[*i] = !unit.features[*i],
            Change::Source(i, t) => next.sources[i % unit.sources.len()] = t.clone(),
            Change::Generated(t) => next.generated = t.clone(),
            Change::OutDirUnit(u) => next.out_dir_unit = u.clone(),
            Change::Rustflag(i) => next.rustflags[*i] = !unit.rustflags[*i],
            Change::CargoCfg(i, v) => {
                next.cargo_cfgs[*i] = (unit.cargo_cfgs[*i].as_ref() != Some(v)).then(|| v.clone())
            }
            Change::EnvDep(i, v) => next.env_deps[*i] = v.clone(),
            Change::Extern(i, t) => {
                next.externs[*i] = (unit.externs[*i].as_ref() != Some(t)).then(|| t.clone())
            }
        }
        (next != *unit).then_some(next)
    }

    /// Deterministic shuffle; seed 0 keeps the order.
    fn shuffle<T>(items: &mut [T], seed: u64) {
        let mut state = seed;
        for i in (1..items.len()).rev() {
            if seed == 0 {
                return;
            }
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            items.swap(i, (state >> 33) as usize % (i + 1));
        }
    }

    /// Write `unit` under `root` and key it the way the wrapper does: the
    /// workspace and target rules from `root`, OUT_DIR in the snapshot, and the
    /// closure the compile would emit. `seed` reorders every input the key
    /// treats as a set.
    fn key_in(unit: &Unit, root: &Path, seed: u64) -> String {
        let src = root.join("src");
        let target = root.join("target");
        let deps = target.join("debug/deps");
        let out_dir = target
            .join("debug/build")
            .join(format!("probe-{}", unit.out_dir_unit))
            .join("out");
        for dir in [&src, &deps, &out_dir] {
            std::fs::create_dir_all(dir).unwrap();
        }
        let lib = src.join("lib.rs");
        std::fs::write(
            &lib,
            format!(
                "include!(concat!(env!(\"OUT_DIR\"), \"/gen.rs\"));\n// {}\n",
                unit.sources[0]
            ),
        )
        .unwrap();
        let generated = out_dir.join("gen.rs");
        std::fs::write(&generated, format!("// {}\n", unit.generated)).unwrap();
        let mut source_files = vec![lib.clone(), generated];
        for (i, text) in unit.sources.iter().enumerate().skip(1) {
            let module = src.join(format!("m{i}.rs"));
            std::fs::write(&module, format!("// {text}\n")).unwrap();
            source_files.push(module);
        }

        let mut groups: Vec<Vec<String>> = vec![
            vec!["--crate-name".into(), "probe".into()],
            vec!["--crate-type".into(), "lib".into()],
            vec!["--edition=2021".into()],
            vec![lib.to_string_lossy().into_owned()],
        ];
        for ((name, values), value) in CODEGEN.iter().zip(unit.codegen) {
            if let Some(v) = value {
                groups.push(vec!["-C".into(), format!("{name}={}", values[v])]);
            }
        }
        for (cfg, on) in CFGS.iter().zip(unit.cfgs) {
            if on {
                groups.push(vec!["--cfg".into(), (*cfg).into()]);
            }
        }
        for (feature, on) in FEATURES.iter().zip(unit.features) {
            if on {
                groups.push(vec!["--cfg".into(), format!("feature=\"{feature}\"")]);
            }
        }
        for (name, content) in EXTERNS.iter().zip(&unit.externs) {
            if let Some(content) = content {
                let rlib = deps.join(format!("lib{name}.rlib"));
                std::fs::write(&rlib, content).unwrap();
                groups.push(vec![
                    "--extern".into(),
                    format!("{name}={}", rlib.display()),
                ]);
            }
        }
        shuffle(&mut groups, seed);
        shuffle(&mut source_files, seed);
        let argv: Vec<String> = std::iter::once("rustc".to_string())
            .chain(groups.into_iter().flatten())
            .collect();

        let mut rustflags = vec![format!("-Lnative={}", root.join("native").display())];
        rustflags.extend(
            RUSTFLAGS
                .iter()
                .zip(unit.rustflags)
                .filter(|(_, on)| *on)
                .map(|(flag, _)| flag.to_string()),
        );
        let out_dir = out_dir.to_string_lossy().into_owned();
        let mut vars = vec![
            ("OUT_DIR".to_string(), out_dir.clone()),
            ("RUSTFLAGS".to_string(), rustflags.join(" ")),
        ];
        for (name, value) in CARGO_CFGS.iter().zip(&unit.cargo_cfgs) {
            if let Some(value) = value {
                vars.push(((*name).into(), value.clone()));
            }
        }
        shuffle(&mut vars, seed);
        let env = KeyEnv::from_parts(vars, Some(root.to_path_buf()));

        let mut env_deps = vec![("OUT_DIR".to_string(), out_dir)];
        env_deps.extend(
            ENV_DEPS
                .iter()
                .zip(&unit.env_deps)
                .map(|(name, value)| ((*name).to_string(), value.clone())),
        );
        let normalizer = PathNormalizer::from_env(Some(root)).with_target_dir(Some(&target));
        provide_dep_info(
            DepInfo {
                source_files,
                env_deps,
            },
            None,
        );
        compute_cache_key(
            &RustcArgs::parse(&argv).unwrap(),
            &FileHasher::new(),
            &normalizer,
            &env,
        )
        .unwrap()
    }

    /// A temp dir by its canonical spelling, as Cargo reports paths.
    fn checkout() -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let root = PathBuf::from(crate::path_normalizer::canonical_string(dir.path()).unwrap());
        (dir, root)
    }

    proptest! {
        #![proptest_config(ProptestConfig {
            cases: 32,
            max_shrink_iters: 256,
            ..ProptestConfig::default()
        })]

        // Editing any one keyed input (codegen flag, cfg, feature, source or
        // generated file, OUT_DIR unit, RUSTFLAGS, CARGO_CFG_*, env-dep value,
        // extern content) moves the key. A miss here is a false hit.
        #[test]
        fn every_keyed_input_changes_the_key(unit in unit(), change in change()) {
            let edited = apply(&unit, &change);
            prop_assume!(edited.is_some());
            let _lock = key_test_lock();
            let (_dir, root) = checkout();
            let before = key_in(&unit, &root, 0);
            let after = key_in(&edited.unwrap(), &root, 0);
            prop_assert_ne!(before, after, "{:?} left the key unchanged", change);
        }

        // The same crate in another checkout, with its flags, closure, and
        // CARGO_CFG_* vars in another order, gets the same key.
        #[test]
        fn checkout_location_and_input_order_do_not_change_the_key(
            unit in unit(),
            seed in any::<u64>(),
        ) {
            let _lock = key_test_lock();
            let (_a, root_a) = checkout();
            let (_b, root_b) = checkout();
            prop_assert_eq!(key_in(&unit, &root_a, 0), key_in(&unit, &root_b, seed));
        }
    }
}

#[test]
fn environment_detail_hashes_follow_the_normalized_key_inputs() {
    let _lock = key_test_lock();
    let dir = tempfile::tempdir().unwrap();
    let source = dir.path().join("lib.rs");
    std::fs::write(&source, "pub fn f() {}").unwrap();
    let args = RustcArgs::parse(&[
        "rustc".into(),
        "--crate-name".into(),
        "example".into(),
        source.to_str().unwrap().into(),
    ])
    .unwrap();
    let hashed = |pairs: Vec<(String, String)>| {
        provide_dep_info(
            DepInfo {
                source_files: vec![source.clone()],
                env_deps: pairs,
            },
            None,
        );
        let (key, outputs) = compute_cache_key_with_outputs(
            &args,
            &FileHasher::new(),
            &PathNormalizer::empty(),
            &KeyEnv::default(),
        );
        key.unwrap();
        outputs.env_deps.unwrap()
    };
    let first = hashed(vec![("BUILD_MODE".into(), "private-first-value".into())]);
    let second = hashed(vec![("BUILD_MODE".into(), "private-second-value".into())]);
    assert_eq!(
        first["BUILD_MODE"],
        blake3::hash(b"private-first-value").to_hex()[..16]
    );
    assert_ne!(first["BUILD_MODE"], second["BUILD_MODE"]);
    assert!(hashed(Vec::new()).is_empty());
}