kache 0.23.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more, with S3 and shared-filesystem remotes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
use assert_cmd::Command;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

mod common;
use common::{build_kache, hermetic_command, isolated_config_path, kache_binary};

fn run_kache_cc(project: &Path, cache_dir: &Path, args: &[&str]) {
    run_kache_cc_from(project, cache_dir, args);
}

fn run_kache_cc_from(cwd: &Path, cache_dir: &Path, args: &[&str]) {
    let output = hermetic_command(
        kache_binary(),
        cache_dir,
        Some(&isolated_config_path(cache_dir)),
    )
    .args(args)
    .current_dir(cwd)
    .env("KACHE_LOG", "kache=debug")
    .output()
    .expect("failed to run kache cc");

    assert!(
        output.status.success(),
        "kache cc failed.\nargs: {args:?}\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

fn run_cargo_build_with_kache(project: &Path, cache_dir: &Path, target_dir: &Path) {
    let output = hermetic_command("cargo", cache_dir, Some(&isolated_config_path(cache_dir)))
        .args(["build", "--lib"])
        .current_dir(project)
        .env("RUSTC_WRAPPER", kache_binary())
        .env("CARGO_TARGET_DIR", target_dir)
        .env("CARGO_INCREMENTAL", "0")
        .env("KACHE_LOG", "kache=debug")
        .output()
        .expect("failed to run cargo build with kache");

    assert!(
        output.status.success(),
        "cargo build failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

fn run_cargo_test_with_kache(project: &Path, cache_dir: &Path, target_dir: &Path, package: &str) {
    let output = hermetic_command("cargo", cache_dir, Some(&isolated_config_path(cache_dir)))
        .args(["test", "-q", "-p", package])
        .current_dir(project)
        .env("RUSTC_WRAPPER", kache_binary())
        .env("CARGO_TARGET_DIR", target_dir)
        .env("CARGO_INCREMENTAL", "0")
        .env("KACHE_LOG", "kache=debug")
        .output()
        .expect("failed to run cargo test with kache");

    assert!(
        output.status.success(),
        "cargo test failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// #971: a CoW restore must allow rustc to reuse the output paths after the
/// user removes the wrapper. Real hardlinks retain their read-only contract.
#[cfg(unix)]
#[test]
fn test_rust_restored_outputs_allow_build_without_wrapper() {
    use std::fs;
    use std::os::unix::fs::PermissionsExt;

    let project = TempDir::new_in(common::scratch_dir()).unwrap();
    let cache = TempDir::new_in(common::scratch_dir()).unwrap();
    let target = project.path().join("target");
    let source = project.path().join("lib.rs");
    fs::write(&source, "pub fn value() -> u32 { 42 }\n").unwrap();
    let probe = project.path().join("clone-probe");
    if let Err(error) = kache_store::link::try_reflink(&source, &probe) {
        eprintln!("reflink unavailable on test filesystem: {error}");
        return;
    }
    fs::remove_file(&probe).unwrap();
    fs::write(
        project.path().join("Cargo.toml"),
        "[package]\nname = \"permission_probe\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\
         [lib]\npath = \"lib.rs\"\n[workspace]\n",
    )
    .unwrap();

    run_cargo_build_with_kache(project.path(), cache.path(), &target);
    fs::remove_dir_all(&target).unwrap();
    run_cargo_build_with_kache(project.path(), cache.path(), &target);
    let report = kache_report(cache.path());
    let event = report["all_events"]
        .as_array()
        .unwrap()
        .iter()
        .rev()
        .find(|event| event["crate_name"] == "permission_probe")
        .unwrap();
    assert_eq!(event["result"], "local_hit");
    assert_eq!(event["compiler_runs"], 0);

    let mut blobs = Vec::new();
    for shard in fs::read_dir(cache.path().join("store/blobs")).unwrap() {
        for entry in fs::read_dir(shard.unwrap().path()).unwrap() {
            let path = entry.unwrap().path();
            let mode = fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o222, 0, "cached blob must be read-only");
            blobs.push((path.clone(), fs::read(&path).unwrap(), mode));
        }
    }
    assert!(!blobs.is_empty());

    // Keep the restored artifacts while forcing Cargo to invoke rustc again.
    fs::remove_dir_all(target.join("debug/.fingerprint")).unwrap();
    let unwrapped = hermetic_command(
        "cargo",
        cache.path(),
        Some(&isolated_config_path(cache.path())),
    )
    .args([
        "build",
        "--lib",
        "--offline",
        "--config",
        "build.rustc-wrapper=\"\"",
    ])
    .current_dir(project.path())
    .env("RUSTC_WRAPPER", "")
    .env("CARGO_TARGET_DIR", &target)
    .env("CARGO_INCREMENTAL", "0")
    .env("CARGO_TERM_COLOR", "never")
    .output()
    .unwrap();
    assert!(
        unwrapped.status.success(),
        "unwrapped rebuild failed: {}",
        String::from_utf8_lossy(&unwrapped.stderr)
    );
    assert!(String::from_utf8_lossy(&unwrapped.stderr).contains("Compiling permission_probe"));
    for (path, bytes, mode) in blobs {
        assert_eq!(
            fs::read(&path).unwrap(),
            bytes,
            "unwrapped build changed cache bytes"
        );
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode(),
            mode,
            "unwrapped build changed cache permissions"
        );
    }
}

fn kache_report(cache_dir: &Path) -> serde_json::Value {
    let output = hermetic_command(
        kache_binary(),
        cache_dir,
        Some(&isolated_config_path(cache_dir)),
    )
    .args(["report", "--format", "json", "--since", "1h"])
    .output()
    .expect("failed to run kache report");

    assert!(
        output.status.success(),
        "kache report failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    serde_json::from_slice(&output.stdout).expect("report should be valid json")
}

fn kache_perfetto_report(cache_dir: &Path, root: &Path) -> serde_json::Value {
    let output = hermetic_command(
        kache_binary(),
        cache_dir,
        Some(&isolated_config_path(cache_dir)),
    )
    .arg("report")
    .args(["--format", "perfetto", "--since", "1h", "--root"])
    .arg(root)
    .output()
    .expect("failed to run kache perfetto report");

    assert!(
        output.status.success(),
        "kache perfetto report failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    serde_json::from_slice(&output.stdout).expect("perfetto report should be valid json")
}

fn assert_cc_report_counts(report: &serde_json::Value, expected_misses: u64, expected_hits: u64) {
    let summary = &report["summary"];
    assert_eq!(summary["misses"].as_u64(), Some(expected_misses));
    assert_eq!(summary["local_hits"].as_u64(), Some(expected_hits));
}

fn assert_last_cc_event(report: &serde_json::Value, result: &str, compiler_runs: u64) {
    let events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    let last = events
        .last()
        .expect("report should include at least one event");
    assert_eq!(last["crate_name"].as_str(), Some("foo.c"));
    assert_eq!(last["result"].as_str(), Some(result));
    assert_eq!(last["compiler_runs"].as_u64(), Some(compiler_runs));
}

fn assert_last_cc_preprocessor_runs(report: &serde_json::Value, preprocessor_runs: u64) {
    let last = report["all_events"]
        .as_array()
        .and_then(|events| events.last())
        .expect("report should include at least one event");
    assert_eq!(last["preprocessor_runs"].as_u64(), Some(preprocessor_runs));
}

fn find_depinfo_containing(root: &Path, needle: &str) -> Option<(PathBuf, String)> {
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Ok(file_type) = entry.file_type() else {
                continue;
            };
            if file_type.is_dir() {
                stack.push(path);
                continue;
            }
            if path.extension().and_then(|e| e.to_str()) != Some("d") {
                continue;
            }
            let Ok(content) = std::fs::read_to_string(&path) else {
                continue;
            };
            if content.contains(needle) {
                return Some((path, content));
            }
        }
    }
    None
}

fn write_manifest_dir_workspace(root: &Path) {
    std::fs::create_dir_all(root.join("helper/src")).unwrap();
    std::fs::create_dir_all(root.join("consumer/src")).unwrap();
    std::fs::create_dir_all(root.join("consumer/tests")).unwrap();

    std::fs::write(
        root.join("Cargo.toml"),
        r#"[workspace]
members = ["helper", "consumer"]
resolver = "3"
"#,
    )
    .unwrap();
    std::fs::write(
        root.join("helper/Cargo.toml"),
        r#"[package]
name = "helper"
version = "0.1.0"
edition = "2024"

[lib]
path = "src/lib.rs"
"#,
    )
    .unwrap();
    std::fs::write(
        root.join("helper/src/lib.rs"),
        r#"#[inline(never)]
pub fn manifest_dir() -> &'static str {
    env!("CARGO_MANIFEST_DIR")
}
"#,
    )
    .unwrap();
    std::fs::write(
        root.join("consumer/Cargo.toml"),
        r#"[package]
name = "consumer"
version = "0.1.0"
edition = "2024"

[dependencies]
helper = { path = "../helper" }
"#,
    )
    .unwrap();
    std::fs::write(
        root.join("consumer/src/lib.rs"),
        r#"pub fn helper_manifest_dir() -> &'static str {
    helper::manifest_dir()
}
"#,
    )
    .unwrap();
    std::fs::write(
        root.join("consumer/tests/manifest.rs"),
        r#"use std::path::Path;

#[test]
fn helper_manifest_dir_matches_this_checkout() {
    let embedded = Path::new(consumer::helper_manifest_dir()).canonicalize().unwrap();
    let expected = std::env::current_dir()
        .unwrap()
        .parent()
        .unwrap()
        .join("helper")
        .canonicalize()
        .unwrap();
    assert_eq!(embedded, expected);
}
"#,
    )
    .unwrap();
}

#[test]
fn test_cli_version_matches_package_version() {
    build_kache();
    assert_ne!(
        env!("CARGO_PKG_VERSION"),
        "0.0.0",
        "release builds must not use the placeholder package version"
    );

    Command::new(kache_binary())
        .arg("--version")
        .assert()
        .success()
        .stdout(predicates::str::contains(format!(
            "kache {}",
            env!("CARGO_PKG_VERSION")
        )));
}

#[test]
fn test_cli_help() {
    build_kache();
    Command::new(kache_binary())
        .arg("--help")
        .assert()
        .success()
        .stdout(predicates::str::contains("kache"));
}

#[test]
fn test_cli_list_empty() {
    build_kache();
    let cache_dir = TempDir::new().unwrap();

    Command::from(hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    ))
    .arg("list")
    .assert()
    .success()
    .stdout(predicates::str::contains("No cached entries"));
}

#[test]
fn test_cli_purge_empty() {
    build_kache();
    let cache_dir = TempDir::new().unwrap();

    Command::from(hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    ))
    .arg("purge")
    .assert()
    .success()
    .stdout(predicates::str::contains("Cleared"));
}

#[test]
fn test_disabled_passthrough() {
    build_kache();

    let test_project = Path::new(env!("CARGO_MANIFEST_DIR")).join("test-projects/hello-world");
    let cache_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    // Build with kache disabled — should work just like normal cargo
    let status = hermetic_command(
        "cargo",
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["build"])
    .current_dir(&test_project)
    .env("RUSTC_WRAPPER", kache_binary())
    .env("KACHE_DISABLED", "1")
    .env("CARGO_TARGET_DIR", target_dir.path())
    .status()
    .expect("failed to run cargo build with kache disabled");

    assert!(
        status.success(),
        "cargo build with KACHE_DISABLED should succeed"
    );
}

#[test]
fn test_wrapper_hello_world() {
    build_kache();

    let test_project = Path::new(env!("CARGO_MANIFEST_DIR")).join("test-projects/hello-world");
    let cache_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();

    // First build (should be all cache misses)
    let status = hermetic_command(
        "cargo",
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["build"])
    .current_dir(&test_project)
    .env("RUSTC_WRAPPER", kache_binary())
    .env("KACHE_EVENT_ROOT", &test_project)
    .env("CARGO_TARGET_DIR", target_dir.path())
    .env("KACHE_LOG", "kache=debug")
    .status()
    .expect("failed to run cargo build with kache");

    assert!(status.success(), "first build with kache should succeed");

    // Verify the binary was produced (`.exe` on Windows).
    assert!(
        target_dir
            .path()
            .join(format!("debug/hello-world{}", std::env::consts::EXE_SUFFIX))
            .exists(),
        "binary should be produced"
    );

    // Check that the store has entries
    let store_dir = cache_dir.path().join("store");
    if store_dir.exists() {
        let entries: Vec<_> = std::fs::read_dir(&store_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        // Should have at least one cached entry (the hello-world lib)
        println!("Store entries after first build: {}", entries.len());
    }

    // Clean and rebuild (should be cache hits)
    let _ = std::process::Command::new("cargo")
        .args(["clean"])
        .current_dir(&test_project)
        .env("CARGO_TARGET_DIR", target_dir.path())
        .status();

    let status = hermetic_command(
        "cargo",
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["build"])
    .current_dir(&test_project)
    .env("RUSTC_WRAPPER", kache_binary())
    .env("KACHE_EVENT_ROOT", &test_project)
    .env("CARGO_TARGET_DIR", target_dir.path())
    .env("KACHE_LOG", "kache=debug")
    .status()
    .expect("failed to run second cargo build with kache");

    assert!(status.success(), "second build (cache hit) should succeed");

    let trace = kache_perfetto_report(cache_dir.path(), &test_project);
    let trace_obj = trace.as_object().expect("trace report should be an object");
    assert_eq!(trace_obj.len(), 2);
    assert_eq!(trace["displayTimeUnit"].as_str(), Some("ms"));
    let trace_events = trace["traceEvents"]
        .as_array()
        .expect("trace report should include traceEvents");
    assert!(!trace_events.is_empty());
    // The trace leads with metadata events (ph "M": process_name / thread_name)
    // that name the kache process and worker lanes (#456); the compile slices
    // are ph "X". Assert on the first slice, not blindly on index 0.
    let first_slice = trace_events
        .iter()
        .find(|e| e["ph"].as_str() == Some("X"))
        .expect("trace report should include at least one X slice");
    assert_eq!(
        first_slice["args"]["root"].as_str(),
        Some(
            test_project
                .canonicalize()
                .unwrap()
                .to_string_lossy()
                .as_ref()
        )
    );
}

#[test]
fn test_manifest_dir_env_dep_does_not_restore_stale_rlib_across_worktrees() {
    build_kache();

    let root = TempDir::new().unwrap();
    let workspace_a = root.path().join("checkout-a");
    let workspace_b = root.path().join("checkout-b");
    write_manifest_dir_workspace(&workspace_a);
    write_manifest_dir_workspace(&workspace_b);

    let cache_dir = TempDir::new().unwrap();
    let target_a = TempDir::new().unwrap();
    let target_b = TempDir::new().unwrap();

    run_cargo_test_with_kache(&workspace_a, cache_dir.path(), target_a.path(), "consumer");
    let events_after_a = kache_report(cache_dir.path())["all_events"]
        .as_array()
        .expect("report should include all_events")
        .len();

    run_cargo_test_with_kache(&workspace_b, cache_dir.path(), target_b.path(), "consumer");
    let report = kache_report(cache_dir.path());
    let all_events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    let checkout_b_events = &all_events[events_after_a..];

    assert!(
        checkout_b_events
            .iter()
            .any(|event| event["crate_name"].as_str() == Some("helper")
                && event["result"].as_str() == Some("miss")),
        "helper embeds CARGO_MANIFEST_DIR and must miss in checkout B, not restore checkout A's rlib: {checkout_b_events:?}"
    );
}

/// kunobi-ninja/kache#330: the classic cross-clone `.rmeta` cascade — an
/// upstream crate's metadata embedding clone-local paths, diverging its
/// bytes, and cascading through every dependent's `extern:` content hash —
/// converges on current rustc with kache's injected `--remap-path-prefix`.
/// This pins that convergence: both the dependency and its dependent must
/// hit when the identical workspace builds at a second absolute path.
#[test]
fn test_rust_extern_cascade_converges_across_clones() {
    build_kache();

    let root = TempDir::new().unwrap();
    let write_ws = |ws: &Path| {
        std::fs::create_dir_all(ws.join("dep/src")).unwrap();
        std::fs::create_dir_all(ws.join("app/src")).unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            "[workspace]\nmembers = [\"dep\", \"app\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        std::fs::write(
            ws.join("dep/Cargo.toml"),
            "[package]\nname = \"dep\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(ws.join("dep/src/lib.rs"), "pub fn f() -> u32 { 7 }\n").unwrap();
        std::fs::write(
            ws.join("app/Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\
             [dependencies]\ndep = { path = \"../dep\" }\n",
        )
        .unwrap();
        std::fs::write(
            ws.join("app/src/lib.rs"),
            "pub fn g() -> u32 { dep::f() + 1 }\n",
        )
        .unwrap();
    };
    let clone_a = root.path().join("clone-a");
    let clone_b = root.path().join("clone-b-at-a-much-longer-absolute-path");
    write_ws(&clone_a);
    write_ws(&clone_b);

    let cache_dir = TempDir::new().unwrap();
    let target_a = TempDir::new().unwrap();
    let target_b = TempDir::new().unwrap();

    run_cargo_build_with_kache(&clone_a, cache_dir.path(), target_a.path());
    let events_after_a = kache_report(cache_dir.path())["all_events"]
        .as_array()
        .expect("report should include all_events")
        .len();

    run_cargo_build_with_kache(&clone_b, cache_dir.path(), target_b.path());
    let report = kache_report(cache_dir.path());
    let all_events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    let clone_b_events = &all_events[events_after_a..];

    for krate in ["dep", "app"] {
        assert!(
            clone_b_events
                .iter()
                .any(|e| e["crate_name"].as_str() == Some(krate)
                    && e["result"].as_str() == Some("local_hit")),
            "{krate} must hit in clone B — the extern cascade regressed: {clone_b_events:?}"
        );
    }
}

/// kunobi-ninja/kache#330: the build-script `include!(env!("OUT_DIR"))`
/// pattern — the shape the issue's field report reduced to — also converges
/// across clones: the generated file's path differs per clone but the
/// content-hashed key and the normalized env-dep (cache-key v18) line up.
#[test]
fn test_rust_out_dir_include_converges_across_clones() {
    build_kache();

    let root = TempDir::new().unwrap();
    let write_proj = |proj: &Path| {
        std::fs::create_dir_all(proj.join("src")).unwrap();
        std::fs::write(
            proj.join("Cargo.toml"),
            "[package]\nname = \"genlib\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n",
        )
        .unwrap();
        std::fs::write(
            proj.join("build.rs"),
            "fn main() {\n    let out = std::env::var(\"OUT_DIR\").unwrap();\n    \
             std::fs::write(std::path::Path::new(&out).join(\"generated.rs\"),\n        \
             \"pub const G: u32 = 9;\\n\").unwrap();\n}\n",
        )
        .unwrap();
        std::fs::write(
            proj.join("src/lib.rs"),
            "include!(concat!(env!(\"OUT_DIR\"), \"/generated.rs\"));\npub fn h() -> u32 { G }\n",
        )
        .unwrap();
    };
    let clone_a = root.path().join("clone-a");
    let clone_b = root.path().join("clone-b-at-a-much-longer-absolute-path");
    write_proj(&clone_a);
    write_proj(&clone_b);

    let cache_dir = TempDir::new().unwrap();
    let target_a = TempDir::new().unwrap();
    let target_b = TempDir::new().unwrap();

    run_cargo_build_with_kache(&clone_a, cache_dir.path(), target_a.path());
    let events_after_a = kache_report(cache_dir.path())["all_events"]
        .as_array()
        .expect("report should include all_events")
        .len();

    run_cargo_build_with_kache(&clone_b, cache_dir.path(), target_b.path());
    let report = kache_report(cache_dir.path());
    let all_events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    let clone_b_events = &all_events[events_after_a..];

    assert!(
        clone_b_events
            .iter()
            .any(|e| e["crate_name"].as_str() == Some("genlib")
                && e["result"].as_str() == Some("local_hit")),
        "genlib must hit in clone B despite its OUT_DIR-generated include: {clone_b_events:?}"
    );
}

#[test]
fn test_rust_depinfo_restore_preserves_include_str_parent_relative_path() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();
    std::fs::create_dir_all(project.path().join("src")).unwrap();
    std::fs::write(
        project.path().join("Cargo.toml"),
        r#"[package]
name = "kache-depinfo-repro"
version = "0.1.0"
edition = "2024"

[lib]
path = "src/lib.rs"

# Standalone workspace root so cargo never walks up into an ancestor workspace
# (e.g. when the system temp dir lives under one — common on Windows, where
# %TEMP% is under the user profile).
[workspace]
"#,
    )
    .unwrap();
    std::fs::write(
        project.path().join("README.md"),
        "included by the crate root\n",
    )
    .unwrap();
    std::fs::write(
        project.path().join("src/lib.rs"),
        r#"#![doc = include_str!("../README.md")]

pub fn value() -> u8 {
    1
}
"#,
    )
    .unwrap();

    run_cargo_build_with_kache(project.path(), cache_dir.path(), target_dir.path());
    std::fs::remove_dir_all(target_dir.path()).unwrap();
    run_cargo_build_with_kache(project.path(), cache_dir.path(), target_dir.path());

    // rustc joins the package-relative dir with the OS separator but keeps the
    // `include_str!` literal's own slashes verbatim, so the recorded path is
    // "src/../README.md" on Unix and "src\../README.md" on Windows.
    let sep = std::path::MAIN_SEPARATOR;
    let parent_rel = format!("src{sep}../README.md");
    let (depinfo_path, depinfo) = find_depinfo_containing(target_dir.path(), &parent_rel)
        .expect("restored target dir should contain rustc's parent-relative README.md dep-info");
    assert!(
        depinfo.contains(&parent_rel),
        "restored dep-info should preserve rustc's parent-relative include_str path in {}:\n{}",
        depinfo_path.display(),
        depinfo
    );
    assert!(
        !depinfo.contains(&format!("src{sep}./")),
        "restore must not inject the target dir into a parent-relative source path in {}:\n{}",
        depinfo_path.display(),
        depinfo
    );
    assert!(
        // Match either separator so a leaked sentinel can't slip through on
        // Windows (`__kache_root__\`).
        !depinfo.contains("__kache_root__"),
        "restored-facing dep-info must not expose kache sentinels in {}:\n{}",
        depinfo_path.display(),
        depinfo
    );

    let report = kache_report(cache_dir.path());
    assert!(
        report["summary"]["local_hits"].as_u64().unwrap_or(0) >= 1,
        "second build should restore at least one artifact from the local cache: {report}"
    );
}

/// True if kache can cache a compile carrying a *probe-keyed* flag on this
/// host, checked by actually running one.
///
/// `-fstack-protector-strong` is `CapturedByProbe` and predates #580, so this
/// measures the platform's `cc -###` support rather than anything this change
/// added. Where the probe cannot be resolved, kache refuses to cache every
/// probe-keyed invocation by design (refusing is the safe direction), and the
/// aws-lc-sys flags below cannot be exercised end to end no matter how they
/// are classified.
///
/// Prints the head of `cc -###` on failure, so a platform that lands here
/// leaves behind the output needed to fix it instead of just a skip.
fn kache_caches_probe_keyed_flags(work: &Path) -> bool {
    let cache_dir = work.join("probe-gate-cache");
    let source = work.join("gate.c");
    std::fs::create_dir_all(&cache_dir).unwrap();
    std::fs::write(&source, "int gate(void) { return 0; }\n").unwrap();

    let ok = hermetic_command(
        kache_binary(),
        &cache_dir,
        Some(&isolated_config_path(&cache_dir)),
    )
    .arg("cc")
    .arg("-c")
    .arg(&source)
    .arg("-o")
    .arg(work.join("gate.o"))
    .args(["-fstack-protector-strong", "-O0", "-g0"])
    .current_dir(work)
    .output()
    .map(|o| o.status.success())
    .unwrap_or(false);
    if !ok {
        return false;
    }

    let report = kache_report(&cache_dir);
    if report["summary"]["misses"].as_u64().unwrap_or(0) >= 1 {
        return true;
    }

    let probe = std::process::Command::new("cc")
        .arg("-###")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(work.join("gate.o"))
        .output()
        .map(|o| String::from_utf8_lossy(&o.stderr).into_owned())
        .unwrap_or_else(|e| format!("(could not run cc -###: {e})"));
    eprintln!(
        "probe-keyed flags do not cache on this host; `cc -###` said:\n{}",
        probe.lines().take(12).collect::<Vec<_>>().join("\n")
    );
    false
}

/// True if `cc` on PATH accepts the GNU-dialect flag set the aws-lc-sys test
/// below drives, checked by actually compiling with it.
///
/// The flags are the ones aws-lc-sys passes to a non-cl-like driver; on a
/// cl-like driver it uses `/FI` instead and this shape never arises, so a
/// compiler that rejects them has nothing to say about the fix. Probing beats
/// guessing from the platform: the runner's `cc` may be MSVC, clang-cl, clang
/// or gcc, and only the driver itself knows which spellings it takes.
fn cc_accepts_gnu_forced_include(dir: &Path) -> bool {
    let header = dir.join("probe.h");
    let source = dir.join("probe.c");
    if std::fs::write(&header, "#define PROBE 1\n").is_err()
        || std::fs::write(&source, "int probe(void) { return PROBE; }\n").is_err()
    {
        return false;
    }
    std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(dir.join("probe.o"))
        .arg(format!("--include={}", header.display()))
        .args(["-fwrapv", "--param", "ssp-buffer-size=4", "-O0"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// First lines of `cc -###` stderr for the given compile args — the one fact
/// a probe-resolution failure report needs (#626).
fn cc_probe_stderr_head(cwd: &Path, args: &[&str]) -> String {
    std::process::Command::new("cc")
        .arg("-###")
        .args(args)
        .current_dir(cwd)
        .output()
        .map(|o| {
            String::from_utf8_lossy(&o.stderr)
                .lines()
                .take(12)
                .collect::<Vec<_>>()
                .join("\n")
        })
        .unwrap_or_else(|e| format!("(could not run cc -###: {e})"))
}

/// Do a real raw compile with each flag the #626 test keys on. Deliberately
/// NOT gated on `-###` parsing — gating on the machinery under test would
/// recreate the vacuity #626 is about. Old or vendor-derived drivers that
/// reject one of these flags skip the test instead of false-failing.
fn cc_accepts_probe_keyed_test_flags(dir: &Path) -> bool {
    let source = dir.join("flag-support.c");
    if std::fs::write(&source, "int flag_support(void) { return 0; }\n").is_err() {
        return false;
    }
    ["-fstack-protector-strong", "-fwrapv", "-fno-wrapv"]
        .iter()
        .all(|flag| {
            std::process::Command::new("cc")
                .args(["-c", "-O0", "-g0"])
                .arg(&source)
                .arg("-o")
                .arg(dir.join("flag-support.o"))
                .arg(flag)
                .output()
                .map(|output| output.status.success())
                .unwrap_or(false)
        })
}

/// Live verification for #626: a probe-keyed flag must produce a real cache
/// entry, and different values of a probe-keyed knob must key differently.
///
/// #607's two bugs each made `resolve_invocation` return `None` on Windows,
/// so every `CapturedByProbe` flag refused fail-closed and passed through —
/// builds correct, caching silently gone, and every prior test either ran
/// against frozen `-###` fixtures or skipped when resolution failed. On a
/// gcc/clang-family `cc` (both families support `-###` and both have an
/// extractor) this test therefore FAILS when the probe resolves nothing; it
/// skips only for a missing `cc` or a non-gnu/clang driver, where `-###`
/// resolution genuinely does not apply.
#[test]
fn probe_keyed_flags_cache_and_key_on_value_live() {
    let work = TempDir::new().unwrap();

    // Family gate, run-and-check like every other compiler gate here: a
    // preprocessed marker TU says what the driver is, `which` does not.
    let family_src = work.path().join("family.c");
    std::fs::write(
        &family_src,
        "#if defined(__clang__)\nKACHE_TEST_CLANG\n#elif defined(__GNUC__)\nKACHE_TEST_GNU\n#endif\n",
    )
    .unwrap();
    let Ok(family) = std::process::Command::new("cc")
        .args(["-E", "-P", "-x", "c"])
        .arg(&family_src)
        .output()
    else {
        eprintln!("skipping: no `cc` on PATH");
        return;
    };
    let family_out = String::from_utf8_lossy(&family.stdout);
    if !family.status.success()
        || !(family_out.contains("KACHE_TEST_CLANG") || family_out.contains("KACHE_TEST_GNU"))
    {
        eprintln!("skipping: `cc` is not a gcc/clang-family driver");
        return;
    }
    if !cc_accepts_probe_keyed_test_flags(work.path()) {
        eprintln!("skipping: `cc` does not accept the probe-keyed test flags");
        return;
    }

    build_kache();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(work.path().join("tu.c"), "int tu(void) { return 7; }\n").unwrap();

    // `-fstack-protector-strong` is `CapturedByProbe`; a cold compile that
    // records no miss means kache refused (unresolvable probe) and passed
    // through — the #626 silent-refusal class this test exists to catch.
    let strong = [
        "cc",
        "-c",
        "tu.c",
        "-o",
        "tu.o",
        "-fstack-protector-strong",
        "-O0",
        "-g0",
    ];
    run_kache_cc(work.path(), cache_dir.path(), &strong);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "probe-keyed flag was passed through instead of cached on a \
         gcc/clang-family driver (#626).\n`cc -###` said:\n{}\nevents.jsonl:\n{}",
        cc_probe_stderr_head(work.path(), &strong[1..]),
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );

    // The entry must be real: the same compile hits it. The output is
    // removed before every re-run — an existing output file takes the #645
    // passthrough path and would never consult the cache.
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &strong);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // Two values of one probe-keyed knob must key differently. `-fwrapv` /
    // `-fno-wrapv` are both `CapturedByProbe` (the stem list covers both
    // polarities) and both clang and gcc resolve them to different cc1
    // streams. Asserted as "local_hits did not grow", not "misses grew": a
    // distinct key whose object comes out byte-identical records as a `dup`,
    // and a false HIT is the only wrong answer (see the #580 test's note).
    let wrapv = ["cc", "-c", "tu.c", "-o", "tu.o", "-fwrapv", "-O0", "-g0"];
    let no_wrapv = ["cc", "-c", "tu.c", "-o", "tu.o", "-fno-wrapv", "-O0", "-g0"];
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &wrapv);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(1),
        "-fwrapv must not hit the -fstack-protector-strong entry: {report}"
    );
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &no_wrapv);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(1),
        "-fno-wrapv must not hit the -fwrapv (or any earlier) entry: {report}"
    );

    // The distinct key stored something reusable: repeating the value hits.
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &no_wrapv);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(2),
        "repeated -fno-wrapv compile should hit its own entry: {report}"
    );

    // Key-level proof, straight from the events: five compiles, three flag
    // sets, exactly three distinct cache keys.
    let events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    assert_eq!(events.len(), 5, "expected one event per compile: {report}");
    let keys: std::collections::BTreeSet<&str> = events
        .iter()
        .map(|e| {
            let key = e["cache_key"].as_str().unwrap_or_default();
            assert!(!key.is_empty(), "every event should carry a cache key: {e}");
            key
        })
        .collect();
    assert_eq!(
        keys.len(),
        3,
        "each probe-keyed flag value must map to its own cache key: {report}"
    );
}

/// Regression for #645. Existing output symlink semantics differ by compiler:
/// GCC writes through the link, while some clang versions replace it. Kache
/// must passthrough and match the selected compiler instead of unlinking first.
#[cfg(unix)]
#[test]
fn test_cc_existing_symlink_output_matches_selected_compiler() {
    use std::os::unix::fs::symlink;

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let control = project.path().join("control");
    let seed = project.path().join("seed");
    let wrapped = project.path().join("wrapped");
    std::fs::create_dir_all(&control).unwrap();
    std::fs::create_dir_all(&seed).unwrap();
    std::fs::create_dir_all(&wrapped).unwrap();

    let source = project.path().join("foo.c");
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();
    let control_target = control.join("real.o");
    let control_output = control.join("link.o");
    let wrapped_target = wrapped.join("real.o");
    let wrapped_output = wrapped.join("link.o");
    for target in [&control_target, &wrapped_target] {
        std::fs::write(target, b"original").unwrap();
    }
    symlink("real.o", &control_output).unwrap();
    symlink("real.o", &wrapped_output).unwrap();

    let plain = std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(&control_output)
        .args(["-O0", "-g0"])
        .output()
        .expect("failed to run control cc");
    assert!(
        plain.status.success(),
        "control cc failed: {}",
        String::from_utf8_lossy(&plain.stderr)
    );

    let source_str = source.to_string_lossy().into_owned();
    let seed_output = seed.join("link.o");
    let seed_output_str = seed_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &[
            "cc",
            "-c",
            &source_str,
            "-o",
            &seed_output_str,
            "-O0",
            "-g0",
        ],
    );
    assert!(seed_output.is_file(), "seed compile must produce an object");

    // The seed has the same source, flags, and output basename, so it creates
    // the entry this invocation would hit if the symlink-specific refusal were
    // accidentally bypassed. The wrapper must still run the selected compiler.
    let wrapped_output_str = wrapped_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &[
            "cc",
            "-c",
            &source_str,
            "-o",
            &wrapped_output_str,
            "-O0",
            "-g0",
        ],
    );

    let control_is_symlink = std::fs::symlink_metadata(&control_output)
        .unwrap()
        .file_type()
        .is_symlink();
    let wrapped_is_symlink = std::fs::symlink_metadata(&wrapped_output)
        .unwrap()
        .file_type()
        .is_symlink();
    assert_eq!(
        wrapped_is_symlink, control_is_symlink,
        "kache must preserve the selected compiler's symlink semantics"
    );
    assert_eq!(
        std::fs::read(&wrapped_target).unwrap() != b"original",
        std::fs::read(&control_target).unwrap() != b"original",
        "kache and the control compiler must update the same referent"
    );

    let report = kache_report(cache_dir.path());
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
    assert_cc_report_counts(&report, 1, 0);
}

/// Read-only regular files are user-owned, not evidence of a Kache restore.
/// Normal and disabled wrapper paths must produce the selected compiler's
/// status and leave/replace the directory entry exactly as that compiler does.
#[cfg(unix)]
#[test]
fn test_cc_existing_readonly_output_matches_selected_compiler() {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    fn prepare(path: &Path) -> std::fs::File {
        std::fs::write(path, b"user-owned").unwrap();
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o444)).unwrap();
        // Keep the original inode alive so a remove-and-recreate compiler
        // cannot immediately receive the same inode number and look like an
        // in-place write (observed on ext4 in Linux CI).
        std::fs::File::open(path).unwrap()
    }

    fn state(path: &Path, before: &std::fs::File) -> (bool, bool, bool, u32) {
        let Ok(meta) = std::fs::metadata(path) else {
            return (false, false, true, 0);
        };
        let before = before.metadata().unwrap();
        (
            true,
            (meta.dev(), meta.ino()) == (before.dev(), before.ino()),
            std::fs::read(path).unwrap() != b"user-owned",
            meta.permissions().mode() & 0o777,
        )
    }

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let control_dir = project.path().join("control");
    let seed_dir = project.path().join("seed");
    let wrapped_dir = project.path().join("wrapped");
    let disabled_dir = project.path().join("disabled");
    for dir in [&control_dir, &seed_dir, &wrapped_dir, &disabled_dir] {
        std::fs::create_dir_all(dir).unwrap();
    }
    let source = project.path().join("foo.c");
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();
    let source_str = source.to_string_lossy().into_owned();

    let seed_output = seed_dir.join("output.o");
    let seed_str = seed_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &["cc", "-c", &source_str, "-o", &seed_str, "-O0", "-g0"],
    );

    let control_output = control_dir.join("output.o");
    let control_before = prepare(&control_output);
    let plain = std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(&control_output)
        .args(["-O0", "-g0"])
        .output()
        .expect("failed to run control cc");
    let plain_state = state(&control_output, &control_before);

    let wrapped_output = wrapped_dir.join("output.o");
    let wrapped_before = prepare(&wrapped_output);
    let wrapped = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["cc", "-c"])
    .arg(&source)
    .arg("-o")
    .arg(&wrapped_output)
    .args(["-O0", "-g0"])
    .current_dir(project.path())
    .output()
    .expect("failed to run wrapped cc");

    assert_eq!(wrapped.status.code(), plain.status.code());
    assert_eq!(state(&wrapped_output, &wrapped_before), plain_state);
    let report = kache_report(cache_dir.path());
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
    assert_cc_report_counts(&report, 1, 0);

    let disabled_output = disabled_dir.join("output.o");
    let disabled_before = prepare(&disabled_output);
    let disabled = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["cc", "-c"])
    .arg(&source)
    .arg("-o")
    .arg(&disabled_output)
    .args(["-O0", "-g0"])
    .current_dir(project.path())
    .env("KACHE_DISABLED", "1")
    .output()
    .expect("failed to run disabled wrapped cc");
    assert_eq!(disabled.status.code(), plain.status.code());
    assert_eq!(state(&disabled_output, &disabled_before), plain_state);
}

/// Refused C/C++ invocations are a true process passthrough: byte streams and
/// exit status must not be buffered through UTF-8 conversion.
#[cfg(unix)]
#[test]
fn test_cc_passthrough_preserves_non_utf8_streams_and_exit_status() {
    use std::os::unix::fs::PermissionsExt;

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let shell = std::process::Command::new("sh")
        .args(["-c", "command -v sh"])
        .output()
        .expect("sh must be available on PATH");
    assert!(shell.status.success());
    let shell = String::from_utf8(shell.stdout).unwrap();
    let fake_cc = project.path().join("cc");
    std::fs::write(
        &fake_cc,
        format!(
            "#!{}\nprintf '\\377'\nprintf '\\376' >&2\nexit 7\n",
            shell.trim()
        ),
    )
    .unwrap();
    std::fs::set_permissions(&fake_cc, std::fs::Permissions::from_mode(0o755)).unwrap();
    let output_path = project.path().join("existing.o");
    std::fs::write(&output_path, b"existing").unwrap();

    let output = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .arg(&fake_cc)
    .args(["-c", "foo.c", "-o"])
    .arg(&output_path)
    .current_dir(project.path())
    .env_remove("KACHE_LOG")
    .env_remove("KACHE_PROGRESS")
    .output()
    .expect("failed to run kache cc passthrough");

    assert_eq!(output.status.code(), Some(7));
    assert_eq!(output.stdout, [0xff]);
    assert_eq!(output.stderr, [0xfe]);
    assert_eq!(std::fs::read(&output_path).unwrap(), b"existing");
}

/// A writable hardlinked `-o` needs the selected compiler's overwrite
/// semantics just like a symlink. Even with a matching cache entry present,
/// kache must passthrough instead of unlinking one name of the hardlink pair.
#[cfg(unix)]
#[test]
fn test_cc_existing_writable_hardlink_output_matches_selected_compiler() {
    use std::os::unix::fs::MetadataExt;

    fn reset_pair(referent: &Path, output: &Path) {
        if output.exists() {
            std::fs::remove_file(output).unwrap();
        }
        if referent.exists() {
            std::fs::remove_file(referent).unwrap();
        }
        std::fs::write(referent, b"original").unwrap();
        std::fs::hard_link(referent, output).unwrap();
        let meta = std::fs::metadata(output).unwrap();
        assert!(!meta.permissions().readonly());
        assert_eq!(meta.nlink(), 2);
    }

    fn link_state(referent: &Path, output: &Path) -> (bool, u64, u64) {
        let referent_meta = std::fs::metadata(referent).unwrap();
        let output_meta = std::fs::metadata(output).unwrap();
        (
            (referent_meta.dev(), referent_meta.ino()) == (output_meta.dev(), output_meta.ino()),
            referent_meta.nlink(),
            output_meta.nlink(),
        )
    }

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let seed_dir = project.path().join("seed");
    let hardlink_dir = project.path().join("hardlink");
    std::fs::create_dir_all(&seed_dir).unwrap();
    std::fs::create_dir_all(&hardlink_dir).unwrap();
    let source = project.path().join("foo.c");
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();

    let source_str = source.to_string_lossy().into_owned();
    let seed_output = seed_dir.join("output.o");
    let seed_output_str = seed_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &[
            "cc",
            "-c",
            &source_str,
            "-o",
            &seed_output_str,
            "-O0",
            "-g0",
        ],
    );

    let referent = hardlink_dir.join("real.o");
    let output = hardlink_dir.join("output.o");
    let output_str = output.to_string_lossy().into_owned();
    reset_pair(&referent, &output);
    let plain = std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(&output)
        .args(["-O0", "-g0"])
        .output()
        .expect("failed to run control cc");
    assert!(
        plain.status.success(),
        "control cc failed: {}",
        String::from_utf8_lossy(&plain.stderr)
    );
    let plain_state = link_state(&referent, &output);
    let plain_referent = std::fs::read(&referent).unwrap();

    reset_pair(&referent, &output);
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &["cc", "-c", &source_str, "-o", &output_str, "-O0", "-g0"],
    );

    assert_eq!(
        link_state(&referent, &output),
        plain_state,
        "kache must preserve the selected compiler's hardlink semantics"
    );
    assert_eq!(
        std::fs::read(&referent).unwrap(),
        plain_referent,
        "kache and the control compiler must leave identical referent bytes"
    );

    let report = kache_report(cache_dir.path());
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
    assert_cc_report_counts(&report, 1, 0);
}

/// Read-only hardlinks are no more Kache-owned than writable hardlinks. The
/// wrapper must not unlink one name before the selected compiler sees it.
#[cfg(unix)]
#[test]
fn test_cc_existing_readonly_hardlink_output_matches_selected_compiler() {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    fn prepare(dir: &Path) -> (PathBuf, PathBuf, (u64, u64)) {
        let referent = dir.join("real.o");
        let output = dir.join("output.o");
        std::fs::write(&referent, b"user-owned").unwrap();
        std::fs::hard_link(&referent, &output).unwrap();
        std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o444)).unwrap();
        let meta = std::fs::metadata(&output).unwrap();
        (referent, output, (meta.dev(), meta.ino()))
    }

    fn state(referent: &Path, output: &Path, before: (u64, u64)) -> (bool, bool, u64, bool, u32) {
        let referent_meta = std::fs::metadata(referent).unwrap();
        let output_meta = std::fs::metadata(output).unwrap();
        (
            (referent_meta.dev(), referent_meta.ino()) == (output_meta.dev(), output_meta.ino()),
            (output_meta.dev(), output_meta.ino()) == before,
            output_meta.nlink(),
            std::fs::read(referent).unwrap() != b"user-owned",
            output_meta.permissions().mode() & 0o777,
        )
    }

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let control_dir = project.path().join("control");
    let seed_dir = project.path().join("seed");
    let wrapped_dir = project.path().join("wrapped");
    for dir in [&control_dir, &seed_dir, &wrapped_dir] {
        std::fs::create_dir_all(dir).unwrap();
    }
    let source = project.path().join("foo.c");
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();
    let source_str = source.to_string_lossy().into_owned();
    let seed_output = seed_dir.join("output.o");
    let seed_str = seed_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &["cc", "-c", &source_str, "-o", &seed_str, "-O0", "-g0"],
    );

    let (control_referent, control_output, control_before) = prepare(&control_dir);
    let plain = std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(&control_output)
        .args(["-O0", "-g0"])
        .output()
        .expect("failed to run control cc");
    let plain_state = state(&control_referent, &control_output, control_before);

    let (wrapped_referent, wrapped_output, wrapped_before) = prepare(&wrapped_dir);
    let wrapped = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["cc", "-c"])
    .arg(&source)
    .arg("-o")
    .arg(&wrapped_output)
    .args(["-O0", "-g0"])
    .current_dir(project.path())
    .output()
    .expect("failed to run wrapped cc");

    assert_eq!(wrapped.status.code(), plain.status.code());
    assert_eq!(
        state(&wrapped_referent, &wrapped_output, wrapped_before),
        plain_state
    );
    let report = kache_report(cache_dir.path());
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
    assert_cc_report_counts(&report, 1, 0);
}

/// Exact device-node regression for #645. Run only as the current non-root
/// process: the broken implementation attempted to unlink `/dev/null`, so a
/// root test of the pre-fix code would damage its own test environment.
#[cfg(unix)]
#[test]
fn test_cc_dev_null_output_is_passthrough_and_preserved() {
    use std::os::unix::fs::{FileTypeExt, MetadataExt};

    if unsafe { libc::geteuid() } == 0 {
        eprintln!("skipping /dev/null regression as root");
        return;
    }

    let dev_null = Path::new("/dev/null");
    let before = std::fs::symlink_metadata(dev_null).expect("stat /dev/null before compile");
    assert!(
        before.file_type().is_char_device(),
        "precondition: /dev/null must be a character device"
    );
    let before_identity = (before.dev(), before.ino(), before.rdev(), before.mode());

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(project.path().join("foo.c"), "int f(void) { return 42; }\n").unwrap();

    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &["cc", "-c", "foo.c", "-o", "/dev/null", "-O0", "-g0"],
    );

    let after = std::fs::symlink_metadata(dev_null).expect("stat /dev/null after compile");
    assert!(
        after.file_type().is_char_device(),
        "kache must not replace /dev/null with a regular file"
    );
    assert_eq!(
        (after.dev(), after.ino(), after.rdev(), after.mode()),
        before_identity,
        "kache must not unlink, replace, or chmod /dev/null"
    );

    let report = kache_report(cache_dir.path());
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
    assert_cc_report_counts(&report, 0, 0);
    let refusal_reasons = report["bypass"]["reasons"]
        .as_array()
        .expect("report should include passthrough reasons");
    assert!(
        refusal_reasons.iter().any(|entry| {
            entry["reason"]
                .as_str()
                .is_some_and(|reason| reason.contains("requires compiler write semantics"))
        }),
        "report must attribute /dev/null passthrough to output-path safety: {report}"
    );
}

/// C/C++ cache materialization must never recreate the read-only/shared shape
/// that forced unsafe pre-cleaning. A private writable output remains cacheable,
/// while every restored output remains independently compiler-writable.
#[cfg(unix)]
#[test]
fn test_cc_cache_output_stays_writable_across_miss_hit_and_recompile() {
    use std::os::unix::fs::PermissionsExt;

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let source = project.path().join("foo.c");
    let output = project.path().join("foo.o");
    std::fs::write(&source, "int f(void) { return 1; }\n").unwrap();

    let source_str = source.to_string_lossy().into_owned();
    let output_str = output.to_string_lossy().into_owned();
    let args = ["cc", "-c", &source_str, "-o", &output_str, "-O0", "-g0"];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    let miss_mode = std::fs::metadata(&output).unwrap().permissions().mode() & 0o777;
    assert_ne!(miss_mode & 0o200, 0, "miss output must stay owner-writable");

    std::fs::remove_file(&output).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let hit_mode = std::fs::metadata(&output).unwrap().permissions().mode() & 0o777;
    assert_eq!(hit_mode, miss_mode, "hit must restore the compiler's mode");
    assert_ne!(hit_mode & 0o200, 0, "hit output must be owner-writable");

    std::fs::write(&source, "int f(void) { return 2002; }\n").unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert_ne!(
        std::fs::metadata(&output).unwrap().permissions().mode() & 0o200,
        0,
        "compiler must overwrite the warm output without unsafe pre-clean"
    );

    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 2, 1);
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(0));
}

/// Regression for #744: an ordinary compiler-owned object remains cacheable
/// when the build system leaves it in place. This covers both halves of the
/// regression: a matching key may replace the stale object from cache, and a
/// configuration change must compile and store rather than pass through.
#[test]
fn test_cc_existing_plain_output_hits_and_reconfigured_miss_is_stored() {
    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let source = project.path().join("foo.c");
    let output = project.path().join("foo.o");
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();

    let source_str = source.to_string_lossy().into_owned();
    let output_str = output.to_string_lossy().into_owned();
    let o0 = ["cc", "-c", &source_str, "-o", &output_str, "-O0", "-g0"];
    let o2 = ["cc", "-c", &source_str, "-o", &output_str, "-O2", "-g0"];

    run_kache_cc(project.path(), cache_dir.path(), &o0);
    let cached_o0 = std::fs::read(&output).unwrap();

    std::fs::write(&output, b"stale ordinary object").unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &o0);
    assert_eq!(
        std::fs::read(&output).unwrap(),
        cached_o0,
        "an existing private regular object must be replaceable on a cache hit"
    );

    run_kache_cc(project.path(), cache_dir.path(), &o2);
    std::fs::remove_file(&output).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &o2);

    let report = kache_report(cache_dir.path());
    let summary = &report["summary"];
    assert_eq!(summary["local_hits"].as_u64(), Some(2));
    assert_eq!(summary["passthroughs"].as_u64(), Some(0));
    assert_eq!(
        summary["misses"].as_u64().unwrap_or(0) + summary["dups"].as_u64().unwrap_or(0),
        2,
        "both cold configurations must be admitted to the cache"
    );
}

/// A cache hit must not create an output directory that the selected compiler
/// would reject as missing.
#[cfg(unix)]
#[test]
fn test_cc_hit_preserves_missing_parent_failure() {
    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let source = project.path().join("foo.c");
    let seed_dir = project.path().join("seed");
    std::fs::create_dir(&seed_dir).unwrap();
    std::fs::write(&source, "int f(void) { return 42; }\n").unwrap();
    let source_str = source.to_string_lossy().into_owned();
    let seed_output = seed_dir.join("foo.o");
    let seed_str = seed_output.to_string_lossy().into_owned();
    run_kache_cc(
        project.path(),
        cache_dir.path(),
        &["cc", "-c", &source_str, "-o", &seed_str, "-O0", "-g0"],
    );

    let control_parent = project.path().join("missing-control");
    let control_output = control_parent.join("foo.o");
    let plain = std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(&control_output)
        .args(["-O0", "-g0"])
        .output()
        .expect("failed to run control cc");

    let wrapped_parent = project.path().join("missing-wrapped");
    let wrapped_output = wrapped_parent.join("foo.o");
    let wrapped = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["cc", "-c"])
    .arg(&source)
    .arg("-o")
    .arg(&wrapped_output)
    .args(["-O0", "-g0"])
    .current_dir(project.path())
    .output()
    .expect("failed to run wrapped cc");

    assert_eq!(wrapped.status.code(), plain.status.code());
    assert!(!control_parent.exists());
    assert!(!wrapped_parent.exists());
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 0);
    assert_eq!(report["summary"]["passthroughs"].as_u64(), Some(1));
}

/// Relative dep-info can require no content transform, so the raw blob restore
/// path must still produce independent outputs with the current invocation's
/// umask, not the producer's cached mode.
#[cfg(unix)]
#[test]
fn test_cc_relative_depinfo_stays_writable_across_repeated_hits() {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    use std::os::unix::process::CommandExt;

    fn run_with_umask(project: &Path, cache_dir: &Path, args: &[&str], mask: u32) {
        let mut command = hermetic_command(
            kache_binary(),
            cache_dir,
            Some(&isolated_config_path(cache_dir)),
        );
        command
            .args(args)
            .current_dir(project)
            .env("KACHE_LOG", "kache=debug");
        // SAFETY: pre_exec runs after fork in the child, and umask is an
        // async-signal-safe syscall that changes only that child process.
        unsafe {
            command.pre_exec(move || {
                libc::umask(mask as libc::mode_t);
                Ok(())
            });
        }
        let output = command.output().expect("failed to run kache cc");
        assert!(
            output.status.success(),
            "kache cc failed.\nargs: {args:?}\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    }

    build_kache();
    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::create_dir(project.path().join("build")).unwrap();
    std::fs::write(project.path().join("foo.c"), "int f(void) { return 42; }\n").unwrap();
    let args = [
        "cc",
        "-c",
        "foo.c",
        "-MMD",
        "-MF",
        "build/foo.d",
        "-o",
        "build/foo.o",
        "-O0",
        "-g0",
    ];
    let object = project.path().join("build/foo.o");
    let depinfo = project.path().join("build/foo.d");

    run_with_umask(project.path(), cache_dir.path(), &args, 0o000);
    let miss_modes = (
        std::fs::metadata(&object).unwrap().permissions().mode() & 0o777,
        std::fs::metadata(&depinfo).unwrap().permissions().mode() & 0o777,
    );
    assert_eq!(miss_modes, (0o666, 0o666));

    std::fs::remove_file(&object).unwrap();
    std::fs::remove_file(&depinfo).unwrap();
    run_with_umask(project.path(), cache_dir.path(), &args, 0o077);
    for path in [&object, &depinfo] {
        let meta = std::fs::metadata(path).unwrap();
        assert_eq!(meta.permissions().mode() & 0o777, 0o600);
        assert_eq!(
            meta.nlink(),
            1,
            "{} must not share a blob inode",
            path.display()
        );
    }

    std::fs::remove_file(&object).unwrap();
    std::fs::remove_file(&depinfo).unwrap();
    run_with_umask(project.path(), cache_dir.path(), &args, 0o022);
    for path in [&object, &depinfo] {
        let meta = std::fs::metadata(path).unwrap();
        assert_eq!(meta.permissions().mode() & 0o777, 0o644);
        assert_eq!(meta.nlink(), 1);
    }

    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 2);
}

/// aws-lc-sys drives BoringSSL symbol prefixing with
/// `--include=<generated-include>/boringssl_prefix_symbols*.h` and compiles
/// jitterentropy with `-fwrapv --param ssp-buffer-size=4`. Unclassified,
/// those flags sent ~62 TUs through as passthrough, so the archive they land
/// in differed per checkout and the `extern:` content hash re-keyed the whole
/// rustls/TLS subtree above it (#580).
///
/// Two project dirs share one cache and one forced-include header — the
/// registry-path shape, where the header is stable across checkouts but the
/// source dir is not. The second dir must hit the first dir's entry.
#[test]
fn test_cc_forced_include_and_param_converge_across_clones_issue_580() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_gnu_forced_include(probe_dir.path()) {
        eprintln!(
            "skipping: `cc` does not accept --include=/-fwrapv/--param \
             (cl-like driver, or no cc on PATH)"
        );
        return;
    }
    build_kache();
    // Two of the flags under test are probe-keyed, so a host that cannot
    // resolve `cc -###` refuses to cache them however they are classified.
    // That is a pre-existing platform gap (see the message this prints), not
    // something the classification change can fix.
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }

    let cache_dir = TempDir::new().unwrap();
    // Stands in for `$CARGO_HOME/registry/src/…/generated-include` — one
    // absolute path both clones pass verbatim.
    let shared = TempDir::new().unwrap();
    let prefix_header = shared.path().join("boringssl_prefix_symbols.h");
    std::fs::write(&prefix_header, "#define AWS_LC_PFX(name) pfx_##name\n").unwrap();

    let source = "#if !defined(AWS_LC_PFX)\n#error \"forced include did not apply\"\n#endif\n\
         int AWS_LC_PFX(add_one)(int a) { return a + 1; }\n";

    let clone_a = TempDir::new().unwrap();
    let clone_b = TempDir::new().unwrap();
    for clone in [&clone_a, &clone_b] {
        std::fs::write(clone.path().join("bcm.c"), source).unwrap();
    }

    let forced_include = format!("--include={}", prefix_header.display());
    let args = [
        "cc",
        "-c",
        "bcm.c",
        "-o",
        "bcm.o",
        &forced_include,
        "-fwrapv",
        "--param",
        "ssp-buffer-size=4",
        "-O0",
        "-g0",
    ];

    // Cold: compiles and stores. A passthrough would record neither, so the
    // miss count is what proves the flags classified at all.
    run_kache_cc(clone_a.path(), cache_dir.path(), &args);
    assert!(clone_a.path().join("bcm.o").exists());
    let report = kache_report(cache_dir.path());
    // Named assertion with the raw event log attached: "left: Some(0), right:
    // Some(1)" says nothing about WHY kache declined, and the reason (a
    // passthrough reason string, an unresolvable `-###` probe) is the whole
    // content of a failure here.
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold compile must be cached, not passed through.\nevents.jsonl:\n{}",
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );
    assert_cc_report_counts(&report, 1, 0);

    // Different source dir, same content and same forced-include path.
    run_kache_cc(clone_b.path(), cache_dir.path(), &args);
    assert!(clone_b.path().join("bcm.o").exists());
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // The opposite `-fwrapv` polarity must NOT hit — both clang and gcc
    // resolve the two spellings to different cc1 token streams, so this
    // guards the missed-polarity class of #422/#426 on the flag added here.
    //
    // Asserted as "local_hits did not grow", not "misses grew": a distinct
    // key whose object comes out byte-identical (as it does for this TU under
    // clang, where wrapping semantics change nothing about `a + 1`) is
    // recorded as a `dup`, not a miss. Either bucket is correct — a false HIT
    // is the only wrong answer, so that is what the assertion pins.
    //
    // Note what is deliberately NOT asserted: that a changed `--param` VALUE
    // misses. gcc forwards `--param=<name>=<value>` to cc1 (so it does miss
    // there), but clang drops the option before cc1 — and also ignores it, so
    // the objects are identical and the hit is correct rather than lossy. The
    // gcc side of that premise is pinned on a frozen `-###` fixture in
    // `probe::resolve` instead of on whichever compiler runs this test.
    let no_wrapv = [
        "cc",
        "-c",
        "bcm.c",
        "-o",
        "bcm.o",
        &forced_include,
        "-fno-wrapv",
        "--param",
        "ssp-buffer-size=4",
        "-O0",
        "-g0",
    ];
    std::fs::remove_file(clone_a.path().join("bcm.o")).unwrap();
    run_kache_cc(clone_a.path(), cache_dir.path(), &no_wrapv);
    let report = kache_report(cache_dir.path());
    let summary = &report["summary"];
    assert_eq!(
        summary["local_hits"].as_u64(),
        Some(1),
        "-fno-wrapv must not reuse the -fwrapv entry: {report}"
    );
    assert_eq!(
        summary["misses"].as_u64().unwrap_or(0) + summary["dups"].as_u64().unwrap_or(0),
        2,
        "-fno-wrapv should have compiled under its own key: {report}"
    );
}

/// cc-rs emits `-mno-omit-leaf-frame-pointer` when Rust requests forced
/// frame pointers (and in debug-mode tool setup), so every aws-lc-sys TU of
/// a macOS debug build passed through on it (#839). The flag is
/// `CapturedByProbe`: clang's `-###` resolves it to `-mframe-pointer=all`
/// against the default `-mframe-pointer=non-leaf`, so the resolved-token
/// hash must key the two codegen modes apart.
///
/// Gated like the other probe-keyed tests: a driver that rejects the flag or
/// a host whose `cc -###` cannot resolve skips rather than false-fails.
#[test]
fn test_cc_no_omit_leaf_frame_pointer_keys_on_probe_issue_839() {
    let probe_dir = TempDir::new().unwrap();
    let gate_src = probe_dir.path().join("gate.c");
    std::fs::write(&gate_src, "int gate(void) { return 0; }\n").unwrap();
    let accepts = std::process::Command::new("cc")
        .arg("-c")
        .arg(&gate_src)
        .arg("-o")
        .arg(probe_dir.path().join("gate.o"))
        .args(["-mno-omit-leaf-frame-pointer", "-O0", "-g0"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if !accepts {
        eprintln!("skipping: `cc` does not accept -mno-omit-leaf-frame-pointer");
        return;
    }
    build_kache();
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }

    let work = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(work.path().join("tu.c"), "int tu(void) { return 7; }\n").unwrap();

    // Cold: compiles and stores. A passthrough records no miss, so this is
    // what proves the flag classified at all.
    let flagged = [
        "cc",
        "-c",
        "tu.c",
        "-o",
        "tu.o",
        "-mno-omit-leaf-frame-pointer",
        "-O0",
        "-g0",
    ];
    run_kache_cc(work.path(), cache_dir.path(), &flagged);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold -mno-omit-leaf-frame-pointer compile must be cached, not passed \
         through.\n`cc -###` said:\n{}\nevents.jsonl:\n{}",
        cc_probe_stderr_head(work.path(), &flagged[1..]),
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );

    // The entry is real: the same compile hits it.
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &flagged);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // The default frame-pointer mode must NOT hit the flagged entry: clang
    // resolves the two to `-mframe-pointer=all` vs `-mframe-pointer=non-leaf`
    // in the cc1 stream, so a false hit would mean the probe under-keys a
    // codegen difference. Asserted as "local_hits did not grow" (a distinct
    // key with byte-identical output records as a `dup`, not a miss).
    let default_mode = ["cc", "-c", "tu.c", "-o", "tu.o", "-O0", "-g0"];
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &default_mode);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(1),
        "default -mframe-pointer=non-leaf must not hit the \
         -mno-omit-leaf-frame-pointer entry: {report}"
    );

    // Key-level proof from the events: three compiles, two flag modes,
    // exactly two distinct cache keys.
    let events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    assert_eq!(events.len(), 3, "expected one event per compile: {report}");
    let keys: std::collections::BTreeSet<&str> = events
        .iter()
        .map(|e| {
            let key = e["cache_key"].as_str().unwrap_or_default();
            assert!(!key.is_empty(), "every event should carry a cache key: {e}");
            key
        })
        .collect();
    assert_eq!(
        keys.len(),
        2,
        "the two frame-pointer modes must map to distinct cache keys: {report}"
    );
}

/// True if `cc` on PATH accepts `-fsanitize-undefined-strip-path-components=-1`,
/// checked by actually compiling with it. The option is clang-only — gcc
/// rejects it, and aws-lc-sys itself adds it only after a compiler support
/// probe — so a driver that rejects it has nothing to say about #840.
fn cc_accepts_ubsan_strip_path_components(dir: &Path) -> bool {
    let source = dir.join("ubsan-strip-probe.c");
    if std::fs::write(&source, "int ubsan_strip_probe(void) { return 0; }\n").is_err() {
        return false;
    }
    std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(dir.join("ubsan-strip-probe.o"))
        .args(["-fsanitize-undefined-strip-path-components=-1", "-O0"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Live end-to-end for #840: aws-lc-sys 0.44 compiles its jitterentropy TUs
/// with `-fsanitize-undefined-strip-path-components=-1` on clang. The flag
/// must not refuse an otherwise cacheable compile, and because its only
/// keying is the resolved `-cc1` token, absence of the flag must key apart
/// from its presence.
#[test]
fn test_cc_ubsan_strip_path_components_caches_issue_840() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_ubsan_strip_path_components(probe_dir.path()) {
        eprintln!(
            "skipping: `cc` does not accept \
             -fsanitize-undefined-strip-path-components=-1 \
             (non-clang driver, or no cc on PATH)"
        );
        return;
    }
    build_kache();
    // The flag is probe-keyed, so a host that cannot resolve `cc -###`
    // refuses to cache it however it is classified (see the message this
    // gate prints). Pre-existing platform gap, not something the
    // classification change can fix.
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }

    let work = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(work.path().join("je.c"), "int je(void) { return 0; }\n").unwrap();

    let with_flag = [
        "cc",
        "-c",
        "je.c",
        "-o",
        "je.o",
        "-fsanitize-undefined-strip-path-components=-1",
        "-O0",
        "-g0",
    ];
    // Cold: compiles and stores. A passthrough would record neither, so the
    // miss count is what proves the flag classified at all. Attach the raw
    // event log — the refusal reason is the whole content of a failure here.
    run_kache_cc(work.path(), cache_dir.path(), &with_flag);
    assert!(work.path().join("je.o").exists());
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold compile with the #840 flag must be cached, not passed through.\nevents.jsonl:\n{}",
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );

    // The entry must be real: the same compile hits it.
    std::fs::remove_file(work.path().join("je.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &with_flag);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // Absence of the flag must NOT hit — clang leaves the token out of the
    // resolved cc1 stream, so the no-flag compile is a different key.
    // Asserted as "local_hits did not grow", not "misses grew": the flag
    // only strips UBSan metadata paths and this TU carries none, so the
    // object can come out byte-identical and record as a `dup`. Either
    // bucket is correct — a false HIT is the only wrong answer.
    let without_flag = ["cc", "-c", "je.c", "-o", "je.o", "-O0", "-g0"];
    std::fs::remove_file(work.path().join("je.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &without_flag);
    let report = kache_report(cache_dir.path());
    let summary = &report["summary"];
    assert_eq!(
        summary["local_hits"].as_u64(),
        Some(1),
        "the flag-less compile must not reuse the flagged entry: {report}"
    );
    assert_eq!(
        summary["misses"].as_u64().unwrap_or(0) + summary["dups"].as_u64().unwrap_or(0),
        2,
        "the flag-less compile should have compiled under its own key: {report}"
    );
}

/// True if `cc` on PATH accepts both `-gdwarf-2` and `-gdwarf-4`, checked
/// by actually compiling with each. A cl-like driver rejects the GNU
/// spellings outright and has nothing to say about #838.
fn cc_accepts_gdwarf_versions(dir: &Path) -> bool {
    let source = dir.join("dwarf-support.c");
    if std::fs::write(&source, "int dwarf_support(void) { return 0; }\n").is_err() {
        return false;
    }
    ["-gdwarf-2", "-gdwarf-4"].iter().all(|flag| {
        std::process::Command::new("cc")
            .args(["-c", "-O0"])
            .arg(&source)
            .arg("-o")
            .arg(dir.join("dwarf-support.o"))
            .arg(flag)
            .output()
            .map(|output| output.status.success())
            .unwrap_or(false)
    })
}

/// cc-rs adds `-gdwarf-2` on every Apple target with debug info enabled, so
/// it lands on effectively every native-dep TU of a macOS Rust debug build
/// (#838; aws-lc-sys was the sampled root). Like `-gdwarf-4` (#117) it is
/// `CapturedByProbe`: the resolved cc1 line carries `-dwarf-version=N`, so
/// DWARF 2, DWARF 4 and the no-flag baseline must key apart while identical
/// invocations hit.
#[test]
fn test_cc_gdwarf2_caches_and_keys_dwarf_version_issue_838() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_gdwarf_versions(probe_dir.path()) {
        eprintln!(
            "skipping: `cc` does not accept -gdwarf-2/-gdwarf-4 \
             (cl-like driver, or no cc on PATH)"
        );
        return;
    }

    build_kache();
    // Accepting the driver flags is not enough: a host whose `cc -###`
    // output cannot be resolved should fail closed in production and should
    // not turn this portability test red.
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }
    let cache_dir = TempDir::new().unwrap();
    let work = TempDir::new().unwrap();
    std::fs::write(work.path().join("tu.c"), "int tu(void) { return 7; }\n").unwrap();
    let object = work.path().join("tu.o");

    let compile = |extra: &[&str]| {
        let _ = std::fs::remove_file(&object);
        let mut args = vec!["cc", "-c", "tu.c", "-o", "tu.o", "-O0"];
        args.extend_from_slice(extra);
        run_kache_cc(work.path(), cache_dir.path(), &args);
        assert!(object.exists(), "compile must produce tu.o: {args:?}");
    };

    // Cold: compiles and stores. A passthrough would record neither, so the
    // miss count is what proves `-gdwarf-2` classified at all — attach the
    // raw event log so a failure names the refusal reason.
    compile(&["-gdwarf-2"]);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold -gdwarf-2 compile must be cached, not passed through.\nevents.jsonl:\n{}",
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );
    assert_cc_report_counts(&report, 1, 0);

    // Identical invocation: hit.
    compile(&["-gdwarf-2"]);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // `-gdwarf-4` and the no-flag baseline resolve to different cc1 token
    // streams (`-dwarf-version=4` vs none), so neither may reuse the
    // DWARF-2 entry. Asserted as "local_hits did not grow": a distinct key
    // whose object comes out byte-identical is recorded as a `dup`, not a
    // miss — a false HIT is the only wrong answer.
    for extra in [&["-gdwarf-4"][..], &[][..]] {
        compile(extra);
    }
    let report = kache_report(cache_dir.path());
    let summary = &report["summary"];
    assert_eq!(
        summary["local_hits"].as_u64(),
        Some(1),
        "-gdwarf-4 / no-flag must not reuse the -gdwarf-2 entry: {report}"
    );
    assert_eq!(
        summary["misses"].as_u64().unwrap_or(0) + summary["dups"].as_u64().unwrap_or(0),
        3,
        "-gdwarf-4 and no-flag should have compiled under their own keys: {report}"
    );

    // Four compiles represent exactly three semantic modes: the repeated
    // DWARF-2 invocation shares its key, while DWARF 4 and the no-flag
    // baseline each have their own. This proves separation directly rather
    // than inferring it only from aggregate hit/miss counters.
    let events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    assert_eq!(events.len(), 4, "expected one event per compile: {report}");
    let keys: std::collections::BTreeSet<&str> = events
        .iter()
        .map(|event| {
            let key = event["cache_key"].as_str().unwrap_or_default();
            assert!(
                !key.is_empty(),
                "every DWARF test event should carry a cache key: {event}"
            );
            key
        })
        .collect();
    assert_eq!(
        keys.len(),
        3,
        "DWARF 2, DWARF 4, and no-flag must map to three cache keys: {report}"
    );
}

/// True if `cc` on PATH accepts `-gfull`, checked by actually compiling
/// with it. GCC and cl-like drivers reject the Apple spelling and have
/// nothing to say about #857.
fn cc_accepts_gfull(dir: &Path) -> bool {
    let source = dir.join("gfull-support.c");
    if std::fs::write(&source, "int gfull_support(void) { return 0; }\n").is_err() {
        return false;
    }
    std::process::Command::new("cc")
        .args(["-c", "-O0"])
        .arg(&source)
        .arg("-o")
        .arg(dir.join("gfull-support.o"))
        .arg("-gfull")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

/// ring adds `-gfull` on Apple ABI targets so Darwin dead stripping can
/// see used symbols (#857). The flag is `CapturedByProbe`: Apple clang
/// `-###` resolves it to `-debug-info-kind=standalone -dwarf-version=5`,
/// so the no-debug baseline must key apart while an identical second
/// compile hits. Where `-g` resolves to the same cc1 tokens it may share
/// the key; this test only requires the no-debug invocation to stay
/// distinct.
#[test]
fn test_cc_gfull_caches_and_keys_apart_from_no_debug_issue_857() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_gfull(probe_dir.path()) {
        eprintln!(
            "skipping: `cc` does not accept -gfull \
             (non-Apple driver, or no cc on PATH)"
        );
        return;
    }

    build_kache();
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }
    let cache_dir = TempDir::new().unwrap();
    let work = TempDir::new().unwrap();
    std::fs::write(work.path().join("tu.c"), "int tu(void) { return 7; }\n").unwrap();
    let object = work.path().join("tu.o");

    let compile = |extra: &[&str]| {
        let _ = std::fs::remove_file(&object);
        let mut args = vec!["cc", "-c", "tu.c", "-o", "tu.o", "-O0"];
        args.extend_from_slice(extra);
        run_kache_cc(work.path(), cache_dir.path(), &args);
        assert!(object.exists(), "compile must produce tu.o: {args:?}");
    };

    compile(&["-gfull"]);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold -gfull compile must be cached, not passed through.\nevents.jsonl:\n{}",
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );
    assert_cc_report_counts(&report, 1, 0);

    compile(&["-gfull"]);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    compile(&[]);
    let report = kache_report(cache_dir.path());
    let summary = &report["summary"];
    assert_eq!(
        summary["local_hits"].as_u64(),
        Some(1),
        "no-debug must not reuse the -gfull entry: {report}"
    );
    assert_eq!(
        summary["misses"].as_u64().unwrap_or(0) + summary["dups"].as_u64().unwrap_or(0),
        2,
        "no-debug should have compiled under its own key: {report}"
    );
}

/// True when the host `cc` accepts Firefox's Clang automatic-variable
/// hardening mode. GCC and older Clang versions may reject it, so they cannot
/// exercise the issue #849 path.
fn cc_accepts_trivial_auto_var_init_pattern(dir: &Path) -> bool {
    let source = dir.join("auto-var-init-probe.c");
    if std::fs::write(
        &source,
        "int auto_var_init_probe(void) { int value; return value; }\n",
    )
    .is_err()
    {
        return false;
    }
    std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(dir.join("auto-var-init-probe.o"))
        .args(["-ftrivial-auto-var-init=pattern", "-O0"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Live end-to-end for #849: the reported Firefox hardening flag must produce
/// a normal cold cache store and warm hit, while the default initialization
/// mode remains a distinct cache key.
#[test]
fn test_cc_trivial_auto_var_init_pattern_caches_issue_849() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_trivial_auto_var_init_pattern(probe_dir.path()) {
        eprintln!("skipping: `cc` does not accept -ftrivial-auto-var-init=pattern");
        return;
    }
    build_kache();
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }

    let work = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(
        work.path().join("tu.c"),
        "int use_auto_var(void) { int value; return value; }\n",
    )
    .unwrap();

    let with_flag = [
        "cc",
        "-c",
        "tu.c",
        "-o",
        "tu.o",
        "-ftrivial-auto-var-init=pattern",
        "-O0",
        "-g0",
    ];
    run_kache_cc(work.path(), cache_dir.path(), &with_flag);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold compile with the #849 flag must be cached, not passed through: {report}"
    );

    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &with_flag);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    let without_flag = ["cc", "-c", "tu.c", "-o", "tu.o", "-O0", "-g0"];
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &without_flag);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(1),
        "the flag-less compile must not reuse the pattern-initialized entry: {report}"
    );
}

/// True when the host `cc` accepts zstd-sys's merge-all-constants knob.
/// gcc and clang both have it; a cl-like driver does not, so a host that
/// rejects the spelling cannot exercise #856.
fn cc_accepts_merge_all_constants(dir: &Path) -> bool {
    let source = dir.join("merge-all-constants-probe.c");
    if std::fs::write(&source, "int merge_probe(void) { return 0; }\n").is_err() {
        return false;
    }
    std::process::Command::new("cc")
        .arg("-c")
        .arg(&source)
        .arg("-o")
        .arg(dir.join("merge-all-constants-probe.o"))
        .args(["-fmerge-all-constants", "-O0", "-g0"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Live end-to-end for #856: zstd-sys's `-fmerge-all-constants` must cache,
/// hit on an identical second compile, and stay keyed apart from the
/// default mode. `-fno-merge-all-constants` is accepted and may share the
/// default key when the resolved tokens are identical.
#[test]
fn test_cc_merge_all_constants_keys_on_probe_issue_856() {
    let probe_dir = TempDir::new().unwrap();
    if !cc_accepts_merge_all_constants(probe_dir.path()) {
        eprintln!("skipping: `cc` does not accept -fmerge-all-constants");
        return;
    }
    build_kache();
    if !kache_caches_probe_keyed_flags(probe_dir.path()) {
        eprintln!("skipping: probe-keyed flags are not cacheable on this host");
        return;
    }

    let work = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(work.path().join("tu.c"), "int tu(void) { return 7; }\n").unwrap();

    let enabled = [
        "cc",
        "-c",
        "tu.c",
        "-o",
        "tu.o",
        "-fmerge-all-constants",
        "-O0",
        "-g0",
    ];
    run_kache_cc(work.path(), cache_dir.path(), &enabled);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "cold -fmerge-all-constants compile must be cached, not passed \
         through.\n`cc -###` said:\n{}\nevents.jsonl:\n{}",
        cc_probe_stderr_head(work.path(), &enabled[1..]),
        std::fs::read_to_string(cache_dir.path().join("events.jsonl"))
            .unwrap_or_else(|e| format!("(unreadable: {e})"))
    );

    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &enabled);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);

    // Default mode must not reuse the enabled key. Asserted as "local_hits
    // did not grow": the objects can be byte-identical and record as a
    // `dup`. A false HIT is the only wrong answer.
    let default_mode = ["cc", "-c", "tu.c", "-o", "tu.o", "-O0", "-g0"];
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &default_mode);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["local_hits"].as_u64(),
        Some(1),
        "default merge-constants mode must not hit the \
         -fmerge-all-constants entry: {report}"
    );

    // Disabled polarity must classify (not passthrough) and must not reuse
    // the enabled key. It may share the default key when the probe emits no
    // extra token (Apple clang 21).
    let disabled = [
        "cc",
        "-c",
        "tu.c",
        "-o",
        "tu.o",
        "-fno-merge-all-constants",
        "-O0",
        "-g0",
    ];
    std::fs::remove_file(work.path().join("tu.o")).unwrap();
    run_kache_cc(work.path(), cache_dir.path(), &disabled);
    let report = kache_report(cache_dir.path());
    assert_eq!(
        report["summary"]["passthroughs"].as_u64().unwrap_or(0),
        0,
        "-fno-merge-all-constants must cache, not pass through: {report}"
    );

    let events = report["all_events"]
        .as_array()
        .expect("report should include all_events");
    assert_eq!(events.len(), 4, "expected one event per compile: {report}");
    let keys: Vec<&str> = events
        .iter()
        .map(|event| {
            let key = event["cache_key"].as_str().unwrap_or_default();
            assert!(
                !key.is_empty(),
                "every event should carry a cache key: {event}"
            );
            key
        })
        .collect();
    assert_eq!(
        keys[0], keys[1],
        "the repeated enabled compile must reuse its own key: {report}"
    );
    assert_ne!(
        keys[0], keys[2],
        "enabled mode must not reuse the default key: {report}"
    );
    assert_ne!(
        keys[0], keys[3],
        "enabled mode must not reuse the disabled key: {report}"
    );
}

#[test]
fn test_cc_depinfo_sidecar_restores_on_hit_and_new_mf_path() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::create_dir_all(project.path().join("src")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    std::fs::write(
        project.path().join("src/bar.h"),
        "#define BAR_GREETING \"hello depinfo\"\n",
    )
    .unwrap();
    std::fs::write(
        project.path().join("src/foo.c"),
        "#include \"bar.h\"\nconst char *greeting(void) { return BAR_GREETING; }\n",
    )
    .unwrap();

    let base_args = [
        "cc",
        "-O0",
        "-g0",
        "-MMD",
        "-MP",
        "-Isrc",
        "-c",
        "src/foo.c",
        "-o",
        "build/foo.o",
    ];

    run_kache_cc(project.path(), cache_dir.path(), &base_args);
    let cold_depinfo = std::fs::read_to_string(project.path().join("build/foo.d")).unwrap();
    assert!(project.path().join("build/foo.o").exists());
    assert!(cold_depinfo.contains("build/foo.o"));
    assert!(cold_depinfo.contains("src/foo.c"));
    assert!(cold_depinfo.contains("src/bar.h"));
    assert!(!cold_depinfo.contains("./foo.o"));
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 0);
    assert_last_cc_event(&report, "miss", 1);

    std::fs::remove_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &base_args);
    let warm_depinfo = std::fs::read_to_string(project.path().join("build/foo.d")).unwrap();
    assert!(project.path().join("build/foo.o").exists());
    assert_eq!(warm_depinfo, cold_depinfo);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);
    assert_last_cc_event(&report, "local_hit", 0);

    std::fs::remove_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("deps")).unwrap();
    let mf_args = [
        "cc",
        "-O0",
        "-g0",
        "-MMD",
        "-MP",
        "-MF",
        "deps/custom.d",
        "-Isrc",
        "-c",
        "src/foo.c",
        "-o",
        "build/foo.o",
    ];
    run_kache_cc(project.path(), cache_dir.path(), &mf_args);
    let mf_depinfo = std::fs::read_to_string(project.path().join("deps/custom.d")).unwrap();
    assert!(project.path().join("build/foo.o").exists());
    assert!(!project.path().join("build/foo.d").exists());
    assert_eq!(mf_depinfo, cold_depinfo);
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 2);
    assert_last_cc_event(&report, "local_hit", 0);

    let pp_cache_dir = TempDir::new().unwrap();
    let _ = std::fs::remove_dir_all(project.path().join("build"));
    let _ = std::fs::remove_dir_all(project.path().join("deps"));
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("deps")).unwrap();
    let pp_args = [
        "cc",
        "-O0",
        "-g0",
        "-MMD",
        "-MP",
        "-MF",
        "deps/custom.pp",
        "-Isrc",
        "-c",
        "src/foo.c",
        "-o",
        "build/foo.o",
    ];
    run_kache_cc(project.path(), pp_cache_dir.path(), &pp_args);
    let cold_pp_depinfo = std::fs::read_to_string(project.path().join("deps/custom.pp")).unwrap();
    assert!(project.path().join("build/foo.o").exists());
    assert!(cold_pp_depinfo.contains("build/foo.o"));
    assert!(cold_pp_depinfo.contains("src/foo.c"));
    assert!(cold_pp_depinfo.contains("src/bar.h"));
    let report = kache_report(pp_cache_dir.path());
    assert_cc_report_counts(&report, 1, 0);
    assert_last_cc_event(&report, "miss", 1);

    std::fs::remove_dir_all(project.path().join("build")).unwrap();
    std::fs::remove_dir_all(project.path().join("deps")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("deps")).unwrap();
    run_kache_cc(project.path(), pp_cache_dir.path(), &pp_args);
    let warm_pp_depinfo = std::fs::read_to_string(project.path().join("deps/custom.pp")).unwrap();
    assert!(project.path().join("build/foo.o").exists());
    assert_eq!(warm_pp_depinfo, cold_pp_depinfo);
    let report = kache_report(pp_cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);
    assert_last_cc_event(&report, "local_hit", 0);
}

#[test]
fn test_cc_preprocess_memo_skips_warm_probe_and_invalidates_on_header_change() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(project.path().join("value.h"), "#define VALUE 7\n").unwrap();
    std::fs::write(
        project.path().join("foo.c"),
        "#include \"value.h\"\nint value(void) { return VALUE; }\n",
    )
    .unwrap();
    let args = [
        "cc", "-O0", "-g0", "-MMD", "-MF", "foo.d", "-c", "foo.c", "-o", "foo.o",
    ];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 1);

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    std::fs::remove_file(project.path().join("foo.d")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
    assert_last_cc_preprocessor_runs(&report, 0);

    // Different length guarantees a metadata fingerprint change even on a
    // coarse-timestamp filesystem. The stale memo must run the preprocessor,
    // derive a new object key, and compile rather than restore VALUE=7.
    std::fs::write(project.path().join("value.h"), "#define VALUE 12345\n").unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 1);

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    std::fs::remove_file(project.path().join("foo.d")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
    assert_last_cc_preprocessor_runs(&report, 0);
}

#[cfg(unix)]
#[test]
fn test_cc_compound_depinfo_suffix_restores_across_relocated_build_root() {
    build_kache();

    let root = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let clone_a = root.path().join("clone-a");
    let clone_b = root.path().join("clone-b");

    for clone in [&clone_a, &clone_b] {
        std::fs::create_dir_all(clone.join("src")).unwrap();
        std::fs::create_dir_all(clone.join("build")).unwrap();
        std::fs::write(clone.join("src/bar.h"), "#define ANSWER 42\n").unwrap();
        std::fs::write(
            clone.join("src/foo.c"),
            "#include \"bar.h\"\nint answer(void) { return ANSWER; }\n",
        )
        .unwrap();
    }

    // OpenSSL writes dependency data through a temporary compound suffix and
    // then renames it. Absolute paths make the warm compile prove both cache
    // portability and dep-info re-rooting to a recreated build tree.
    let compile_args = |clone: &Path| {
        vec![
            "cc".to_string(),
            "-O0".to_string(),
            "-g0".to_string(),
            "-MMD".to_string(),
            "-MP".to_string(),
            "-MF".to_string(),
            clone.join("build/foo.d.tmp").to_string_lossy().into_owned(),
            "-MT".to_string(),
            "build/foo.o".to_string(),
            format!("-I{}", clone.join("src").display()),
            "-c".to_string(),
            clone.join("src/foo.c").to_string_lossy().into_owned(),
            "-o".to_string(),
            clone.join("build/foo.o").to_string_lossy().into_owned(),
        ]
    };

    let cold_args = compile_args(&clone_a);
    let cold_args_ref: Vec<&str> = cold_args.iter().map(String::as_str).collect();
    run_kache_cc(&clone_a, cache_dir.path(), &cold_args_ref);

    let cold_depinfo = std::fs::read_to_string(clone_a.join("build/foo.d.tmp")).unwrap();
    assert!(clone_a.join("build/foo.o").exists());
    assert!(cold_depinfo.contains("build/foo.o"));
    assert!(cold_depinfo.contains(&clone_a.join("src/foo.c").to_string_lossy().to_string()));
    assert!(cold_depinfo.contains(&clone_a.join("src/bar.h").to_string_lossy().to_string()));
    assert_cc_report_counts(&kache_report(cache_dir.path()), 1, 0);

    let warm_args = compile_args(&clone_b);
    let warm_args_ref: Vec<&str> = warm_args.iter().map(String::as_str).collect();
    run_kache_cc(&clone_b, cache_dir.path(), &warm_args_ref);

    let warm_depinfo = std::fs::read_to_string(clone_b.join("build/foo.d.tmp")).unwrap();
    let expected_warm_depinfo = cold_depinfo.replace(
        &format!("{}/", clone_a.display()),
        &format!("{}/", clone_b.display()),
    );
    assert!(clone_b.join("build/foo.o").exists());
    assert_eq!(
        warm_depinfo, expected_warm_depinfo,
        "restored compound-suffix dep-info must be re-rooted to the warm build"
    );
    assert!(
        !warm_depinfo.contains(&clone_a.to_string_lossy().to_string()),
        "restored dep-info must not retain the cold build root: {warm_depinfo}"
    );

    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);
    assert_last_cc_event(&report, "local_hit", 0);
}

#[cfg(unix)]
#[test]
fn test_cc_legacy_compound_depinfo_entry_self_heals_and_why_miss_explains_it() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::create_dir_all(project.path().join("src")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    std::fs::write(
        project.path().join("src/foo.c"),
        "int answer(void) { return 42; }\n",
    )
    .unwrap();
    let args = [
        "cc",
        "-O0",
        "-g0",
        "-MMD",
        "-MF",
        "build/foo.d.tmp",
        "-c",
        "src/foo.c",
        "-o",
        "build/foo.o",
    ];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    let key = report["all_events"][0]["cache_key"]
        .as_str()
        .expect("cold event should carry its key");

    // Simulate the metadata written by v0.12/v0.13 before #655: the parsed
    // dep-info role was discarded and only OpenSSL's raw `.d.tmp` name
    // survived. Its blob contents remain valid; the old name must nevertheless
    // be rejected once because old versions skipped dep-info normalization.
    let meta_path = cache_dir.path().join("store").join(key).join("meta.json");
    let mut meta: serde_json::Value =
        serde_json::from_slice(&std::fs::read(&meta_path).unwrap()).unwrap();
    let files = meta["files"].as_array_mut().unwrap();
    let depinfo = files
        .iter_mut()
        .find(|file| file["name"] == "__kache_cc_depinfo.d")
        .expect("fixed cold entry should use the semantic dep-info name");
    depinfo["name"] = serde_json::Value::String("foo.d.tmp".to_string());
    std::fs::write(&meta_path, serde_json::to_vec_pretty(&meta).unwrap()).unwrap();

    std::fs::remove_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);

    let why = hermetic_command(
        kache_binary(),
        cache_dir.path(),
        Some(&isolated_config_path(cache_dir.path())),
    )
    .args(["why-miss", "foo.c"])
    .output()
    .expect("failed to run why-miss");
    assert!(why.status.success());
    let stdout = String::from_utf8_lossy(&why.stdout);
    assert!(
        stdout.contains("matching key was found but rejected before restore"),
        "why-miss should report the exact-key rejection: {stdout}"
    );
    assert!(
        stdout.contains("matching entry lacks dep-info required by this invocation"),
        "why-miss should name the missing artifact role: {stdout}"
    );
    assert!(
        !stdout.contains("Diagnosis: key mismatch"),
        "why-miss must not mislabel an exact-key rejection: {stdout}"
    );

    // The rejected legacy entry was replaced in the new format, so the next
    // recreation is a normal warm hit rather than another self-eviction.
    std::fs::remove_dir_all(project.path().join("build")).unwrap();
    std::fs::create_dir_all(project.path().join("build")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert_cc_report_counts(&kache_report(cache_dir.path()), 2, 1);
}

#[test]
fn test_cc_depinfo_restore_preserves_parent_relative_deps() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let source_dir = project.path().join("src");
    let object_dir = project.path().join("obj/a/b/c");
    std::fs::create_dir_all(&source_dir).unwrap();
    std::fs::create_dir_all(object_dir.join(".deps")).unwrap();
    std::fs::write(source_dir.join("bar.h"), "#define VALUE 42\n").unwrap();
    std::fs::write(
        source_dir.join("foo.c"),
        "#include \"bar.h\"\nint answer(void) { return VALUE; }\n",
    )
    .unwrap();

    let args = [
        "cc",
        "-O0",
        "-g0",
        "-MMD",
        "-MP",
        "-MF",
        ".deps/foo.o.pp",
        "-I../../../../src",
        "-c",
        "../../../../src/foo.c",
        "-o",
        "foo.o",
    ];

    run_kache_cc_from(&object_dir, cache_dir.path(), &args);
    let cold_depinfo = std::fs::read_to_string(object_dir.join(".deps/foo.o.pp")).unwrap();
    assert!(object_dir.join("foo.o").exists());
    assert!(
        cold_depinfo.contains("../../../../src/foo.c"),
        "cold depfile should preserve compiler parent-relative source path: {cold_depinfo}"
    );
    assert!(
        cold_depinfo.contains("../../../../src/bar.h"),
        "cold depfile should preserve compiler parent-relative header path: {cold_depinfo}"
    );
    assert!(
        !cold_depinfo.contains("__kache_root__/"),
        "restored-facing depfiles must not expose kache sentinels: {cold_depinfo}"
    );

    std::fs::remove_file(object_dir.join("foo.o")).unwrap();
    std::fs::remove_dir_all(object_dir.join(".deps")).unwrap();
    std::fs::create_dir_all(object_dir.join(".deps")).unwrap();

    run_kache_cc_from(&object_dir, cache_dir.path(), &args);
    let warm_depinfo = std::fs::read_to_string(object_dir.join(".deps/foo.o.pp")).unwrap();
    assert!(object_dir.join("foo.o").exists());
    assert_eq!(
        warm_depinfo, cold_depinfo,
        "cache-hit restore must reproduce parent-relative depfiles byte-for-byte"
    );
    assert!(
        !warm_depinfo.contains(&object_dir.to_string_lossy().to_string()),
        "restore must not inject the object dir into parent-relative paths: {warm_depinfo}"
    );

    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 1, 1);
}

#[test]
fn test_auto_gc_bounds_store_size() {
    build_kache();

    let test_project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    let target_dir = TempDir::new().unwrap();
    let src_dir = test_project.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    std::fs::write(
        test_project.path().join("Cargo.toml"),
        r#"[package]
name = "hello-world"
version = "0.1.0"
edition = "2021"

[workspace]
"#,
    )
    .unwrap();
    std::fs::write(
        src_dir.join("main.rs"),
        r#"fn main() {
    println!("Hello from kache test project v1!");
}
"#,
    )
    .unwrap();

    // First populate one entry with auto-GC disabled. The budget used for the
    // second build is derived from this entry's actual size, which varies
    // substantially across platforms/toolchains.
    let config_content = r#"[cache]
local_only = true
local_max_size = "10GiB"
auto_gc = false
cache_executables = true
"#;
    let config_path = isolated_config_path(cache_dir.path());
    std::fs::write(&config_path, config_content).unwrap();

    // First build (populates the cache past the size budget)
    let output = hermetic_command("cargo", cache_dir.path(), Some(&config_path))
        .args(["build"])
        .current_dir(&test_project)
        .env("RUSTC_WRAPPER", kache_binary())
        .env("CARGO_TARGET_DIR", target_dir.path())
        .env("CARGO_INCREMENTAL", "0")
        .env("KACHE_LOG", "kache=debug")
        .output()
        .expect("failed to run cargo build");
    assert!(
        output.status.success(),
        "first cargo build failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    println!("STDOUT:\n{}", String::from_utf8_lossy(&output.stdout));
    println!("STDERR:\n{}", String::from_utf8_lossy(&output.stderr));

    // Connect to SQLite to check initial size and age the entries
    let db_path = cache_dir.path().join("index.db");
    assert!(db_path.exists(), "index.db should exist");

    let total_store_size = || -> i64 {
        let conn = rusqlite::Connection::open(&db_path).unwrap();
        conn.pragma_update(None, "busy_timeout", "5000").unwrap();
        conn.query_row("SELECT COALESCE(SUM(size), 0) FROM entries", [], |row| {
            row.get(0)
        })
        .unwrap()
    };

    let age_entries = || {
        let conn = rusqlite::Connection::open(&db_path).unwrap();
        conn.pragma_update(None, "busy_timeout", "5000").unwrap();
        conn.execute(
            "UPDATE entries SET last_accessed = datetime('now', '-300 seconds'), created_at = datetime('now', '-300 seconds')",
            [],
        )
        .unwrap();
    };

    let size_before = total_store_size();

    let entry_count_before: i64 = {
        let conn = rusqlite::Connection::open(&db_path).unwrap();
        conn.pragma_update(None, "busy_timeout", "5000").unwrap();
        conn.query_row("SELECT COUNT(*) FROM entries", [], |row| row.get(0))
            .unwrap()
    };
    assert_eq!(
        entry_count_before, 1,
        "first build should populate exactly one cache entry"
    );

    println!("Store size before GC: {size_before} bytes");
    assert!(size_before > 0, "store should be populated");

    // Age the first entry so the background worker's first sweep can evict it
    // immediately. This avoids depending on the retry-delay env var surviving
    // Cargo's rustc-wrapper environment on every platform.
    age_entries();

    // Set the budget so one entry fits but two entries exceed max+slack. The
    // second build below changes the source to force a second cache entry; GC
    // should evict the aged first entry and leave the fresh entry intact.
    let gc_budget = ((size_before as u64) * 3 / 2).max(size_before as u64 + 1);
    let config_content = format!(
        r#"[cache]
local_only = true
local_max_size = "{gc_budget}B"
auto_gc = true
gc_evict_shared = true
cache_executables = true
"#
    );
    std::fs::write(&config_path, config_content).unwrap();

    std::fs::write(
        src_dir.join("main.rs"),
        r#"fn main() {
    println!("Hello from kache test project v2!");
}
"#,
    )
    .unwrap();

    // Second build creates a second entry and triggers put() -> maybe_spawn_auto_gc
    let output = hermetic_command("cargo", cache_dir.path(), Some(&config_path))
        .args(["build"])
        .current_dir(test_project.path())
        .env("RUSTC_WRAPPER", kache_binary())
        .env("CARGO_TARGET_DIR", target_dir.path())
        .env("CARGO_INCREMENTAL", "0")
        .env("KACHE_LOG", "kache=debug")
        .output()
        .expect("failed to run cargo build");
    assert!(
        output.status.success(),
        "second cargo build failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("auto-gc: spawned background `kache gc`"),
        "second build should trigger background auto-GC.\nstderr: {stderr}"
    );

    // Poll fresh SQLite connections until the aged first entry is evicted.
    let mut size_after = total_store_size();
    let start = std::time::Instant::now();
    while start.elapsed() < std::time::Duration::from_secs(10) {
        size_after = total_store_size();
        if size_after <= gc_budget as i64 {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }

    println!("Store size after GC: {size_after} bytes");
    if size_after > gc_budget as i64 {
        let log_path = cache_dir.path().join("auto-gc.log");
        if log_path.exists()
            && let Ok(log_content) = std::fs::read_to_string(&log_path)
        {
            println!("--- AUTO-GC.LOG CONTENT ---");
            println!("{}", log_content);
            println!("----------------------------");
        }
    }
    assert!(
        size_after <= gc_budget as i64,
        "auto-GC failed to evict store below budget {gc_budget}, current size: {size_after}"
    );
}

/// Issue #505: unrecognized RUSTC_WORKSPACE_WRAPPER tools must pass through
/// uncached — the wrapper must execute on every build, not just the first.
/// If someone routes unknown wrappers back through the cache, the second
/// invocation would be a cache hit and the wrapper would NOT execute,
/// failing the marker-count assertion.
#[cfg(unix)]
#[test]
fn workspace_wrapper_passthrough_executes_every_time() {
    use std::os::unix::fs::PermissionsExt;

    build_kache();
    let cache_dir = TempDir::new().unwrap();
    let marker = cache_dir.path().join("wrapper-runs.log");

    // Fake workspace wrapper: records each execution, then forwards to rustc.
    let wrapper = cache_dir.path().join("fake-driver");
    std::fs::write(
        &wrapper,
        format!("#!/bin/sh\necho ran >> {}\nexec \"$@\"\n", marker.display()),
    )
    .unwrap();
    std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();

    let src = cache_dir.path().join("lib.rs");
    std::fs::write(&src, "pub fn foo() -> u32 { 42 }\n").unwrap();
    let out = cache_dir.path().join("out.rlib");

    let run = || {
        hermetic_command(
            kache_binary(),
            cache_dir.path(),
            Some(&isolated_config_path(cache_dir.path())),
        )
        .arg(&wrapper)
        .arg("rustc")
        .args([
            "--edition",
            "2024",
            "--crate-type",
            "lib",
            "--crate-name",
            "fakedriver",
            "-o",
            out.to_str().unwrap(),
            src.to_str().unwrap(),
        ])
        .output()
        .expect("failed to run kache")
    };

    let out1 = run();
    assert!(
        out1.status.success(),
        "first build failed\nstderr: {}",
        String::from_utf8_lossy(&out1.stderr)
    );
    let count1 = std::fs::read_to_string(&marker).unwrap().lines().count();
    assert_eq!(count1, 1);

    let out2 = run();
    assert!(
        out2.status.success(),
        "second build failed\nstderr: {}",
        String::from_utf8_lossy(&out2.stderr)
    );
    let count2 = std::fs::read_to_string(&marker).unwrap().lines().count();
    assert_eq!(
        count2, 2,
        "wrapper must execute on every build (uncached passthrough)"
    );
}

/// Without a memo the key comes from what the compile read, so a cold
/// object costs one compiler run and no preprocess; the memo it leaves
/// makes the next build a hit, and a changed header a miss.
#[test]
fn test_cc_direct_key_compiles_once_without_a_preprocess() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(project.path().join("value.h"), "#define VALUE 7\n").unwrap();
    // A system header brings the libc's macro-built asm operands into the
    // read set; they must not read as files the assembler opens.
    std::fs::write(
        project.path().join("foo.c"),
        "#include <stdio.h>\n#include \"value.h\"\nint value(void) { return VALUE; }\n",
    )
    .unwrap();
    let args = ["cc", "-O0", "-g0", "-c", "foo.c", "-o", "foo.o"];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert!(project.path().join("foo.o").exists());
    assert!(
        !project.path().join("foo.d").exists(),
        "the private dependency capture leaves nothing beside the object"
    );
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 0);

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert!(project.path().join("foo.o").exists());
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
    assert_last_cc_preprocessor_runs(&report, 0);

    // A memo that no longer matches is rediscovered with the preprocessor,
    // not by compiling first: the key it finds is the same one a compile
    // would have derived, so an entry an earlier tree state left is a hit.
    std::fs::write(project.path().join("value.h"), "#define VALUE 7777\n").unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 1);

    std::fs::write(project.path().join("value.h"), "#define VALUE 7\n").unwrap();
    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
    assert_last_cc_preprocessor_runs(&report, 1);
    assert_cc_report_counts(&report, 2, 2);
}

/// A caller that asks for a complete depfile gets it from the same compile
/// the key is derived from, and a hit writes it back.
#[test]
fn test_cc_direct_key_uses_the_callers_depfile() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(project.path().join("value.h"), "#define VALUE 7\n").unwrap();
    std::fs::write(
        project.path().join("foo.c"),
        "#include \"value.h\"\nint value(void) { return VALUE; }\n",
    )
    .unwrap();
    let args = [
        "cc", "-O0", "-g0", "-MD", "-MF", "foo.d", "-c", "foo.c", "-o", "foo.o",
    ];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    let cold = std::fs::read_to_string(project.path().join("foo.d")).unwrap();
    assert!(cold.contains("value.h"), "{cold}");
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 0);

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    std::fs::remove_file(project.path().join("foo.d")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert!(project.path().join("foo.o").exists());
    assert_eq!(
        std::fs::read_to_string(project.path().join("foo.d")).unwrap(),
        cold
    );
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
}

/// A translation unit whose assembler reads a file the compiler never
/// opens cannot be keyed from the read set: it compiles and is not cached.
#[test]
fn test_cc_direct_key_refuses_an_assembler_read_file() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    std::fs::write(project.path().join("blob.bin"), b"payload").unwrap();
    std::fs::write(
        project.path().join("foo.c"),
        "__asm__(\".incbin \\\"blob.bin\\\"\");\nint value(void) { return 1; }\n",
    )
    .unwrap();
    let args = ["cc", "-O0", "-g0", "-c", "foo.c", "-o", "foo.o"];

    // Skipped compiles are kept out of the report's hit/miss summary, so
    // read the event log itself.
    let last_event = |cache: &Path| -> serde_json::Value {
        let text = std::fs::read_to_string(cache.join("events.jsonl")).unwrap();
        let line = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap();
        serde_json::from_str(line).unwrap()
    };
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert!(project.path().join("foo.o").exists());
    let event = last_event(cache_dir.path());
    assert_eq!(event["crate_name"].as_str(), Some("foo.c"));
    assert_eq!(event["result"].as_str(), Some("skipped"), "{event}");
    assert_eq!(event["compiler_runs"].as_u64(), Some(1));
    assert_eq!(event["preprocessor_runs"].as_u64(), Some(0));

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    assert!(project.path().join("foo.o").exists());
    let event = last_event(cache_dir.path());
    assert_eq!(event["result"].as_str(), Some("skipped"), "{event}");
    assert_eq!(event["compiler_runs"].as_u64(), Some(1));
    let report = kache_report(cache_dir.path());
    assert_cc_report_counts(&report, 0, 0);
}

/// A unit whose object spells its own checkout root is keyed to that
/// checkout: cached and hit there, compiled again from another checkout.
#[test]
fn test_cc_direct_key_binds_a_root_spelling_object_to_its_checkout() {
    build_kache();

    let project = TempDir::new().unwrap();
    let cache_dir = TempDir::new().unwrap();
    // The canonical spelling: that is the root the wrapper derives from its
    // working directory, and the one the object must be seen to embed.
    let root = std::fs::canonicalize(project.path()).unwrap();
    // Spelled as a C string: a Windows path's backslashes are escapes.
    let literal = format!("{}/data", root.display()).replace('\\', "\\\\");
    let write = |dir: &Path| {
        std::fs::write(
            dir.join("foo.c"),
            format!("const char *where(void) {{ return \"{literal}\"; }}\n"),
        )
        .unwrap();
    };
    write(project.path());
    let args = ["cc", "-O0", "-g0", "-c", "foo.c", "-o", "foo.o"];

    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "miss", 1);
    assert_last_cc_preprocessor_runs(&report, 0);
    assert_eq!(
        report["summary"]["misses"].as_u64(),
        Some(1),
        "the bound entry is stored: {report}"
    );

    std::fs::remove_file(project.path().join("foo.o")).unwrap();
    run_kache_cc(project.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
    assert_last_cc_preprocessor_runs(&report, 0);

    // The same source text elsewhere still spells the first checkout, which
    // is not a root of this one: a miss, then its own entry.
    let elsewhere = TempDir::new().unwrap();
    write(elsewhere.path());
    run_kache_cc(elsewhere.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    // Its object is byte-identical to the first checkout's (the literal is
    // the same text), so the store already holds every blob: a compile
    // reported as a duplicate, never a hit.
    let last = report["all_events"]
        .as_array()
        .unwrap()
        .last()
        .unwrap()
        .clone();
    assert!(
        matches!(last["result"].as_str(), Some("miss") | Some("dup")),
        "{last}"
    );
    assert_eq!(last["compiler_runs"].as_u64(), Some(1));
    std::fs::remove_file(elsewhere.path().join("foo.o")).unwrap();
    run_kache_cc(elsewhere.path(), cache_dir.path(), &args);
    let report = kache_report(cache_dir.path());
    assert_last_cc_event(&report, "local_hit", 0);
}