fdu-core 0.3.0

The fdu engine: incremental hierarchical tallies over large directory trees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
//! The scan layer: walking a tree, producing observations, and applying reconciliation.
//!
//! Public scans emit upsert observations, and a revalidation sweep is the diff between
//! what the index believes and what the filesystem says. Both speak the same
//! [`Observation`] vocabulary as the watch layer. A detached one-shot index may consume
//! equivalent parent-first directory groups privately because no observer can see its
//! construction; every later mutation still crosses the shared observation boundary.
//!
//! # Status
//!
//! The portable `read_dir` plus non-following metadata reference is what every listing
//! falls back to. Parallel scans use it on most platforms; on macOS they first try a
//! measured `getattrlistbulk` backend that returns directory entries and stat-tier
//! metadata together. Unsupported filesystems, malformed results, mount points, and
//! firmlinks fail closed to the portable path for the complete containing directory.
//! On Linux with glibc every route that lists a directory (the serial and concurrent
//! walks, revalidation, reconciliation, opened discovery) first tries a reader that
//! lists with raw `getdents64` and stats with `statx` against the listing's descriptor,
//! passing `AT_NO_AUTOMOUNT`; an open or enumeration failure, a malformed record, or a
//! kernel without `statx` falls back the same way, and the fallback's own stats then
//! pass the flag too (`observe_dir_entry`), as does every stat of a path a route
//! verifies by itself (`observe_path`). Only the walk root is resolved through a mount
//! (`root_device`). So an autofs tree answers the same on every route and delivery.
//! Every backend produces the same [`Observation`] contract.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::ffi::{OsStr, OsString};
use std::fmt::Write as _;
use std::fs;
use std::io::Read as _;
use std::path::{Component, Path, PathBuf};

use crate::ApplyStats;
use crate::engine_contract::{
    Attrs, Commit, EntryKind, Error, Observation, ObservationOp, Op, PathExpectation, PathState,
    Result, ScanScope,
};
use crate::execution::TreeRetention;
use crate::index::{
    DetachedIndexBuilder, Index, IndexHandle, ReconcileErrors, ReconcileFinish,
    collect_child_expectations,
};
use crate::query::ScopeAxis;
use crate::stored_state::{ControlTierIdentity, EntryScope, EntryTierIdentity, SnapshotIdentity};

// Keep the FFI exception at the platform boundary. The rest of the engine, including
// every consumer of these observations, remains under the workspace's unsafe-code
// denial.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
mod macos_bulk;

// glibc builds only: `libc` defines `struct statx` for glibc, not for default musl.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[allow(unsafe_code)]
mod linux_dents;

#[cfg(windows)]
#[allow(unsafe_code)]
mod windows_metadata;

/// How many ops accumulate before an observation is handed to the sink.
///
/// Batching matters for more than syscall economy: consumers coalesce per path within a
/// batch and stat once per batch, and a live UI wants partial results while a large tree
/// is still being walked rather than one delta at the end.
const DEFAULT_BATCH_SIZE: usize = crate::platform_tuning::tuning().batch_size.get();

/// Largest producer batch accepted before work must be published incrementally.
pub const MAX_SCAN_BATCH_SIZE: usize = 64 * 1024;

/// Most changed paths an exclusive parallel reconciliation may defer before applying.
///
/// Workers compare against one immutable index image, so mutations wait until the wave
/// joins. Bounding that change set keeps a churned tree from turning the fast unchanged
/// path into an unbounded allocation; overflow discards the wave and retries through
/// the incremental serial reconciler.
const MAX_DEFERRED_RECONCILE_OPS: usize = MAX_SCAN_BATCH_SIZE;

/// Directories compared against one immutable index baseline before changes are applied.
///
/// The wave is large enough to amortize scoped worker creation and small enough that a
/// changed tree publishes progress throughout a long reconciliation.
const RECONCILE_WAVE_DIRECTORIES: usize =
    crate::platform_tuning::tuning().reconcile_wave_directories.get();

/// Identity of the fixed stat-tier reducer set.
const REDUCERS_FINGERPRINT: u64 = 1;

/// The order directories are visited in.
///
/// This changes *when* observations are produced, never *which* ones: both orders
/// visit every entry exactly once and leave an identical index behind. It therefore
/// stays out of [`ScanScope`] and cannot invalidate a cache, exactly like the worker
/// count.
///
/// The choice only matters to a consumer that reads the index while the walk is still
/// running, and there it matters a great deal.
///
/// # Strength of the guarantee
///
/// **These are scheduling preferences, not strict orders, whenever more than one worker
/// is running** — which is the default.
///
/// The queue is ordered, but the *claims* are not. Workers take directories from the
/// shared queue in the policy's order; a worker that finishes early can enqueue its
/// children and another worker can claim them while a slower worker still holds
/// unfinished work from a shallower level. Nothing releases a level barrier, because
/// a barrier would idle every fast worker at each level boundary and give back most of
/// the parallel producer's win.
///
/// So:
///
/// - With `threads: Some(1)`, [`ScanOrder::BreadthFirst`] is strict: no directory is
///   read before one closer to the root.
/// - With several workers it is *shallow-first*: shallow work is always preferred when
///   a worker chooses, and deeper observations can still interleave.
///
/// That weaker property is what the browser use case actually needs — every top-level
/// subtree starts filling early, so a mid-scan ranking is meaningful — and it is the
/// property the tests pin. A caller that needs strict level order must ask for one
/// worker and pay for it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum ScanOrder {
    /// Shallow directories before deep ones.
    ///
    /// The default, because it is the order whose partial results mean something.
    /// Roll-ups are maintained per directory as the walk proceeds, so a consumer that
    /// looks mid-scan sees top-level totals grow together — bars fill, rankings
    /// converge — instead of one subtree finishing while its siblings read zero.
    /// Interrupting early leaves a usefully complete picture of the top of the tree.
    ///
    /// Under several workers this is a preference rather than a guarantee; see the
    /// type-level note above.
    ///
    /// Note that totals only grow *while an additive walk is running*. Monotonicity
    /// comes from the producer being additive, not from the order — the order decides
    /// which subtrees get to grow early.
    #[default]
    BreadthFirst,
    /// One subtree toward completion before starting the next.
    ///
    /// Lower peak memory, since the frontier is bounded by depth rather than by the
    /// width of a level, and better locality within a subtree. The cost is that
    /// partial results are actively misleading: one child of the root approaches its
    /// final total while its siblings read zero, so anything ranking by size mid-scan
    /// ranks confidently and wrongly. Correct for a caller that only reads the
    /// finished index and wants the smallest footprint.
    ///
    /// Under several workers this too is a preference: several subtrees will be in
    /// flight at once, one per worker.
    DepthFirst,
}

/// Knobs for a scan.
#[derive(Clone, Debug)]
// Four booleans, each an independent admission or observation switch with its own
// semantic-scope consequence, not an enum in disguise: any combination is legal and
// means what its fields say. The lint suspects flag-soup states; this is a config
// surface whose fields are documented one by one.
#[allow(clippy::struct_excessive_bools)]
pub struct ScanConfig {
    /// Maximum relative entry depth to retain. Zero keeps only the index root and `None`
    /// means unlimited.
    pub max_depth: Option<usize>,
    /// Ops per emitted observation. Must be between one and [`MAX_SCAN_BATCH_SIZE`].
    pub batch_size: usize,
    /// Follow symlinks to directories. Off by default: following them turns a tree walk
    /// into a graph walk with cycles, and every surveyed tool defaults to off.
    pub follow_symlinks: bool,
    /// Stay on the filesystem the root lives on.
    pub one_filesystem: bool,
    /// Hidden-component admission, or `None` to retain every component.
    pub hidden: Option<std::sync::Arc<crate::admission::HiddenPolicy>>,
    /// Exclude filesystem objects other than files, directories, and symlinks.
    pub exclude_special: bool,
    /// Directory-reading worker threads.
    ///
    /// A tree walk is a pile of independent, latency-bound directory reads, so it
    /// scales with threads far better than most work does. One means the serial
    /// walker, which stays the reference implementation and the thing every result is
    /// checked against, with two exceptions that take the concurrent walker with one
    /// worker instead: the detached index build, and a transient summary that reads
    /// `.gitignore`, which must deliver each directory's control ahead of its entries
    /// as that build consumes them. [`None`] asks for a bounded default derived from the
    /// machine's available parallelism. The automatic pool starts conservatively and
    /// unlocks more latency-hiding workers only when initial chunk timing identifies a
    /// slow filesystem path.
    ///
    /// This is an operational knob, not a semantic one: it changes how fast the same
    /// observations are produced, never which observations they are. That is why it
    /// stays out of [`ScanScope`] and cannot invalidate a cache.
    pub threads: Option<usize>,
    /// The order directories are visited in. See [`ScanOrder`].
    pub order: ScanOrder,
    /// File-type rules to classify against, or `None` for the ones compiled into fdu.
    ///
    /// Unlike [`Self::threads`] this *is* semantic: a different taxonomy classifies the
    /// same tree differently, which is why its fingerprint rides in [`ScanScope`] and a
    /// change to it invalidates a snapshot. Shared rather than owned because a scan
    /// clones its config per wave and a registry is read-only once built.
    pub types: Option<std::sync::Arc<crate::classify::TypeRegistry>>,
    /// Observe `.gitignore` control files and retain ignore classification.
    ///
    /// On by default on every surface: an [`Index`] from [`crate::open`] or a scan keeps
    /// the exact control state it exposes and a watch maintains -- which entries are
    /// ignored, and the ignored and unignored partitions of every roll-up -- and a one-shot
    /// report from [`crate::prepare_report`] shows the ignored share of every row
    /// (fdu-elnn). It costs a read of every `.gitignore` in the tree. A file past the
    /// [`Self::control_limits`] is refused and named in [`Index::control_coverage`] rather
    /// than ending the scan; a file that cannot be read is an error at its path, which
    /// makes the result partial.
    ///
    /// Off, the scan performs no control-file I/O and retains no control table, and that is
    /// stamped into [`ScanScope`], so an index-returning call never serves a snapshot taken
    /// one way as the other. An [`Index`] built that way answers [`Index::is_ignored`],
    /// [`Index::controls`], and the partition accessors with
    /// [`crate::Error::ControlStateNotObserved`], never with "not ignored", and refuses
    /// control input; a report's rows carry no ignored share, and a selection by ignored
    /// state is refused. The command line spells it `--no-gitignore`.
    ///
    /// An opened root ([`crate::OpenedIndex`]) always observes control state, because its
    /// ignored and unignored partitions are part of what it serves.
    pub read_controls: bool,
    /// Which ignored population shapes retained entries and content candidates.
    pub population: crate::query::IgnoredEntries,
    /// The budget and the line limit `.gitignore` files are applied under, each a size or
    /// unbounded. See [`crate::control::ControlLimits`].
    ///
    /// A source that would take the table past the budget, or that has a line longer than
    /// the line limit, is refused: its rules do not apply, the scan continues with every
    /// size exact, and [`Index::control_coverage`] names it and the limit that fired. The
    /// command line spells these `--gitignore-budget SIZE|all` and
    /// `--gitignore-line-limit SIZE|all`; the Python API spells them `control_budget` and
    /// `control_line_limit`.
    ///
    /// Semantic, like [`Self::read_controls`]: the limits decide which rules apply, so both
    /// are part of [`ScanScope`] and a snapshot taken under other limits is not reused.
    /// Ignored when control state is not observed.
    pub control_limits: crate::control::ControlLimits,
    /// Where to report how much of the walk has been done, or `None` to report nothing.
    ///
    /// An observer rather than a knob: it changes neither which observations a walk
    /// produces nor how it produces them, so it is no part of [`ScanScope`] or of any
    /// snapshot identity, and two configs that differ only here are the same scan.
    /// Honoured by every walker in this module -- the cold scans, the summary fold,
    /// [`revalidate`], and each `reconcile` entry point -- which enter
    /// [`ProgressPhase::Scanning`](crate::ProgressPhase) or
    /// [`ProgressPhase::Revalidating`](crate::ProgressPhase) and add their counts once
    /// per chunk of directories, never per entry. See [`crate::Progress`] for what the
    /// counts mean and what holds when a walk returns.
    pub progress: Option<crate::Progress>,
}

impl Default for ScanConfig {
    fn default() -> Self {
        Self {
            max_depth: None,
            batch_size: DEFAULT_BATCH_SIZE,
            follow_symlinks: false,
            one_filesystem: false,
            hidden: None,
            exclude_special: false,
            threads: None,
            order: ScanOrder::default(),
            types: None,
            read_controls: crate::query::Request::DEFAULTS.read_controls,
            population: crate::query::IgnoredEntries::Include,
            control_limits: crate::query::Request::DEFAULTS.control_limits,
            progress: None,
        }
    }
}

/// Why watching cannot narrow its structural scan boundary, said once for every surface.
/// Ignored population is a supported retained-scope choice because control edits
/// reconcile the governing directory and rebuild that population.
///
/// The CLI used to carry this guidance and the library carried "requires event-scope
/// filtering", which names the implementation rather than the caller's next move -- so a
/// library caller hitting the same wall got jargon and the CLI user got help. Two
/// messages for one rule also drift, and the parity harness could not tell they were the
/// same rule.
///
/// The knobs are named by the calling surface: `--scan-depth` on the command line,
/// `max_depth` through the API. Everything else is identical, so the harness can verify
/// mechanically that both surfaces state the same rule.
pub const WATCH_SCOPE_GUIDANCE: &str = concat!(
    "watching requires full scope and cannot be combined with max_depth or one_filesystem: ",
    "a watcher cannot filter backend events against a narrowed boundary. Selection such as ",
    "depth, include, and modified_since does work while watching, because it filters the ",
    "retained index rather than narrowing the scan"
);

impl ScanConfig {
    /// Classify this scan with `types` and include their derived identity in its scope.
    #[must_use]
    pub fn with_types(mut self, types: std::sync::Arc<crate::classify::TypeRegistry>) -> Self {
        self.types = Some(types);
        self
    }

    /// The file-type rules in effect: the supplied registry, or the compiled default.
    pub fn types(&self) -> &crate::classify::TypeRegistry {
        match &self.types {
            Some(types) => types,
            None => crate::classify::TypeRegistry::compiled(),
        }
    }

    /// Share the file-type rules with an index that retains them.
    pub(crate) fn types_shared(&self) -> std::sync::Arc<crate::classify::TypeRegistry> {
        self.types
            .as_ref()
            .map_or_else(crate::classify::TypeRegistry::compiled_shared, std::sync::Arc::clone)
    }

    /// Hidden-component policy in effect.
    pub fn hidden(&self) -> &crate::admission::HiddenPolicy {
        self.hidden.as_deref().unwrap_or_else(|| crate::admission::HiddenPolicy::keep_all())
    }

    /// Semantic cache identity, excluding operational batching choices.
    ///
    /// Composed from [`Self::snapshot_identity`], so the scope an index records and the
    /// tier identities a snapshot of it carries are one value in two shapes.
    ///
    /// No longer `const`: the type-rule fingerprint is now a property of the registry in
    /// effect rather than a compiled-in constant, which is the whole point of letting a
    /// caller supply one. A snapshot taken under different rules must not be reused.
    pub fn scope(&self) -> ScanScope {
        self.snapshot_identity().scan_scope()
    }

    /// Which entries this scan retains, the part of its scope no `.gitignore` setting
    /// changes.
    pub fn entry_scope(&self) -> EntryScope {
        EntryScope {
            max_depth: self.max_depth,
            follow_symlinks: self.follow_symlinks,
            one_filesystem: self.one_filesystem,
            hidden_fingerprint: self.hidden().fingerprint(),
            exclude_special: self.exclude_special,
            population: self.population,
            control_fingerprint: if self.population == crate::query::IgnoredEntries::Include {
                0
            } else {
                self.control_identity().ignore_rules_fingerprint()
            },
        }
    }

    /// Whether this scan observes `.gitignore` control state, and under which limits.
    ///
    /// The limits are part of the identity only when control state is observed: a scan
    /// that reads no control file applies none, whatever [`Self::control_limits`] says.
    pub fn control_identity(&self) -> ControlTierIdentity {
        if self.read_controls {
            ControlTierIdentity::Observed { limits: self.control_limits }
        } else {
            ControlTierIdentity::NotObserved
        }
    }

    /// The identity of every tier a snapshot of this scan holds.
    pub fn snapshot_identity(&self) -> SnapshotIdentity {
        SnapshotIdentity {
            entries: EntryTierIdentity {
                engine: crate::snapshot::engine_fingerprint(),
                scope: self.entry_scope(),
                type_rules_fingerprint: self.types().fingerprint(),
                reducers_fingerprint: REDUCERS_FINGERPRINT,
            },
            controls: self.control_identity(),
        }
    }

    /// Resolve [`Self::threads`] to the workers active when a scan begins.
    #[cfg(any(target_os = "macos", test))]
    fn worker_threads(&self) -> usize {
        self.worker_pool().initial
    }

    /// Resolve the worker count for immutable-baseline reconciliation waves.
    fn reconciliation_worker_threads(&self) -> usize {
        match self.threads {
            Some(threads) => threads.clamp(1, MAX_SCAN_THREADS),
            None => std::thread::available_parallelism()
                .map_or(1, std::num::NonZero::get)
                .clamp(1, DEFAULT_RECONCILE_THREADS_CAP),
        }
    }

    /// Resolve the initial and maximum worker counts for one scan.
    #[cfg(any(target_os = "macos", test))]
    fn worker_pool(&self) -> WorkerPool {
        self.worker_pool_for(std::thread::available_parallelism().map_or(1, std::num::NonZero::get))
    }

    /// Resolve the worker pool from one captured operating-system parallelism value.
    fn worker_pool_for(&self, available_parallelism: usize) -> WorkerPool {
        match self.threads {
            Some(threads) => WorkerPool::fixed(threads.clamp(1, MAX_SCAN_THREADS)),
            None => automatic_worker_pool(available_parallelism),
        }
    }

    /// The scope axis this build cannot honour, if any.
    ///
    /// The one statement of the capability rule, so it is asked rather than restated.
    /// [`Request::validate`](crate::query::Request::validate) asks it before any stored
    /// state is read, which is what makes a scope this build cannot honour refuse the same
    /// way on every route, every cache policy, and both surfaces; [`Self::validate`] asks
    /// it for the engine-internal callers -- a bound root, a raw scan, an observation --
    /// that never carry a request.
    pub(crate) const fn unsupported_axis(&self) -> Option<ScopeAxis> {
        if self.follow_symlinks {
            return Some(ScopeAxis::FollowSymlinks);
        }
        #[cfg(not(unix))]
        if self.one_filesystem {
            return Some(ScopeAxis::OneFilesystem);
        }
        None
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if !self.read_controls && self.population != crate::query::IgnoredEntries::Include {
            return Err(Error::UnsupportedScanConfig(
                "ignored population requires .gitignore observation",
            ));
        }
        if self.batch_size == 0 || self.batch_size > MAX_SCAN_BATCH_SIZE {
            return Err(Error::UnsupportedScanConfig(
                "batch_size must be nonzero and no greater than MAX_SCAN_BATCH_SIZE",
            ));
        }
        if let Some(axis) = self.unsupported_axis() {
            return Err(Error::UnsupportedScanConfig(axis.reason()));
        }
        Ok(())
    }

    pub(crate) fn validate_for_scope(&self, indexed: ScanScope) -> Result<()> {
        self.validate()?;
        let requested = self.scope();
        if indexed != requested {
            return Err(Error::ScanScopeMismatch { indexed, requested });
        }
        Ok(())
    }

    /// Scope equality, plus the boundary a watcher cannot filter its backend's events
    /// against.
    ///
    /// The rule belongs to the request model, which refuses a watch of a narrowed scope
    /// before anything is opened ([`RequestError::WatchScope`](crate::query::RequestError));
    /// this is the same rule where a watcher is bound without a request -- an opened root
    /// that observes, and each batch the adapter applies -- and it renders the one
    /// guidance string the model renders.
    #[cfg(feature = "watch")]
    pub(crate) fn validate_for_watch_scope(&self, indexed: ScanScope) -> Result<()> {
        self.validate_for_scope(indexed)?;
        if self.max_depth.is_some() || self.one_filesystem {
            return Err(Error::UnsupportedScanConfig(WATCH_SCOPE_GUIDANCE));
        }
        Ok(())
    }
}

impl Default for ScanScope {
    fn default() -> Self {
        ScanConfig::default().scope()
    }
}

/// What a scan did, including the errors it walked past.
///
/// Unreadable directories are skipped rather than aborting the scan — a permission-denied
/// subdirectory should not cost you the other 499,000 files — but they are reported
/// rather than swallowed, so a caller can tell a complete answer from a partial one.
#[derive(Debug, Default)]
pub struct ScanReport {
    /// Directories successfully listed.
    pub dirs_read: u64,
    /// Entries observed, directories included.
    pub entries: u64,
    /// Regular files whose metadata was observed.
    pub files_walked: u64,
    /// Apparent bytes represented by the regular files whose metadata was observed,
    /// saturating at `u64::MAX`.
    ///
    /// A measure of the walk's work, not an answer: a tree whose total no `u64` can hold
    /// is refused where it is counted ([`crate::Error::UnrepresentableTotal`]), and this
    /// tally stops at the bound rather than wrapping or panicking before that refusal.
    pub bytes_walked: u64,
    /// Allocated bytes of those files: what the default size metric counts, and what a
    /// sparse disk image or a clone makes far smaller than their apparent bytes. It
    /// saturates as `bytes_walked` does.
    pub allocated_walked: u64,
    /// Paths that could not be read, with the reason.
    pub errors: Vec<Error>,
    /// Where the walk's time went, summed across workers.
    pub attribution: WalkAttribution,
}

impl ScanReport {
    /// True when every directory in scope was read successfully.
    pub fn is_complete(&self) -> bool {
        self.errors.is_empty()
    }

    /// Fold one worker's share of a parallel walk into the whole-walk report.
    fn absorb(&mut self, other: Self) {
        self.dirs_read += other.dirs_read;
        self.entries += other.entries;
        self.files_walked += other.files_walked;
        self.bytes_walked = self.bytes_walked.saturating_add(other.bytes_walked);
        self.allocated_walked = self.allocated_walked.saturating_add(other.allocated_walked);
        self.errors.extend(other.errors);
        self.attribution.absorb(other.attribution);
    }

    /// Record one successfully stated directory entry.
    fn observe(&mut self, kind: EntryKind, attrs: Attrs) {
        self.entries += 1;
        if kind == EntryKind::File {
            self.files_walked += 1;
            self.bytes_walked = self.bytes_walked.saturating_add(attrs.size);
            self.allocated_walked = self.allocated_walked.saturating_add(attrs.allocated);
        }
    }
}

/// One walker's running share of the progress counters.
///
/// Each walker keeps its own [`ScanReport`]; this remembers how much of that report it
/// has already added to the shared [`crate::Progress`] cells, so each addition is the
/// difference since the last. It lives on the worker's stack beside the report rather
/// than inside it, so a report absorbed into another never carries a stale baseline.
struct ProgressTally<'a> {
    progress: Option<&'a crate::Progress>,
    directories: u64,
    files: u64,
    bytes: u64,
    allocated: u64,
}

impl<'a> ProgressTally<'a> {
    const fn new(progress: Option<&'a crate::Progress>) -> Self {
        Self { progress, directories: 0, files: 0, bytes: 0, allocated: 0 }
    }

    /// Add what `report` has counted since the last call.
    ///
    /// The one `Option` check is the whole cost when no handle is attached. Called once
    /// per chunk of directories a walker hands over, never per entry.
    fn flush(&mut self, report: &ScanReport) {
        let Some(progress) = self.progress else { return };
        let directories = report.dirs_read - self.directories;
        let files = report.files_walked - self.files;
        let bytes = report.bytes_walked - self.bytes;
        let allocated = report.allocated_walked - self.allocated;
        if directories != 0 || files != 0 || bytes != 0 || allocated != 0 {
            progress.add_walked(directories, files, bytes, allocated);
            self.directories = report.dirs_read;
            self.files = report.files_walked;
            self.bytes = report.bytes_walked;
            self.allocated = report.allocated_walked;
        }
    }

    /// Treat everything `report` holds as already added.
    ///
    /// For a walker that continues a report whose counts other workers added themselves.
    fn skip_to(&mut self, report: &ScanReport) {
        self.directories = report.dirs_read;
        self.files = report.files_walked;
        self.bytes = report.bytes_walked;
        self.allocated = report.allocated_walked;
    }
}

/// Normalize filesystem failures before one of the bounded status collectors retains them.
///
/// A walk may encounter the same inaccessible path from several worker paths. The report is
/// already the full, transient set for this pass, so sorting and deduplicating it here avoids
/// allocating or formatting a second unbounded set solely to decide which 64 details survive.
/// I/O causes are keyed by their native root-relative path and the issue category, exactly the
/// cause identity retained by an index. Other engine failures are left distinct: walker errors
/// are I/O failures, and treating arbitrary engine errors as equivalent without constructing
/// their bounded issue representation would lose information.
pub(crate) fn normalize_walk_errors(root: &Path, errors: &mut Vec<Error>) {
    errors.sort_by(|left, right| match (left, right) {
        (
            Error::Io { path: left_path, source: left_source },
            Error::Io { path: right_path, source: right_source },
        ) => left_path
            .strip_prefix(root)
            .unwrap_or(left_path)
            .cmp(right_path.strip_prefix(root).unwrap_or(right_path))
            .then_with(|| {
                walk_issue_kind_rank(left_source).cmp(&walk_issue_kind_rank(right_source))
            }),
        (Error::Io { .. }, _) => std::cmp::Ordering::Less,
        (_, Error::Io { .. }) => std::cmp::Ordering::Greater,
        _ => std::cmp::Ordering::Equal,
    });
    errors.dedup_by(|right, left| match (left, right) {
        (
            Error::Io { path: left_path, source: left_source },
            Error::Io { path: right_path, source: right_source },
        ) => {
            left_path.strip_prefix(root).unwrap_or(left_path)
                == right_path.strip_prefix(root).unwrap_or(right_path)
                && walk_issue_kind_rank(left_source) == walk_issue_kind_rank(right_source)
        }
        _ => false,
    });
}

fn walk_issue_kind_rank(error: &std::io::Error) -> u8 {
    match error.kind() {
        std::io::ErrorKind::PermissionDenied => 0,
        std::io::ErrorKind::NotFound => 1,
        std::io::ErrorKind::InvalidData | std::io::ErrorKind::InvalidInput => 2,
        _ => 5,
    }
}

/// Schema carried by [`ScanDiagnostics`].
///
/// Diagnostics are an opt-in measurement contract rather than stable human output.
/// Consumers must reject an unknown schema instead of guessing that fields retained
/// their meaning.
pub const SCAN_DIAGNOSTICS_SCHEMA: &str = "fdu-scan-diagnostics-v1";

/// Maximum policy-window records retained by one diagnostic scan.
///
/// The bound is on controller evaluations, not filesystem entries. A controller that
/// needs more history must mark the artifact truncated; claim-grade consumers reject
/// that artifact rather than silently analyzing an incomplete policy history.
const MAX_POLICY_TRACE_EVENTS: usize = 256;

/// Opt-in, run-scoped evidence about a filesystem scan.
///
/// Obtain this through [`scan_with_diagnostics`] or
/// [`scan_into_index_with_diagnostics`]. Keeping it out of [`ScanReport`] preserves the
/// existing scan API and keeps ordinary callers off the measurement path entirely.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScanDiagnostics {
    /// Version of this diagnostic contract.
    pub schema: &'static str,
    /// Automatic worker-controller history and queue state.
    pub worker_policy: WorkerPolicyDiagnostics,
    /// Directory-enumeration backends used by this run.
    pub backend: ScanBackendDiagnostics,
}

/// Repository-only controller variants used by the performance evidence probe.
///
/// These variants are not selected by [`scan`] or [`scan_with_diagnostics`]; both keep
/// the shipped one-shot policy. The explicit experimental APIs make candidate behavior
/// measurable without hiding a production change behind an environment variable.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WorkerPolicyExperiment {
    /// The production controller: one prefix window and at most one expansion.
    #[default]
    ShippedOneShot,
    /// Re-evaluate independent windows until a slow phase requests the full reserve.
    RepeatedWindows,
    /// Re-evaluate independent windows, gate on useful frontier/handoff backlog, and grow
    /// the pool in stages.
    StagedGatedWindows,
}

/// Final state of the automatic worker controller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WorkerPolicyOutcome {
    /// The scan did no walking, for example because `max_depth` was zero.
    NotRun,
    /// A fixed pool had no adaptive decision to make.
    Fixed,
    /// The walk ended before an adaptive window became observable.
    Undecided,
    /// The controller measured a window and retained the initial pool.
    Held,
    /// The controller requested and activated the reserve workers.
    ScaledUp,
    /// Slow work was observed only after no useful queued or in-flight work remained.
    HeldNoUsefulWork,
}

/// One controller evaluation over a half-open range of completed entry ordinals.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkerPolicyWindow {
    /// Monotonic record number within this scan.
    pub sequence: u64,
    /// First completed-entry ordinal represented by this window, inclusive.
    pub start_entry_ordinal: u64,
    /// Ordinal immediately after the last represented entry.
    pub end_entry_ordinal: u64,
    /// Entries contributing to the service-time signal.
    pub observed_entries: u64,
    /// Completed directory claims contributing to the service-time signal.
    pub observed_chunks: u64,
    /// Worker time contributing to the service-time signal.
    pub observed_work_ns: u64,
    /// Derived service time, or null when no entry made the signal observable.
    pub work_ns_per_entry: Option<u64>,
    /// Why `work_ns_per_entry` is null.
    pub work_ns_per_entry_unavailable_reason: Option<&'static str>,
    /// Directories ready to claim when the controller evaluated the window.
    pub ready_directories: usize,
    /// Claimed directories still being processed at that point.
    pub in_flight_directories: usize,
    /// Live worker threads at that point, including workers waiting for a claim.
    pub active_workers: usize,
    /// Observation batches sent but not yet received by the consumer.
    pub handoff_backlog: usize,
    /// Worker target requested by a scale decision.
    pub requested_workers: Option<usize>,
    /// What the controller concluded from this window.
    pub decision: WorkerPolicyDecision,
}

/// Decision represented by a [`WorkerPolicyWindow`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WorkerPolicyDecision {
    /// The walk ended before the window could support a decision.
    Undecided,
    /// The observed window retained the current pool.
    Hold,
    /// The observed window activated reserve workers.
    ScaleUp,
    /// The trigger fired after all useful work had drained.
    HoldNoUsefulWork,
    /// A complete window held because reserve workers had no useful frontier to claim.
    HoldInsufficientFrontier,
    /// A complete window held because the unbounded handoff backlog was already high.
    HoldHandoffBacklog,
    /// A post-decision observation window remained below the slow threshold.
    ObserveFast,
    /// A post-decision observation window met the slow threshold.
    ObserveSlow,
    /// A trailing partial window carried no new terminal decision.
    Incomplete,
    /// A trailing partial post-decision observation carried no policy decision.
    ObserveIncomplete,
}

/// Worker-controller configuration, trace, and terminal queue state.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkerPolicyDiagnostics {
    /// Controller variant exercised by this scan.
    pub controller: &'static str,
    /// Parallelism reported by the operating system when the scan began.
    pub available_parallelism: usize,
    /// Workers in the pool before any adaptive decision.
    pub initial_workers: usize,
    /// Hard maximum workers this scan could activate.
    pub maximum_workers: usize,
    /// Entry target for an adaptive window, or null for a fixed pool.
    pub calibration_window_entries: Option<u64>,
    /// Slow-service trigger, or null for a fixed pool.
    pub slow_threshold_ns_per_entry: Option<u64>,
    /// Directory chunks folded into live controller windows.
    pub calibration_chunks: u64,
    /// Entries folded into live controller windows.
    pub calibration_entries: u64,
    /// Worker time folded into live controller windows.
    pub calibration_work_ns: u64,
    /// Expansion messages that caused the consumer to create more workers.
    pub worker_expansions: u64,
    /// Terminal policy outcome.
    pub outcome: WorkerPolicyOutcome,
    /// Explanation when no adaptive evaluation exists.
    pub outcome_reason: Option<&'static str>,
    /// Total worker threads created during the walk.
    pub workers_spawned: usize,
    /// Maximum simultaneously live worker threads, including workers waiting for work.
    pub peak_active_workers: usize,
    /// Ready directories at scan completion; a complete walk must leave zero.
    pub ready_directories_at_finish: usize,
    /// In-flight directories at scan completion; a complete walk must leave zero.
    pub in_flight_directories_at_finish: usize,
    /// Observation batches outstanding at scan completion.
    pub handoff_backlog_at_finish: usize,
    /// Maximum outstanding observation batches during the scan.
    pub handoff_backlog_high_water: usize,
    /// Bounded controller history.
    pub windows: Vec<WorkerPolicyWindow>,
    /// True when controller history exceeded the 256-event diagnostic bound.
    pub events_truncated: bool,
}

/// Directory enumeration backends used by one scan.
///
/// Each native reader's listings are counted in its own fields, and a directory it
/// declines is counted as its fallback and then as a portable attempt. On Linux, for the
/// native reader (`getdents64` and `statx`, glibc builds):
///
/// - `linux_dents_attempts` = `linux_dents_successes` + `linux_dents_fallbacks`;
/// - the report's `dirs_read` = `linux_dents_successes` + `portable_directory_reads`.
///
/// `unavailable_reason` describes only the macOS fields.
///
/// Non-exhaustive, as [`crate::counters::Counts`] is: a diagnostics record grows with the
/// backends it describes, so a later field is an additive change. Code outside the engine
/// reads its fields; only the engine builds one.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScanBackendDiagnostics {
    /// Portable `read_dir` calls attempted.
    pub portable_attempts: u64,
    /// Portable directory listings completed successfully.
    pub portable_directory_reads: u64,
    /// macOS bulk enumeration attempts, or null off macOS.
    pub macos_bulk_attempts: Option<u64>,
    /// Successful macOS bulk listings, or null off macOS.
    pub macos_bulk_successes: Option<u64>,
    /// Bulk attempts that fell back to portable enumeration, or null off macOS.
    pub macos_bulk_fallbacks: Option<u64>,
    /// Why macOS fields are null.
    pub unavailable_reason: Option<&'static str>,
    /// Linux native `getdents64` listing attempts, or null off Linux (and on a Linux
    /// build without glibc, where the native reader is not compiled).
    pub linux_dents_attempts: Option<u64>,
    /// Successful Linux native listings, or null off Linux.
    pub linux_dents_successes: Option<u64>,
    /// Linux native attempts that fell back to portable enumeration, or null off Linux.
    pub linux_dents_fallbacks: Option<u64>,
}

impl ScanDiagnostics {
    /// Serialize this versioned diagnostic contract as compact JSON.
    ///
    /// This deliberately lives beside the contract instead of in a benchmark binary:
    /// claim-grade installed-command measurements and the repository probe must emit
    /// byte-for-byte equivalent evidence without adding a serialization dependency to
    /// the core crate.
    pub fn to_json(&self) -> String {
        let policy = &self.worker_policy;
        let backend = &self.backend;
        let mut windows = String::from("[");
        for (index, window) in policy.windows.iter().enumerate() {
            if index > 0 {
                windows.push(',');
            }
            let _ = write!(
                windows,
                concat!(
                    "{{\"active_workers\":{},\"decision\":\"{}\",",
                    "\"end_entry_ordinal\":{},\"handoff_backlog\":{},",
                    "\"in_flight_directories\":{},\"observed_chunks\":{},",
                    "\"observed_entries\":{},",
                    "\"observed_work_ns\":{},\"ready_directories\":{},",
                    "\"requested_workers\":{},\"sequence\":{},\"start_entry_ordinal\":{},",
                    "\"work_ns_per_entry\":{},",
                    "\"work_ns_per_entry_unavailable_reason\":{}}}"
                ),
                window.active_workers,
                worker_policy_decision_name(window.decision),
                window.end_entry_ordinal,
                window.handoff_backlog,
                window.in_flight_directories,
                window.observed_chunks,
                window.observed_entries,
                window.observed_work_ns,
                window.ready_directories,
                json_optional_usize(window.requested_workers),
                window.sequence,
                window.start_entry_ordinal,
                json_optional_u64(window.work_ns_per_entry),
                json_optional_string(window.work_ns_per_entry_unavailable_reason),
            );
        }
        windows.push(']');
        format!(
            concat!(
                "{{\"backend\":{{\"linux_dents_attempts\":{},",
                "\"linux_dents_fallbacks\":{},\"linux_dents_successes\":{},",
                "\"macos_bulk_attempts\":{},",
                "\"macos_bulk_fallbacks\":{},\"macos_bulk_successes\":{},",
                "\"portable_attempts\":{},\"portable_directory_reads\":{},",
                "\"unavailable_reason\":{}}},",
                "\"schema\":\"{}\",\"worker_policy\":{{",
                "\"available_parallelism\":{},\"calibration_chunks\":{},",
                "\"calibration_entries\":{},\"calibration_window_entries\":{},",
                "\"calibration_work_ns\":{},",
                "\"controller\":\"{}\",",
                "\"events_truncated\":{},\"handoff_backlog_at_finish\":{},",
                "\"handoff_backlog_high_water\":{},\"in_flight_directories_at_finish\":{},",
                "\"initial_workers\":{},\"maximum_workers\":{},\"outcome\":\"{}\",",
                "\"outcome_reason\":{},\"peak_active_workers\":{},",
                "\"ready_directories_at_finish\":{},\"slow_threshold_ns_per_entry\":{},",
                "\"windows\":{},\"worker_expansions\":{},\"workers_spawned\":{}}}}}"
            ),
            json_optional_u64(backend.linux_dents_attempts),
            json_optional_u64(backend.linux_dents_fallbacks),
            json_optional_u64(backend.linux_dents_successes),
            json_optional_u64(backend.macos_bulk_attempts),
            json_optional_u64(backend.macos_bulk_fallbacks),
            json_optional_u64(backend.macos_bulk_successes),
            backend.portable_attempts,
            backend.portable_directory_reads,
            json_optional_string(backend.unavailable_reason),
            self.schema,
            policy.available_parallelism,
            policy.calibration_chunks,
            policy.calibration_entries,
            json_optional_u64(policy.calibration_window_entries),
            policy.calibration_work_ns,
            policy.controller,
            policy.events_truncated,
            policy.handoff_backlog_at_finish,
            policy.handoff_backlog_high_water,
            policy.in_flight_directories_at_finish,
            policy.initial_workers,
            policy.maximum_workers,
            worker_policy_outcome_name(policy.outcome),
            json_optional_string(policy.outcome_reason),
            policy.peak_active_workers,
            policy.ready_directories_at_finish,
            json_optional_u64(policy.slow_threshold_ns_per_entry),
            windows,
            policy.worker_expansions,
            policy.workers_spawned,
        )
    }
}

const fn worker_policy_outcome_name(value: WorkerPolicyOutcome) -> &'static str {
    match value {
        WorkerPolicyOutcome::NotRun => "not_run",
        WorkerPolicyOutcome::Fixed => "fixed",
        WorkerPolicyOutcome::Undecided => "undecided",
        WorkerPolicyOutcome::Held => "held",
        WorkerPolicyOutcome::ScaledUp => "scaled_up",
        WorkerPolicyOutcome::HeldNoUsefulWork => "held_no_useful_work",
    }
}

const fn worker_policy_decision_name(value: WorkerPolicyDecision) -> &'static str {
    match value {
        WorkerPolicyDecision::Undecided => "undecided",
        WorkerPolicyDecision::Hold => "hold",
        WorkerPolicyDecision::ScaleUp => "scale_up",
        WorkerPolicyDecision::HoldNoUsefulWork => "hold_no_useful_work",
        WorkerPolicyDecision::HoldInsufficientFrontier => "hold_insufficient_frontier",
        WorkerPolicyDecision::HoldHandoffBacklog => "hold_handoff_backlog",
        WorkerPolicyDecision::ObserveFast => "observe_fast",
        WorkerPolicyDecision::ObserveSlow => "observe_slow",
        WorkerPolicyDecision::Incomplete => "incomplete",
        WorkerPolicyDecision::ObserveIncomplete => "observe_incomplete",
    }
}

fn json_optional_string(value: Option<&str>) -> String {
    value.map_or_else(|| "null".into(), |value| format!("\"{}\"", json_escape(value)))
}

fn json_optional_u64(value: Option<u64>) -> String {
    value.map_or_else(|| "null".into(), |value| value.to_string())
}

fn json_optional_usize(value: Option<usize>) -> String {
    value.map_or_else(|| "null".into(), |value| value.to_string())
}

fn json_escape(value: &str) -> String {
    let mut escaped = String::new();
    for character in value.chars() {
        match character {
            '"' => escaped.push_str("\\\""),
            '\\' => escaped.push_str("\\\\"),
            '\u{08}' => escaped.push_str("\\b"),
            '\u{0c}' => escaped.push_str("\\f"),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            character if character <= '\u{1f}' => {
                let _ = write!(escaped, "\\u{:04x}", u32::from(character));
            }
            character => escaped.push(character),
        }
    }
    escaped
}

/// Where a walk's time went, so "blocked" is never one undifferentiated number.
///
/// The performance loop's standing question is whether a walk is bound by disk I/O,
/// by CPU, or by coordination, and process-level counters cannot answer it: user and
/// system time say how much CPU was burned, but a fused "blocked" number cannot say
/// whether workers were waiting on the filesystem, on the queue lock, or on nothing
/// at all because the queue was empty. These counters split that out at the source.
///
/// Everything is measured in *chunks*, never per file: one timing pair per claimed
/// run of directories, per contended lock, per batch handoff. On the 60k-entry
/// reference tree that is a few thousand `Instant` reads against hundreds of
/// milliseconds of walking — the instrumentation follows the same amortization rule
/// it exists to verify.
///
/// In a parallel walk the fields sum over workers, so `wall_ns` is worker-seconds
/// (it can exceed the scan's wall clock) and every other duration is a disjoint
/// slice of it: `work_ns + starved_ns + lock_wait_ns + send_ns <= wall_ns`, with the
/// remainder being uninstrumented odds and ends (uncontended lock ops, loop
/// bookkeeping). A serial walk fills only `wall_ns`, `work_ns`, and `send_ns` —
/// there is no coordination to attribute.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct WalkAttribution {
    /// Total time workers spent in the walk loop, summed across workers.
    pub wall_ns: u64,
    /// Reading directories and stating entries — the real work, syscalls plus the
    /// compute between them. Separating disk from CPU *within* this span needs the
    /// process-level user/system counters alongside; per-syscall timing would break
    /// the chunk-amortization rule.
    pub work_ns: u64,
    /// Waiting on the queue's condvar because no work was available. Starvation:
    /// either the frontier is momentarily narrower than the worker pool, or the walk
    /// is ending.
    pub starved_ns: u64,
    /// Waiting to acquire the queue lock when another worker held it. This is the
    /// contention the shared-queue design bets stays negligible; now it is measured
    /// instead of argued.
    pub lock_wait_ns: u64,
    /// Handing observation batches to the consumer: the channel send in a parallel
    /// walk, the inline sink call — which is the consumer actually running — in a
    /// serial one.
    pub send_ns: u64,
    /// Chunks of directories claimed from the queue.
    pub claims: u64,
    /// Queue lock acquisitions, contended or not.
    pub lock_ops: u64,
    /// Lock acquisitions that found the lock already held.
    pub lock_contended: u64,
}

impl WalkAttribution {
    /// Fold one worker's counters into the whole-walk totals.
    fn absorb(&mut self, other: Self) {
        self.wall_ns += other.wall_ns;
        self.work_ns += other.work_ns;
        self.starved_ns += other.starved_ns;
        self.lock_wait_ns += other.lock_wait_ns;
        self.send_ns += other.send_ns;
        self.claims += other.claims;
        self.lock_ops += other.lock_ops;
        self.lock_contended += other.lock_contended;
    }

    /// Time attributed to a named cause, as opposed to `wall_ns`'s total.
    pub fn accounted_ns(&self) -> u64 {
        self.work_ns + self.starved_ns + self.lock_wait_ns + self.send_ns
    }
}

/// Filesystem and index effects from an applying reconciliation pass.
#[derive(Debug, Default)]
pub struct ReconcileReport {
    /// Filesystem walk effects and partial errors.
    ///
    /// [`ScanReport::attribution`] remains zero for reconciliation because neither the
    /// serial nor parallel path has complete, comparable instrumentation yet. Zero
    /// means "not measured" here, not "no work".
    pub scan: ScanReport,
    /// Index arbitration and mutation effects.
    pub apply: ApplyStats,
    /// Exact producer operations considered, including no-op controls that do not
    /// increment an effect counter or create a commit.
    pub(crate) observations: u64,
    /// Directories this pass listed in full, with no error inside them, that the index did
    /// not yet hold as complete.
    ///
    /// The closing commit records each one's child set as authoritative, as discovery's
    /// own listing commit does, whether or not the rest of the pass completed: one transient
    /// child error
    /// elsewhere used to keep every directory the pass listed incomplete, and a directory
    /// first listed by such a pass stayed `Unknown { Building }` under a complete root.
    pub(crate) listed_incomplete: Vec<PathBuf>,
    /// Ownership epoch for conditional reconciliation batches.
    reconcile_epoch: Option<u64>,
    /// Retry after bounded verification evidence was superseded.
    retry_required: bool,
}

impl ReconcileReport {
    /// True when the filesystem walk was complete and no conditional observation lost
    /// a race with another producer.
    pub fn is_complete(&self) -> bool {
        self.scan.is_complete()
            && self.apply.stale == 0
            && self.apply.resource_refused == 0
            && !self.retry_required
    }

    /// True when a newer verification retired this pass's bounded evidence before it
    /// closed, so its scope is published partial and must be walked again.
    pub(crate) const fn retry_required(&self) -> bool {
        self.retry_required
    }

    /// The directories whose listings this pass can vouch for, taken out of the report.
    ///
    /// None when a conditional commit lost a race or was refused: a child of any listed
    /// directory may then be missing from the index until the retry that race earns, and
    /// the retry records completeness for what it lists.
    pub(crate) fn take_recordable_completeness(&mut self) -> Vec<PathBuf> {
        let listed = std::mem::take(&mut self.listed_incomplete);
        if self.apply.stale > 0 || self.apply.resource_refused > 0 { Vec::new() } else { listed }
    }
}

enum ReconcileTarget<'a> {
    Direct(&'a mut Index),
    Shared(&'a IndexHandle),
    Controlled { handle: &'a IndexHandle, control: &'a dyn ReconcileControl },
}

/// Lifecycle checkpoints used by an owned long-running reconciliation.
///
/// The ordinary one-shot APIs use no controller. An [`crate::OpenedIndex`] supplies one
/// so close can stop a refresh before another write, and deterministic tests can pause
/// after filesystem verification but before conditional arbitration.
pub(crate) trait ReconcileControl {
    /// Fail when the owning operation may no longer publish state.
    fn check_active(&self) -> Result<()>;

    /// Boundary after filesystem verification and before a conditional fact commit.
    fn before_conditional_commit(&self) -> Result<()>;

    /// Atomic file-retention limit shared with every producer for this opened root.
    fn max_files(&self) -> Option<u64>;
}

impl ReconcileTarget<'_> {
    fn scope(&self) -> Result<ScanScope> {
        match self {
            Self::Direct(index) => Ok(index.scope()),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.scope(),
        }
    }

    fn root_path(&self) -> Result<PathBuf> {
        match self {
            Self::Direct(index) => Ok(index.root_path().to_path_buf()),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.root_path(),
        }
    }

    fn expectation(&self, path: &Path) -> Result<PathExpectation> {
        match self {
            Self::Direct(index) => Ok(index.expectation(path)),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.expectation(path),
        }
    }

    fn child_states(&self, path: &Path) -> Result<BTreeMap<OsString, PathExpectation>> {
        match self {
            Self::Direct(index) => Ok(collect_child_expectations(index, path)),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.child_states(path),
        }
    }

    /// Child baselines for one directory listing, and whether a complete listing of it
    /// would be news to the index's directory completeness.
    ///
    /// A directory whose upsert has not been flushed yet is not held at all and counts as
    /// incomplete.
    fn listing_baseline(&self, path: &Path) -> Result<(BTreeMap<OsString, PathExpectation>, bool)> {
        match self {
            Self::Direct(index) => Ok((
                collect_child_expectations(index, path),
                index.directory_complete(path) != Some(true),
            )),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.listing_baseline(path),
        }
    }

    fn has_control(&self, path: &Path) -> Result<bool> {
        match self {
            Self::Direct(index) => Ok(index.control_table().contains(path)),
            Self::Shared(handle) | Self::Controlled { handle, .. } => handle.has_control(path),
        }
    }

    fn control_table(&self) -> Result<crate::control::ControlTable> {
        match self {
            Self::Direct(index) => Ok(index.control_table().clone()),
            Self::Shared(handle) | Self::Controlled { handle, .. } => {
                handle.read_with(|index| index.control_table().clone())
            }
        }
    }

    fn control_classification_known(&self, path: &Path) -> Result<bool> {
        match self {
            Self::Direct(index) => Ok(index.control_classification_known(path)),
            Self::Shared(handle) | Self::Controlled { handle, .. } => {
                handle.read_with(|index| index.control_classification_known(path))
            }
        }
    }

    fn apply(&mut self, started_at: u64, observation: &Observation) -> Result<crate::ApplyOutcome> {
        match self {
            Self::Direct(index) => index.apply(observation),
            Self::Shared(handle) => handle.apply_reconcile(started_at, observation),
            Self::Controlled { handle, control } => {
                control.before_conditional_commit()?;
                handle.apply_opened_reconcile(started_at, observation, control.max_files())
            }
        }
    }

    fn direct_upsert_is_unchanged(
        &self,
        baseline: PathExpectation,
        kind: EntryKind,
        attrs: Attrs,
    ) -> bool {
        matches!(self, Self::Direct(_)) && baseline.state == (PathState::Present { kind, attrs })
    }

    fn take_pending_invalidations(&mut self) -> Result<Vec<(PathBuf, crate::InvalidateReason)>> {
        match self {
            Self::Direct(index) => Ok(index.take_pending_invalidations()),
            Self::Shared(handle) | Self::Controlled { handle, .. } => {
                handle.take_pending_invalidations()
            }
        }
    }

    fn restore_pending_invalidations(
        &mut self,
        invalidations: Vec<(PathBuf, crate::InvalidateReason)>,
    ) -> Result<()> {
        match self {
            Self::Direct(index) => index.restore_pending_invalidations(invalidations),
            Self::Shared(handle) | Self::Controlled { handle, .. } => {
                handle.restore_pending_invalidations(invalidations)?;
            }
        }
        Ok(())
    }

    /// Whether an invalidation whose reconciliation came back incomplete is queued again.
    ///
    /// A caller of the one-shot API owns its index exclusively and drains the queue when it
    /// chooses, so an unreadable subtree stays queued for it to retry. The shared API and an
    /// opened root are drained after every observed event -- by `Watcher::apply_next` and by
    /// the opened root's observer -- where that retry is a full walk of the same unreadable
    /// subtree per unrelated event, for the life of the session. There only a lost race is
    /// worth retrying: a stale conditional commit, or one the budget refused. A scan error
    /// is a settled boundary: the subtree stays partial, as it does at the observation
    /// handoff, and the report names the error once.
    fn retries_incomplete(&self, report: &ReconcileReport) -> bool {
        match self {
            Self::Direct(_) => !report.is_complete(),
            Self::Shared(_) | Self::Controlled { .. } => {
                report.apply.stale > 0 || report.apply.resource_refused > 0 || report.retry_required
            }
        }
    }

    fn begin_reconcile(&mut self, path: &Path) -> Result<(u64, Option<Commit>)> {
        match self {
            Self::Direct(index) => index.begin_reconcile(path),
            Self::Shared(handle) => handle.begin_reconcile(path),
            Self::Controlled { handle, control } => {
                control.check_active()?;
                handle.begin_reconcile(path)
            }
        }
    }

    fn finish_reconcile(
        &mut self,
        path: &Path,
        started_at: u64,
        complete: bool,
        listed_incomplete: &[PathBuf],
        failed_paths: &[PathBuf],
        errors: ReconcileErrors<'_>,
    ) -> Result<ReconcileFinish> {
        match self {
            Self::Direct(index) => index.finish_reconcile(
                path,
                started_at,
                complete,
                listed_incomplete,
                failed_paths,
                errors,
            ),
            Self::Shared(handle) => handle.finish_reconcile(
                path,
                started_at,
                complete,
                listed_incomplete,
                failed_paths,
                errors,
            ),
            Self::Controlled { handle, control } => {
                control.check_active()?;
                handle.finish_reconcile(
                    path,
                    started_at,
                    complete,
                    listed_incomplete,
                    failed_paths,
                    errors,
                )
            }
        }
    }
}

#[cfg(unix)]
pub(crate) fn metadata_for_fingerprint(entry: &fs::DirEntry) -> std::io::Result<fs::Metadata> {
    crate::counters::bump(|c| c.stats += 1);
    entry.metadata()
}

#[cfg(any(all(windows, test), not(any(unix, windows))))]
pub(crate) fn metadata_for_fingerprint(entry: &fs::DirEntry) -> std::io::Result<fs::Metadata> {
    crate::counters::bump(|c| c.stats += 1);
    // Windows serves DirEntry metadata from directory-enumeration data, which the
    // platform permits to be stale. Fingerprints need a fresh non-following query.
    fs::symlink_metadata(entry.path())
}

#[cfg(test)]
type WalkHook = std::sync::Arc<dyn Fn(WalkHookPoint<'_>) -> Option<std::io::Error> + Send + Sync>;

/// Where a test hook runs in a listing walk.
#[cfg(test)]
#[derive(Clone, Copy, Debug)]
pub(crate) enum WalkHookPoint<'a> {
    /// Before the metadata lookup of the listed child at this absolute path; an error
    /// stands in for the lookup's.
    ChildMetadata(&'a Path),
    /// After a reconciliation's listing of a directory returns its last entry; an error is
    /// read as one more listing item, which leaves the listing incomplete.
    ListingEnd,
    /// After a lookup of a directory's canonical control path, at this absolute path, has
    /// returned and before its answer is used; an error stands in for that answer.
    ControlLookup(&'a Path),
}

/// Hooks run at each [`WalkHookPoint`], each for the paths under its root.
///
/// Process-wide, because a parallel walk looks children up on its worker threads; keyed
/// by root, because tests run in parallel and each walks its own temporary directory.
#[cfg(test)]
static WALK_HOOKS: std::sync::RwLock<Vec<(Vec<PathBuf>, WalkHook)>> =
    std::sync::RwLock::new(Vec::new());

/// Removes its hook from [`WALK_HOOKS`] when dropped.
#[cfg(test)]
#[must_use = "the hook is removed as soon as the guard is dropped"]
pub(crate) struct WalkHookGuard(WalkHook);

#[cfg(test)]
impl Drop for WalkHookGuard {
    fn drop(&mut self) {
        WALK_HOOKS
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .retain(|(_, hook)| !std::sync::Arc::ptr_eq(hook, &self.0));
    }
}

/// Run `hook` at every [`WalkHookPoint`] under `root`, on any thread, until the guard drops.
///
/// The hook may also change the tree before it returns. `root` matches as given and
/// canonical, since an opened root and a detached scan walk the canonical path.
#[cfg(test)]
pub(crate) fn install_walk_hook(
    root: &Path,
    hook: impl Fn(WalkHookPoint<'_>) -> Option<std::io::Error> + Send + Sync + 'static,
) -> WalkHookGuard {
    let mut roots = vec![root.to_path_buf()];
    if let Ok(canonical) = root.canonicalize() {
        roots.push(canonical);
    }
    let hook: WalkHook = std::sync::Arc::new(hook);
    WALK_HOOKS
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .push((roots, std::sync::Arc::clone(&hook)));
    WalkHookGuard(hook)
}

/// Run `hook` before every listed child's metadata lookup under `root`, with the child's
/// absolute path, until the guard drops.
#[cfg(test)]
pub(crate) fn install_child_metadata_hook(
    root: &Path,
    hook: impl Fn(&Path) -> Option<std::io::Error> + Send + Sync + 'static,
) -> WalkHookGuard {
    install_walk_hook(root, move |point| match point {
        WalkHookPoint::ChildMetadata(path) => hook(path),
        WalkHookPoint::ListingEnd | WalkHookPoint::ControlLookup(_) => None,
    })
}

/// The hook installed for a root containing `path`, if any.
#[cfg(test)]
fn walk_hook(path: &Path) -> Option<WalkHook> {
    WALK_HOOKS
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .iter()
        .find(|(roots, _)| roots.iter().any(|root| path.starts_with(root)))
        .map(|(_, hook)| std::sync::Arc::clone(hook))
}

/// A reconciliation's listing of `dir`, followed by any error a test hook injects.
///
/// Callers bind the result to `listing` and iterate it as `for … in listing`, because the
/// admission audit (`scripts/check-admission-sites.mjs`) counts routed listing loops by that
/// shape. Keep the binding when editing a call site; dropping it silently removes the loop
/// from the audit, whose expected count would then look too high rather than wrong.
#[cfg(test)]
fn reconcile_listing<'r>(listing: Listing<'r>, dir: &Path) -> impl Iterator<Item = Listed<'r>> {
    let injected = walk_hook(dir).and_then(|hook| hook(WalkHookPoint::ListingEnd));
    listing.chain(injected.map(Listed::Failed))
}

/// A reconciliation's listing of `dir`.
#[cfg(not(test))]
fn reconcile_listing<'r>(listing: Listing<'r>, _dir: &Path) -> Listing<'r> {
    listing
}

/// The error a test hook injects for the metadata lookup of the listed child at `path`.
#[cfg(all(test, not(windows)))]
fn child_metadata_hook(path: &Path) -> Option<std::io::Error> {
    walk_hook(path).and_then(|hook| hook(WalkHookPoint::ChildMetadata(path)))
}

/// Whether std's stat of a listed child, `DirEntry::file_type` of a `DT_UNKNOWN` entry
/// included, is one the kernel treats as `AT_NO_AUTOMOUNT`.
///
/// It is `fstatat` everywhere but glibc, where it is `statx` without the flag wherever
/// `statx` is served, and `fstatat` only once the reader has found it unavailable
/// (`linux_dents`).
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn std_child_stat_never_automounts() -> bool {
    linux_dents::statx_unavailable()
}

#[cfg(not(any(windows, all(target_os = "linux", target_env = "gnu"))))]
const fn std_child_stat_never_automounts() -> bool {
    true
}

/// Kind and attributes for one listed child.
///
/// The transient summary fold counts directories and ignores symlink attributes, so a
/// listing `file_type` (`d_type` on Linux) is enough for those kinds when the walk is
/// not bound to one filesystem. Files and specials still need a metadata lookup for
/// size, allocated bytes, and mtime. `one_filesystem` still stats directories because
/// descent compares `attrs.dev` to the root device, and `dev == 0` would otherwise
/// cross a mount. The listing's kind is taken only once the listing has proved its
/// directory searchable ([`Searchability`]); until then every child is stated, and the
/// skip applies to what the stat found.
///
/// Where `d_type` is `DT_UNKNOWN` (XFS without `ftype`, some FUSE/NFS mounts, older
/// ext3), std's `file_type` performs the non-following stat itself, and the skip then
/// applies to the kind it found. On glibc that stat would trigger an automount, so
/// while `statx` is served the listing's `file_type` is not consulted at all: every
/// child is stated by [`observe_dir_entry`], which never automounts, and the skip
/// applies to what that stat found, as it does to a `DT_UNKNOWN` entry. That route is
/// the fallback for a directory the native reader declined; the reader itself keeps
/// the `d_type` skip.
///
/// Windows never takes the skip: its observation contract reads every listed entry
/// through a fresh non-following handle ([`observe_dir_entry`]), so the transient fold
/// there performs exactly the observations the retained walk performs.
fn listed_child_kind_and_attrs(
    entry: &fs::DirEntry,
    policy: ListingPolicy,
    searchability: &mut Searchability,
) -> std::io::Result<Option<(EntryKind, Attrs)>> {
    #[cfg(not(windows))]
    {
        let listing_kind_suffices = policy.skip_dir_symlink_stat
            && *searchability == Searchability::Proven
            && std_child_stat_never_automounts();
        if listing_kind_suffices {
            if let Ok(file_type) = entry.file_type() {
                if file_type.is_dir() && !policy.one_filesystem {
                    return Ok(Some((EntryKind::Dir, Attrs::default())));
                }
                if file_type.is_symlink() {
                    return Ok(Some((EntryKind::Symlink, Attrs::default())));
                }
            }
        }
        let observed = observe_dir_entry(entry)?;
        if observed.is_some() {
            *searchability = Searchability::Proven;
        }
        if policy.skip_dir_symlink_stat && !listing_kind_suffices {
            return Ok(observed.map(|(kind, attrs)| match kind {
                EntryKind::Dir if !policy.one_filesystem => (kind, Attrs::default()),
                EntryKind::Symlink => (kind, Attrs::default()),
                EntryKind::Dir | EntryKind::File | EntryKind::Other => (kind, attrs),
            }));
        }
        Ok(observed)
    }
    #[cfg(windows)]
    {
        // Windows observes every listed entry through a fresh handle on both routes, so
        // the skip does not apply there; a successful observation proves the directory
        // searchable all the same, so the listing's state means the same on every host.
        let _ = (policy.skip_dir_symlink_stat, policy.one_filesystem);
        let observed = observe_dir_entry(entry)?;
        if observed.is_some() {
            *searchability = Searchability::Proven;
        }
        Ok(observed)
    }
}

/// How a listing observes its children.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ListingPolicy {
    /// H72: directory and symlink kinds come from the listing without a stat, once the
    /// listing has proved its directory searchable ([`Searchability`]).
    pub(crate) skip_dir_symlink_stat: bool,
    /// Descent compares `attrs.dev`, so directories are stated even under the skip.
    pub(crate) one_filesystem: bool,
}

/// Whether one listing has proved its directory searchable, which the skip of
/// [`ListingPolicy::skip_dir_symlink_stat`] requires before it takes a child's kind from
/// the listing alone. Per listing: it starts unproven with each directory.
///
/// A stat is also an observation of failure. A directory that is readable but not
/// searchable (mode `0400`) opens and lists, and then every child's stat fails with
/// `EACCES`; a walk that stats every child reports each child as an error and holds no
/// entry for it. A `DT_DIR` child admitted on its `d_type` alone would be a directory
/// entry the full index does not have, queued and then reported again when it fails to
/// open, and a `DT_LNK` child a symlink entry with no error at all, so the folded tree
/// and the summary would count one directory more and report one error fewer than the
/// full index (R163-1). Under the skip, therefore, every child is stated until one stat
/// in the listing succeeds, which proves the directory searchable, as the skip assumes;
/// only then are directory and symlink kinds taken from the listing. The cost is one
/// stat per listing whose first children are directories or symlinks. A child that
/// vanished before its stat proves nothing here, which costs a stat and never an entry.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Searchability {
    /// No child's stat has succeeded yet, so every child is stated.
    #[default]
    Unproven,
    /// A child's stat succeeded, so the listing's kind stands for a directory or symlink.
    Proven,
}

impl ListingPolicy {
    /// Every child stated: what the retained index, a reconciliation, and discovery need.
    pub(crate) const fn every_child_stated(one_filesystem: bool) -> Self {
        Self { skip_dir_symlink_stat: false, one_filesystem }
    }
}

/// The platform readers a listing loop keeps between the directories it lists.
///
/// One per walker or reconciliation worker: the Linux reader holds a 64 KiB record
/// buffer that each of its listings borrows for the directory's duration. Elsewhere
/// there is nothing to keep, and every listing is portable.
pub(crate) struct Readers {
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    dents: linux_dents::Reader,
}

impl Readers {
    pub(crate) fn new() -> Self {
        Self {
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            dents: linux_dents::Reader::new(),
        }
    }
}

/// One item of a directory listing, whichever backend served it.
pub(crate) enum Listed<'a> {
    /// The listing failed to yield an item, so the directory is listed incompletely.
    Failed(std::io::Error),
    /// A child by name, with its kind and attributes, or `Ok(None)` when it vanished
    /// between the listing and its stat, or the error that stat failed with.
    ///
    /// `NotFound` for a name the listing just returned means the entry was deleted in
    /// between, and every walk records it as it records a name the listing never
    /// returned: a cold walk has nothing to record, and a reconciliation removes what
    /// its baseline held. Reported as an error, it would make a walk over a tree being
    /// cleaned partial, and in a reconciliation it would settle as a phantom entry with
    /// permanent partial freshness. A native listing does not yield such a child at all.
    /// Any other error means the entry is present but unreadable.
    Child {
        name: std::borrow::Cow<'a, OsStr>,
        observed: std::io::Result<Option<(EntryKind, Attrs)>>,
    },
}

/// One directory's children, natively where a reader served it and portably otherwise.
pub(crate) enum Listing<'r> {
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    Native(linux_dents::Listing<'r>),
    Portable {
        entries: fs::ReadDir,
        policy: ListingPolicy,
        /// What this listing has proved of its directory so far.
        searchability: Searchability,
        readers: std::marker::PhantomData<&'r mut Readers>,
    },
}

impl<'r> Iterator for Listing<'r> {
    type Item = Listed<'r>;

    fn next(&mut self) -> Option<Listed<'r>> {
        match self {
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            Self::Native(listing) => {
                let entry = listing.next()?;
                let observed = match entry.outcome {
                    linux_dents::Outcome::Observed { kind, attrs } => Ok(Some((kind, attrs))),
                    linux_dents::Outcome::Failed(error) => Err(error),
                };
                Some(Listed::Child { name: std::borrow::Cow::Borrowed(entry.name), observed })
            }
            Self::Portable { entries, policy, searchability, .. } => {
                let item = match entries.next()? {
                    Ok(item) => item,
                    Err(error) => return Some(Listed::Failed(error)),
                };
                crate::counters::bump(|c| c.dir_entries += 1);
                let observed = listed_child_kind_and_attrs(&item, *policy, searchability);
                Some(Listed::Child { name: std::borrow::Cow::Owned(item.file_name()), observed })
            }
        }
    }
}

/// List `abs_dir` for a walk, a reconciliation, or discovery.
///
/// On Linux with glibc the native reader serves the directory unless it declines or a
/// test hook covers the directory; the portable `read_dir` answers otherwise, and an
/// error opening it is the caller's to report. Each backend produces the same items:
/// a native listing counts itself, and the portable one is counted here, as a
/// `dir_opens` and a portable attempt in `diagnostics`.
pub(crate) fn list_directory<'r>(
    readers: &'r mut Readers,
    abs_dir: &Path,
    policy: ListingPolicy,
    diagnostics: Option<&ScanDiagnosticsRecorder>,
) -> std::io::Result<Listing<'r>> {
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    {
        // Plain `if`, not `bool::then(|| …)`: the listing borrows the reader.
        if !walk_hook_covers(abs_dir) {
            if let Some(diagnostics) = diagnostics {
                diagnostics.linux_dents_attempted();
            }
            let native = linux_dents::StatPolicy {
                skip_dir_symlink_stat: policy.skip_dir_symlink_stat,
                one_filesystem: policy.one_filesystem,
            };
            if let Some(listing) = readers.dents.read(abs_dir, native) {
                if let Some(diagnostics) = diagnostics {
                    diagnostics.linux_dents_succeeded();
                }
                return Ok(Listing::Native(listing));
            }
            // A declined directory is counted as a fallback here and as the portable
            // attempt below, as the walker counts it.
            if let Some(diagnostics) = diagnostics {
                diagnostics.linux_dents_fell_back();
            }
        }
    }
    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
    let _ = &readers;
    crate::counters::bump(|c| c.dir_opens += 1);
    if let Some(diagnostics) = diagnostics {
        diagnostics.portable_attempted();
    }
    let entries = fs::read_dir(abs_dir)?;
    if let Some(diagnostics) = diagnostics {
        diagnostics.portable_succeeded();
    }
    Ok(Listing::Portable {
        entries,
        policy,
        searchability: Searchability::Unproven,
        readers: std::marker::PhantomData,
    })
}

fn missing_as_none<T>(lookup: std::io::Result<T>) -> std::io::Result<Option<T>> {
    match lookup {
        Ok(metadata) => Ok(Some(metadata)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

/// Whether a test hook observes lookups or listings under `path`, which a native read
/// would not make.
#[cfg(all(test, any(target_os = "macos", all(target_os = "linux", target_env = "gnu"))))]
fn walk_hook_covers(path: &Path) -> bool {
    walk_hook(path).is_some()
}

#[cfg(all(not(test), any(target_os = "macos", all(target_os = "linux", target_env = "gnu"))))]
const fn walk_hook_covers(_path: &Path) -> bool {
    false
}

/// Owned output from the filesystem walker before it crosses a public mutation boundary.
///
/// Only the scan and opened-discovery producers construct this type. Their admission,
/// depth, filesystem, and symlink checks have already selected every operation, and the
/// index consumes the owned paths while proving their parent identities under its write
/// boundary. Public scan callers receive an [`Observation`] instead and therefore keep
/// the full public normalization and atomic-validation contract.
#[derive(Debug)]
pub(crate) struct ScannerBatch {
    ops: Vec<ObservationOp>,
    /// When set, the consumer must return `ops` through this sender instead of dropping
    /// them. Workers allocate the `PathBuf`s; returning the drained vec lets glibc free
    /// those arenas on the producing thread. The public [`scan`] path leaves this unset.
    recycle: Option<std::sync::mpsc::Sender<Vec<ObservationOp>>>,
}

impl ScannerBatch {
    pub(crate) const fn new(ops: Vec<ObservationOp>) -> Self {
        Self { ops, recycle: None }
    }

    fn with_recycle(self, recycle: std::sync::mpsc::Sender<Vec<ObservationOp>>) -> Self {
        Self { recycle: Some(recycle), ..self }
    }

    #[cfg(test)]
    pub(crate) fn from_ops(ops: Vec<Op>) -> Self {
        Self { ops: ops.into_iter().map(ObservationOp::unconditional).collect(), recycle: None }
    }

    pub(crate) fn len(&self) -> usize {
        self.ops.len()
    }

    pub(crate) fn ops(&self) -> &[ObservationOp] {
        &self.ops
    }

    pub(crate) fn into_ops(self) -> Vec<ObservationOp> {
        self.ops
    }

    fn into_observation(self) -> Observation {
        Observation::from_ops(self.ops)
    }

    fn recycle(self) {
        if let Some(recycle) = self.recycle {
            let _ = recycle.send(self.ops);
        }
    }
}

/// One direct child retained by the private detached cold-bootstrap builder.
///
/// The worker owns the component once. Unlike [`ScannerBatch`], this record does not
/// manufacture a full relative path or a public observation for every entry.
#[derive(Debug)]
pub(crate) struct DetachedChild {
    pub(crate) name: OsString,
    pub(crate) kind: EntryKind,
    pub(crate) attrs: Attrs,
    /// Enumeration order within the listing. An enumerator can repeat a name while its
    /// directory is modified, and the builder keeps the later observation, as a
    /// streaming re-upsert does.
    pub(crate) position: u32,
}

/// One directory listing retained by a worker for detached bootstrap consolidation.
///
/// `path` is paid once per directory. Its children remain grouped exactly as the
/// filesystem enumerator produced them, so consolidation resolves the parent once and
/// never reconstructs a child path for nondirectories. A fixed control is retained
/// separately so the consumer can install the directory's complete control state
/// before it classifies any sibling or makes descendants visible.
#[derive(Debug)]
pub(crate) struct DetachedDirectory {
    pub(crate) path: PathBuf,
    pub(crate) children: Vec<DetachedChild>,
    pub(crate) control: Option<Op>,
}

/// Walk `root` and emit observations describing everything found.
pub fn scan(
    root: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(Observation),
) -> Result<ScanReport> {
    let mut public_sink = |batch: ScannerBatch| sink(batch.into_observation());
    let (mut report, _diagnostics) = scan_internal(
        root,
        config,
        &mut public_sink,
        false,
        WorkerPolicyExperiment::ShippedOneShot,
        SinkMode::Retained,
    )?;
    normalize_walk_errors(root, &mut report.errors);
    Ok(report)
}

/// Walk `root` for the transient summary tier, folding each op without retaining it.
///
/// The public [`scan`] path hands each batch to the caller as an [`Observation`], so
/// worker-allocated `PathBuf`s are freed on the consumer thread. This path returns
/// drained batches to the producing worker so each arena is allocated and freed on one
/// thread. Tallies must match [`scan`], and so must the normalized error set: the
/// summary report's status is built from these errors exactly as a retained walk's is.
/// A scan that reads `.gitignore` delivers each directory's control ahead of every entry
/// it governs, so the fold can classify each entry as the index would
/// ([`SinkMode::groups_directories`]).
pub(crate) fn scan_summary_fold(
    root: &Path,
    config: &ScanConfig,
    fold: &mut dyn FnMut(&ObservationOp),
) -> Result<ScanReport> {
    let mut sink = |batch: ScannerBatch| {
        for op in batch.ops() {
            fold(op);
        }
        batch.recycle();
    };
    let (mut report, _diagnostics) = scan_internal(
        root,
        config,
        &mut sink,
        false,
        WorkerPolicyExperiment::ShippedOneShot,
        SinkMode::TransientFold,
    )?;
    normalize_walk_errors(root, &mut report.errors);
    Ok(report)
}

/// [`scan_summary_fold`] plus the diagnostic trace [`scan_with_diagnostics`] collects.
pub(crate) fn scan_summary_fold_with_diagnostics(
    root: &Path,
    config: &ScanConfig,
    fold: &mut dyn FnMut(&ObservationOp),
) -> Result<(ScanReport, ScanDiagnostics)> {
    let mut sink = |batch: ScannerBatch| {
        for op in batch.ops() {
            fold(op);
        }
        batch.recycle();
    };
    let (mut report, diagnostics) = scan_internal(
        root,
        config,
        &mut sink,
        true,
        WorkerPolicyExperiment::ShippedOneShot,
        SinkMode::TransientFold,
    )?;
    normalize_walk_errors(root, &mut report.errors);
    Ok((report, diagnostics.expect("diagnostic scan creates a recorder")))
}

/// Walk `root`, emitting observations and a bounded run-scoped diagnostic trace.
///
/// This is the measurement counterpart to [`scan`]. It produces the same observation
/// stream and report while recording controller and backend evidence that ordinary
/// scans intentionally do not collect.
pub fn scan_with_diagnostics(
    root: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(Observation),
) -> Result<(ScanReport, ScanDiagnostics)> {
    scan_with_policy_diagnostics(root, config, sink, WorkerPolicyExperiment::ShippedOneShot)
}

/// Exercise a repository-only worker-controller candidate and retain its trace.
#[doc(hidden)]
pub fn scan_with_policy_diagnostics(
    root: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(Observation),
    policy: WorkerPolicyExperiment,
) -> Result<(ScanReport, ScanDiagnostics)> {
    let mut public_sink = |batch: ScannerBatch| sink(batch.into_observation());
    let (mut report, diagnostics) =
        scan_internal(root, config, &mut public_sink, true, policy, SinkMode::Retained)?;
    normalize_walk_errors(root, &mut report.errors);
    Ok((report, diagnostics.expect("diagnostic scan creates a recorder")))
}

/// What the caller does with each batch of observations.
///
/// Two measured keeps hang off this one concept, and both were measured on the
/// transient fold alone: returning drained batches to the producing worker (H147,
/// exp-151) and taking directory and symlink kind from the listing without a stat
/// (H72, exp-153). They are named here as properties of the mode rather than passed as
/// one flag under one of their names, so a measurement on another platform can move
/// one without silently moving the other.
///
/// A third property is semantic rather than measured: a transient fold that observes
/// `.gitignore` classifies on its consumer, and that needs each directory's control
/// before its entries ([`Self::groups_directories`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SinkMode {
    /// The consumer keeps the observations: the public [`scan`] and the index.
    Retained,
    /// The consumer folds each batch and drops it: the transient summary tier.
    TransientFold,
}

impl SinkMode {
    /// Drained batches go back to the worker that allocated them (H147).
    fn recycles_batches(self) -> bool {
        self == Self::TransientFold
    }

    /// Directory and symlink kind come from the listing without a stat (H72).
    fn skips_dir_symlink_stat(self) -> bool {
        self == Self::TransientFold
    }

    /// Each directory's control reaches the consumer ahead of every entry it governs
    /// (fdu-1ovb).
    ///
    /// The transient summary classifies every entry against `.gitignore` on its
    /// consumer, as the detached index builder does, and the builder applies a
    /// directory's control before it classifies any child because it receives each
    /// listing whole. A streaming batch keeps listing order, where `.gitignore` can come
    /// last, so a worker holds a listing's observations and moves the control ahead of
    /// them when the listing ends, or, if the batch fills first, reads the directory's
    /// control directly and lets that read stand for the listing
    /// (`StreamingEmission::send_if_full`). The retained stream keeps listing order: the
    /// index reclassifies the subtree a control governs when that control arrives.
    fn groups_directories(self, config: &ScanConfig) -> bool {
        self == Self::TransientFold && config.read_controls
    }
}

fn scan_internal(
    root: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(ScannerBatch),
    collect_diagnostics: bool,
    policy: WorkerPolicyExperiment,
    sink_mode: SinkMode,
) -> Result<(ScanReport, Option<ScanDiagnostics>)> {
    config.validate()?;
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Scanning);
    }
    let root_meta = {
        crate::counters::bump(|c| c.stats += 1);
        fs::symlink_metadata(root)
    }
    .map_err(|e| Error::io(root, e))?;
    if !root_meta.is_dir() {
        return Err(Error::io(
            root,
            std::io::Error::new(std::io::ErrorKind::NotADirectory, "scan root is not a directory"),
        ));
    }
    let root_dev = root_device(root, &root_meta).map_err(|error| Error::io(root, error))?;
    let available_parallelism =
        std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
    // Narrow populations need control admission before child enumeration. Keep one ordered
    // producer and control table so a bounded budget makes the same decisions as the
    // index that consumes the observations.
    let pool = if config.population == crate::query::IgnoredEntries::Include {
        config.worker_pool_for(available_parallelism)
    } else {
        WorkerPool::fixed(1)
    };
    let diagnostics = collect_diagnostics
        .then(|| ScanDiagnosticsRecorder::new(pool, available_parallelism, policy));

    // The serial walk below emits in listing order and never groups a directory, so a
    // transient fold that classifies takes the concurrent walk even with one worker. That
    // is the walk the detached index takes at every worker count, and one worker visits
    // directories in the order that builder consumes them, so a control budget admits
    // the same files on both routes. A narrowed population keeps the serial walk, which
    // reads each directory's control before listing it.
    let groups = sink_mode.groups_directories(config)
        && config.population == crate::query::IgnoredEntries::Include;
    if config.max_depth != Some(0) && (pool.initial > 1 || groups) {
        let report = scan_concurrent(
            root,
            config,
            root_dev,
            sink,
            pool,
            diagnostics.as_ref(),
            policy,
            sink_mode,
        );
        return Ok((report, diagnostics.as_ref().map(|value| value.finish())));
    }

    let mut report = ScanReport::default();
    if config.max_depth == Some(0) {
        if let Some(diagnostics) = &diagnostics {
            diagnostics.mark_not_run();
            diagnostics.record_queue_finish(0, 0);
        }
        return Ok((report, diagnostics.as_ref().map(|value| value.finish())));
    }
    let worker_guard = diagnostics.as_ref().map(ScanDiagnosticsRecorder::worker_guard);
    let walk_started = std::time::Instant::now();
    let mut batch: Vec<ObservationOp> = Vec::with_capacity(config.batch_size);
    let mut queue: VecDeque<(PathBuf, usize)> = VecDeque::from(vec![(PathBuf::new(), 0)]);
    let mut controls = (config.population != crate::query::IgnoredEntries::Include)
        .then(|| crate::control::ControlTable::with_limits(config.control_limits));
    let mut unreadable_controls = std::collections::BTreeSet::new();
    let mut tally = ProgressTally::new(config.progress.as_ref());
    let mut readers = Readers::new();
    let policy = ListingPolicy {
        skip_dir_symlink_stat: sink_mode.skips_dir_symlink_stat(),
        one_filesystem: config.one_filesystem,
    };
    // Every batch leaves through here, so the batch is where the serial walk reports
    // its progress: the handoff the consumer already pays for, never the entry.
    let mut emit = |ops: Vec<ObservationOp>, report: &mut ScanReport| {
        let send_started = std::time::Instant::now();
        sink(ScannerBatch::new(ops));
        report.attribution.send_ns += elapsed_ns(send_started);
        tally.flush(report);
    };

    while let Some((rel_dir, depth)) = take_next(&mut queue, config.order) {
        let abs_dir = root.join(&rel_dir);
        if let Some(controls) = controls.as_mut() {
            let control_path = rel_dir.join(crate::control::CONTROL_FILE_NAME);
            match read_directory_control(config, root, &control_path) {
                Ok(Some(op)) => {
                    apply_discovery_control(controls, &op)?;
                    batch.push(ObservationOp::unconditional(op));
                }
                Ok(None) => {}
                Err(error) => {
                    unreadable_controls.insert(rel_dir.clone());
                    report.errors.push(error);
                }
            }
        }
        let listing = match list_directory(&mut readers, &abs_dir, policy, diagnostics.as_deref()) {
            Ok(listing) => listing,
            Err(e) => {
                report.errors.push(Error::io(abs_dir, e));
                continue;
            }
        };
        report.dirs_read += 1;

        for item in listing {
            let (name, observed) = match item {
                Listed::Child { name, observed } => (name, observed),
                Listed::Failed(e) => {
                    report.errors.push(Error::io(&abs_dir, e));
                    continue;
                }
            };
            let rel_path = rel_dir.join(&name);
            let (kind, attrs) = match observed {
                Ok(Some(observed)) => observed,
                Ok(None) => continue,
                Err(error) => {
                    report.errors.push(Error::io(abs_dir.join(&name), error));
                    continue;
                }
            };
            let disposition =
                crate::admission::decide(&name, kind, config.hidden(), config.exclude_special);
            if disposition == crate::admission::Disposition::Reject {
                continue;
            }
            if population_prunes(
                config.population,
                &rel_path,
                kind,
                disposition,
                controls.as_ref(),
                &unreadable_controls,
            ) {
                continue;
            }
            // A narrowed walk looked the directory's control up before listing it, and that
            // lookup stands for every spelling the listing shows.
            let control =
                match if controls.is_some() && crate::control::control_spelling(&name).is_some() {
                    Ok(None)
                } else {
                    read_control_op(config, root, &rel_path, kind)
                } {
                    Ok(control) => control,
                    Err(error) => {
                        report.errors.push(error);
                        None
                    }
                };
            if disposition == crate::admission::Disposition::ControlOnly {
                if let Some(control) = control {
                    batch.push(ObservationOp::unconditional(control));
                    if batch.len() >= config.batch_size {
                        emit(std::mem::take(&mut batch), &mut report);
                        batch.reserve(config.batch_size);
                    }
                }
                continue;
            }
            report.observe(kind, attrs);
            batch.push(ObservationOp::unconditional(Op::Upsert {
                path: rel_path.clone(),
                kind,
                attrs,
            }));
            if batch.len() >= config.batch_size {
                emit(std::mem::take(&mut batch), &mut report);
                batch.reserve(config.batch_size);
            }
            if let Some(control) = control {
                batch.push(ObservationOp::unconditional(control));
                if batch.len() >= config.batch_size {
                    emit(std::mem::take(&mut batch), &mut report);
                    batch.reserve(config.batch_size);
                }
            }

            if should_descend(kind, attrs, depth, root_dev, config) {
                queue.push_back((rel_path, depth + 1));
            }
        }
    }

    if !batch.is_empty() {
        emit(batch, &mut report);
    }
    // A walk whose last directories filled no batch has counted them and sent nothing.
    tally.flush(&report);
    // A serial walk has no coordination to attribute: wall is the loop, "send" is the
    // inline sink — which is the consumer actually running — and work is the rest.
    report.attribution.wall_ns = elapsed_ns(walk_started);
    report.attribution.work_ns =
        report.attribution.wall_ns.saturating_sub(report.attribution.send_ns);
    drop(worker_guard);
    if let Some(diagnostics) = &diagnostics {
        diagnostics.record_queue_finish(0, 0);
    }
    Ok((report, diagnostics.as_ref().map(|value| value.finish())))
}

/// Take the next directory in the configured order.
///
/// Both orders push to the back; only the end they are taken from differs, which is
/// what keeps this a one-line policy rather than two walkers.
fn take_next(queue: &mut VecDeque<(PathBuf, usize)>, order: ScanOrder) -> Option<(PathBuf, usize)> {
    match order {
        ScanOrder::BreadthFirst => queue.pop_front(),
        ScanOrder::DepthFirst => queue.pop_back(),
    }
}

/// Largest worker pool a caller may ask for explicitly.
///
/// Well past anything measured to help. It exists so a caller that computes a thread
/// count from something silly cannot spawn thousands of threads.
const MAX_SCAN_THREADS: usize = 32;

/// Ceiling on the workers active at the start of an automatic scan.
///
/// Measured, not guessed. On a 10-core machine walking a 60k-entry `node_modules`
/// tree, wall time fell 37% at two workers and 50% at four, then stopped improving:
/// six matched four within noise and eight was 4% worse than four. The walk becomes
/// bound by the single index consumer, so past this point extra workers buy queue
/// contention and efficiency-core scheduling rather than throughput. See
/// `docs/project/reports/report-2026-08-10-fdu-performance-experiments.md`.
///
/// That measurement was taken on macOS, and every constant in this group now reads its
/// value from [`crate::platform_tuning`], which records per platform whether the number
/// was measured there or inherited. On Linux these are inherited.
const DEFAULT_SCAN_THREADS_CAP: usize = crate::platform_tuning::tuning().scan_threads_cap.get();

/// Ceiling on automatic workers for an immutable-baseline reconciliation wave.
///
/// Reconciliation reads both filesystem and index state. Its measured knee arrives
/// before the cold producer's because additional metadata calls amplify kernel work
/// after the index comparisons already saturate the performance cores.
const DEFAULT_RECONCILE_THREADS_CAP: usize =
    crate::platform_tuning::tuning().reconcile_threads_cap.get();

/// Ceiling an automatic scan may unlock after it establishes that the tree is large.
///
/// Sixteen was the knee on the 720k-entry cache-pressure corpus in exp-015. Thirty-two
/// did not improve on it and spent substantially more worker time waiting at the end.
const ADAPTIVE_SCAN_THREADS_CAP: usize =
    crate::platform_tuning::tuning().adaptive_scan_threads_cap.get();

/// Maximum reserve depth relative to the host's reported parallelism.
const ADAPTIVE_SCAN_PARALLELISM_MULTIPLIER: usize =
    crate::platform_tuning::tuning().adaptive_scan_parallelism_multiplier.get();

/// Entries used to calibrate the initial workers' filesystem service time.
const ADAPTIVE_SCAN_CALIBRATION_ENTRIES: u64 =
    crate::platform_tuning::tuning().adaptive_scan_calibration_entries.get();

/// Average worker time per observed entry that identifies a latency-bound scan.
///
/// Whole-run attribution separated the measured regimes: roughly 18 microseconds on
/// the 60k tree, 22 on the 120k boundary, and 42 or more on the 720k cache-pressure
/// tree. Thirty leaves margin between them. The calibration uses the same chunk timing
/// already collected for attribution, so it adds no per-entry clock reads.
///
/// Those are APFS regimes. The Linux warm floor is about 1.5 µs per entry, twenty times
/// below this threshold, so the trigger may never fire there — which is exactly the kind
/// of inherited constant [`crate::platform_tuning`] exists to make visible (H84).
const ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY: u64 =
    crate::platform_tuning::tuning().adaptive_scan_slow_work_ns_per_entry.get();

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct WorkerPool {
    initial: usize,
    maximum: usize,
    calibration: Option<WorkerCalibration>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct WorkerCalibration {
    minimum_entries: u64,
    slow_work_ns_per_entry: u64,
    entries: u64,
    work_ns: u64,
    chunks: u64,
}

#[derive(Clone, Copy, Debug)]
struct PolicyWindowSnapshot {
    sequence: u64,
    start_entry_ordinal: u64,
    end_entry_ordinal: u64,
    observed_entries: u64,
    observed_chunks: u64,
    observed_work_ns: u64,
    ready_directories: usize,
    in_flight_directories: usize,
    active_workers: usize,
    handoff_backlog: usize,
    requested_workers: Option<usize>,
    decision: WorkerPolicyDecision,
}

struct PolicyTraceState {
    outcome: WorkerPolicyOutcome,
    outcome_reason: Option<&'static str>,
    outcome_sequence: Option<u64>,
    windows: Vec<WorkerPolicyWindow>,
    events_truncated: bool,
    ready_directories_at_finish: usize,
    in_flight_directories_at_finish: usize,
}

/// Shared state used only by the opt-in diagnostic scan APIs.
///
/// Normal scans pass no recorder and therefore never touch these atomics or locks. The
/// trace mutex is deliberately separate from the directory queue: recording a policy
/// window may add diagnostic cost, but it cannot alter the queue's synchronization or
/// the controller's decision.
pub(crate) struct ScanDiagnosticsRecorder {
    available_parallelism: usize,
    pool: WorkerPool,
    policy: WorkerPolicyExperiment,
    trace: std::sync::Mutex<PolicyTraceState>,
    workers_spawned: std::sync::atomic::AtomicUsize,
    active_workers: std::sync::atomic::AtomicUsize,
    peak_active_workers: std::sync::atomic::AtomicUsize,
    handoff_backlog: std::sync::atomic::AtomicUsize,
    handoff_backlog_high_water: std::sync::atomic::AtomicUsize,
    calibration_chunks: std::sync::atomic::AtomicU64,
    calibration_entries: std::sync::atomic::AtomicU64,
    calibration_work_ns: std::sync::atomic::AtomicU64,
    worker_expansions: std::sync::atomic::AtomicU64,
    portable_attempts: std::sync::atomic::AtomicU64,
    portable_successes: std::sync::atomic::AtomicU64,
    #[cfg(target_os = "macos")]
    macos_bulk_attempts: std::sync::atomic::AtomicU64,
    #[cfg(target_os = "macos")]
    macos_bulk_successes: std::sync::atomic::AtomicU64,
    #[cfg(target_os = "macos")]
    macos_bulk_fallbacks: std::sync::atomic::AtomicU64,
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    linux_dents_attempts: std::sync::atomic::AtomicU64,
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    linux_dents_successes: std::sync::atomic::AtomicU64,
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    linux_dents_fallbacks: std::sync::atomic::AtomicU64,
}

impl ScanDiagnosticsRecorder {
    fn new(
        pool: WorkerPool,
        available_parallelism: usize,
        policy: WorkerPolicyExperiment,
    ) -> std::sync::Arc<Self> {
        let (outcome, outcome_reason) = if pool.calibration.is_some() {
            (
                WorkerPolicyOutcome::Undecided,
                Some("the adaptive calibration window has not completed"),
            )
        } else {
            (WorkerPolicyOutcome::Fixed, Some("this worker pool has no adaptive reserve"))
        };
        std::sync::Arc::new(Self {
            available_parallelism,
            pool,
            policy,
            trace: std::sync::Mutex::new(PolicyTraceState {
                outcome,
                outcome_reason,
                outcome_sequence: None,
                windows: Vec::new(),
                events_truncated: false,
                ready_directories_at_finish: 0,
                in_flight_directories_at_finish: 0,
            }),
            workers_spawned: std::sync::atomic::AtomicUsize::new(0),
            active_workers: std::sync::atomic::AtomicUsize::new(0),
            peak_active_workers: std::sync::atomic::AtomicUsize::new(0),
            handoff_backlog: std::sync::atomic::AtomicUsize::new(0),
            handoff_backlog_high_water: std::sync::atomic::AtomicUsize::new(0),
            calibration_chunks: std::sync::atomic::AtomicU64::new(0),
            calibration_entries: std::sync::atomic::AtomicU64::new(0),
            calibration_work_ns: std::sync::atomic::AtomicU64::new(0),
            worker_expansions: std::sync::atomic::AtomicU64::new(0),
            portable_attempts: std::sync::atomic::AtomicU64::new(0),
            portable_successes: std::sync::atomic::AtomicU64::new(0),
            #[cfg(target_os = "macos")]
            macos_bulk_attempts: std::sync::atomic::AtomicU64::new(0),
            #[cfg(target_os = "macos")]
            macos_bulk_successes: std::sync::atomic::AtomicU64::new(0),
            #[cfg(target_os = "macos")]
            macos_bulk_fallbacks: std::sync::atomic::AtomicU64::new(0),
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_attempts: std::sync::atomic::AtomicU64::new(0),
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_successes: std::sync::atomic::AtomicU64::new(0),
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_fallbacks: std::sync::atomic::AtomicU64::new(0),
        })
    }

    fn worker_guard(self: &std::sync::Arc<Self>) -> ScanWorkerGuard {
        let active = self
            .active_workers
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            .saturating_add(1);
        self.workers_spawned.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        atomic_update_max(&self.peak_active_workers, active);
        ScanWorkerGuard { recorder: self.clone() }
    }

    fn record_policy_window(&self, snapshot: PolicyWindowSnapshot) {
        let mut trace = self.trace.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        let sequence = snapshot.sequence;
        let supersedes = trace.outcome_sequence.is_none_or(|current| sequence >= current);
        match snapshot.decision {
            WorkerPolicyDecision::Undecided if supersedes => {
                trace.outcome = WorkerPolicyOutcome::Undecided;
                trace.outcome_reason =
                    Some("the walk ended before the adaptive calibration window completed");
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::Hold
                if trace.outcome != WorkerPolicyOutcome::ScaledUp && supersedes =>
            {
                trace.outcome = WorkerPolicyOutcome::Held;
                trace.outcome_reason = None;
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::ScaleUp => {
                trace.outcome = WorkerPolicyOutcome::ScaledUp;
                trace.outcome_reason = None;
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::HoldNoUsefulWork
                if trace.outcome != WorkerPolicyOutcome::ScaledUp && supersedes =>
            {
                trace.outcome = WorkerPolicyOutcome::HeldNoUsefulWork;
                trace.outcome_reason =
                    Some("the slow trigger fired only after ready and in-flight work had drained");
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::HoldInsufficientFrontier
                if trace.outcome != WorkerPolicyOutcome::ScaledUp && supersedes =>
            {
                trace.outcome = WorkerPolicyOutcome::Held;
                trace.outcome_reason =
                    Some("the observed frontier could not use additional workers");
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::HoldHandoffBacklog
                if trace.outcome != WorkerPolicyOutcome::ScaledUp && supersedes =>
            {
                trace.outcome = WorkerPolicyOutcome::Held;
                trace.outcome_reason =
                    Some("the observation handoff backlog was already at the controller limit");
                trace.outcome_sequence = Some(sequence);
            }
            WorkerPolicyDecision::Incomplete
                if supersedes && trace.outcome == WorkerPolicyOutcome::Undecided =>
            {
                trace.outcome_reason =
                    Some("the walk ended before any adaptive calibration window completed");
                trace.outcome_sequence = Some(sequence);
            }
            _ => {}
        }
        if sequence >= MAX_POLICY_TRACE_EVENTS as u64 {
            trace.events_truncated = true;
            return;
        }
        let work_ns_per_entry = (snapshot.observed_entries > 0)
            .then(|| snapshot.observed_work_ns / snapshot.observed_entries);
        trace.windows.push(WorkerPolicyWindow {
            sequence,
            start_entry_ordinal: snapshot.start_entry_ordinal,
            end_entry_ordinal: snapshot.end_entry_ordinal,
            observed_entries: snapshot.observed_entries,
            observed_chunks: snapshot.observed_chunks,
            observed_work_ns: snapshot.observed_work_ns,
            work_ns_per_entry,
            work_ns_per_entry_unavailable_reason: work_ns_per_entry
                .is_none()
                .then_some("the window observed no entries"),
            ready_directories: snapshot.ready_directories,
            in_flight_directories: snapshot.in_flight_directories,
            active_workers: snapshot.active_workers,
            handoff_backlog: snapshot.handoff_backlog,
            requested_workers: snapshot.requested_workers,
            decision: snapshot.decision,
        });
    }

    fn mark_not_run(&self) {
        let mut trace = self.trace.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        trace.outcome = WorkerPolicyOutcome::NotRun;
        trace.outcome_reason = Some("max_depth zero requested no directory walk");
    }

    fn record_queue_finish(&self, ready_directories: usize, in_flight_directories: usize) {
        let mut trace = self.trace.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        trace.ready_directories_at_finish = ready_directories;
        trace.in_flight_directories_at_finish = in_flight_directories;
    }

    fn handoff_sent(&self) {
        let backlog = self
            .handoff_backlog
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            .saturating_add(1);
        atomic_update_max(&self.handoff_backlog_high_water, backlog);
    }

    fn handoff_received(&self) {
        let previous = self.handoff_backlog.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
        debug_assert!(previous > 0, "received handoff must have been sent");
    }

    fn calibration_chunk(&self, entries: u64, work_ns: u64) {
        self.calibration_chunks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.calibration_entries.fetch_add(entries, std::sync::atomic::Ordering::Relaxed);
        self.calibration_work_ns.fetch_add(work_ns, std::sync::atomic::Ordering::Relaxed);
    }

    fn worker_expanded(&self) {
        self.worker_expansions.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    fn portable_attempted(&self) {
        self.portable_attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    fn portable_succeeded(&self) {
        self.portable_successes.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(target_os = "macos")]
    fn macos_bulk_attempted(&self) {
        self.macos_bulk_attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(target_os = "macos")]
    fn macos_bulk_succeeded(&self) {
        self.macos_bulk_successes.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(target_os = "macos")]
    fn macos_bulk_fell_back(&self) {
        self.macos_bulk_fallbacks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    fn linux_dents_attempted(&self) {
        self.linux_dents_attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    fn linux_dents_succeeded(&self) {
        self.linux_dents_successes.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    fn linux_dents_fell_back(&self) {
        self.linux_dents_fallbacks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    fn finish(&self) -> ScanDiagnostics {
        let trace = self.trace.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        let calibration = self.pool.calibration;
        let backend = ScanBackendDiagnostics {
            portable_attempts: self.portable_attempts.load(std::sync::atomic::Ordering::Relaxed),
            portable_directory_reads: self
                .portable_successes
                .load(std::sync::atomic::Ordering::Relaxed),
            #[cfg(target_os = "macos")]
            macos_bulk_attempts: Some(
                self.macos_bulk_attempts.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(target_os = "macos"))]
            macos_bulk_attempts: None,
            #[cfg(target_os = "macos")]
            macos_bulk_successes: Some(
                self.macos_bulk_successes.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(target_os = "macos"))]
            macos_bulk_successes: None,
            #[cfg(target_os = "macos")]
            macos_bulk_fallbacks: Some(
                self.macos_bulk_fallbacks.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(target_os = "macos"))]
            macos_bulk_fallbacks: None,
            #[cfg(target_os = "macos")]
            unavailable_reason: None,
            #[cfg(not(target_os = "macos"))]
            unavailable_reason: Some(
                "macOS bulk directory enumeration is unavailable on this platform",
            ),
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_attempts: Some(
                self.linux_dents_attempts.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
            linux_dents_attempts: None,
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_successes: Some(
                self.linux_dents_successes.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
            linux_dents_successes: None,
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            linux_dents_fallbacks: Some(
                self.linux_dents_fallbacks.load(std::sync::atomic::Ordering::Relaxed),
            ),
            #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
            linux_dents_fallbacks: None,
        };
        ScanDiagnostics {
            schema: SCAN_DIAGNOSTICS_SCHEMA,
            worker_policy: WorkerPolicyDiagnostics {
                controller: worker_policy_experiment_name(self.policy),
                available_parallelism: self.available_parallelism,
                initial_workers: self.pool.initial,
                maximum_workers: self.pool.maximum,
                calibration_window_entries: calibration.map(|value| value.minimum_entries),
                slow_threshold_ns_per_entry: calibration.map(|value| value.slow_work_ns_per_entry),
                calibration_chunks: self
                    .calibration_chunks
                    .load(std::sync::atomic::Ordering::Relaxed),
                calibration_entries: self
                    .calibration_entries
                    .load(std::sync::atomic::Ordering::Relaxed),
                calibration_work_ns: self
                    .calibration_work_ns
                    .load(std::sync::atomic::Ordering::Relaxed),
                worker_expansions: self
                    .worker_expansions
                    .load(std::sync::atomic::Ordering::Relaxed),
                outcome: trace.outcome,
                outcome_reason: trace.outcome_reason,
                workers_spawned: self.workers_spawned.load(std::sync::atomic::Ordering::Relaxed),
                peak_active_workers: self
                    .peak_active_workers
                    .load(std::sync::atomic::Ordering::Relaxed),
                ready_directories_at_finish: trace.ready_directories_at_finish,
                in_flight_directories_at_finish: trace.in_flight_directories_at_finish,
                handoff_backlog_at_finish: self
                    .handoff_backlog
                    .load(std::sync::atomic::Ordering::Relaxed),
                handoff_backlog_high_water: self
                    .handoff_backlog_high_water
                    .load(std::sync::atomic::Ordering::Relaxed),
                windows: {
                    let mut windows = trace.windows.clone();
                    windows.sort_by_key(|window| window.sequence);
                    windows
                },
                events_truncated: trace.events_truncated,
            },
            backend,
        }
    }
}

const fn worker_policy_experiment_name(value: WorkerPolicyExperiment) -> &'static str {
    match value {
        WorkerPolicyExperiment::ShippedOneShot => "shipped_one_shot",
        WorkerPolicyExperiment::RepeatedWindows => "repeated_windows",
        WorkerPolicyExperiment::StagedGatedWindows => "staged_gated_windows",
    }
}

struct ScanWorkerGuard {
    recorder: std::sync::Arc<ScanDiagnosticsRecorder>,
}

impl Drop for ScanWorkerGuard {
    fn drop(&mut self) {
        let previous =
            self.recorder.active_workers.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
        debug_assert!(previous > 0, "worker guard must balance worker start");
    }
}

fn atomic_update_max(target: &std::sync::atomic::AtomicUsize, value: usize) {
    let mut observed = target.load(std::sync::atomic::Ordering::Relaxed);
    while value > observed {
        match target.compare_exchange_weak(
            observed,
            value,
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(actual) => observed = actual,
        }
    }
}

enum WalkMessage {
    Batch(ScannerBatch),
    DetachedDirectories {
        directories: Vec<DetachedDirectory>,
        /// The worker that allocated `directories`. The consumer drains each listing
        /// into the index and sends the emptied listings back here, so their path and
        /// child buffers are freed or reused on that worker's thread (H159).
        recycle: std::sync::mpsc::Sender<Vec<DetachedDirectory>>,
    },
    ScaleUp {
        sender: std::sync::mpsc::Sender<Self>,
        target_workers: usize,
    },
}

impl WorkerPool {
    const fn fixed(workers: usize) -> Self {
        Self { initial: workers, maximum: workers, calibration: None }
    }
}

impl WorkerCalibration {
    const fn new(minimum_entries: u64, slow_work_ns_per_entry: u64) -> Self {
        Self { minimum_entries, slow_work_ns_per_entry, entries: 0, work_ns: 0, chunks: 0 }
    }

    fn observe(&mut self, entries: u64, work_ns: u64) -> Option<bool> {
        self.chunks = self.chunks.saturating_add(1);
        self.entries = self.entries.saturating_add(entries);
        self.work_ns = self.work_ns.saturating_add(work_ns);
        (self.entries >= self.minimum_entries)
            .then(|| self.work_ns / self.entries >= self.slow_work_ns_per_entry)
    }
}

#[derive(Clone, Copy, Debug)]
struct CalibrationWindow {
    start_entry_ordinal: u64,
    end_entry_ordinal: u64,
    entries: u64,
    chunks: u64,
    work_ns: u64,
    slow: bool,
}

#[derive(Debug)]
struct RepeatedCalibration {
    minimum_entries: u64,
    slow_work_ns_per_entry: u64,
    window_start: u64,
    entries: u64,
    chunks: u64,
    work_ns: u64,
    completed_windows: u64,
}

impl RepeatedCalibration {
    const fn new(calibration: WorkerCalibration) -> Self {
        Self {
            minimum_entries: calibration.minimum_entries,
            slow_work_ns_per_entry: calibration.slow_work_ns_per_entry,
            window_start: 0,
            entries: 0,
            chunks: 0,
            work_ns: 0,
            completed_windows: 0,
        }
    }

    const fn starting_at(calibration: WorkerCalibration, window_start: u64) -> Self {
        let mut repeated = Self::new(calibration);
        repeated.window_start = window_start;
        repeated
    }

    fn observe(&mut self, entries: u64, work_ns: u64) -> Option<CalibrationWindow> {
        self.chunks = self.chunks.saturating_add(1);
        self.entries = self.entries.saturating_add(entries);
        self.work_ns = self.work_ns.saturating_add(work_ns);
        if self.entries < self.minimum_entries {
            return None;
        }
        let end_entry_ordinal = self.window_start.saturating_add(self.entries);
        let window = CalibrationWindow {
            start_entry_ordinal: self.window_start,
            end_entry_ordinal,
            entries: self.entries,
            chunks: self.chunks,
            work_ns: self.work_ns,
            slow: self.work_ns / self.entries >= self.slow_work_ns_per_entry,
        };
        self.window_start = end_entry_ordinal;
        self.entries = 0;
        self.chunks = 0;
        self.work_ns = 0;
        self.completed_windows = self.completed_windows.saturating_add(1);
        Some(window)
    }
}

#[derive(Debug)]
enum WorkerController {
    OneShot(WorkerCalibration),
    Repeated { calibration: RepeatedCalibration, staged_gated: bool },
}

impl WorkerController {
    fn new(calibration: WorkerCalibration, policy: WorkerPolicyExperiment) -> Self {
        match policy {
            WorkerPolicyExperiment::ShippedOneShot => Self::OneShot(calibration),
            WorkerPolicyExperiment::RepeatedWindows => Self::Repeated {
                calibration: RepeatedCalibration::new(calibration),
                staged_gated: false,
            },
            WorkerPolicyExperiment::StagedGatedWindows => Self::Repeated {
                calibration: RepeatedCalibration::new(calibration),
                staged_gated: true,
            },
        }
    }

    fn observe(&mut self, entries: u64, work_ns: u64) -> Option<CalibrationWindow> {
        match self {
            Self::OneShot(calibration) => {
                let slow = calibration.observe(entries, work_ns)?;
                Some(CalibrationWindow {
                    start_entry_ordinal: 0,
                    end_entry_ordinal: calibration.entries,
                    entries: calibration.entries,
                    chunks: calibration.chunks,
                    work_ns: calibration.work_ns,
                    slow,
                })
            }
            Self::Repeated { calibration, .. } => calibration.observe(entries, work_ns),
        }
    }

    fn partial_window(&self) -> (CalibrationWindow, WorkerPolicyDecision) {
        match self {
            Self::OneShot(calibration) => (
                CalibrationWindow {
                    start_entry_ordinal: 0,
                    end_entry_ordinal: calibration.entries,
                    entries: calibration.entries,
                    chunks: calibration.chunks,
                    work_ns: calibration.work_ns,
                    slow: false,
                },
                WorkerPolicyDecision::Undecided,
            ),
            Self::Repeated { calibration, .. } => (
                CalibrationWindow {
                    start_entry_ordinal: calibration.window_start,
                    end_entry_ordinal: calibration.window_start.saturating_add(calibration.entries),
                    entries: calibration.entries,
                    chunks: calibration.chunks,
                    work_ns: calibration.work_ns,
                    slow: false,
                },
                if calibration.completed_windows == 0 {
                    WorkerPolicyDecision::Undecided
                } else {
                    WorkerPolicyDecision::Incomplete
                },
            ),
        }
    }

    const fn is_staged_gated(&self) -> bool {
        matches!(self, Self::Repeated { staged_gated: true, .. })
    }

    const fn is_one_shot(&self) -> bool {
        matches!(self, Self::OneShot(_))
    }

    const fn calibration_spec(&self) -> WorkerCalibration {
        match self {
            Self::OneShot(calibration) => WorkerCalibration::new(
                calibration.minimum_entries,
                calibration.slow_work_ns_per_entry,
            ),
            Self::Repeated { calibration, .. } => WorkerCalibration::new(
                calibration.minimum_entries,
                calibration.slow_work_ns_per_entry,
            ),
        }
    }
}

fn automatic_worker_pool(available: usize) -> WorkerPool {
    let initial = available.clamp(1, DEFAULT_SCAN_THREADS_CAP);
    // Preserve the serial fallback when the platform cannot report more than one
    // available processor. There is no measured basis for inventing parallelism there.
    if initial == 1 {
        return WorkerPool::fixed(1);
    }
    let maximum = available
        .saturating_mul(ADAPTIVE_SCAN_PARALLELISM_MULTIPLIER)
        .clamp(initial, ADAPTIVE_SCAN_THREADS_CAP);
    WorkerPool {
        initial,
        maximum,
        calibration: (maximum > initial).then_some(WorkerCalibration::new(
            ADAPTIVE_SCAN_CALIBRATION_ENTRIES,
            ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY,
        )),
    }
}

/// Directories handed to a worker in one go.
///
/// Popping one directory at a time makes the queue lock the bottleneck on a wide,
/// shallow tree; taking a small run amortizes the lock without letting one worker
/// starve the others by hoarding the queue.
const DIR_CLAIM: usize = 4;

/// A parallel directory walk that produces exactly the observations the serial walk does.
///
/// The shape is deliberate. Workers read directories and *produce* observations; they
/// never touch an index. A single consumer — the caller's sink, on this thread —
/// applies them. That keeps the crate's one mutation contract intact: parallelism is a
/// property of the producer, and the index still sees one ordered stream of observations.
///
/// Ordering across independent subtrees is not fixed, but a directory observation is
/// published before that directory becomes claimable. The index therefore sees a
/// parent-first causal stream without imposing a global level barrier or serializing
/// filesystem work. The resulting index is byte-identical to the serial walker's,
/// which the benchmark harness re-proves on every trial by comparing engine digests
/// against an independent oracle.
#[allow(clippy::too_many_arguments)]
fn scan_concurrent(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    sink: &mut dyn FnMut(ScannerBatch),
    pool: WorkerPool,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    policy: WorkerPolicyExperiment,
    sink_mode: SinkMode,
) -> ScanReport {
    let mut consume = |message| match message {
        WalkMessage::Batch(batch) => {
            if let Some(diagnostics) = diagnostics {
                diagnostics.handoff_received();
            }
            sink(batch);
        }
        WalkMessage::DetachedDirectories { .. } => {
            unreachable!("the streaming walker never publishes detached directories")
        }
        WalkMessage::ScaleUp { .. } => {
            unreachable!("the shared runner consumes scale-up messages")
        }
    };
    run_concurrent_walk(
        root,
        config,
        root_dev,
        pool,
        diagnostics,
        policy,
        match sink_mode {
            SinkMode::Retained => walk_worker,
            SinkMode::TransientFold => walk_worker_transient_fold,
        },
        &mut consume,
    )
}

/// Parallel cold walk for a detached index that has no streaming consumer.
///
/// Workers publish directory-shaped facts before making their children claimable. The
/// caller consumes those groups into a private builder while filesystem work continues,
/// preserving parent-first causality and pipeline overlap without sending one full path
/// or public observation per entry.
fn scan_concurrent_detached(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    pool: WorkerPool,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    policy: WorkerPolicyExperiment,
    retention: Option<TreeRetention>,
) -> Result<(ScanReport, DetachedIndexBuilder)> {
    let mut builder = detached_builder(root, config, retention);
    let mut build_error = None;
    let output = {
        let mut consume = |message| match message {
            WalkMessage::Batch(_) => {
                unreachable!("the detached walker never publishes scanner batches")
            }
            WalkMessage::DetachedDirectories { mut directories, recycle } => {
                if let Some(diagnostics) = diagnostics {
                    diagnostics.handoff_received();
                }
                if build_error.is_none() {
                    for directory in &mut directories {
                        if let Err(error) = builder.push_directory(directory) {
                            build_error = Some(error);
                            break;
                        }
                    }
                }
                // A worker that has already left has dropped its receiver, and then the
                // listings are freed here, as every listing was before H159.
                let _ = recycle.send(directories);
            }
            WalkMessage::ScaleUp { .. } => {
                unreachable!("the shared runner consumes scale-up messages")
            }
        };
        // A folded index takes H72's listing policy (H185); the full index stats every
        // entry, since its directory attributes are the cache's freshness fingerprint.
        let worker: WalkWorker =
            if retention.is_some() { walk_detached_folding_worker } else { walk_detached_worker };
        run_concurrent_walk(root, config, root_dev, pool, diagnostics, policy, worker, &mut consume)
    };
    if let Some(error) = build_error {
        return Err(error);
    }
    Ok((output, builder))
}

type WalkWorker = fn(
    &Path,
    &ScanConfig,
    u64,
    &DirectoryQueue,
    &std::sync::mpsc::Sender<WalkMessage>,
    Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
) -> ScanReport;

/// Run the shared pool, scaling controller, diagnostics, and report reduction.
///
/// Streaming and detached scans differ only in their worker emission and main-thread
/// consumer. Keeping orchestration here prevents fixes to termination, diagnostics, or
/// panic handling from diverging between the two cold paths.
#[allow(clippy::too_many_arguments)]
fn run_concurrent_walk<C>(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    pool: WorkerPool,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    policy: WorkerPolicyExperiment,
    worker: WalkWorker,
    consume: &mut C,
) -> ScanReport
where
    C: FnMut(WalkMessage),
{
    let diagnostics = diagnostics.cloned();
    let queue = DirectoryQueue::new_with_policy(
        (PathBuf::new(), 0),
        config.order,
        pool.calibration,
        diagnostics.clone(),
        pool.initial,
        pool.maximum,
        policy,
    );
    let (sender, receiver) = std::sync::mpsc::channel::<WalkMessage>();

    let mut report = std::thread::scope(|scope| {
        let mut handles: Vec<_> = (0..pool.initial)
            .map(|_| {
                let sender = sender.clone();
                let queue = &queue;
                let diagnostics = diagnostics.clone();
                scope.spawn(move || {
                    worker(root, config, root_dev, queue, &sender, diagnostics.as_ref())
                })
            })
            .collect();
        // The loop below ends when every sender is gone, so this one must go first.
        drop(sender);

        let mut spawned_workers = pool.initial;
        for message in receiver {
            match message {
                WalkMessage::ScaleUp { sender, target_workers }
                    if target_workers > spawned_workers =>
                {
                    let target_workers = target_workers.min(pool.maximum);
                    record_adaptive_worker_expansion(diagnostics.as_ref());
                    for _ in spawned_workers..target_workers {
                        let sender = sender.clone();
                        let queue = &queue;
                        let diagnostics = diagnostics.clone();
                        handles.push(scope.spawn(move || {
                            worker(root, config, root_dev, queue, &sender, diagnostics.as_ref())
                        }));
                    }
                    spawned_workers = target_workers;
                }
                WalkMessage::ScaleUp { .. } => {}
                output => consume(output),
            }
        }

        // A walk that ends before its calibration window fills never observed enough to
        // decide anything. That is an *unobservable* policy, not a decision to hold the
        // initial pool, and an artifact that conflated the two would report a held pool
        // as if the walk had measured one and chosen it.
        let queue_finish = {
            let mut state = queue.lock();
            let mut trailing_window = None;
            if let Some(controller) = &state.controller {
                let (window, decision) = controller.partial_window();
                if decision == WorkerPolicyDecision::Undecided {
                    crate::counters::bump(|counts| {
                        counts.adaptive_policy_undecided =
                            counts.adaptive_policy_undecided.saturating_add(1);
                    });
                }
                if diagnostics.is_some() {
                    let sequence = state.allocate_policy_sequence();
                    trailing_window = Some(PolicyWindowSnapshot {
                        sequence,
                        start_entry_ordinal: window.start_entry_ordinal,
                        end_entry_ordinal: window.end_entry_ordinal,
                        observed_entries: window.entries,
                        observed_chunks: window.chunks,
                        observed_work_ns: window.work_ns,
                        ready_directories: state.ready_directories,
                        in_flight_directories: state.in_flight_directories,
                        active_workers: diagnostics.as_ref().map_or(0, |diagnostics| {
                            diagnostics.active_workers.load(std::sync::atomic::Ordering::Relaxed)
                        }),
                        handoff_backlog: diagnostics.as_ref().map_or(0, |diagnostics| {
                            diagnostics.handoff_backlog.load(std::sync::atomic::Ordering::Relaxed)
                        }),
                        requested_workers: None,
                        decision,
                    });
                }
            } else if diagnostics.is_some() {
                let shadow = state.shadow_calibration.as_ref().and_then(|shadow| {
                    (shadow.entries > 0).then_some((
                        shadow.window_start,
                        shadow.entries,
                        shadow.chunks,
                        shadow.work_ns,
                    ))
                });
                if let Some((window_start, entries, chunks, work_ns)) = shadow {
                    let sequence = state.allocate_policy_sequence();
                    trailing_window = Some(PolicyWindowSnapshot {
                        sequence,
                        start_entry_ordinal: window_start,
                        end_entry_ordinal: window_start.saturating_add(entries),
                        observed_entries: entries,
                        observed_chunks: chunks,
                        observed_work_ns: work_ns,
                        ready_directories: state.ready_directories,
                        in_flight_directories: state.in_flight_directories,
                        active_workers: diagnostics.as_ref().map_or(0, |diagnostics| {
                            diagnostics.active_workers.load(std::sync::atomic::Ordering::Relaxed)
                        }),
                        handoff_backlog: diagnostics.as_ref().map_or(0, |diagnostics| {
                            diagnostics.handoff_backlog.load(std::sync::atomic::Ordering::Relaxed)
                        }),
                        requested_workers: None,
                        decision: WorkerPolicyDecision::ObserveIncomplete,
                    });
                }
            }
            (state.ready_directories, state.in_flight_directories, trailing_window)
        };
        if let Some(diagnostics) = &diagnostics {
            diagnostics.record_queue_finish(queue_finish.0, queue_finish.1);
            if let Some(window) = queue_finish.2 {
                diagnostics.record_policy_window(window);
            }
        }

        let mut report = ScanReport::default();
        for handle in handles {
            match handle.join() {
                Ok(worker) => report.absorb(worker),
                Err(_) => {
                    // A worker panic leaves directories unaccounted for. Preserve that
                    // as a partial scan instead of reporting a short tree as complete.
                    report.errors.push(Error::io(
                        root,
                        std::io::Error::other("a scan worker thread panicked"),
                    ));
                }
            }
        }
        report
    });

    // Workers finish in filesystem order, so normalize errors before they escape.
    report.errors.sort_by_cached_key(ToString::to_string);
    report
}

/// Compile-time adapter for the one directory walker.
///
/// The filesystem, queue, admission, and diagnostics logic stays singular. Generic
/// emission keeps the public streaming path and private detached path branch-free in
/// their per-entry loops after monomorphization.
trait WalkEmission {
    type Directory;

    fn begin_directory(&mut self, path: &Path) -> Self::Directory;

    #[allow(clippy::too_many_arguments)]
    fn record_entry(
        &mut self,
        root: &Path,
        rel_dir: &Path,
        depth: usize,
        region: RegionId,
        name: &OsStr,
        kind: EntryKind,
        attrs: Attrs,
        root_dev: u64,
        config: &ScanConfig,
        directory: &mut Self::Directory,
        discovered: &mut Vec<(PathBuf, usize, RegionId)>,
        report: &mut ScanReport,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool;

    fn finish_directory(&mut self, directory: Self::Directory);

    fn publish_before_discovery(
        &mut self,
        has_discovered: bool,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool;

    fn finish(
        &mut self,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        report: &mut ScanReport,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    );

    /// The transient summary and the folded index take directory and symlink kind from
    /// the listing, with default attributes (H72, H185); every other route stats them.
    fn skip_dir_symlink_stat(&self) -> bool {
        false
    }
}

struct StreamingEmission {
    batch: Vec<ObservationOp>,
    batch_size: usize,
    recycle_tx: Option<std::sync::mpsc::Sender<Vec<ObservationOp>>>,
    recycle_rx: Option<std::sync::mpsc::Receiver<Vec<ObservationOp>>>,
    skip_dir_symlink_stat: bool,
    /// Whether each listing's control goes ahead of its entries
    /// ([`SinkMode::groups_directories`]).
    group_directories: bool,
    /// Where the listing being recorded begins in `batch`.
    directory_start: usize,
    /// Whether that listing's control already leads its observations, so the batch may be
    /// sent before the listing ends.
    listing_settled: bool,
    /// Where that listing stands on its directory's control.
    listing_control: ListingControl,
}

/// Where the listing a grouping worker is recording stands on its directory's control.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ListingControl {
    /// No listed spelling of `.gitignore` has read the directory's control yet.
    Unread,
    /// A listed spelling read the directory's control, or failed to; its observation, if
    /// any, is among the held ones.
    Listed,
    /// The held observations filled the batch before any listed spelling read the
    /// control, so the directory's control was looked up directly (`read_directory_control`)
    /// and stands for the whole listing, as in the narrowed-population walk.
    ///
    /// A spelling listed afterwards is recorded as a row and not read again, so the
    /// directory's control file is read once. On a tree nothing modifies during the walk
    /// the probed file is the listed one; if the file changes between the two, the listing
    /// keeps what the probe read, and an error the second read would have met is never
    /// met.
    Probed,
}

impl StreamingEmission {
    /// An emission with the properties [`SinkMode`] names for `mode` under `config`.
    ///
    /// The recycle channel returns drained `PathBuf` arenas to this worker so glibc
    /// frees them on the thread that allocated them.
    fn for_sink(config: &ScanConfig, mode: SinkMode) -> Self {
        let batch_size = config.batch_size;
        let (recycle_tx, recycle_rx) = if mode.recycles_batches() {
            let (tx, rx) = std::sync::mpsc::channel();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };
        Self {
            batch: Vec::with_capacity(batch_size),
            batch_size,
            recycle_tx,
            recycle_rx,
            skip_dir_symlink_stat: mode.skips_dir_symlink_stat(),
            group_directories: mode.groups_directories(config),
            directory_start: 0,
            listing_settled: false,
            listing_control: ListingControl::Unread,
        }
    }

    /// Send the batch once it is full, settling a grouped listing's control first.
    ///
    /// A grouped listing's observations are held until its control leads them: at the
    /// listing's end ([`WalkEmission::finish_directory`]), or here, when the batch fills
    /// first. So a batch never holds more than `batch_size` observations and one control,
    /// however long the listing, and a fill that finds no spelling of `.gitignore` listed
    /// yet probes for it once per listing: one metadata lookup, and a read on a hit
    /// (`read_directory_control`). Returns whether the consumer is still there.
    #[allow(clippy::too_many_arguments)]
    fn send_if_full(
        &mut self,
        root: &Path,
        rel_dir: &Path,
        config: &ScanConfig,
        report: &mut ScanReport,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        if self.batch.len() < self.batch_size {
            return true;
        }
        if self.group_directories && !self.listing_settled {
            self.settle_listing(root, rel_dir, config, report);
        }
        let send_started = std::time::Instant::now();
        let sent = self.send_full(sender, diagnostics);
        *chunk_send_ns += elapsed_ns(send_started);
        sent
    }

    /// Put the current listing's control ahead of its held observations.
    fn settle_listing(
        &mut self,
        root: &Path,
        rel_dir: &Path,
        config: &ScanConfig,
        report: &mut ScanReport,
    ) {
        self.listing_settled = true;
        if self.listing_control != ListingControl::Unread {
            controls_first(&mut self.batch[self.directory_start..]);
            return;
        }
        self.listing_control = ListingControl::Probed;
        let control = rel_dir.join(crate::control::CONTROL_FILE_NAME);
        // The probe is the lookup the rule names, so a hit stands for the directory
        // whichever spelling it resolved to, exactly as a listed spelling's read would.
        match read_directory_control(config, root, &control) {
            Ok(Some(op)) => {
                self.batch.insert(self.directory_start, ObservationOp::unconditional(op));
            }
            Ok(None) => {}
            Err(error) => report.errors.push(error),
        }
    }

    /// Whether the entries this listing still lists must not read their control: its
    /// directory's control was already probed, and one read stands for the listing, as in
    /// the narrowed-population walk (`read_listed_control_op`).
    fn control_probed(&self) -> bool {
        self.group_directories && self.listing_control == ListingControl::Probed
    }

    /// Note that a listed entry read this listing's control, or failed to.
    fn note_listed_control(&mut self, control: Option<&Op>, control_error: Option<&Error>) {
        if control.is_some() || control_error.is_some() {
            self.listing_control = ListingControl::Listed;
        }
    }

    fn wrap(&self, ops: Vec<ObservationOp>) -> ScannerBatch {
        match &self.recycle_tx {
            Some(recycle) => ScannerBatch::new(ops).with_recycle(recycle.clone()),
            None => ScannerBatch::new(ops),
        }
    }

    fn next_vec(&self) -> Vec<ObservationOp> {
        // The retained path keeps its pre-H147 shape: an empty vec that grows by
        // doubling. Pre-sizing every batch there was never measured, and the public
        // `scan` is what a library caller pays for.
        let Some(recycle_rx) = &self.recycle_rx else {
            return Vec::new();
        };
        let mut kept = None;
        while let Ok(mut recycled) = recycle_rx.try_recv() {
            recycled.clear();
            kept = Some(recycled);
        }
        kept.unwrap_or_else(|| Vec::with_capacity(self.batch_size))
    }

    fn send_full(
        &mut self,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        let ops = std::mem::take(&mut self.batch);
        let sent = send_scanner_batch(sender, self.wrap(ops), diagnostics);
        self.batch = self.next_vec();
        // A listing sent partway continues at the start of the new batch.
        self.directory_start = 0;
        sent
    }
}

impl WalkEmission for StreamingEmission {
    type Directory = ();

    fn begin_directory(&mut self, _path: &Path) {
        self.directory_start = self.batch.len();
        self.listing_settled = false;
        self.listing_control = ListingControl::Unread;
    }

    #[allow(clippy::too_many_arguments)]
    fn record_entry(
        &mut self,
        root: &Path,
        rel_dir: &Path,
        depth: usize,
        region: RegionId,
        name: &OsStr,
        kind: EntryKind,
        attrs: Attrs,
        root_dev: u64,
        config: &ScanConfig,
        _directory: &mut Self::Directory,
        discovered: &mut Vec<(PathBuf, usize, RegionId)>,
        report: &mut ScanReport,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        record_walk_entry(
            root,
            rel_dir,
            depth,
            region,
            name,
            kind,
            attrs,
            root_dev,
            config,
            self,
            discovered,
            report,
            sender,
            chunk_send_ns,
            diagnostics,
        )
    }

    fn finish_directory(&mut self, _directory: Self::Directory) {
        if self.group_directories && !self.listing_settled {
            controls_first(&mut self.batch[self.directory_start..]);
        }
    }

    fn publish_before_discovery(
        &mut self,
        has_discovered: bool,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        if self.batch.is_empty() || !has_discovered {
            return true;
        }
        let send_started = std::time::Instant::now();
        let sent = self.send_full(sender, diagnostics);
        *chunk_send_ns += elapsed_ns(send_started);
        sent
    }

    fn finish(
        &mut self,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        report: &mut ScanReport,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) {
        if self.batch.is_empty() {
            return;
        }
        let send_started = std::time::Instant::now();
        // The walk is over: do not ask `send_full` for a replacement vec that no
        // later `record_entry` would use.
        let ops = std::mem::take(&mut self.batch);
        let _ = send_scanner_batch(sender, self.wrap(ops), diagnostics);
        self.batch = Vec::new();
        report.attribution.send_ns += elapsed_ns(send_started);
    }

    fn skip_dir_symlink_stat(&self) -> bool {
        self.skip_dir_symlink_stat
    }
}

/// Emptied listings one detached worker keeps for reuse: one chunk's worth.
///
/// A bound on retention, not a tuned speed value. A chunk claims at most [`DIR_CLAIM`]
/// directories, and the worker takes returned listings back once per chunk, so this
/// covers the next chunk; a listing returned past it is freed at once, still on its own
/// thread, which is the property H159 needs. Retained listings are memory the consumer
/// can no longer reuse for the index: four chunks' worth of listings up to 256 children
/// each cost 1.0 MiB (+1.4%) of peak RSS on a 158,705-entry macOS subject and 2.3 MiB
/// (+5.0%) on a 77,159-entry one.
const DETACHED_SPARE_LISTINGS: usize = DIR_CLAIM;

/// The largest child buffer, in children, a spare listing may keep.
///
/// Also a bound on retention rather than a tuned value: most directories are small, and
/// a listing whose buffer grew past this, at about 80 bytes per child, is freed when it
/// comes back, on its own thread, instead of being pinned for the rest of the walk.
const DETACHED_SPARE_CHILD_CAPACITY: usize = 64;

/// One worker's detached emission: listings built here and published to the consumer.
///
/// Every path and child buffer in a listing is allocated on this worker's thread. The
/// consumer drains each listing into the index and sends the emptied listings back
/// (H159), and the worker reuses them or frees them itself. Under glibc a chunk freed on
/// another thread goes back to the arena that allocated it, under that arena's lock,
/// while this worker is allocating from it; the 2026-09-27 Linux comparison's allocator
/// screen and context-switch profile point at that contention for the index tier's gap
/// to its peers. A reused listing carries exactly the facts a fresh one would: the same
/// path bytes, and children and control only from this directory's listing.
struct DetachedEmission {
    /// H72's listing policy for the folded index (H185): a directory or symlink takes its
    /// kind from `d_type` and default attributes, as the transient summary does. A
    /// one-shot tree report reads no directory's or symlink's own attributes: its rows
    /// carry roll-ups, `newest_mtime_ns` is the files', symlinks and other kinds
    /// contribute nothing, and `dev` is read only under `--one-filesystem`, where the
    /// policy keeps the stat. The full index keeps every stat: its directory attributes
    /// are the cache's freshness fingerprint.
    skip_dir_symlink_stat: bool,
    directories: Vec<DetachedDirectory>,
    /// Emptied listings ready to be reused by [`WalkEmission::begin_directory`].
    spare: Vec<DetachedDirectory>,
    /// An emptied list to publish the next chunk's listings in.
    spare_list: Vec<DetachedDirectory>,
    recycle_tx: std::sync::mpsc::Sender<Vec<DetachedDirectory>>,
    recycle_rx: std::sync::mpsc::Receiver<Vec<DetachedDirectory>>,
}

impl DetachedEmission {
    fn new(skip_dir_symlink_stat: bool) -> Self {
        let (recycle_tx, recycle_rx) = std::sync::mpsc::channel();
        Self {
            skip_dir_symlink_stat,
            directories: Vec::new(),
            spare: Vec::new(),
            spare_list: Vec::new(),
            recycle_tx,
            recycle_rx,
        }
    }

    /// Take back every list the consumer has returned since the last chunk.
    ///
    /// A listing the consumer skipped, after a build error or for a repeated directory,
    /// comes back with its children and control still in it; they are dropped here, on
    /// the thread that allocated them, before the listing can be reused.
    fn collect_returned(&mut self) {
        while let Ok(mut returned) = self.recycle_rx.try_recv() {
            for mut directory in returned.drain(..) {
                directory.children.clear();
                directory.control = None;
                if self.spare.len() < DETACHED_SPARE_LISTINGS
                    && directory.children.capacity() <= DETACHED_SPARE_CHILD_CAPACITY
                {
                    self.spare.push(directory);
                }
            }
            if self.spare_list.capacity() == 0 {
                self.spare_list = returned;
            }
        }
    }
}

impl WalkEmission for DetachedEmission {
    type Directory = DetachedDirectory;

    fn skip_dir_symlink_stat(&self) -> bool {
        self.skip_dir_symlink_stat
    }

    fn begin_directory(&mut self, path: &Path) -> Self::Directory {
        let Some(mut directory) = self.spare.pop() else {
            return DetachedDirectory {
                path: path.to_path_buf(),
                children: Vec::new(),
                control: None,
            };
        };
        // The same bytes `to_path_buf` would copy, into a buffer this thread already owns.
        let buffer = directory.path.as_mut_os_string();
        buffer.clear();
        buffer.push(path);
        debug_assert!(directory.children.is_empty() && directory.control.is_none());
        directory
    }

    #[allow(clippy::too_many_arguments)]
    fn record_entry(
        &mut self,
        root: &Path,
        rel_dir: &Path,
        depth: usize,
        region: RegionId,
        name: &OsStr,
        kind: EntryKind,
        attrs: Attrs,
        root_dev: u64,
        config: &ScanConfig,
        directory: &mut Self::Directory,
        discovered: &mut Vec<(PathBuf, usize, RegionId)>,
        report: &mut ScanReport,
        _sender: &std::sync::mpsc::Sender<WalkMessage>,
        _chunk_send_ns: &mut u64,
        _diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        record_detached_entry(
            root,
            rel_dir,
            depth,
            region,
            name,
            kind,
            attrs,
            root_dev,
            config,
            &mut directory.children,
            &mut directory.control,
            discovered,
            report,
        );
        true
    }

    fn finish_directory(&mut self, directory: Self::Directory) {
        self.directories.push(directory);
    }

    fn publish_before_discovery(
        &mut self,
        _has_discovered: bool,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        chunk_send_ns: &mut u64,
        diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) -> bool {
        if self.directories.is_empty() {
            return true;
        }
        // Taking back returned listings is handoff work, timed with the send so the
        // chunk's work time, which calibrates the worker pool, stays the walk's own.
        let send_started = std::time::Instant::now();
        self.collect_returned();
        let next = std::mem::take(&mut self.spare_list);
        let directories = std::mem::replace(&mut self.directories, next);
        let sent =
            send_detached_directories(sender, directories, self.recycle_tx.clone(), diagnostics);
        *chunk_send_ns += elapsed_ns(send_started);
        sent
    }

    fn finish(
        &mut self,
        _sender: &std::sync::mpsc::Sender<WalkMessage>,
        _report: &mut ScanReport,
        _diagnostics: Option<&ScanDiagnosticsRecorder>,
    ) {
    }
}

fn walk_detached_worker(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
) -> ScanReport {
    walk_detached_with(root, config, root_dev, queue, sender, diagnostics, false)
}

/// [`walk_detached_worker`] for a folded index, which describes each directory once, by
/// its own listing (H185): see [`DetachedEmission::skip_dir_symlink_stat`].
fn walk_detached_folding_worker(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
) -> ScanReport {
    walk_detached_with(root, config, root_dev, queue, sender, diagnostics, true)
}

fn walk_detached_with(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    skip_dir_symlink_stat: bool,
) -> ScanReport {
    let report = walk_worker_with(
        root,
        config,
        root_dev,
        queue,
        sender,
        diagnostics,
        DetachedEmission::new(skip_dir_symlink_stat),
    );
    // A walker leaves only when the queue is empty with nothing in flight, or when its
    // consumer is gone, so the walk is over. The index may still be assembling the
    // listings already sent; the counters have stopped, and the phase says why.
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Indexing);
    }
    report
}

/// One worker's share of the public observation walk.
fn walk_worker(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
) -> ScanReport {
    walk_worker_with(
        root,
        config,
        root_dev,
        queue,
        sender,
        diagnostics,
        StreamingEmission::for_sink(config, SinkMode::Retained),
    )
}

/// One worker's share of the transient summary walk.
fn walk_worker_transient_fold(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
) -> ScanReport {
    walk_worker_with(
        root,
        config,
        root_dev,
        queue,
        sender,
        diagnostics,
        StreamingEmission::for_sink(config, SinkMode::TransientFold),
    )
}

fn walk_worker_with<E: WalkEmission>(
    root: &Path,
    config: &ScanConfig,
    root_dev: u64,
    queue: &DirectoryQueue,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    mut emission: E,
) -> ScanReport {
    let _counter_guard = crate::counters::thread_flush_guard();
    let _worker_guard = diagnostics.map(ScanDiagnosticsRecorder::worker_guard);
    let worker_started = std::time::Instant::now();
    let mut report = ScanReport::default();
    let mut tally = ProgressTally::new(config.progress.as_ref());
    let mut claimed: Vec<(PathBuf, usize, RegionId)> = Vec::with_capacity(DIR_CLAIM);
    let mut discovered: Vec<(PathBuf, usize, RegionId)> = Vec::new();
    let mut consumer_gone = false;
    #[cfg(target_os = "macos")]
    let mut bulk_reader = macos_bulk::Reader::new();
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    let mut dents_reader = linux_dents::Reader::new();

    'walk: while let Some(claim) = queue.claim(&mut claimed, &mut report.attribution) {
        // One timing pair per claimed chunk, never per entry: the chunk is the unit
        // the amortization argument is made in, so it is the unit the evidence is
        // collected in.
        let chunk_started = std::time::Instant::now();
        let mut chunk_send_ns: u64 = 0;
        let entries_before = report.entries;
        for (rel_dir, depth, region) in claimed.drain(..) {
            let abs_dir = root.join(&rel_dir);
            let mut directory = emission.begin_directory(&rel_dir);
            #[cfg(target_os = "macos")]
            {
                if let Some(diagnostics) = diagnostics {
                    diagnostics.macos_bulk_attempted();
                }
                if let Some(entries) =
                    (!walk_hook_covers(&abs_dir)).then(|| bulk_reader.read(&abs_dir)).flatten()
                {
                    if let Some(diagnostics) = diagnostics {
                        diagnostics.macos_bulk_succeeded();
                    }
                    report.dirs_read += 1;
                    for entry in entries {
                        if !emission.record_entry(
                            root,
                            &rel_dir,
                            depth,
                            region,
                            &entry.name,
                            entry.kind,
                            entry.attrs,
                            root_dev,
                            config,
                            &mut directory,
                            &mut discovered,
                            &mut report,
                            sender,
                            &mut chunk_send_ns,
                            diagnostics.map(AsRef::as_ref),
                        ) {
                            consumer_gone = true;
                            break 'walk;
                        }
                    }
                    emission.finish_directory(directory);
                    continue;
                }
                if let Some(diagnostics) = diagnostics {
                    diagnostics.macos_bulk_fell_back();
                }
            }
            // Counted in the Linux backend fields: an attempt, then a success or a
            // fallback, and a fallback goes on to count as a portable attempt below, so
            // `dirs_read` is the native successes plus the portable reads.
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            {
                if let Some(diagnostics) = diagnostics {
                    diagnostics.linux_dents_attempted();
                }
                let policy = linux_dents::StatPolicy {
                    skip_dir_symlink_stat: emission.skip_dir_symlink_stat(),
                    one_filesystem: config.one_filesystem,
                };
                // Plain `if`, not `bool::then(|| …)`: the listing borrows the reader for the
                // loop.
                let listing = if walk_hook_covers(&abs_dir) {
                    None
                } else {
                    dents_reader.read(&abs_dir, policy)
                };
                if let Some(listing) = listing {
                    if let Some(diagnostics) = diagnostics {
                        diagnostics.linux_dents_succeeded();
                    }
                    report.dirs_read += 1;
                    for entry in listing {
                        let (kind, attrs) = match entry.outcome {
                            linux_dents::Outcome::Observed { kind, attrs } => (kind, attrs),
                            linux_dents::Outcome::Failed(error) => {
                                // The same path std's `DirEntry::path` builds: the listing
                                // path joined with the name.
                                report.errors.push(Error::io(abs_dir.join(entry.name), error));
                                continue;
                            }
                        };
                        if !emission.record_entry(
                            root,
                            &rel_dir,
                            depth,
                            region,
                            entry.name,
                            kind,
                            attrs,
                            root_dev,
                            config,
                            &mut directory,
                            &mut discovered,
                            &mut report,
                            sender,
                            &mut chunk_send_ns,
                            diagnostics.map(AsRef::as_ref),
                        ) {
                            consumer_gone = true;
                            break 'walk;
                        }
                    }
                    emission.finish_directory(directory);
                    continue;
                }
                if let Some(diagnostics) = diagnostics {
                    diagnostics.linux_dents_fell_back();
                }
            }

            crate::counters::bump(|c| c.dir_opens += 1);
            if let Some(diagnostics) = diagnostics {
                diagnostics.portable_attempted();
            }

            let listing = match fs::read_dir(&abs_dir) {
                Ok(listing) => {
                    if let Some(diagnostics) = diagnostics {
                        diagnostics.portable_succeeded();
                    }
                    listing
                }
                Err(e) => {
                    report.errors.push(Error::io(abs_dir, e));
                    continue;
                }
            };
            report.dirs_read += 1;

            let policy = ListingPolicy {
                skip_dir_symlink_stat: emission.skip_dir_symlink_stat(),
                one_filesystem: config.one_filesystem,
            };
            let mut searchability = Searchability::Unproven;
            for item in listing {
                let item = match item {
                    Ok(item) => item,
                    Err(e) => {
                        report.errors.push(Error::io(&abs_dir, e));
                        continue;
                    }
                };
                crate::counters::bump(|c| c.dir_entries += 1);
                let name = item.file_name();
                let (kind, attrs) =
                    match listed_child_kind_and_attrs(&item, policy, &mut searchability) {
                        Ok(Some(observed)) => observed,
                        Ok(None) => continue,
                        Err(error) => {
                            report.errors.push(Error::io(item.path(), error));
                            continue;
                        }
                    };
                if !emission.record_entry(
                    root,
                    &rel_dir,
                    depth,
                    region,
                    &name,
                    kind,
                    attrs,
                    root_dev,
                    config,
                    &mut directory,
                    &mut discovered,
                    &mut report,
                    sender,
                    &mut chunk_send_ns,
                    diagnostics.map(AsRef::as_ref),
                ) {
                    // The consumer is gone; nothing further will be read.
                    consumer_gone = true;
                    break 'walk;
                }
            }
            emission.finish_directory(directory);
        }
        // Publish facts that authorize newly discovered directories before making
        // those directories claimable. Both emission modes preserve this boundary.
        if !emission.publish_before_discovery(
            !discovered.is_empty(),
            sender,
            &mut chunk_send_ns,
            diagnostics.map(AsRef::as_ref),
        ) {
            report.attribution.send_ns += chunk_send_ns;
            report.attribution.work_ns += elapsed_ns(chunk_started).saturating_sub(chunk_send_ns);
            consumer_gone = true;
            break 'walk;
        }
        report.attribution.send_ns += chunk_send_ns;
        let chunk_work_ns = elapsed_ns(chunk_started).saturating_sub(chunk_send_ns);
        report.attribution.work_ns += chunk_work_ns;
        // Progress is reported per chunk for the same reason timing is: the chunk is
        // the unit of handoff, so it is the unit the shared counters are touched in.
        tally.flush(&report);

        // Publish new work before releasing the claim so a worker that finds nothing
        // new does not hold work that others could be doing.
        if !discovered.is_empty() {
            queue.extend(discovered.drain(..), &mut report.attribution);
        }
        if let Some(target_workers) = claim.release(
            report.entries.saturating_sub(entries_before),
            chunk_work_ns,
            &mut report.attribution,
        ) {
            // Carry a sender in-band so the consumer can create the reserve workers
            // without retaining a channel endpoint that would keep a small scan alive.
            // Only the release that completes a slow calibration returns true, so one
            // message expands the pool exactly once.
            let _ = sender.send(WalkMessage::ScaleUp { sender: sender.clone(), target_workers });
        }
    }

    if !consumer_gone {
        emission.finish(sender, &mut report, diagnostics.map(AsRef::as_ref));
    }
    // A worker that left mid-chunk because its consumer was gone still read what it
    // read, and the report it returns says so.
    tally.flush(&report);
    report.attribution.wall_ns = elapsed_ns(worker_started);
    report
}

#[allow(clippy::too_many_arguments)]
fn record_detached_entry(
    root: &Path,
    rel_dir: &Path,
    depth: usize,
    region: RegionId,
    name: &OsStr,
    kind: EntryKind,
    attrs: Attrs,
    root_dev: u64,
    config: &ScanConfig,
    children: &mut Vec<DetachedChild>,
    control: &mut Option<Op>,
    discovered: &mut Vec<(PathBuf, usize, RegionId)>,
    report: &mut ScanReport,
) {
    let disposition = crate::admission::decide(name, kind, config.hidden(), config.exclude_special);
    if disposition == crate::admission::Disposition::Reject {
        return;
    }
    // Construct a full path only for a spelling of the control name. The scanner's public
    // preparation builds one for every retained entry because that path escapes in an
    // observation; this private builder keeps ordinary children component-only.
    if config.read_controls && crate::control::control_spelling(name).is_some() {
        let path = rel_dir.join(name);
        match read_control_op(config, root, &path, kind) {
            // A listing can repeat the control name while the directory changes, and a
            // case-sensitive one can list `.gitignore` beside `.GITIGNORE`, whose lookup
            // reads the same file. The later read wins, as the builder keeps the later
            // observation of the entry.
            Ok(observed) => *control = observed,
            Err(error) => report.errors.push(error),
        }
    }
    if disposition != crate::admission::Disposition::Retain {
        return;
    }
    report.observe(kind, attrs);
    // Positions only order repeated names, and no real listing reaches `u32::MAX` entries.
    let position = u32::try_from(children.len()).unwrap_or(u32::MAX);
    children.push(DetachedChild { name: name.to_os_string(), kind, attrs, position });
    if should_descend(kind, attrs, depth, root_dev, config) {
        let child_region = if depth == 0 { RegionId::UNASSIGNED } else { region };
        discovered.push((rel_dir.join(name), depth + 1, child_region));
    }
}

/// One filesystem entry after the scan's shared admission, control, and descent rules.
pub(crate) struct PreparedWalkEntry {
    pub(crate) path: PathBuf,
    pub(crate) kind: EntryKind,
    pub(crate) attrs: Attrs,
    pub(crate) retained: bool,
    pub(crate) control: Option<Op>,
    pub(crate) descend: bool,
    pub(crate) control_error: Option<Error>,
}

/// Apply the producer-independent part of a directory walk to one verified entry.
///
/// Both blocking and opened-root scans call this after obtaining non-following metadata,
/// which keeps admission, fixed controls, and traversal boundaries from drifting.
#[allow(clippy::too_many_arguments)]
pub(crate) fn prepare_walk_entry(
    root: &Path,
    rel_dir: &Path,
    depth: usize,
    name: &OsStr,
    kind: EntryKind,
    attrs: Attrs,
    root_dev: u64,
    config: &ScanConfig,
) -> Option<PreparedWalkEntry> {
    prepare_walk_entry_reading(root, rel_dir, depth, name, kind, attrs, root_dev, config, true)
}

/// [`prepare_walk_entry`], reading the entry's control only when `read_control` allows.
///
/// A grouping emission whose listing already probed its directory's control passes
/// `false`, so a `.gitignore` listed afterwards is not read a second time
/// (`StreamingEmission::control_probed`).
#[allow(clippy::too_many_arguments)]
fn prepare_walk_entry_reading(
    root: &Path,
    rel_dir: &Path,
    depth: usize,
    name: &OsStr,
    kind: EntryKind,
    attrs: Attrs,
    root_dev: u64,
    config: &ScanConfig,
    read_control: bool,
) -> Option<PreparedWalkEntry> {
    let disposition = crate::admission::decide(name, kind, config.hidden(), config.exclude_special);
    if disposition == crate::admission::Disposition::Reject {
        return None;
    }
    let path = join_listed_name(rel_dir, name);
    let (control, control_error) = if read_control {
        match read_named_control_op(config, root, &path, name, kind) {
            Ok(control) => (control, None),
            Err(error) => (None, Some(error)),
        }
    } else {
        (None, None)
    };
    Some(PreparedWalkEntry {
        path,
        kind,
        attrs,
        retained: disposition == crate::admission::Disposition::Retain,
        control,
        descend: should_descend(kind, attrs, depth, root_dev, config),
        control_error,
    })
}

/// `rel_dir.join(name)`, allocated once at the joined length.
///
/// [`Path::join`] copies `rel_dir` at its exact length and pushes onto the copy, so the
/// separator grows it and, for a name longer than the directory, so does the name: a
/// `realloc` for nearly every entry a streaming walk prepares. The summary route's
/// walkers spent 760-820 instructions per entry joining, and 410-450 in `realloc`
/// against the detached route's 85-150 (H180). The same push onto a copy that already
/// fits both makes the same path, byte for byte, on every platform.
fn join_listed_name(rel_dir: &Path, name: &OsStr) -> PathBuf {
    let mut path = PathBuf::with_capacity(rel_dir.as_os_str().len() + 1 + name.len());
    path.as_mut_os_string().push(rel_dir);
    path.push(name);
    path
}

#[allow(clippy::too_many_arguments)]
fn record_walk_entry(
    root: &Path,
    rel_dir: &Path,
    depth: usize,
    region: RegionId,
    name: &OsStr,
    kind: EntryKind,
    attrs: Attrs,
    root_dev: u64,
    config: &ScanConfig,
    emission: &mut StreamingEmission,
    discovered: &mut Vec<(PathBuf, usize, RegionId)>,
    report: &mut ScanReport,
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    chunk_send_ns: &mut u64,
    diagnostics: Option<&ScanDiagnosticsRecorder>,
) -> bool {
    let read_control = !emission.control_probed();
    let Some(prepared) = prepare_walk_entry_reading(
        root,
        rel_dir,
        depth,
        name,
        kind,
        attrs,
        root_dev,
        config,
        read_control,
    ) else {
        return true;
    };
    emission.note_listed_control(prepared.control.as_ref(), prepared.control_error.as_ref());
    let (mut control, control_error) = (prepared.control, prepared.control_error);
    if let Some(error) = control_error {
        report.errors.push(error);
    }
    // A grouping emission holds an entry's control ahead of the entry itself, so no send
    // can take the entry, `.gitignore` included, before the control that governs it.
    if !prepared.retained || emission.group_directories {
        if let Some(control) = control.take() {
            emission.batch.push(ObservationOp::unconditional(control));
            if !emission.send_if_full(
                root,
                rel_dir,
                config,
                report,
                sender,
                chunk_send_ns,
                diagnostics,
            ) {
                return false;
            }
        }
        if !prepared.retained {
            return true;
        }
    }
    report.observe(kind, attrs);
    // Only a directory the walk descends into needs its path twice, in its observation
    // and in the queue. Every other entry's path moves into its observation, so it is
    // allocated once and freed with its batch rather than copied and freed at once
    // (H180).
    let (path, descend_path) = if prepared.descend {
        (prepared.path.clone(), Some(prepared.path))
    } else {
        (prepared.path, None)
    };
    emission.batch.push(ObservationOp::unconditional(Op::Upsert { path, kind, attrs }));
    if !emission.send_if_full(root, rel_dir, config, report, sender, chunk_send_ns, diagnostics) {
        return false;
    }
    if let Some(control) = control {
        emission.batch.push(ObservationOp::unconditional(control));
        if !emission.send_if_full(root, rel_dir, config, report, sender, chunk_send_ns, diagnostics)
        {
            return false;
        }
    }
    if let Some(path) = descend_path {
        // A child of the root seeds a new region; everything deeper inherits its
        // parent's. Region membership therefore costs one integer copy and never
        // inspects a path.
        let child_region = if depth == 0 { RegionId::UNASSIGNED } else { region };
        discovered.push((path, depth + 1, child_region));
    }
    true
}

/// Move one listing's control observations ahead of its entries, each kind in its order.
///
/// A listing that repeats `.gitignore` while the directory changes keeps its reads in
/// order, so the later one still wins, as it does in the detached builder. Only the rare
/// listing that holds a control moves; every other listing costs one pass over the tags
/// it has just written.
fn controls_first(listing: &mut [ObservationOp]) {
    let mut placed = 0;
    for position in 0..listing.len() {
        if matches!(listing[position].op, Op::ControlUpsert { .. } | Op::ControlRemove { .. }) {
            listing[placed..=position].rotate_right(1);
            placed += 1;
        }
    }
}

/// Observe the control an entry at `path` stands for, if the scan's policy asks for
/// control state at all.
///
/// Every control observation goes through here -- each walk and reconcile site, and the
/// watch layer's verification -- or through [`read_named_control_op`], which shares its
/// gate, so the policy cannot be forgotten at one of them. A watch must honor it like a
/// scan does: its scope has to equal the index's, the scope carries this bit, and a
/// verifier that read control files regardless would grow a partial rule set, from
/// whichever sources events touched, under a scope that says there is none.
///
/// It is also where a listed name becomes a control read, by the rule the module
/// documentation of [`crate::control`] states: the directory's control is what a lookup
/// of `<dir>/.gitignore` resolves to. An entry named exactly `.gitignore` is that
/// lookup's target on every filesystem, so it is read through its own path with the kind
/// its listing observed, and costs nothing more than it did. A case variant such as
/// `.GITIGNORE` may or may not be the target, so the canonical path is looked up
/// ([`read_directory_control`]): the entry decides only whether to look. The observation
/// names the canonical path either way, and its bytes are the ones git reads. A name
/// that spells no control is answered without a system call.
pub(crate) fn read_control_op(
    config: &ScanConfig,
    root: &Path,
    path: &Path,
    kind: EntryKind,
) -> Result<Option<Op>> {
    read_spelled_control_op(config, root, path, kind, crate::control::path_control_spelling)
}

/// [`read_control_op`] for the entry `name` a listing just produced, at `path`, the
/// listed directory joined with `name`.
///
/// The walker already holds the name, so its spelling is tested on those bytes: a length
/// comparison for nearly every entry, as in the detached builder. Parsing the last
/// component back out of the joined path cost the transient summary about 270
/// instructions for every entry, on a tree with no `.gitignore` as much as on one with
/// many (H180). A listed name is one normal component, so it is the path's last one and
/// the decision is the same.
fn read_named_control_op(
    config: &ScanConfig,
    root: &Path,
    path: &Path,
    name: &OsStr,
    kind: EntryKind,
) -> Result<Option<Op>> {
    debug_assert_eq!(path.file_name(), Some(name), "a listed name ends its path");
    read_spelled_control_op(config, root, path, kind, |_| crate::control::control_spelling(name))
}

/// [`read_control_op`], with the spelling of `path`'s last component found by `spelling`
/// once the policy allows a read at all.
fn read_spelled_control_op(
    config: &ScanConfig,
    root: &Path,
    path: &Path,
    kind: EntryKind,
    spelling: impl FnOnce(&Path) -> Option<crate::control::ControlSpelling>,
) -> Result<Option<Op>> {
    if !config.read_controls {
        return Ok(None);
    }
    match spelling(path) {
        Some(crate::control::ControlSpelling::Exact) => {
            read_control_op_unconditional(root, path, kind, config.control_limits.budget)
        }
        Some(crate::control::ControlSpelling::Variant) => {
            read_directory_control(config, root, &crate::control::sibling_control_path(path))
        }
        None => Ok(None),
    }
}

/// Read a directory's control by looking up its canonical path, `<dir>/.gitignore`.
///
/// This is the rule itself: on a case-insensitive directory the lookup resolves to
/// whichever spelling the directory stores, as git's open does, and on a case-sensitive
/// one only to the exact name. `Ok(None)` means nothing resolves. It costs one metadata
/// lookup, and a read on a hit, so it runs only where a listing cannot stand in for it: a
/// narrowed population reads each directory's control before listing it, a classifying
/// transient fold whose batch fills first probes for it (`StreamingEmission::send_if_full`),
/// and a listed case variant resolves through it ([`read_control_op`]).
fn read_directory_control(
    config: &ScanConfig,
    root: &Path,
    control_path: &Path,
) -> Result<Option<Op>> {
    if !config.read_controls {
        return Ok(None);
    }
    let absolute = control_lookup_path(root, control_path);
    let found = look_up_control(&absolute, control_path, config.control_limits.budget);
    #[cfg(test)]
    {
        if let Some(error) =
            walk_hook(&absolute).and_then(|hook| hook(WalkHookPoint::ControlLookup(&absolute)))
        {
            return Err(Error::io(&absolute, error));
        }
    }
    found
}

/// The lookup [`read_directory_control`] makes, at `absolute`, of the control it names
/// `control_path`.
fn look_up_control(
    absolute: &Path,
    control_path: &Path,
    budget: Option<usize>,
) -> Result<Option<Op>> {
    let kind = match observe_path(absolute) {
        Ok((EntryKind::File, _)) => EntryKind::File,
        Ok(_) => EntryKind::Other,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(Error::io(absolute, error)),
    };
    read_control_source(absolute, control_path, kind, budget)
}

/// [`read_directory_control`], answering a miss with the removal of the directory's rules.
///
/// For a producer that saw one spelling of the control name vanish or fail: whether the
/// directory still has a control is the lookup's question, and a removal of rules the
/// table does not hold is inert.
pub(crate) fn read_directory_control_or_removal(
    config: &ScanConfig,
    root: &Path,
    control_path: &Path,
) -> Result<Option<Op>> {
    if !config.read_controls {
        return Ok(None);
    }
    Ok(Some(
        read_directory_control(config, root, control_path)?
            .unwrap_or_else(|| Op::ControlRemove { path: control_path.to_path_buf() }),
    ))
}

/// Where a lookup of the control path `control_path` under `root` goes.
#[cfg(not(test))]
fn control_lookup_path(root: &Path, control_path: &Path) -> PathBuf {
    root.join(control_path)
}

/// Where a lookup of the control path `control_path` under `root` goes, which a test may
/// resolve as a case-insensitive directory would ([`install_case_folding_control_lookup`]).
#[cfg(test)]
fn control_lookup_path(root: &Path, control_path: &Path) -> PathBuf {
    let absolute = root.join(control_path);
    let folds = CASE_FOLDING_LOOKUPS
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .iter()
        .any(|folded| absolute.starts_with(folded));
    let Some(directory) = absolute.parent().filter(|_| folds) else {
        return absolute;
    };
    // A case-insensitive directory holds at most one spelling, and the lookup returns it.
    // A test tree may hold two only where the host is case-sensitive, and then the exact
    // name is what the host itself resolves.
    if fs::symlink_metadata(&absolute).is_ok() {
        return absolute;
    }
    let Ok(mut names) = fs::read_dir(directory) else {
        return absolute;
    };
    names
        .find_map(|item| {
            let name = item.ok()?.file_name();
            crate::control::control_spelling(&name).map(|_| directory.join(name))
        })
        .unwrap_or(absolute)
}

/// Roots whose control lookups [`control_lookup_path`] resolves case-insensitively.
#[cfg(test)]
static CASE_FOLDING_LOOKUPS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());

/// Removes its root from [`CASE_FOLDING_LOOKUPS`] when dropped.
#[cfg(test)]
#[must_use = "the lookups fold only until the guard is dropped"]
pub(crate) struct CaseFoldingGuard(Vec<PathBuf>);

#[cfg(test)]
impl Drop for CaseFoldingGuard {
    fn drop(&mut self) {
        CASE_FOLDING_LOOKUPS
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .retain(|root| !self.0.contains(root));
    }
}

/// Resolve every control lookup under `root` as a case-insensitive directory would, until
/// the guard drops: `<dir>/.gitignore` opens whichever spelling `<dir>` stores.
///
/// A case-sensitive test host cannot make a case-insensitive directory (an ext4 casefold
/// directory needs a kernel built with Unicode support and an empty directory to flag), so
/// this is how the rule's case-insensitive branch runs on every CI runner. It changes only
/// the lookup the rule depends on: listings still show stored names, and every other path
/// resolves as the host resolves it. A real case-insensitive volume is tested where the
/// temporary directory is one. `root` matches as given and canonical.
#[cfg(test)]
pub(crate) fn install_case_folding_control_lookup(root: &Path) -> CaseFoldingGuard {
    let mut roots = vec![root.to_path_buf()];
    if let Ok(canonical) = root.canonicalize() {
        if canonical != root {
            roots.push(canonical);
        }
    }
    CASE_FOLDING_LOOKUPS
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .extend(roots.iter().cloned());
    CaseFoldingGuard(roots)
}

fn read_listed_control_op(
    config: &ScanConfig,
    root: &Path,
    path: &Path,
    kind: EntryKind,
) -> Result<Option<Op>> {
    if config.population != crate::query::IgnoredEntries::Include
        && crate::control::path_control_spelling(path).is_some()
    {
        // The exclusion walk already looked the directory's control up before any
        // sibling, whichever spelling holds it.
        Ok(None)
    } else {
        read_control_op(config, root, path, kind)
    }
}

fn population_prunes(
    population: crate::query::IgnoredEntries,
    path: &Path,
    kind: EntryKind,
    disposition: crate::admission::Disposition,
    controls: Option<&crate::control::ControlTable>,
    unreadable_controls: &std::collections::BTreeSet<PathBuf>,
) -> bool {
    // The fixed control source stays in the entry tier even for `only`: removing its
    // entry would also remove the retained rule source during a watch reconciliation.
    // Every spelling is kept, because the listing cannot tell which one a case-insensitive
    // directory resolves `.gitignore` to without the lookup the walk made before it.
    if crate::control::path_control_spelling(path).is_some() {
        return false;
    }
    let Some(table) = controls else { return false };
    if !table.classification_known(path)
        || path.ancestors().skip(1).any(|ancestor| unreadable_controls.contains(ancestor))
    {
        return false;
    }
    let ignored = table.is_ignored(path, kind.is_dir());
    match population {
        crate::query::IgnoredEntries::Include => false,
        crate::query::IgnoredEntries::Exclude => ignored,
        crate::query::IgnoredEntries::Only => {
            !ignored && !kind.is_dir() && disposition != crate::admission::Disposition::ControlOnly
        }
    }
}

fn apply_discovery_control(table: &mut crate::control::ControlTable, op: &Op) -> Result<()> {
    match op {
        Op::ControlUpsert { path, source } => {
            table.upsert(path, source.clone())?;
        }
        Op::ControlRemove { path } => {
            table.remove(path)?;
        }
        _ => unreachable!("directory control probe emits only control operations"),
    }
    Ok(())
}

/// Read one fixed control source without allowing a raced or hostile file to allocate
/// beyond the index-wide control budget.
///
/// A file longer than the budget is read only to one byte past it. No table under that
/// budget can admit a source that long, since every retained byte is charged at least
/// once, so the truncated source it sends is refused for the budget rather than parsed.
///
/// Private to this module, so no caller elsewhere can step around the policy gate in
/// `read_control_op`.
fn read_control_op_unconditional(
    root: &Path,
    path: &Path,
    kind: EntryKind,
    budget: Option<usize>,
) -> Result<Option<Op>> {
    if !crate::control::is_control_file(path) {
        return Ok(None);
    }
    read_control_source(&root.join(path), path, kind, budget)
}

/// The most a control file's read buffer is sized from its metadata length (H189): every
/// `.gitignore` in the nominated subjects is under 16 KiB, and a larger one grows its
/// buffer by reading, as any file did before.
const CONTROL_READ_RESERVE_BYTES: usize = 64 * 1024;

/// Read the control at `absolute`, whose kind is `kind`, as an observation of `path`.
///
/// `absolute` is where the lookup went and `path` the canonical control path the
/// observation names; on a real filesystem the first is `root.join(path)`.
fn read_control_source(
    absolute: &Path,
    path: &Path,
    kind: EntryKind,
    budget: Option<usize>,
) -> Result<Option<Op>> {
    if kind != EntryKind::File {
        return Ok(Some(Op::ControlRemove { path: path.to_path_buf() }));
    }
    let file = open_control_file(absolute).map_err(|error| Error::io(absolute, error))?;
    let metadata = file.metadata().map_err(|error| Error::io(absolute, error))?;
    if !metadata.file_type().is_file() {
        return Ok(Some(Op::ControlRemove { path: path.to_path_buf() }));
    }
    let read_limit = budget
        .map_or(u64::MAX, |budget| u64::try_from(budget).unwrap_or(u64::MAX).saturating_add(1));
    // Room for the length the metadata already carries, within the read limit and a
    // fixed bound, plus the byte `read_to_end` reads to see the end (H189). `take` hides
    // the length from `read_to_end`, which otherwise grows from 32 bytes by doubling: eight
    // `read` calls for the 2 KiB root `.gitignore` of a kernel tree, two now. A file that
    // grew since its stat reads on as before; a longer one is bounded by the limit as
    // before, and its buffer is grown by `read_to_end` past the reservation, not sized
    // from its length.
    let reserve = usize::try_from(metadata.len().min(read_limit))
        .unwrap_or(usize::MAX)
        .min(CONTROL_READ_RESERVE_BYTES)
        .saturating_add(1);
    let mut source = Vec::with_capacity(reserve);
    file.take(read_limit).read_to_end(&mut source).map_err(|error| Error::io(absolute, error))?;
    crate::counters::bump(|counts| counts.control_reads = counts.control_reads.saturating_add(1));
    Ok(Some(Op::ControlUpsert { path: path.to_path_buf(), source }))
}

#[cfg(unix)]
fn open_control_file(path: &Path) -> std::io::Result<fs::File> {
    use std::os::unix::fs::OpenOptionsExt as _;

    fs::OpenOptions::new().read(true).custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW).open(path)
}

#[cfg(not(unix))]
fn open_control_file(path: &Path) -> std::io::Result<fs::File> {
    fs::File::open(path)
}

fn send_scanner_batch(
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    batch: ScannerBatch,
    diagnostics: Option<&ScanDiagnosticsRecorder>,
) -> bool {
    if let Some(diagnostics) = diagnostics {
        diagnostics.handoff_sent();
    }
    let sent = sender.send(WalkMessage::Batch(batch)).is_ok();
    if !sent {
        // Balance the reservation when the receiver disappeared before accepting it.
        if let Some(diagnostics) = diagnostics {
            diagnostics.handoff_received();
        }
    }
    sent
}

fn send_detached_directories(
    sender: &std::sync::mpsc::Sender<WalkMessage>,
    directories: Vec<DetachedDirectory>,
    recycle: std::sync::mpsc::Sender<Vec<DetachedDirectory>>,
    diagnostics: Option<&ScanDiagnosticsRecorder>,
) -> bool {
    if let Some(diagnostics) = diagnostics {
        diagnostics.handoff_sent();
    }
    let sent = sender.send(WalkMessage::DetachedDirectories { directories, recycle }).is_ok();
    if !sent {
        if let Some(diagnostics) = diagnostics {
            diagnostics.handoff_received();
        }
    }
    sent
}

/// Nanoseconds since `started`, saturating rather than panicking on the absurd.
fn elapsed_ns(started: std::time::Instant) -> u64 {
    u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)
}

/// A top-level subtree, used to spread workers across the breadth of the tree.
///
/// Every directory below the root belongs to the region seeded by its depth-1
/// ancestor, inherited from its parent rather than recomputed from its path. The root
/// itself is [`RegionId::ROOT`], which exists only to bootstrap.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct RegionId(usize);

impl RegionId {
    /// The root's own region, which exists only to bootstrap the walk.
    const ROOT: Self = Self(0);
    /// "Allocate a fresh region for this directory." Resolved by
    /// [`DirectoryQueueState::push`], which is the only place holding the lock that
    /// owns the region table.
    const UNASSIGNED: Self = Self(usize::MAX);
}

/// Directories still to read, plus enough state to know when the walk is finished.
///
/// The termination condition is the only subtle part: the queue being empty does not
/// mean the walk is done, because a worker that is mid-directory may be about to push
/// its children. So a worker holds a claim from the moment it takes work until the
/// moment it has published everything that work produced, and the walk ends only when
/// the queue is empty *and* no claim is outstanding.
///
/// # Why breadth-first is region-scheduled rather than a global FIFO
///
/// A global FIFO orders the *queue*, but claims are unordered: workers take whatever
/// is at the front, which on a real tree means several workers grinding through the
/// same top-level subtree while others sit untouched. Measured on the branching
/// fixture, that left a global-FIFO walk starting the same 7–8 of 12 subtrees at the
/// halfway mark as depth-first did — the ordering bought nothing a consumer could see.
/// It also made the pending set hold a whole level of the tree, which is where the
/// +1.5–3.7% peak RSS in exp-012 came from.
///
/// So breadth-first keeps work in per-region buckets and hands each free worker a
/// *different* region, round-robin. Within a region the bucket is LIFO, which restores
/// depth-first's locality and spine-bounded memory. Nothing waits on a level boundary:
/// if only one region has work, every worker takes it. The result is a scheduler whose
/// shallow preference is expressed in *which subtree a worker picks up*, not in the
/// order a single queue drains — which is the property progressive consumers actually
/// need.
struct DirectoryQueue {
    state: std::sync::Mutex<DirectoryQueueState>,
    ready: std::sync::Condvar,
    order: ScanOrder,
    diagnostics: Option<std::sync::Arc<ScanDiagnosticsRecorder>>,
}

/// One outstanding claim, held for exactly as long as the worker owes the queue the
/// work it took.
///
/// Giving the claim back is the queue's liveness condition, not a courtesy: [`claim`]
/// parks every other worker on the condvar while `outstanding` is nonzero, so a single
/// claim that is never returned stops the whole walk and the scoped join that waits on
/// it. That makes `Drop` the only safe place to put the release, because the paths that
/// skip a hand-written call are exactly the ones that matter — the `break` taken when
/// the consumer disconnects, and an unwinding panic inside a directory read.
///
/// [`claim`]: DirectoryQueue::claim
struct DirectoryClaim<'a> {
    queue: &'a DirectoryQueue,
    /// Directories represented by the claim, for exact in-flight accounting.
    directories: usize,
    /// Whether the worker already returned this claim through [`Self::release`].
    released: bool,
}

impl DirectoryClaim<'_> {
    /// Return the claim at the end of a completed chunk, feeding the chunk's own
    /// measurements to the shared calibration.
    ///
    /// Returns the queue's scale-up decision, which is why the normal path cannot be
    /// `Drop`: a destructor has neither the chunk's timing nor anywhere to put an
    /// answer.
    fn release(
        mut self,
        entries: u64,
        work_ns: u64,
        timing: &mut WalkAttribution,
    ) -> Option<usize> {
        self.released = true;
        self.queue.release(self.directories, entries, work_ns, timing)
    }
}

impl Drop for DirectoryClaim<'_> {
    fn drop(&mut self) {
        if self.released {
            return;
        }
        // An abandoned chunk: the consumer went away mid-directory, or a read panicked.
        // Either way the partial timing describes an aborted chunk rather than the cost
        // of reading directories, so it must not reach the calibration that sizes the
        // worker pool. Returning the claim is the whole job.
        self.queue.abandon(self.directories);
    }
}

struct DirectoryQueueState {
    /// Depth-first's single stack. Unused under breadth-first.
    pending: VecDeque<(PathBuf, usize, RegionId)>,
    /// Breadth-first's per-region work, indexed by [`RegionId`]. Each is a LIFO stack.
    regions: Vec<Vec<(PathBuf, usize, RegionId)>>,
    /// Regions with work, in round-robin order. A region appears at most once; the
    /// flag array is what keeps that true without scanning the ring.
    ready_ring: VecDeque<RegionId>,
    /// Whether each region is currently in `ready_ring`.
    enqueued: Vec<bool>,
    /// Directories currently available for a future claim.
    ready_directories: usize,
    /// Directories held by outstanding claims.
    in_flight_directories: usize,
    outstanding: usize,
    finished: bool,
    controller: Option<WorkerController>,
    /// Observation-only windows retained after the shipped one-shot decision.
    shadow_calibration: Option<RepeatedCalibration>,
    /// Completion-order sequence assigned under the queue lock.
    next_policy_sequence: u64,
    worker_target: usize,
    maximum_workers: usize,
}

impl DirectoryQueueState {
    fn seeded(
        root: (PathBuf, usize),
        order: ScanOrder,
        calibration: Option<WorkerCalibration>,
        initial_workers: usize,
        maximum_workers: usize,
        policy: WorkerPolicyExperiment,
    ) -> Self {
        let mut state = Self {
            pending: VecDeque::new(),
            regions: Vec::new(),
            ready_ring: VecDeque::new(),
            enqueued: Vec::new(),
            ready_directories: 0,
            in_flight_directories: 0,
            outstanding: 0,
            finished: false,
            controller: calibration.map(|value| WorkerController::new(value, policy)),
            shadow_calibration: None,
            next_policy_sequence: 0,
            worker_target: initial_workers,
            maximum_workers,
        };
        state.push((root.0, root.1, RegionId::ROOT), order);
        state
    }

    /// Push one directory into the structure the order uses.
    fn push(&mut self, item: (PathBuf, usize, RegionId), order: ScanOrder) {
        self.ready_directories = self.ready_directories.saturating_add(1);
        match order {
            ScanOrder::DepthFirst => self.pending.push_back(item),
            ScanOrder::BreadthFirst => {
                let region = if item.2 == RegionId::UNASSIGNED {
                    // One region per top-level subtree, numbered as they are found.
                    self.regions.len().max(1)
                } else {
                    item.2.0
                };
                if region >= self.regions.len() {
                    self.regions.resize_with(region + 1, Vec::new);
                    self.enqueued.resize(region + 1, false);
                }
                // Resolve the id *into* the item, so every directory discovered beneath
                // this one inherits a concrete region instead of the sentinel. Without
                // this the sentinel propagates and each directory allocates a region of
                // its own, degenerating the scheduler into round-robin over the whole
                // frontier.
                let mut item = item;
                item.2 = RegionId(region);
                self.regions[region].push(item);
                if !self.enqueued[region] {
                    self.enqueued[region] = true;
                    self.ready_ring.push_back(RegionId(region));
                }
            }
        }
    }

    /// Whether any work is available.
    fn is_empty(&self, order: ScanOrder) -> bool {
        match order {
            ScanOrder::DepthFirst => self.pending.is_empty(),
            ScanOrder::BreadthFirst => self.ready_ring.is_empty(),
        }
    }

    /// Take up to `limit` directories from the next region in the round-robin ring.
    ///
    /// Every region holding work is in the ring exactly once, so popping it always
    /// finds work and always moves to a *different* subtree than the previous claim.
    /// An earlier version preferred the caller's previous region for locality, which
    /// pinned each worker to one subtree: with twelve deep chains and six workers only
    /// six subtrees ever advanced, and depth-first — whose four-directory claims
    /// happen to fan across the root's children — spread wider than breadth-first did.
    /// Locality still comes from the claim being a run of directories out of one
    /// region; it must not come from a worker refusing to leave.
    fn take(
        &mut self,
        limit: usize,
        order: ScanOrder,
        into: &mut Vec<(PathBuf, usize, RegionId)>,
    ) -> usize {
        let before = into.len();
        match order {
            ScanOrder::DepthFirst => {
                let take = self.pending.len().min(limit);
                let start = self.pending.len() - take;
                into.extend(self.pending.drain(start..));
            }
            ScanOrder::BreadthFirst => {
                let Some(region) = self.ready_ring.pop_front() else { return 0 };
                self.enqueued[region.0] = false;
                let bucket = &mut self.regions[region.0];
                let take = bucket.len().min(limit);
                let start = bucket.len() - take;
                into.extend(bucket.drain(start..));
                // Re-arm the region only if work remains and it is not already queued,
                // so a busy region cannot appear twice and starve the others.
                if !bucket.is_empty() && !self.enqueued[region.0] {
                    self.enqueued[region.0] = true;
                    self.ready_ring.push_back(region);
                }
            }
        }
        into.len().saturating_sub(before)
    }

    fn allocate_policy_sequence(&mut self) -> u64 {
        let sequence = self.next_policy_sequence;
        self.next_policy_sequence = self.next_policy_sequence.saturating_add(1);
        sequence
    }
}

impl DirectoryQueue {
    /// Seed the queue with the root, which is region zero until its children fan out.
    #[cfg(test)]
    fn new(
        root: (PathBuf, usize),
        order: ScanOrder,
        calibration: Option<WorkerCalibration>,
        diagnostics: Option<std::sync::Arc<ScanDiagnosticsRecorder>>,
    ) -> Self {
        Self::new_with_policy(
            root,
            order,
            calibration,
            diagnostics,
            1,
            2,
            WorkerPolicyExperiment::ShippedOneShot,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn new_with_policy(
        root: (PathBuf, usize),
        order: ScanOrder,
        calibration: Option<WorkerCalibration>,
        diagnostics: Option<std::sync::Arc<ScanDiagnosticsRecorder>>,
        initial_workers: usize,
        maximum_workers: usize,
        policy: WorkerPolicyExperiment,
    ) -> Self {
        let state = DirectoryQueueState::seeded(
            root,
            order,
            calibration,
            initial_workers,
            maximum_workers,
            policy,
        );
        Self {
            state: std::sync::Mutex::new(state),
            ready: std::sync::Condvar::new(),
            order,
            diagnostics,
        }
    }

    /// Take up to [`DIR_CLAIM`] directories, blocking until there is work or the walk
    /// is over. Returns `None` once no more work will ever arrive.
    ///
    /// Time spent waiting is charged to `timing`: lock acquisition to `lock_wait_ns`
    /// when contended, condvar waits to `starved_ns`. The condvar span includes the
    /// lock re-acquisition on wake, which slightly overstates starvation rather than
    /// understating contention — the fail-honest direction for the number that is
    /// supposed to stay near zero.
    fn claim<'a>(
        &'a self,
        into: &mut Vec<(PathBuf, usize, RegionId)>,
        timing: &mut WalkAttribution,
    ) -> Option<DirectoryClaim<'a>> {
        let mut state = self.lock_timed(timing);
        loop {
            if !state.is_empty(self.order) {
                let directories = state.take(DIR_CLAIM, self.order, into);
                state.ready_directories = state.ready_directories.saturating_sub(directories);
                state.in_flight_directories =
                    state.in_flight_directories.saturating_add(directories);
                state.outstanding += 1;
                timing.claims += 1;
                return Some(DirectoryClaim { queue: self, directories, released: false });
            }
            if state.finished {
                return None;
            }
            if state.outstanding == 0 {
                state.finished = true;
                self.ready.notify_all();
                return None;
            }
            let started = std::time::Instant::now();
            state = self.ready.wait(state).unwrap_or_else(std::sync::PoisonError::into_inner);
            timing.starved_ns += elapsed_ns(started);
        }
    }

    fn extend(
        &self,
        directories: impl Iterator<Item = (PathBuf, usize, RegionId)>,
        timing: &mut WalkAttribution,
    ) {
        let mut state = self.lock_timed(timing);
        for item in directories {
            state.push(item, self.order);
        }
        drop(state);
        self.ready.notify_all();
    }

    /// Give up a claim whose chunk never finished. Wakes everyone if it was the last.
    ///
    /// Reached only from [`DirectoryClaim::drop`], where there is no `WalkAttribution`
    /// to charge and nothing worth charging: an abandoned chunk read some unknown
    /// fraction of its directories, so its lock wait says nothing about contention
    /// during the walk.
    fn abandon(&self, directories: usize) {
        let mut state = self.lock();
        state.outstanding -= 1;
        state.in_flight_directories = state.in_flight_directories.saturating_sub(directories);
        if state.outstanding == 0 && state.is_empty(self.order) {
            state.finished = true;
            drop(state);
            self.ready.notify_all();
        }
    }

    /// Give up a claim taken by [`claim`]. Wakes everyone if this was the last one.
    ///
    /// The chunk's own entry count and work time feed the shared service-time
    /// calibration, so the decision uses the timing the walk already collects for
    /// attribution rather than a second clock. Returns the new worker target when a
    /// controller requests expansion. A release that ends the walk returns no target,
    /// because there is no longer useful work for a reserve worker to take.
    fn release(
        &self,
        directories: usize,
        observed_entries: u64,
        observed_work_ns: u64,
        timing: &mut WalkAttribution,
    ) -> Option<usize> {
        let mut state = self.lock_timed(timing);
        // Whether this chunk reached the calibration at all. Only chunks released while
        // it is still live are policy history; later ones are ordinary walk work.
        let calibrating = state.controller.is_some();
        let one_shot = state.controller.as_ref().is_some_and(WorkerController::is_one_shot);
        let controller_spec = state.controller.as_ref().map(WorkerController::calibration_spec);
        let staged_gated = state.controller.as_ref().is_some_and(WorkerController::is_staged_gated);
        let completed_window = state
            .controller
            .as_mut()
            .and_then(|value| value.observe(observed_entries, observed_work_ns));
        let observed_window = state
            .shadow_calibration
            .as_mut()
            .and_then(|value| value.observe(observed_entries, observed_work_ns));
        let window_completed = completed_window.is_some();
        state.outstanding -= 1;
        state.in_flight_directories = state.in_flight_directories.saturating_sub(directories);
        let finished = state.outstanding == 0 && state.is_empty(self.order);
        if finished {
            state.finished = true;
        }
        let handoff_backlog = self.diagnostics.as_ref().map_or(0, |diagnostics| {
            diagnostics.handoff_backlog.load(std::sync::atomic::Ordering::Relaxed)
        });
        let mut requested_workers = None;
        let policy_window = completed_window.map(|window| {
            let useful_frontier =
                state.ready_directories.saturating_add(state.in_flight_directories);
            let decision = if !window.slow {
                WorkerPolicyDecision::Hold
            } else if finished {
                WorkerPolicyDecision::HoldNoUsefulWork
            } else if staged_gated && useful_frontier <= state.worker_target {
                WorkerPolicyDecision::HoldInsufficientFrontier
            } else if staged_gated && handoff_backlog >= state.worker_target {
                WorkerPolicyDecision::HoldHandoffBacklog
            } else {
                let target = if staged_gated {
                    state.worker_target.saturating_mul(2).min(state.maximum_workers)
                } else {
                    state.maximum_workers
                };
                if target > state.worker_target {
                    state.worker_target = target;
                    requested_workers = Some(target);
                    WorkerPolicyDecision::ScaleUp
                } else {
                    WorkerPolicyDecision::HoldInsufficientFrontier
                }
            };
            let sequence = state.allocate_policy_sequence();
            PolicyWindowSnapshot {
                sequence,
                start_entry_ordinal: window.start_entry_ordinal,
                end_entry_ordinal: window.end_entry_ordinal,
                observed_entries: window.entries,
                observed_chunks: window.chunks,
                observed_work_ns: window.work_ns,
                ready_directories: state.ready_directories,
                in_flight_directories: state.in_flight_directories,
                active_workers: self.diagnostics.as_ref().map_or(0, |diagnostics| {
                    diagnostics.active_workers.load(std::sync::atomic::Ordering::Relaxed)
                }),
                handoff_backlog,
                requested_workers,
                decision,
            }
        });
        let shadow_window = observed_window.map(|window| {
            let sequence = state.allocate_policy_sequence();
            PolicyWindowSnapshot {
                sequence,
                start_entry_ordinal: window.start_entry_ordinal,
                end_entry_ordinal: window.end_entry_ordinal,
                observed_entries: window.entries,
                observed_chunks: window.chunks,
                observed_work_ns: window.work_ns,
                ready_directories: state.ready_directories,
                in_flight_directories: state.in_flight_directories,
                active_workers: self.diagnostics.as_ref().map_or(0, |diagnostics| {
                    diagnostics.active_workers.load(std::sync::atomic::Ordering::Relaxed)
                }),
                handoff_backlog,
                requested_workers: None,
                decision: if window.slow {
                    WorkerPolicyDecision::ObserveSlow
                } else {
                    WorkerPolicyDecision::ObserveFast
                },
            }
        });
        let controller_terminates = (one_shot || finished) && window_completed
            || requested_workers.is_some_and(|target| target == state.maximum_workers);
        if controller_terminates {
            // Continue observing after every terminal decision, including a candidate
            // that reached the maximum pool. Without this shadow history a slow-prefix
            // expansion makes a later fast phase unobservable, precisely the
            // irreversible over-expansion case the evidence matrix must detect.
            if let (Some(spec), Some(window)) = (controller_spec, completed_window) {
                if self.diagnostics.is_some() && !finished {
                    state.shadow_calibration =
                        Some(RepeatedCalibration::starting_at(spec, window.end_entry_ordinal));
                }
            }
            state.controller = None;
        }
        drop(state);

        // The sequence was assigned while the queue was locked, but the trace lock and
        // bounded-vector update stay outside that critical section. Recorder arrival
        // may differ from completion order; `finish` sorts the retained prefix.
        if let (Some(diagnostics), Some(window)) = (&self.diagnostics, policy_window) {
            diagnostics.record_policy_window(window);
        }
        if let (Some(diagnostics), Some(window)) = (&self.diagnostics, shadow_window) {
            diagnostics.record_policy_window(window);
        }

        // Recorded outside the lock: the sampling is off by default, and a disabled
        // counter must not lengthen the critical section it observes.
        if calibrating {
            record_adaptive_calibration_chunk(
                self.diagnostics.as_ref(),
                observed_entries,
                observed_work_ns,
            );
        }

        if finished {
            self.ready.notify_all();
        }
        requested_workers
    }

    /// Acquire the state lock, charging any contention to `timing`.
    ///
    /// The fast path is a `try_lock` that succeeds and costs one counter increment;
    /// only the contended path pays for reading the clock. Poisoning is tolerated for
    /// the same reason as [`Self::lock`].
    fn lock_timed(
        &self,
        timing: &mut WalkAttribution,
    ) -> std::sync::MutexGuard<'_, DirectoryQueueState> {
        timing.lock_ops += 1;
        match self.state.try_lock() {
            Ok(guard) => guard,
            Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
            Err(std::sync::TryLockError::WouldBlock) => {
                timing.lock_contended += 1;
                let started = std::time::Instant::now();
                let guard = self.lock();
                timing.lock_wait_ns += elapsed_ns(started);
                guard
            }
        }
    }

    /// A poisoned queue means a worker panicked mid-walk. The data behind the lock is
    /// a plain work list with no invariant that a panic could have broken, and the
    /// caller already reports the panic as a scan error, so recovering the list is
    /// strictly better than propagating a second panic into every other worker.
    fn lock(&self) -> std::sync::MutexGuard<'_, DirectoryQueueState> {
        self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

fn record_adaptive_calibration_chunk(
    diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>,
    entries: u64,
    work_ns: u64,
) {
    if let Some(diagnostics) = diagnostics {
        diagnostics.calibration_chunk(entries, work_ns);
    }
    crate::counters::bump(|counts| {
        counts.adaptive_calibration_chunks = counts.adaptive_calibration_chunks.saturating_add(1);
        counts.adaptive_calibration_entries =
            counts.adaptive_calibration_entries.saturating_add(entries);
        counts.adaptive_calibration_work_us =
            counts.adaptive_calibration_work_us.saturating_add(work_ns / 1_000);
    });
}

fn record_adaptive_worker_expansion(diagnostics: Option<&std::sync::Arc<ScanDiagnosticsRecorder>>) {
    if let Some(diagnostics) = diagnostics {
        diagnostics.worker_expanded();
    }
    crate::counters::bump(|counts| {
        counts.adaptive_scale_ups = counts.adaptive_scale_ups.saturating_add(1);
    });
}

/// The private builder a detached walk consumes its listings into: a full index, or with
/// `retention` a folded one.
fn detached_builder(
    root: &Path,
    config: &ScanConfig,
    retention: Option<TreeRetention>,
) -> DetachedIndexBuilder {
    let builder = DetachedIndexBuilder::new(root, config.scope(), config.types_shared())
        .with_control_limits(config.control_limits);
    match retention {
        Some(retention) => builder.folding(retention),
        None => builder,
    }
}

fn scan_detached_directories(
    root: &Path,
    config: &ScanConfig,
    collect_diagnostics: bool,
    policy: WorkerPolicyExperiment,
    retention: Option<TreeRetention>,
) -> Result<(ScanReport, DetachedIndexBuilder, Option<ScanDiagnostics>)> {
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Scanning);
    }
    let root_metadata = {
        crate::counters::bump(|counts| counts.stats += 1);
        fs::symlink_metadata(root)
    }
    .map_err(|error| Error::io(root, error))?;
    if !root_metadata.is_dir() {
        return Err(Error::io(
            root,
            std::io::Error::new(std::io::ErrorKind::NotADirectory, "scan root is not a directory"),
        ));
    }
    let root_dev = root_device(root, &root_metadata).map_err(|error| Error::io(root, error))?;
    let available_parallelism =
        std::thread::available_parallelism().map_or(1, std::num::NonZero::get);
    let pool = config.worker_pool_for(available_parallelism);
    let diagnostics = collect_diagnostics
        .then(|| ScanDiagnosticsRecorder::new(pool, available_parallelism, policy));

    if config.max_depth == Some(0) {
        if let Some(diagnostics) = &diagnostics {
            diagnostics.mark_not_run();
            diagnostics.record_queue_finish(0, 0);
        }
        return Ok((
            ScanReport::default(),
            detached_builder(root, config, retention),
            diagnostics.as_ref().map(|value| value.finish()),
        ));
    }

    let walk_started = crate::counters::enabled().then(std::time::Instant::now);
    let (output, builder) = scan_concurrent_detached(
        root,
        config,
        root_dev,
        pool,
        diagnostics.as_ref(),
        policy,
        retention,
    )?;
    // Also reached by a walk no worker left, such as a single-threaded one, so every
    // cold index ends its walk in the same phase.
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Indexing);
    }
    if let Some(started) = walk_started {
        let elapsed = elapsed_ns(started) / 1_000;
        crate::counters::bump(|counts| {
            counts.detached_walk_us = counts.detached_walk_us.saturating_add(elapsed);
        });
    }
    Ok((output, builder, diagnostics.as_ref().map(|value| value.finish())))
}

fn consolidate_detached_index(
    mut output: ScanReport,
    builder: DetachedIndexBuilder,
) -> (Index, ScanReport) {
    let entries = output.entries;
    let consolidate_started = crate::counters::enabled().then(std::time::Instant::now);
    let mut index = builder.finish();
    if let Some(started) = consolidate_started {
        let elapsed = elapsed_ns(started) / 1_000;
        crate::counters::bump(|counts| {
            counts.detached_builds = counts.detached_builds.saturating_add(1);
            counts.detached_entries = counts.detached_entries.saturating_add(entries);
            counts.detached_finish_us = counts.detached_finish_us.saturating_add(elapsed);
        });
    }
    index.record_walk_errors(&mut output.errors);
    index.set_initial_detached_scan_freshness(&output.errors);
    (index, output)
}

/// Walk `root` and return a fully populated index.
pub fn scan_into_index(root: &Path, config: &ScanConfig) -> Result<(Index, ScanReport)> {
    config.validate()?;
    let root = root.canonicalize().map_err(|error| Error::io(root, error))?;
    if config.population != crate::query::IgnoredEntries::Include {
        let (index, report, _) = scan_into_index_with_scanner(
            &root,
            config,
            false,
            WorkerPolicyExperiment::ShippedOneShot,
        )?;
        return Ok((index, report));
    }
    let (output, builder, _diagnostics) = scan_detached_directories(
        &root,
        config,
        false,
        WorkerPolicyExperiment::ShippedOneShot,
        None,
    )?;
    Ok(consolidate_detached_index(output, builder))
}

/// Walk the canonical `root` into a folded index that keeps what `retention` names
/// ([`crate::execution::RetainedState::Tree`]), with the diagnostic trace when asked.
///
/// The same detached walk and builder as [`scan_into_index`], which a folded index
/// differs from only in the files it keeps. Crate-private because a folded index answers
/// one tree report and nothing else; its one caller reports from it and frees it.
pub(crate) fn scan_into_folded_index(
    root: &Path,
    config: &ScanConfig,
    retention: TreeRetention,
    collect_diagnostics: bool,
) -> Result<(Index, ScanReport, Option<ScanDiagnostics>)> {
    config.validate()?;
    debug_assert_eq!(
        config.population,
        crate::query::IgnoredEntries::Include,
        "a folded index keeps the whole population; a narrowed one takes the scanner"
    );
    let (output, builder, diagnostics) = scan_detached_directories(
        root,
        config,
        collect_diagnostics,
        WorkerPolicyExperiment::ShippedOneShot,
        Some(retention),
    )?;
    let (index, report) = consolidate_detached_index(output, builder);
    Ok((index, report, diagnostics))
}

fn scan_into_index_with_scanner(
    root: &Path,
    config: &ScanConfig,
    collect_diagnostics: bool,
    policy: WorkerPolicyExperiment,
) -> Result<(Index, ScanReport, Option<ScanDiagnostics>)> {
    let mut index = Index::new_with_scope_and_types(root, config.scope(), config.types_shared());
    index.set_control_limits(config.control_limits);
    let mut apply_error: Option<Error> = None;
    let (mut report, diagnostics) = scan_internal(
        root,
        config,
        &mut |batch| {
            if apply_error.is_none() {
                if let Err(error) = index.apply_scanner_baseline(batch) {
                    apply_error = Some(error);
                }
            }
        },
        collect_diagnostics,
        policy,
        SinkMode::Retained,
    )?;
    if let Some(error) = apply_error {
        return Err(error);
    }
    index.record_walk_errors(&mut report.errors);
    index.set_initial_scan_freshness(&report.errors);
    Ok((index, report, diagnostics))
}

#[cfg(test)]
fn scan_into_index_via_scanner(root: &Path, config: &ScanConfig) -> Result<(Index, ScanReport)> {
    let (index, report, _) =
        scan_into_index_with_scanner(root, config, false, WorkerPolicyExperiment::ShippedOneShot)?;
    Ok((index, report))
}

/// Walk `root` into an index and retain the opt-in diagnostic trace for that run.
///
/// The index and [`ScanReport`] have the same semantics as [`scan_into_index`]. The
/// additional trace is versioned independently so evidence tooling can fail closed on
/// changes without coupling cache or engine behavior to measurement details.
pub fn scan_into_index_with_diagnostics(
    root: &Path,
    config: &ScanConfig,
) -> Result<(Index, ScanReport, ScanDiagnostics)> {
    scan_into_index_with_policy_diagnostics(root, config, WorkerPolicyExperiment::ShippedOneShot)
}

/// Exercise a repository-only worker-controller candidate while building an index.
#[doc(hidden)]
pub fn scan_into_index_with_policy_diagnostics(
    root: &Path,
    config: &ScanConfig,
    policy: WorkerPolicyExperiment,
) -> Result<(Index, ScanReport, ScanDiagnostics)> {
    config.validate()?;
    let root = root.canonicalize().map_err(|error| Error::io(root, error))?;
    if config.population != crate::query::IgnoredEntries::Include {
        let (index, report, diagnostics) =
            scan_into_index_with_scanner(&root, config, true, policy)?;
        return Ok((index, report, diagnostics.expect("diagnostic scanner creates a recorder")));
    }
    let (output, builder, diagnostics) =
        scan_detached_directories(&root, config, true, policy, None)?;
    let (index, report) = consolidate_detached_index(output, builder);
    Ok((index, report, diagnostics.expect("diagnostic detached scan creates a recorder")))
}

/// Diff the filesystem against an existing index and emit conditional observations.
///
/// This is cache tier 2: after a snapshot is loaded, a sweep like this is what makes the
/// answer trustworthy rather than merely fast. Unchanged entries produce upserts whose
/// fingerprints already match, which the index discards as no-ops, so the caller can
/// apply the whole stream without filtering it first.
///
/// Entries the index holds but the filesystem no longer has become [`Op::Remove`],
/// detected per directory rather than by accumulating every visited path in memory.
///
/// This observation-only reference API assumes its emitted stream is applied to the same
/// unchanged baseline after the borrow ends. Use [`reconcile`] or [`reconcile_handle`]
/// when other producers can write concurrently; those paths capture the stronger
/// generation/revision/absence expectations returned by [`Index::expectation`].
pub fn revalidate(
    index: &Index,
    config: &ScanConfig,
    sink: &mut dyn FnMut(Observation),
) -> Result<ScanReport> {
    config.validate_for_scope(index.scope())?;
    let root = index.root_path().to_path_buf();
    let root_meta = {
        crate::counters::bump(|c| c.stats += 1);
        fs::symlink_metadata(&root)
    }
    .map_err(|error| Error::io(&root, error))?;
    if !root_meta.is_dir() {
        return Err(Error::io(
            &root,
            std::io::Error::new(
                std::io::ErrorKind::NotADirectory,
                "revalidation root is not a directory",
            ),
        ));
    }
    let root_dev = root_device(&root, &root_meta).map_err(|error| Error::io(&root, error))?;
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Revalidating);
    }
    let mut report = ScanReport::default();
    let mut tally = ProgressTally::new(config.progress.as_ref());
    let batch_limit = config.batch_size.max(1);
    let mut batch: Vec<ObservationOp> = Vec::with_capacity(batch_limit);
    if config.max_depth == Some(0) {
        if let Some(children) = index.children(Path::new("")) {
            for (name, _) in children {
                let path = PathBuf::from(name);
                batch.push(ObservationOp::if_state(
                    Op::Remove { path: path.clone() },
                    index.relaxed_expectation(&path),
                ));
                if batch.len() >= batch_limit {
                    sink(Observation::from_ops(std::mem::take(&mut batch)));
                    batch.reserve(batch_limit);
                }
            }
        }
        if !batch.is_empty() {
            sink(Observation::from_ops(batch));
        }
        return Ok(report);
    }
    let mut queue: VecDeque<(PathBuf, usize)> = VecDeque::from(vec![(PathBuf::new(), 0)]);
    let mut controls = (config.population != crate::query::IgnoredEntries::Include)
        .then(|| index.control_table().clone());
    let mut unreadable_controls = std::collections::BTreeSet::new();
    let mut readers = Readers::new();
    let policy = ListingPolicy::every_child_stated(config.one_filesystem);

    while let Some((rel_dir, depth)) = take_next(&mut queue, config.order) {
        let abs_dir = root.join(&rel_dir);
        let control_path = rel_dir.join(crate::control::CONTROL_FILE_NAME);
        let mut had_control = index.control_table().contains(&control_path);
        let mut listed_control = ListedControl::default();
        if let Some(table) = controls.as_mut() {
            let baseline = index.relaxed_expectation(&control_path);
            let lookup = read_directory_control(config, &root, &control_path);
            listed_control.lookup(&lookup);
            match lookup {
                Ok(Some(op)) => {
                    apply_discovery_control(table, &op)?;
                    batch.push(ObservationOp::if_state(op, baseline));
                }
                Ok(None) => {
                    table.remove(&control_path)?;
                    if had_control {
                        batch.push(ObservationOp::if_state(
                            Op::ControlRemove { path: control_path.clone() },
                            baseline,
                        ));
                        had_control = false;
                    }
                }
                Err(error) => {
                    unreadable_controls.insert(rel_dir.clone());
                    report.errors.push(error);
                }
            }
        }
        let listing = match list_directory(&mut readers, &abs_dir, policy, None) {
            Ok(listing) => listing,
            Err(e) => {
                report.errors.push(Error::io(abs_dir, e));
                continue;
            }
        };
        report.dirs_read += 1;

        let mut seen: BTreeSet<OsString> = BTreeSet::new();
        let mut listing_complete = true;
        let listing = reconcile_listing(listing, &abs_dir);
        for item in listing {
            let (name, observed) = match item {
                Listed::Child { name, observed } => (name, observed),
                Listed::Failed(e) => {
                    listing_complete = false;
                    report.errors.push(Error::io(&abs_dir, e));
                    continue;
                }
            };
            // Seeing the name proves it is not absent even when a following metadata
            // lookup fails. Record it before any fallible per-entry work so an
            // operational error cannot become a false removal in the missing sweep.
            seen.insert(name.to_os_string());
            let rel_path = rel_dir.join(&name);
            let baseline = index.relaxed_expectation(&rel_path);
            let (kind, attrs) = match observed {
                Ok(Some(observed)) => observed,
                Ok(None) => {
                    let entry_held = baseline.state != PathState::Absent;
                    for removal in
                        vanished_child_removals(&rel_dir, &name, entry_held, &mut had_control)
                            .into_iter()
                            .flatten()
                    {
                        batch.push(ObservationOp::if_state(removal, baseline));
                    }
                    if batch.len() >= batch_limit {
                        sink(Observation::from_ops(std::mem::take(&mut batch)));
                        batch.reserve(batch_limit);
                    }
                    continue;
                }
                Err(e) => {
                    listed_control.listed(&name);
                    report.errors.push(Error::io(abs_dir.join(&name), e));
                    continue;
                }
            };
            listed_control.listed(&name);
            let disposition =
                crate::admission::decide(&name, kind, config.hidden(), config.exclude_special);
            if population_prunes(
                config.population,
                &rel_path,
                kind,
                disposition,
                controls.as_ref(),
                &unreadable_controls,
            ) {
                if baseline.state != PathState::Absent {
                    batch.push(ObservationOp::if_state(Op::Remove { path: rel_path }, baseline));
                }
                continue;
            }
            let read = read_listed_control_op(config, &root, &rel_path, kind);
            listed_control.read(&name, &read);
            let control = match read {
                Ok(control) => control,
                Err(error) => {
                    report.errors.push(error);
                    None
                }
            };
            if disposition != crate::admission::Disposition::Retain {
                if baseline.state != PathState::Absent {
                    batch.push(ObservationOp::if_state(
                        Op::Remove { path: rel_path.clone() },
                        baseline,
                    ));
                }
                if disposition == crate::admission::Disposition::ControlOnly {
                    if let Some(control) = control {
                        let guard = control_guard(&rel_path, baseline, |path| {
                            index.relaxed_expectation(path)
                        });
                        batch.push(ObservationOp::if_state(control, guard));
                    }
                }
                if batch.len() >= batch_limit {
                    sink(Observation::from_ops(std::mem::take(&mut batch)));
                    batch.reserve(batch_limit);
                }
                continue;
            }
            report.observe(kind, attrs);
            batch.push(ObservationOp::if_state(
                Op::Upsert { path: rel_path.clone(), kind, attrs },
                baseline,
            ));
            if batch.len() >= batch_limit {
                sink(Observation::from_ops(std::mem::take(&mut batch)));
                batch.reserve(batch_limit);
            }
            if let Some(control) = control {
                let guard =
                    control_guard(&rel_path, baseline, |path| index.relaxed_expectation(path));
                batch.push(ObservationOp::if_state(control, guard));
                if batch.len() >= batch_limit {
                    sink(Observation::from_ops(std::mem::take(&mut batch)));
                    batch.reserve(batch_limit);
                }
            }

            if should_descend(kind, attrs, depth, root_dev, config) {
                queue.push_back((rel_path, depth + 1));
            } else if kind.is_dir() {
                if let Some(children) = index.children(&rel_path) {
                    for (child_name, _) in children {
                        let child_path = rel_path.join(child_name);
                        batch.push(ObservationOp::if_state(
                            Op::Remove { path: child_path.clone() },
                            index.relaxed_expectation(&child_path),
                        ));
                        if batch.len() >= batch_limit {
                            sink(Observation::from_ops(std::mem::take(&mut batch)));
                            batch.reserve(batch_limit);
                        }
                    }
                }
            }
        }

        // Anything the index still lists here but the filesystem did not return is gone.
        if listing_complete {
            if let Some(known) = index.children(&rel_dir) {
                for (name, _) in known {
                    if !seen.contains(name) {
                        let path = rel_dir.join(name);
                        batch.push(ObservationOp::if_state(
                            Op::Remove { path: path.clone() },
                            index.relaxed_expectation(&path),
                        ));
                        // In the same batch, so the rules the removal drops are back
                        // before any commit shows the directory without them.
                        if let Some(control) = listed_control.restatement_after_removing(name) {
                            batch.push(ObservationOp::if_state(
                                control,
                                index.relaxed_expectation(&control_path),
                            ));
                        }
                    }
                }
            }
            if had_control && !listed_control.seen {
                batch.push(ObservationOp::if_state(
                    Op::ControlRemove { path: control_path.clone() },
                    index.relaxed_expectation(&control_path),
                ));
            }
        }
        // Per directory: an unchanged tree fills no batch, so the batch cannot be the
        // unit here without the counters standing still for the whole walk.
        tally.flush(&report);
    }

    if !batch.is_empty() {
        sink(Observation::from_ops(batch));
    }
    tally.flush(&report);
    Ok(report)
}

/// Reconcile the full index and publish each exact commit as it lands.
pub fn reconcile(
    index: &mut Index,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    reconcile_subtree(index, Path::new(""), config, sink)
}

/// Reconcile one relative subtree, applying effective changes during the walk.
///
/// If an ancestor vanished or became a non-directory, reconciliation widens to that
/// ancestor so a child invalidation can converge instead of retrying `ENOTDIR` forever.
pub fn reconcile_subtree(
    index: &mut Index,
    subtree: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    reconcile_target(&mut ReconcileTarget::Direct(index), subtree, config, sink)
}

/// Reconcile a shared index while allowing readers between applied batches.
pub fn reconcile_handle(
    handle: &IndexHandle,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    reconcile_subtree_handle(handle, Path::new(""), config, sink)
}

/// Reconcile one subtree of a shared index, widening to a missing/non-directory ancestor
/// when necessary.
pub fn reconcile_subtree_handle(
    handle: &IndexHandle,
    subtree: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    reconcile_target(&mut ReconcileTarget::Shared(handle), subtree, config, sink)
}

/// Internal effects of one opened-root multi-path reconciliation.
#[derive(Debug, Default)]
pub(crate) struct ReconcilePathsReport {
    pub(crate) reconciliation: ReconcileReport,
    pub(crate) accepted: Vec<PathBuf>,
    pub(crate) rejected: Vec<crate::RejectedRefreshPath>,
}

/// Reconcile one bounded path set under an opened-root lifecycle controller.
///
/// Classification precedes I/O, overlapping descendants fold into one walk, and all
/// surviving scopes enter `Reconciling` before the first is read. `forbid_expansion`
/// is the conservative resource-stop rule: removals and same-file verification remain
/// legal, while work that could retain another file or discover children is refused.
pub(crate) fn reconcile_paths_handle_controlled(
    handle: &IndexHandle,
    paths: &[PathBuf],
    config: &ScanConfig,
    forbid_expansion: bool,
    control: &dyn ReconcileControl,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcilePathsReport> {
    let mut target = ReconcileTarget::Controlled { handle, control };
    reconcile_paths_target(&mut target, paths, config, forbid_expansion, sink)
}

fn reconcile_paths_target(
    target: &mut ReconcileTarget<'_>,
    paths: &[PathBuf],
    config: &ScanConfig,
    forbid_expansion: bool,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcilePathsReport> {
    config.validate_for_scope(target.scope()?)?;
    let mut report = ReconcilePathsReport::default();
    let mut accepted = BTreeSet::new();

    for requested in paths {
        let reject = |reason| crate::RejectedRefreshPath { path: requested.clone(), reason };
        let Ok(path) = normalize_subtree(requested) else {
            report.rejected.push(reject(crate::RefreshRejection::OutsideRoot));
            continue;
        };
        if config.max_depth.is_some_and(|maximum| path.components().count() > maximum) {
            report.rejected.push(reject(crate::RefreshRejection::BeyondDepth));
            continue;
        }
        // This is lexical admission before the final kind is observed. Treating the
        // boundary as a file preserves the fixed hidden `.gitignore` control exception;
        // the verified walk still applies the real kind and special-object policy.
        if crate::admission::decide_path(&path, EntryKind::File, config.hidden(), false)
            == crate::admission::Disposition::Reject
        {
            report.rejected.push(reject(crate::RefreshRejection::NotAdmitted));
            continue;
        }
        if forbid_expansion && refresh_may_expand(target, &path, &mut report.reconciliation.scan)? {
            report.rejected.push(reject(crate::RefreshRejection::ResourceBudget));
            continue;
        }
        accepted.insert(path);
    }

    report.accepted = accepted.into_iter().collect();
    let mut resolved = Vec::new();
    let mut unsafe_roots = Vec::new();
    for requested_root in covering_roots(report.accepted.clone()) {
        match resolve_subtree_root(target, &requested_root, config) {
            Ok(root) => resolved.push(root),
            Err(Error::SubtreeOutsideScanScope { .. }) => unsafe_roots.push(requested_root),
            Err(error) => return Err(error),
        }
    }
    if !unsafe_roots.is_empty() {
        let mut retained = Vec::with_capacity(report.accepted.len());
        for path in std::mem::take(&mut report.accepted) {
            if unsafe_roots.iter().any(|root| path.starts_with(root)) {
                report.rejected.push(crate::RejectedRefreshPath {
                    path,
                    reason: crate::RefreshRejection::UnsafeAncestry,
                });
            } else {
                retained.push(path);
            }
        }
        report.accepted = retained;
    }
    let walked = covering_roots(resolved);
    if walked.is_empty() {
        return Ok(report);
    }

    let mut opened = Vec::with_capacity(walked.len());
    for subtree in walked {
        let (started_at, commit) = target.begin_reconcile(&subtree)?;
        if let Some(commit) = commit.as_ref() {
            sink(commit);
        }
        opened.push((subtree, started_at));
    }

    // Each subtree closes on its own walk's outcome, so a subtree that could not be read
    // neither marks a verified sibling partial nor withholds the completeness its listing
    // earned.
    let mut failure = None;
    let mut outcomes = Vec::with_capacity(opened.len());
    for (subtree, started_at) in &opened {
        if failure.is_some() {
            outcomes.push((false, false));
            continue;
        }
        match reconcile_target_inner(
            target,
            subtree,
            *started_at,
            config,
            MAX_DEFERRED_RECONCILE_OPS,
            sink,
        ) {
            Ok(mut reconciliation) => {
                outcomes.push((
                    reconciliation.is_complete(),
                    reconciliation.apply.stale == 0 && reconciliation.apply.resource_refused == 0,
                ));
                reconciliation.listed_incomplete = reconciliation.take_recordable_completeness();
                merge_reconcile_report(&mut report.reconciliation, reconciliation);
            }
            Err(error) => {
                outcomes.push((false, false));
                failure = Some(error);
            }
        }
    }

    let listed_incomplete = std::mem::take(&mut report.reconciliation.listed_incomplete);
    let root = target.root_path()?;
    normalize_walk_errors(&root, &mut report.reconciliation.scan.errors);
    let failed_paths = failure_paths(target, &report.reconciliation.scan.errors)?;
    for ((subtree, started_at), (complete, disproves_old)) in opened.into_iter().zip(outcomes) {
        let commit = target.finish_reconcile(
            &subtree,
            started_at,
            complete,
            &listed_incomplete,
            &failed_paths,
            ReconcileErrors {
                errors: &report.reconciliation.scan.errors,
                terminal: failure.as_ref(),
                disproves_old,
            },
        )?;
        if let Some(commit) = commit.commit.as_ref() {
            sink(commit);
        }
        report.reconciliation.retry_required |= commit.retry;
    }

    match failure {
        Some(error) => Err(error),
        None => Ok(report),
    }
}

/// Root-relative paths whose filesystem facts a failed reconciliation could not verify.
///
/// An unscoped error returns an empty set, which makes the closer conservatively mark the
/// whole requested subtree partial. Precise I/O paths let verified siblings remain fresh.
fn failure_paths(target: &ReconcileTarget<'_>, errors: &[Error]) -> Result<Vec<PathBuf>> {
    if errors.is_empty() {
        return Ok(Vec::new());
    }
    let root = target.root_path()?;
    let mut paths = Vec::with_capacity(errors.len());
    for error in errors {
        let Some(path) = crate::Issue::from_error_under(&root, error).path else {
            return Ok(Vec::new());
        };
        if path.is_absolute() {
            return Ok(Vec::new());
        }
        paths.push(path);
    }
    paths.sort();
    paths.dedup();
    Ok(paths)
}

/// Whether verification could increase the retained-file set.
///
/// This deliberately recognizes only cases that prove non-expansion. At a resource
/// boundary, uncertainty is a refusal rather than permission to exceed the bound.
fn refresh_may_expand(
    target: &ReconcileTarget<'_>,
    path: &Path,
    work: &mut ScanReport,
) -> Result<bool> {
    let current = target.expectation(path)?.state;
    let absolute = target.root_path()?.join(path);
    let observed = match observe_path(&absolute) {
        Ok((kind, attrs)) => {
            work.observe(kind, attrs);
            Some(kind)
        }
        Err(error)
            if matches!(
                error.kind(),
                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
            ) =>
        {
            None
        }
        Err(_) => return Ok(true),
    };
    Ok(!matches!(
        (current, observed),
        (PathState::Present { kind: EntryKind::File, .. }, Some(EntryKind::File)) | (_, None)
    ))
}

/// Drop every path covered by a shallower member of the same sorted set.
fn covering_roots(mut paths: Vec<PathBuf>) -> Vec<PathBuf> {
    paths.sort();
    paths.dedup();
    if paths.first().is_some_and(|first| first.as_os_str().is_empty()) {
        return vec![PathBuf::new()];
    }
    let mut roots: Vec<PathBuf> = Vec::with_capacity(paths.len());
    for path in paths {
        if roots.last().is_some_and(|kept| path.starts_with(kept)) {
            continue;
        }
        roots.push(path);
    }
    roots
}

fn reconcile_target(
    target: &mut ReconcileTarget<'_>,
    subtree: &Path,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    config.validate_for_scope(target.scope()?)?;
    if let Some(progress) = &config.progress {
        progress.enter(crate::ProgressPhase::Revalidating);
    }
    let subtree = normalize_subtree(subtree)?;
    if config.max_depth.is_some_and(|maximum| subtree.components().count() > maximum) {
        return Err(Error::SubtreeOutsideScanScope { path: subtree, scope: config.scope() });
    }
    let subtree = if config.population != crate::query::IgnoredEntries::Include
        && !subtree.as_os_str().is_empty()
    {
        // A narrowed tier may have pruned the requested entry or an ancestor. Start
        // from its nearest retained parent so the governing control is read before the
        // directory listing decides whether the boundary itself belongs in the tier.
        // A control-file edit also needs this parent listing to discover siblings that
        // were absent under the previous rule.
        let mut parent = subtree.parent().map_or_else(PathBuf::new, Path::to_path_buf);
        while !parent.as_os_str().is_empty()
            && (target.expectation(&parent)?.state == PathState::Absent
                || !target.control_classification_known(&parent)?)
        {
            parent = parent.parent().map_or_else(PathBuf::new, Path::to_path_buf);
        }
        parent
    } else {
        subtree
    };
    let subtree = resolve_subtree_root(target, &subtree, config)?;
    let (started_at, started) = target.begin_reconcile(&subtree)?;
    if let Some(commit) = started.as_ref() {
        sink(commit);
    }
    match reconcile_target_inner(
        target,
        &subtree,
        started_at,
        config,
        MAX_DEFERRED_RECONCILE_OPS,
        sink,
    ) {
        Ok(mut report) => {
            let root = target.root_path()?;
            normalize_walk_errors(&root, &mut report.scan.errors);
            let listed_incomplete = report.take_recordable_completeness();
            let failed_paths = failure_paths(target, &report.scan.errors)?;
            let finished = target.finish_reconcile(
                &subtree,
                started_at,
                report.is_complete(),
                &listed_incomplete,
                &failed_paths,
                ReconcileErrors {
                    errors: &report.scan.errors,
                    terminal: None,
                    disproves_old: report.apply.stale == 0 && report.apply.resource_refused == 0,
                },
            )?;
            if let Some(commit) = finished.commit.as_ref() {
                sink(commit);
            }
            report.retry_required |= finished.retry;
            Ok(report)
        }
        Err(error) => {
            let finished = target.finish_reconcile(
                &subtree,
                started_at,
                false,
                &[],
                &[],
                ReconcileErrors { errors: &[], terminal: Some(&error), disproves_old: false },
            )?;
            if let Some(commit) = finished.commit.as_ref() {
                sink(commit);
            }
            Err(error)
        }
    }
}

fn reconcile_target_inner(
    target: &mut ReconcileTarget<'_>,
    subtree: &Path,
    started_at: u64,
    config: &ScanConfig,
    max_deferred_ops: usize,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    let root = target.root_path()?;
    let root_meta = {
        crate::counters::bump(|c| c.stats += 1);
        fs::symlink_metadata(&root)
    }
    .map_err(|error| Error::io(&root, error))?;
    if !root_meta.is_dir() {
        return Err(Error::io(
            &root,
            std::io::Error::new(
                std::io::ErrorKind::NotADirectory,
                "reconciliation root is not a directory",
            ),
        ));
    }
    let root_dev = root_device(&root, &root_meta).map_err(|error| Error::io(&root, error))?;
    let start_depth = subtree.components().count();
    let mut report =
        ReconcileReport { reconcile_epoch: Some(started_at), ..ReconcileReport::default() };
    let mut tally = ProgressTally::new(config.progress.as_ref());
    let mut retry_frontier = None;
    let mut batch: Vec<ObservationOp> = Vec::with_capacity(config.batch_size.max(1));

    if config.max_depth == Some(0) {
        remove_known_children(target, Path::new(""), config, &mut batch, sink, &mut report)?;
        return Ok(report);
    }

    if !subtree.as_os_str().is_empty() {
        let baseline = target.expectation(subtree)?;
        let absolute = root.join(subtree);
        let (kind, attrs) = match observe_path(&absolute) {
            Ok(observed) => observed,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                batch.push(ObservationOp::if_state(
                    Op::Remove { path: subtree.to_path_buf() },
                    baseline,
                ));
                push_lost_spelling_control(
                    target,
                    &root,
                    config,
                    subtree,
                    baseline,
                    &mut batch,
                    &mut report,
                )?;
                flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
                return Ok(report);
            }
            Err(error) => {
                report.scan.errors.push(Error::io(&absolute, error));
                if baseline.state != PathState::Absent {
                    batch.push(ObservationOp::if_state(
                        Op::Remove { path: subtree.to_path_buf() },
                        baseline,
                    ));
                }
                push_lost_spelling_control(
                    target,
                    &root,
                    config,
                    subtree,
                    baseline,
                    &mut batch,
                    &mut report,
                )?;
                flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
                return Ok(report);
            }
        };
        let disposition =
            crate::admission::decide_path(subtree, kind, config.hidden(), config.exclude_special);
        if disposition != crate::admission::Disposition::Retain {
            if baseline.state != PathState::Absent {
                batch.push(ObservationOp::if_state(
                    Op::Remove { path: subtree.to_path_buf() },
                    baseline,
                ));
            }
            if disposition == crate::admission::Disposition::ControlOnly {
                let read = read_control_op(config, &root, subtree, kind);
                push_read_control(target, subtree, baseline, read, &mut batch, &mut report)?;
            }
            flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
            return Ok(report);
        }
        report.scan.observe(kind, attrs);
        push_reconcile_upsert(target, subtree, kind, attrs, baseline, &mut batch, &mut report);
        // A retained control file at the root of the walk reads its rules here, as the
        // listing walk does for every retained entry it lists: a file does not descend,
        // so nothing below would read them, and the table kept the old source while the
        // pass reported complete and marked the path fresh. In the same batch as the
        // upsert, so both are arbitrated against one baseline.
        let read = read_control_op(config, &root, subtree, kind);
        push_read_control(target, subtree, baseline, read, &mut batch, &mut report)?;
        flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
        if !should_descend(kind, attrs, start_depth.saturating_sub(1), root_dev, config) {
            if kind.is_dir() {
                remove_known_children(target, subtree, config, &mut batch, sink, &mut report)?;
            }
            tally.flush(&report.scan);
            return Ok(report);
        }
    }

    if subtree.as_os_str().is_empty()
        && config.population == crate::query::IgnoredEntries::Include
        && config.reconciliation_worker_threads() > 1
    {
        if let ReconcileTarget::Direct(index) = target {
            match reconcile_direct_parallel(index, &root, root_dev, config, max_deferred_ops, sink)?
            {
                DirectParallelOutcome::Complete(parallel) => return Ok(parallel),
                DirectParallelOutcome::RetrySerial { prefix, remaining } => {
                    report = prefix;
                    report.reconcile_epoch = Some(started_at);
                    retry_frontier = Some(remaining);
                    // The wave workers reported the prefix themselves, and the wave
                    // that overflowed as well: progress counts that wave's reads twice,
                    // once there and once as the serial retry rereads it, while this
                    // report counts each directory once. Work done, not the answer.
                    tally.skip_to(&report.scan);
                }
            }
        }
    }

    let mut queue: VecDeque<(PathBuf, usize)> = retry_frontier
        .unwrap_or_else(|| VecDeque::from(vec![(subtree.to_path_buf(), start_depth)]));
    let mut controls = if config.population == crate::query::IgnoredEntries::Include {
        None
    } else {
        Some(target.control_table()?)
    };
    let mut unreadable_controls = std::collections::BTreeSet::new();
    #[cfg(target_os = "macos")]
    let mut bulk_reader = (config.worker_threads() > 1).then(macos_bulk::Reader::new);
    let mut readers = Readers::new();
    let policy = ListingPolicy::every_child_stated(config.one_filesystem);
    while let Some((rel_dir, depth)) = take_next(&mut queue, config.order) {
        let errors_before = report.scan.errors.len();
        let abs_dir = root.join(&rel_dir);
        let control_path = rel_dir.join(crate::control::CONTROL_FILE_NAME);
        let mut had_control = target.has_control(&control_path)?;
        let mut listed_control = ListedControl::default();
        if let Some(table) = controls.as_mut() {
            let lookup = read_directory_control(config, &root, &control_path);
            listed_control.lookup(&lookup);
            match lookup {
                Ok(Some(op)) => {
                    let baseline = target.expectation(&control_path)?;
                    apply_discovery_control(table, &op)?;
                    batch.push(ObservationOp::if_state(op, baseline));
                }
                Ok(None) => {
                    table.remove(&control_path)?;
                    if had_control {
                        let baseline = target.expectation(&control_path)?;
                        batch.push(ObservationOp::if_state(
                            Op::ControlRemove { path: control_path.clone() },
                            baseline,
                        ));
                        had_control = false;
                    }
                }
                Err(error) => {
                    unreadable_controls.insert(rel_dir.clone());
                    report.scan.errors.push(error);
                }
            }
            flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
            if report.apply.stale > 0 || report.apply.resource_refused > 0 {
                // This directory's population decisions use the source just read.
                // If its conditional control commit lost ownership, walking siblings
                // against the local copy could prune under rules the index rejected.
                report.retry_required = true;
                return Ok(report);
            }
        }
        let (mut known, records_completeness) = target.listing_baseline(&rel_dir)?;
        let mut listing_complete = true;
        let process_entry = |name: OsString,
                             kind: EntryKind,
                             attrs: Attrs,
                             baseline: PathExpectation,
                             listed_control: &mut ListedControl,
                             target: &mut ReconcileTarget<'_>,
                             queue: &mut VecDeque<(PathBuf, usize)>,
                             batch: &mut Vec<ObservationOp>,
                             sink: &mut dyn FnMut(&Commit),
                             report: &mut ReconcileReport|
         -> Result<()> {
            let rel_path = rel_dir.join(&name);
            listed_control.listed(&name);
            let disposition =
                crate::admission::decide(&name, kind, config.hidden(), config.exclude_special);
            if population_prunes(
                config.population,
                &rel_path,
                kind,
                disposition,
                controls.as_ref(),
                &unreadable_controls,
            ) {
                if baseline.state != PathState::Absent {
                    batch.push(ObservationOp::if_state(Op::Remove { path: rel_path }, baseline));
                }
                return Ok(());
            }
            if disposition != crate::admission::Disposition::Retain {
                if baseline.state != PathState::Absent {
                    batch.push(ObservationOp::if_state(
                        Op::Remove { path: rel_path.clone() },
                        baseline,
                    ));
                }
                if disposition == crate::admission::Disposition::ControlOnly {
                    let read = read_listed_control_op(config, &root, &rel_path, kind);
                    listed_control.read(&name, &read);
                    push_read_control(target, &rel_path, baseline, read, batch, report)?;
                }
                if batch.len() >= config.batch_size.max(1) {
                    flush_reconcile_batch(target, batch, sink, report)?;
                }
                return Ok(());
            }
            report.scan.observe(kind, attrs);
            push_reconcile_upsert(target, &rel_path, kind, attrs, baseline, batch, report);
            if batch.len() >= config.batch_size.max(1) {
                flush_reconcile_batch(target, batch, sink, report)?;
            }
            let read = read_listed_control_op(config, &root, &rel_path, kind);
            listed_control.read(&name, &read);
            push_read_control(target, &rel_path, baseline, read, batch, report)?;
            if batch.len() >= config.batch_size.max(1) {
                flush_reconcile_batch(target, batch, sink, report)?;
            }

            if should_descend(kind, attrs, depth, root_dev, config) {
                queue.push_back((rel_path, depth + 1));
            } else if kind.is_dir() {
                remove_known_children(target, &rel_path, config, batch, sink, report)?;
            }
            Ok(())
        };

        #[cfg(target_os = "macos")]
        let used_bulk = if walk_hook_covers(&abs_dir) {
            false
        } else if let Some(entries) = bulk_reader.as_mut().and_then(|reader| reader.read(&abs_dir))
        {
            report.scan.dirs_read += 1;
            for entry in entries {
                let baseline = match known.remove(&entry.name) {
                    Some(baseline) => baseline,
                    None => target.expectation(&rel_dir.join(&entry.name))?,
                };
                process_entry(
                    entry.name,
                    entry.kind,
                    entry.attrs,
                    baseline,
                    &mut listed_control,
                    target,
                    &mut queue,
                    &mut batch,
                    sink,
                    &mut report,
                )?;
            }
            true
        } else {
            false
        };
        #[cfg(not(target_os = "macos"))]
        let used_bulk = false;

        if !used_bulk {
            let listing = match list_directory(&mut readers, &abs_dir, policy, None) {
                Ok(listing) => listing,
                Err(error) => {
                    report.scan.errors.push(Error::io(&abs_dir, error));
                    remove_known_children(target, &rel_dir, config, &mut batch, sink, &mut report)?;
                    if had_control {
                        let baseline = target.expectation(&control_path)?;
                        batch.push(ObservationOp::if_state(
                            Op::ControlRemove { path: control_path },
                            baseline,
                        ));
                        flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
                    }
                    continue;
                }
            };
            report.scan.dirs_read += 1;
            let listing = reconcile_listing(listing, &abs_dir);
            for item in listing {
                let (name, observed) = match item {
                    Listed::Child { name, observed } => (name.into_owned(), observed),
                    Listed::Failed(error) => {
                        listing_complete = false;
                        report.scan.errors.push(Error::io(&abs_dir, error));
                        continue;
                    }
                };
                // Seeing the name proves it is not absent even if the following
                // metadata lookup fails. Remove it from the missing set before that
                // fallible lookup so an operational error cannot turn an existing
                // entry into a deletion.
                let baseline = match known.remove(&name) {
                    Some(baseline) => baseline,
                    None => target.expectation(&rel_dir.join(&name))?,
                };
                let (kind, attrs) = match observed {
                    Ok(Some(observed)) => observed,
                    Ok(None) => {
                        let entry_held = baseline.state != PathState::Absent;
                        for removal in
                            vanished_child_removals(&rel_dir, &name, entry_held, &mut had_control)
                                .into_iter()
                                .flatten()
                        {
                            batch.push(ObservationOp::if_state(removal, baseline));
                        }
                        if batch.len() >= config.batch_size.max(1) {
                            flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
                        }
                        continue;
                    }
                    Err(error) => {
                        listed_control.listed(&name);
                        report.scan.errors.push(Error::io(abs_dir.join(&name), error));
                        if baseline.state != PathState::Absent {
                            batch.push(ObservationOp::if_state(
                                Op::Remove { path: rel_dir.join(&name) },
                                baseline,
                            ));
                        }
                        if name == crate::control::CONTROL_FILE_NAME && had_control {
                            batch.push(ObservationOp::if_state(
                                Op::ControlRemove { path: rel_dir.join(&name) },
                                baseline,
                            ));
                            had_control = false;
                        }
                        if batch.len() >= config.batch_size.max(1) {
                            flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
                        }
                        continue;
                    }
                };
                process_entry(
                    name,
                    kind,
                    attrs,
                    baseline,
                    &mut listed_control,
                    target,
                    &mut queue,
                    &mut batch,
                    sink,
                    &mut report,
                )?;
            }
        }

        for (name, baseline) in known {
            let restatement = listed_control.restatement_after_removing(&name);
            batch.push(ObservationOp::if_state(Op::Remove { path: rel_dir.join(name) }, baseline));
            // Before the batch can be flushed, so the rules the removal drops are back in the
            // same commit.
            if let Some(control) = restatement {
                let guard = target.expectation(&control_path)?;
                batch.push(ObservationOp::if_state(control, guard));
            }
            if batch.len() >= config.batch_size.max(1) {
                flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
            }
        }
        if had_control && !listed_control.seen {
            let baseline = target.expectation(&control_path)?;
            batch.push(ObservationOp::if_state(Op::ControlRemove { path: control_path }, baseline));
        }
        if listing_complete {
            // Only a directory with no error inside its own processing vouches for its
            // child set; an error under a sibling or a descendant is that directory's
            // to answer for, as discovery decides completeness per directory.
            if records_completeness && report.scan.errors.len() == errors_before {
                report.listed_incomplete.push(rel_dir);
            }
        }
        // Per directory, as in `revalidate`: an unchanged tree hands the sink nothing.
        tally.flush(&report.scan);
    }

    flush_reconcile_batch(target, &mut batch, sink, &mut report)?;
    report.scan.errors.sort_by_cached_key(ToString::to_string);
    tally.flush(&report.scan);
    Ok(report)
}

#[derive(Debug, Default)]
struct DeferredReconcile {
    scan: ScanReport,
    unchanged: u64,
    operations: Vec<Op>,
    /// Each removal of a stale `.gitignore` entry whose rules a case variant now holds,
    /// followed by the restatement of those rules (`ListedControl`). Applied after the
    /// wave's sorted operations, in one batch, because the sort moves every removal after
    /// every other operation and a batch boundary could fall between the two.
    restated: Vec<Op>,
    discovered: Vec<(PathBuf, usize, RegionId)>,
    listed_incomplete: Vec<PathBuf>,
}

enum DirectParallelOutcome {
    Complete(ReconcileReport),
    RetrySerial { prefix: ReconcileReport, remaining: VecDeque<(PathBuf, usize)> },
}

/// Reconcile an exclusive full tree in bounded immutable-baseline waves.
///
/// No index write occurs while a wave's workers hold shared baseline references. That
/// lets each worker discard exact no-ops where they are observed instead of funnelling
/// every entry through one consumer. Effective changes still enter through ordinary
/// observations between waves, preserving both the index's sole mutation contract and
/// progressive delta delivery.
///
/// Unlike every other reconciliation path, the operations a wave defers are
/// unconditional: they carry no [`ObservationOp::if_state`] guard. Three properties
/// have to hold together for that to be safe, and a change to any one of them puts the
/// guards back. The target is an exclusive `&mut Index`, so no other producer can
/// commit between a worker's read and the wave's write. Nothing is applied while
/// workers run, so no baseline a worker compared against can go stale beneath it. And
/// a directory is only reconciled in a wave after the wave that discovered it has
/// committed, so a parent is never absent when its children arrive.
fn reconcile_direct_parallel(
    index: &mut Index,
    root: &Path,
    root_dev: u64,
    config: &ScanConfig,
    max_deferred_ops: usize,
    sink: &mut dyn FnMut(&Commit),
) -> Result<DirectParallelOutcome> {
    let mut frontier = DirectoryQueueState::seeded(
        (PathBuf::new(), 0),
        config.order,
        None,
        1,
        1,
        WorkerPolicyExperiment::ShippedOneShot,
    );
    let mut report = ReconcileReport::default();
    while !frontier.is_empty(config.order) {
        let mut wave = Vec::with_capacity(RECONCILE_WAVE_DIRECTORIES);
        while wave.len() < RECONCILE_WAVE_DIRECTORIES && !frontier.is_empty(config.order) {
            let remaining = RECONCILE_WAVE_DIRECTORIES - wave.len();
            frontier.take(remaining.min(DIR_CLAIM), config.order, &mut wave);
        }

        let next = std::sync::atomic::AtomicUsize::new(0);
        let deferred_count = std::sync::atomic::AtomicUsize::new(0);
        let overflowed = std::sync::atomic::AtomicBool::new(false);
        let workers = config.reconciliation_worker_threads().min(wave.len());
        let baseline: &Index = index;
        let results: Vec<DeferredReconcile> = std::thread::scope(|scope| {
            let handles: Vec<_> = (0..workers)
                .map(|_| {
                    scope.spawn(|| {
                        reconcile_wave_worker(
                            baseline,
                            root,
                            root_dev,
                            config,
                            &wave,
                            &next,
                            &deferred_count,
                            &overflowed,
                            max_deferred_ops,
                        )
                    })
                })
                .collect();

            handles
                .into_iter()
                .map(|handle| {
                    if let Ok(worker) = handle.join() {
                        return worker;
                    }
                    let mut worker = DeferredReconcile::default();
                    worker.scan.errors.push(Error::io(
                        root,
                        std::io::Error::other("a reconciliation worker thread panicked"),
                    ));
                    worker
                })
                .collect()
        });

        // Nothing from an overflowing wave was applied, so the ordinary incremental
        // reconciler can resume at that wave. Completed waves and their statistics are
        // retained exactly once; restarting from the root would count their unchanged
        // entries again and misreport the logical reconciliation pass.
        if overflowed.load(std::sync::atomic::Ordering::Relaxed) {
            let mut remaining: VecDeque<_> =
                wave.into_iter().map(|(path, depth, _region)| (path, depth)).collect();
            let mut deferred = Vec::with_capacity(DIR_CLAIM);
            while !frontier.is_empty(config.order) {
                frontier.take(DIR_CLAIM, config.order, &mut deferred);
                remaining.extend(deferred.drain(..).map(|(path, depth, _region)| (path, depth)));
            }
            return Ok(DirectParallelOutcome::RetrySerial { prefix: report, remaining });
        }

        let operation_count = deferred_count.load(std::sync::atomic::Ordering::Relaxed);
        let mut operations = Vec::with_capacity(operation_count);
        let mut restated = Vec::new();
        for worker in results {
            report.listed_incomplete.extend(worker.listed_incomplete);
            report.scan.absorb(worker.scan);
            report.apply.unchanged += worker.unchanged;
            report.observations = report.observations.saturating_add(worker.unchanged);
            operations.extend(worker.operations);
            restated.extend(worker.restated);
            for directory in worker.discovered {
                frontier.push(directory, config.order);
            }
        }
        apply_deferred_reconcile(
            index,
            &mut operations,
            restated,
            config,
            sink,
            &mut report.apply,
            &mut report.observations,
        )?;
    }
    report.scan.errors.sort_by_cached_key(ToString::to_string);
    Ok(DirectParallelOutcome::Complete(report))
}

fn apply_deferred_reconcile(
    index: &mut Index,
    operations: &mut Vec<Op>,
    restated: Vec<Op>,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
    stats: &mut ApplyStats,
    observations: &mut u64,
) -> Result<()> {
    // Parent upserts establish real directory attributes before children arrive.
    // Removals run deepest first so a parent removal never precedes an independently
    // observed descendant operation. Deterministic causal order also makes emitted
    // commits stable for callers.
    operations.sort_by(|left, right| {
        let left_remove = matches!(left, Op::Remove { .. });
        let right_remove = matches!(right, Op::Remove { .. });
        left_remove.cmp(&right_remove).then_with(|| {
            let left_depth = left.path().components().count();
            let right_depth = right.path().components().count();
            if left_remove {
                right_depth.cmp(&left_depth).then_with(|| left.path().cmp(right.path()))
            } else {
                left_depth.cmp(&right_depth).then_with(|| left.path().cmp(right.path()))
            }
        })
    });

    let batch_limit = config.batch_size.max(1);
    let mut batch = Vec::with_capacity(batch_limit.min(operations.len()));
    for operation in operations.drain(..) {
        batch.push(operation);
        if batch.len() >= batch_limit {
            flush_direct_reconcile_batch(index, &mut batch, sink, stats, observations)?;
        }
    }
    flush_direct_reconcile_batch(index, &mut batch, sink, stats, observations)?;
    // Whole, so no commit shows a directory without the rules a restatement puts back.
    let mut restated = restated;
    flush_direct_reconcile_batch(index, &mut restated, sink, stats, observations)
}

#[allow(clippy::too_many_arguments)]
fn reconcile_wave_worker(
    index: &Index,
    root: &Path,
    root_dev: u64,
    config: &ScanConfig,
    wave: &[(PathBuf, usize, RegionId)],
    next: &std::sync::atomic::AtomicUsize,
    deferred_count: &std::sync::atomic::AtomicUsize,
    overflowed: &std::sync::atomic::AtomicBool,
    max_deferred_ops: usize,
) -> DeferredReconcile {
    let _counter_guard = crate::counters::thread_flush_guard();
    let mut result = DeferredReconcile::default();
    let mut tally = ProgressTally::new(config.progress.as_ref());
    #[cfg(target_os = "macos")]
    let mut bulk_reader = macos_bulk::Reader::new();
    let mut readers = Readers::new();
    let policy = ListingPolicy::every_child_stated(config.one_filesystem);

    loop {
        let start = next.fetch_add(DIR_CLAIM, std::sync::atomic::Ordering::Relaxed);
        if start >= wave.len() {
            break;
        }
        let end = start.saturating_add(DIR_CLAIM).min(wave.len());
        for (rel_dir, depth, region) in &wave[start..end] {
            let errors_before = result.scan.errors.len();
            let mut known = collect_child_expectations(index, rel_dir);
            let abs_dir = root.join(rel_dir);
            let control_path = rel_dir.join(crate::control::CONTROL_FILE_NAME);
            let mut had_control = index.control_table().contains(&control_path);
            let mut listed_control = ListedControl::default();
            let mut control_errors = Vec::new();
            let mut vanished = Vec::new();
            let mut unverified = Vec::new();
            let mut control_read_failed = false;
            let mut listing_open_failed = false;

            {
                let mut process_entry =
                    |name: OsString,
                     kind: EntryKind,
                     attrs: Attrs,
                     baseline: PathExpectation,
                     listed_control: &mut ListedControl| {
                        let rel_path = rel_dir.join(&name);
                        listed_control.listed(&name);
                        let disposition = crate::admission::decide(
                            &name,
                            kind,
                            config.hidden(),
                            config.exclude_special,
                        );
                        if disposition == crate::admission::Disposition::Reject {
                            if baseline.state != PathState::Absent {
                                defer_reconcile_op(
                                    Op::Remove { path: rel_path },
                                    &mut result.operations,
                                    deferred_count,
                                    overflowed,
                                    max_deferred_ops,
                                );
                            }
                            return;
                        }
                        if disposition == crate::admission::Disposition::ControlOnly {
                            let read = read_control_op(config, root, &rel_path, kind);
                            listed_control.read(&name, &read);
                            match read {
                                Ok(Some(Op::ControlUpsert { path, source })) => {
                                    if !index.control_table().source_is(&path, &source) {
                                        defer_reconcile_op(
                                            Op::ControlUpsert { path, source },
                                            &mut result.operations,
                                            deferred_count,
                                            overflowed,
                                            max_deferred_ops,
                                        );
                                    }
                                }
                                Ok(Some(Op::ControlRemove { path })) => {
                                    if index.control_table().contains(&path) {
                                        defer_reconcile_op(
                                            Op::ControlRemove { path },
                                            &mut result.operations,
                                            deferred_count,
                                            overflowed,
                                            max_deferred_ops,
                                        );
                                    }
                                }
                                Ok(Some(_) | None) => {}
                                Err(error) => {
                                    control_errors.push(error);
                                    control_read_failed = true;
                                }
                            }
                            return;
                        }
                        result.scan.entries += 1;
                        if kind == EntryKind::File {
                            result.scan.files_walked += 1;
                            result.scan.bytes_walked =
                                result.scan.bytes_walked.saturating_add(attrs.size);
                            result.scan.allocated_walked =
                                result.scan.allocated_walked.saturating_add(attrs.allocated);
                        }
                        if baseline.state == (PathState::Present { kind, attrs }) {
                            result.unchanged += 1;
                        } else {
                            defer_reconcile_op(
                                Op::Upsert { path: rel_path.clone(), kind, attrs },
                                &mut result.operations,
                                deferred_count,
                                overflowed,
                                max_deferred_ops,
                            );
                        }
                        let read = read_control_op(config, root, &rel_path, kind);
                        listed_control.read(&name, &read);
                        match read {
                            Ok(Some(Op::ControlUpsert { path, source })) => {
                                if !index.control_table().source_is(&path, &source) {
                                    defer_reconcile_op(
                                        Op::ControlUpsert { path, source },
                                        &mut result.operations,
                                        deferred_count,
                                        overflowed,
                                        max_deferred_ops,
                                    );
                                }
                            }
                            // The exact name's upsert as a non-file drops its rules by
                            // itself; a case variant's does not, so its lookup's removal
                            // is sent.
                            Ok(Some(Op::ControlRemove { path }))
                                if crate::control::control_spelling(&name)
                                    == Some(crate::control::ControlSpelling::Variant)
                                    && index.control_table().contains(&path) =>
                            {
                                defer_reconcile_op(
                                    Op::ControlRemove { path },
                                    &mut result.operations,
                                    deferred_count,
                                    overflowed,
                                    max_deferred_ops,
                                );
                            }
                            Ok(Some(_) | None) => {}
                            Err(error) => {
                                control_errors.push(error);
                                // The failed read was of the directory's control, through
                                // the entry for the exact name and a lookup for a variant.
                                control_read_failed = true;
                            }
                        }

                        if should_descend(kind, attrs, *depth, root_dev, config) {
                            let child_region =
                                if *depth == 0 { RegionId::UNASSIGNED } else { *region };
                            result.discovered.push((rel_path, depth + 1, child_region));
                        } else if kind.is_dir() {
                            for name in collect_child_expectations(index, &rel_path).into_keys() {
                                defer_reconcile_op(
                                    Op::Remove { path: rel_path.join(name) },
                                    &mut result.operations,
                                    deferred_count,
                                    overflowed,
                                    max_deferred_ops,
                                );
                            }
                        }
                    };

                #[cfg(target_os = "macos")]
                let used_bulk = if let Some(entries) =
                    (!walk_hook_covers(&abs_dir)).then(|| bulk_reader.read(&abs_dir)).flatten()
                {
                    result.scan.dirs_read += 1;
                    for entry in entries {
                        let baseline = known
                            .remove(&entry.name)
                            .unwrap_or_else(|| index.expectation(&rel_dir.join(&entry.name)));
                        process_entry(
                            entry.name,
                            entry.kind,
                            entry.attrs,
                            baseline,
                            &mut listed_control,
                        );
                    }
                    true
                } else {
                    false
                };
                #[cfg(not(target_os = "macos"))]
                let used_bulk = false;

                if !used_bulk {
                    let listing = match list_directory(&mut readers, &abs_dir, policy, None) {
                        Ok(listing) => Some(listing),
                        Err(error) => {
                            result.scan.errors.push(Error::io(&abs_dir, error));
                            listing_open_failed = true;
                            None
                        }
                    };
                    if let Some(listing) = listing {
                        result.scan.dirs_read += 1;
                        let listing = reconcile_listing(listing, &abs_dir);
                        for item in listing {
                            let (name, observed) = match item {
                                Listed::Child { name, observed } => (name.into_owned(), observed),
                                Listed::Failed(error) => {
                                    result.scan.errors.push(Error::io(&abs_dir, error));
                                    continue;
                                }
                            };
                            // Match the serial path: an entry whose name was enumerated is
                            // not missing merely because its metadata could not be read.
                            let baseline = known
                                .remove(&name)
                                .unwrap_or_else(|| index.expectation(&rel_dir.join(&name)));
                            let (kind, attrs) = match observed {
                                Ok(Some(observed)) => observed,
                                Ok(None) => {
                                    // Removed once this directory's listing is done.
                                    vanished.push((name, baseline.state != PathState::Absent));
                                    continue;
                                }
                                Err(error) => {
                                    listed_control.listed(&name);
                                    result.scan.errors.push(Error::io(abs_dir.join(&name), error));
                                    unverified.push((name, baseline.state != PathState::Absent));
                                    continue;
                                }
                            };
                            process_entry(name, kind, attrs, baseline, &mut listed_control);
                        }
                    }
                }
            }
            control_read_failed |= listing_open_failed && had_control;
            result.scan.errors.append(&mut control_errors);
            if index.directory_complete(rel_dir) != Some(true)
                && result.scan.errors.len() == errors_before
            {
                result.listed_incomplete.push(rel_dir.clone());
            }
            for (name, entry_held) in vanished {
                for removal in vanished_child_removals(rel_dir, &name, entry_held, &mut had_control)
                    .into_iter()
                    .flatten()
                {
                    defer_reconcile_op(
                        removal,
                        &mut result.operations,
                        deferred_count,
                        overflowed,
                        max_deferred_ops,
                    );
                }
            }
            for (name, entry_held) in unverified {
                if entry_held {
                    defer_reconcile_op(
                        Op::Remove { path: rel_dir.join(&name) },
                        &mut result.operations,
                        deferred_count,
                        overflowed,
                        max_deferred_ops,
                    );
                }
                if name == crate::control::CONTROL_FILE_NAME {
                    control_read_failed = true;
                }
            }
            for (name, _) in known {
                let restatement = listed_control.restatement_after_removing(&name);
                let removal = Op::Remove { path: rel_dir.join(name) };
                match restatement {
                    Some(control) => {
                        for operation in [removal, control] {
                            defer_reconcile_op(
                                operation,
                                &mut result.restated,
                                deferred_count,
                                overflowed,
                                max_deferred_ops,
                            );
                        }
                    }
                    None => defer_reconcile_op(
                        removal,
                        &mut result.operations,
                        deferred_count,
                        overflowed,
                        max_deferred_ops,
                    ),
                }
            }
            if had_control && (!listed_control.seen || control_read_failed) {
                defer_reconcile_op(
                    Op::ControlRemove { path: control_path },
                    &mut result.operations,
                    deferred_count,
                    overflowed,
                    max_deferred_ops,
                );
            }
        }
        // Once per claimed chunk, as the cold walker reports, so a long wave on a slow
        // filesystem moves the counters while it runs rather than when it lands.
        tally.flush(&result.scan);
    }
    result
}

/// What one reconciliation listing has shown about its directory's control file.
///
/// A listing names the control by the spelling the directory stores. The exact name
/// `.gitignore` is the control wherever it is listed, so listing it proves a control
/// present even when its read then fails. A case variant is the control only where a
/// lookup of `.gitignore` resolves to it (`read_control_op`), so what listing one proves is
/// what that lookup returned: a control when it found one, nothing when it missed, and
/// nothing when the variant's own metadata could not be read and no lookup was made.
/// That last case leaves the rules unknown, which the walk error records
/// (`crate::control::unreadable_control`); the sweep removes rules nothing showed, so the
/// table ends as a cold walk's does, having read nothing there either.
#[derive(Default)]
struct ListedControl {
    /// The listing showed the directory's control, or failed to read it, so the closing
    /// sweep must not remove it.
    seen: bool,
    /// The listing showed a case variant of the control name, such as `.GITIGNORE`.
    variant_listed: bool,
    /// The last control a lookup of the canonical path found during this listing: a
    /// listed case variant's, or a narrowed walk's before the listing.
    ///
    /// A case-only rename on a case-insensitive volume (`.gitignore` to `.GITIGNORE`) leaves
    /// the old spelling's entry in the index, and the closing sweep removes it. Removing
    /// the entry at the canonical path drops the rules it governs
    /// (`Index::projected_controls`), yet those rules are now the variant's, so when this
    /// listing showed the variant the sweep restates this observation right after that
    /// removal ([`Self::restatement_after_removing`]).
    looked_up: Option<Op>,
}

impl ListedControl {
    /// Note that `name` was listed, before its metadata or its control is read.
    fn listed(&mut self, name: &OsStr) {
        match crate::control::control_spelling(name) {
            Some(crate::control::ControlSpelling::Exact) => self.seen = true,
            Some(crate::control::ControlSpelling::Variant) => self.variant_listed = true,
            None => {}
        }
    }

    /// Note what reading the control through the listed `name` returned. Only a case
    /// variant's read is a lookup; the exact name already counted when it was listed.
    fn read(&mut self, name: &OsStr, read: &Result<Option<Op>>) {
        if crate::control::control_spelling(name) == Some(crate::control::ControlSpelling::Variant)
        {
            self.lookup(read);
        }
    }

    /// Note what a lookup of the directory's canonical control path returned.
    fn lookup(&mut self, lookup: &Result<Option<Op>>) {
        match lookup {
            Ok(Some(observed)) => {
                self.seen = true;
                self.looked_up = Some(observed.clone());
            }
            Ok(None) => {}
            Err(_) => self.seen = true,
        }
    }

    /// The observation to push right after the sweep removes the entry `name`: what the
    /// lookup found, when `name` is the stale exact spelling and this listing showed a case
    /// variant in its place.
    ///
    /// Only a listed variant can hold rules the removal would drop. Without one, the exact
    /// file is simply gone: a narrowed walk's lookup found it before the listing and it was
    /// deleted in between, and the removal leaves the table as bare as the directory, as a
    /// cold walk would. Restating that lookup would keep rules for a file that no longer
    /// exists until the next pass. That window remains only where a case-sensitive
    /// directory stores a variant beside the exact file deleted in it, a variant that never
    /// held the rules there.
    fn restatement_after_removing(&self, name: &OsStr) -> Option<Op> {
        if name == crate::control::CONTROL_FILE_NAME && self.variant_listed {
            self.looked_up.clone()
        } else {
            None
        }
    }
}

/// The expectation that guards the control observation a listed entry at `path` produced,
/// given the entry's own, `entry`.
///
/// A guard is the expectation of the path its operation names. That is the entry's path
/// for the exact name, but a case variant's observation names the canonical control path,
/// so only a variant pays for `expect` to read that path's expectation. Asked only once an
/// observation exists, so an ordinary entry never pays for it.
fn control_guard<T>(path: &Path, entry: T, expect: impl FnOnce(&Path) -> T) -> T {
    match crate::control::path_control_spelling(path) {
        Some(crate::control::ControlSpelling::Variant) => {
            expect(&crate::control::sibling_control_path(path))
        }
        _ => entry,
    }
}

/// Push what reading the control through the entry at `path` returned: the observation,
/// guarded by the expectation of the path it names ([`control_guard`]), or, when the read
/// failed, the removal of rules the table holds there, since nothing verifies them now.
fn push_read_control(
    target: &ReconcileTarget<'_>,
    path: &Path,
    baseline: PathExpectation,
    read: Result<Option<Op>>,
    batch: &mut Vec<ObservationOp>,
    report: &mut ReconcileReport,
) -> Result<()> {
    match read {
        Ok(Some(control)) => {
            let guard = control_guard(path, Ok(baseline), |named| target.expectation(named))?;
            batch.push(ObservationOp::if_state(control, guard));
        }
        Ok(None) => {}
        Err(error) => {
            // The failed read was of the entry itself for the exact name, and of the
            // canonical path a case variant looked up: the canonical path either way.
            let control_path = crate::control::sibling_control_path(path);
            if target.has_control(&control_path)? {
                let guard = control_guard(path, Ok(baseline), |named| target.expectation(named))?;
                batch
                    .push(ObservationOp::if_state(Op::ControlRemove { path: control_path }, guard));
            }
            report.scan.errors.push(error);
        }
    }
    Ok(())
}

/// Push what a reconcile root at `path` that vanished, or could not be observed, leaves of
/// its directory's control, when `path` spells the control name.
///
/// The exact name was the lookup's target, so its loss removes the rules the table holds,
/// as it always has. A case variant's loss says nothing by itself: another spelling may
/// still resolve, or the variant was never the control, so the canonical path is looked
/// up and its answer stands, a miss removing the rules.
fn push_lost_spelling_control(
    target: &ReconcileTarget<'_>,
    root: &Path,
    config: &ScanConfig,
    path: &Path,
    baseline: PathExpectation,
    batch: &mut Vec<ObservationOp>,
    report: &mut ReconcileReport,
) -> Result<()> {
    match crate::control::path_control_spelling(path) {
        Some(crate::control::ControlSpelling::Exact) => {
            if target.has_control(path)? {
                batch.push(ObservationOp::if_state(
                    Op::ControlRemove { path: path.to_path_buf() },
                    baseline,
                ));
            }
        }
        Some(crate::control::ControlSpelling::Variant) => {
            let control_path = crate::control::sibling_control_path(path);
            let read = read_directory_control_or_removal(config, root, &control_path);
            push_read_control(target, path, baseline, read, batch, report)?;
        }
        None => {}
    }
    Ok(())
}

/// What a listed child gone at its stat removes: its entry, if the baseline holds one, and
/// its rules, if it is the directory's control file and the table holds them.
///
/// The stat's `NotFound` is positive evidence that both are gone, so neither waits for a
/// complete listing; only a name the listing never returned has to, because it may merely
/// be unread. Removing a retained control file's entry drops its rules too, but a
/// hidden-pruned one has no entry, and without its own removal one unreadable sibling would
/// leave its rules applied with no file behind them. Clears `had_control` once the rules
/// are removed, so the listing's closing removals do not repeat it.
fn vanished_child_removals(
    dir: &Path,
    name: &OsStr,
    entry_held: bool,
    had_control: &mut bool,
) -> [Option<Op>; 2] {
    let path = dir.join(name);
    let rules = (*had_control && name == crate::control::CONTROL_FILE_NAME).then(|| {
        *had_control = false;
        Op::ControlRemove { path: path.clone() }
    });
    [entry_held.then_some(Op::Remove { path }), rules]
}

fn defer_reconcile_op(
    operation: Op,
    operations: &mut Vec<Op>,
    deferred_count: &std::sync::atomic::AtomicUsize,
    overflowed: &std::sync::atomic::AtomicBool,
    max_deferred_ops: usize,
) {
    let position = deferred_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    if position < max_deferred_ops {
        operations.push(operation);
    } else {
        overflowed.store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

fn flush_direct_reconcile_batch(
    index: &mut Index,
    batch: &mut Vec<Op>,
    sink: &mut dyn FnMut(&Commit),
    stats: &mut ApplyStats,
    observations: &mut u64,
) -> Result<()> {
    if batch.is_empty() {
        return Ok(());
    }
    *observations = observations.saturating_add(u64::try_from(batch.len()).unwrap_or(u64::MAX));
    let outcome = index.apply(&Observation::new(std::mem::take(batch)))?;
    merge_apply_stats(stats, outcome.stats);
    if let Some(commit) = outcome.commit.as_ref() {
        sink(commit);
    }
    Ok(())
}

/// Drain and reconcile every pending invalidation, collapsing nested requests.
///
/// An invalidation whose reconciliation comes back incomplete -- a subtree that could not
/// be read, or a conditional commit that lost a race -- is queued again, so the next call
/// retries it. That suits a caller that drains when it chooses. A caller that drains after
/// every event would re-walk an unreadable subtree each time, and belongs on
/// [`reconcile_pending_handle`], which settles it instead.
pub fn reconcile_pending(
    index: &mut Index,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    let mut target = ReconcileTarget::Direct(index);
    reconcile_pending_target(&mut target, config, sink)
}

/// Drain and reconcile invalidations on a shared index.
///
/// Unlike [`reconcile_pending`], a subtree that could not be read is not queued again.
/// `Watcher::apply_next` drains after every event, and a retry there re-walks the same
/// unreadable subtree on each unrelated one, for the life of the watch. The error is a
/// settled boundary instead: the subtree stays [`crate::Freshness::Partial`], the returned
/// report names the error once, and the watcher retains its cause as an issue. Only a lost
/// race -- a stale conditional commit -- is queued for the next call. Invalidate the subtree
/// again to retry it deliberately.
pub fn reconcile_pending_handle(
    handle: &IndexHandle,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    let mut target = ReconcileTarget::Shared(handle);
    reconcile_pending_target(&mut target, config, sink)
}

/// Drain and reconcile invalidations under an opened-root lifecycle and resource bound.
#[cfg(feature = "watch")]
pub(crate) fn reconcile_pending_handle_controlled(
    handle: &IndexHandle,
    config: &ScanConfig,
    control: &dyn ReconcileControl,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    let mut target = ReconcileTarget::Controlled { handle, control };
    reconcile_pending_target(&mut target, config, sink)
}

fn reconcile_pending_target(
    target: &mut ReconcileTarget<'_>,
    config: &ScanConfig,
    sink: &mut dyn FnMut(&Commit),
) -> Result<ReconcileReport> {
    config.validate_for_scope(target.scope()?)?;
    let roots = take_invalidation_roots(target)?;
    let mut combined = ReconcileReport::default();
    for (position, (root, reason)) in roots.iter().enumerate() {
        match reconcile_target(target, root, config, sink) {
            Ok(report) => {
                if target.retries_incomplete(&report) {
                    target.restore_pending_invalidations(vec![(root.clone(), *reason)])?;
                }
                merge_reconcile_report(&mut combined, report);
            }
            Err(error) => {
                target.restore_pending_invalidations(roots[position..].to_vec())?;
                return Err(error);
            }
        }
    }
    Ok(combined)
}

fn take_invalidation_roots(
    target: &mut ReconcileTarget<'_>,
) -> Result<Vec<(PathBuf, crate::InvalidateReason)>> {
    let mut pending = target.take_pending_invalidations()?;
    pending.sort_by(|(left, _), (right, _)| {
        left.components().count().cmp(&right.components().count()).then_with(|| left.cmp(right))
    });
    let mut roots: Vec<(PathBuf, crate::InvalidateReason)> = Vec::new();
    for (path, reason) in pending {
        if roots.iter().any(|(root, _)| path.starts_with(root)) {
            continue;
        }
        roots.push((path, reason));
    }

    Ok(roots)
}

fn remove_known_children(
    target: &mut ReconcileTarget<'_>,
    path: &Path,
    config: &ScanConfig,
    batch: &mut Vec<ObservationOp>,
    sink: &mut dyn FnMut(&Commit),
    report: &mut ReconcileReport,
) -> Result<()> {
    for (name, baseline) in target.child_states(path)? {
        batch.push(ObservationOp::if_state(Op::Remove { path: path.join(name) }, baseline));
        if batch.len() >= config.batch_size.max(1) {
            flush_reconcile_batch(target, batch, sink, report)?;
        }
    }
    flush_reconcile_batch(target, batch, sink, report)
}

fn push_reconcile_upsert(
    target: &ReconcileTarget<'_>,
    path: &Path,
    kind: EntryKind,
    attrs: Attrs,
    baseline: PathExpectation,
    batch: &mut Vec<ObservationOp>,
    report: &mut ReconcileReport,
) {
    // An exclusive Index borrow cannot race another index producer. If filesystem
    // metadata exactly matches the captured state, applying this upsert can only be a
    // no-op, so avoid allocating an owned op and walking the index again. Shared
    // reconciliation keeps the conditional observation so ABA arbitration remains
    // authoritative between its read and write lock boundaries.
    if target.direct_upsert_is_unchanged(baseline, kind, attrs) {
        report.observations = report.observations.saturating_add(1);
        report.apply.unchanged = report.apply.unchanged.saturating_add(1);
        return;
    }
    batch.push(ObservationOp::if_state(
        Op::Upsert { path: path.to_path_buf(), kind, attrs },
        baseline,
    ));
}

fn flush_reconcile_batch(
    target: &mut ReconcileTarget<'_>,
    batch: &mut Vec<ObservationOp>,
    sink: &mut dyn FnMut(&Commit),
    report: &mut ReconcileReport,
) -> Result<()> {
    if batch.is_empty() {
        return Ok(());
    }
    report.observations =
        report.observations.saturating_add(u64::try_from(batch.len()).unwrap_or(u64::MAX));
    let started_at = report.reconcile_epoch.expect("reconciliation report has an owner");
    let outcome = target.apply(started_at, &Observation::from_ops(std::mem::take(batch)))?;
    merge_apply_stats(&mut report.apply, outcome.stats);
    if let Some(commit) = outcome.commit.as_ref() {
        sink(commit);
    }
    Ok(())
}

fn merge_apply_stats(total: &mut ApplyStats, addition: ApplyStats) {
    total.inserted += addition.inserted;
    total.updated += addition.updated;
    total.removed += addition.removed;
    total.unchanged += addition.unchanged;
    total.invalidated += addition.invalidated;
    total.controls += addition.controls;
    total.reclassified += addition.reclassified;
    total.stale += addition.stale;
    total.resource_refused += addition.resource_refused;
}

fn merge_reconcile_report(total: &mut ReconcileReport, addition: ReconcileReport) {
    total.retry_required |= addition.retry_required;
    total.scan.dirs_read += addition.scan.dirs_read;
    total.scan.entries += addition.scan.entries;
    total.scan.files_walked += addition.scan.files_walked;
    total.scan.bytes_walked = total.scan.bytes_walked.saturating_add(addition.scan.bytes_walked);
    total.scan.allocated_walked =
        total.scan.allocated_walked.saturating_add(addition.scan.allocated_walked);
    total.scan.errors.extend(addition.scan.errors);
    total.observations = total.observations.saturating_add(addition.observations);
    merge_apply_stats(&mut total.apply, addition.apply);
    total.listed_incomplete.extend(addition.listed_incomplete);
}

fn should_descend(
    kind: EntryKind,
    attrs: Attrs,
    parent_depth: usize,
    root_dev: u64,
    config: &ScanConfig,
) -> bool {
    crate::admission::should_descend(
        kind,
        attrs,
        parent_depth,
        root_dev,
        config.max_depth,
        config.one_filesystem,
    )
}

pub(crate) fn normalize_subtree(path: &Path) -> Result<PathBuf> {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Normal(part) => normalized.push(part),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(Error::PathEscapesRoot(path.to_path_buf()));
            }
        }
    }
    Ok(normalized)
}

fn resolve_subtree_root(
    target: &ReconcileTarget<'_>,
    subtree: &Path,
    config: &ScanConfig,
) -> Result<PathBuf> {
    if subtree.as_os_str().is_empty() {
        return Ok(PathBuf::new());
    }
    let root = target.root_path()?;
    crate::counters::bump(|c| c.stats += 1);
    let Ok(root_metadata) = fs::symlink_metadata(&root) else {
        // The applying pass reports operational root failures as partial.
        return Ok(subtree.to_path_buf());
    };
    if !root_metadata.is_dir() {
        return Ok(subtree.to_path_buf());
    }
    let Ok(root_dev) = root_device(&root, &root_metadata) else {
        return Ok(subtree.to_path_buf());
    };
    let mut prefix = PathBuf::new();
    let mut components = subtree.components().peekable();
    while let Some(component) = components.next() {
        if components.peek().is_none() {
            break; // The boundary entry itself remains visible even when descent stops.
        }
        prefix.push(component.as_os_str());
        let (kind, attrs) = match observe_path(&root.join(&prefix)) {
            Ok(observed) => observed,
            Err(error)
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
                ) =>
            {
                return Ok(prefix);
            }
            Err(_) => break, // The applying pass records operational failures as partial.
        };
        if kind == EntryKind::Symlink {
            return Err(Error::SubtreeOutsideScanScope {
                path: subtree.to_path_buf(),
                scope: config.scope(),
            });
        }
        if kind != EntryKind::Dir {
            return Ok(prefix);
        }
        if config.one_filesystem && root_dev != 0 && attrs.dev != 0 && attrs.dev != root_dev {
            return Err(Error::SubtreeOutsideScanScope {
                path: subtree.to_path_buf(),
                scope: config.scope(),
            });
        }
    }
    Ok(subtree.to_path_buf())
}

/// Read an entry's kind and roll-up attributes out of its metadata.
///
/// Exposed so the watch layer verifies entries exactly the way the walker records them —
/// two stat interpretations that could drift would show up as an index that disagrees
/// with itself depending on which producer last touched a path.
///
/// On Windows the observation comes from a fresh non-following handle, and `meta` is
/// what answers for an entry whose handle cannot be opened because it is locked or
/// access is denied — the same fallback std's `metadata` makes, with identity and change
/// time unavailable for that entry.
pub fn observe(path: &Path, meta: &fs::Metadata) -> std::io::Result<(EntryKind, Attrs)> {
    #[cfg(windows)]
    {
        windows_metadata::observe(path, || Ok(meta.clone()))
    }
    #[cfg(not(windows))]
    {
        Ok((kind_from(meta), attrs_from(path, meta)?))
    }
}

pub(crate) fn observe_dir_entry(
    entry: &fs::DirEntry,
) -> std::io::Result<Option<(EntryKind, Attrs)>> {
    #[cfg(windows)]
    {
        crate::counters::bump(|c| c.stats += 1);
        #[cfg(test)]
        {
            let path = entry.path();
            if let Some(error) =
                walk_hook(&path).and_then(|hook| hook(WalkHookPoint::ChildMetadata(&path)))
            {
                return missing_as_none(Err(error));
            }
        }
        // The listing already holds the entry's enumeration data; it is read only when
        // the handle cannot be opened, so the ordinary path allocates nothing more.
        missing_as_none(windows_metadata::observe(&entry.path(), || entry.metadata()))
    }
    #[cfg(not(windows))]
    {
        #[cfg(test)]
        {
            let path = entry.path();
            if let Some(error) = child_metadata_hook(&path) {
                return missing_as_none(Err(error));
            }
        }
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        {
            // std's `DirEntry::metadata` is `statx` without `AT_NO_AUTOMOUNT` wherever
            // `statx` is served, and std keeps the listing's descriptor to itself, so the
            // reader's stat answers by path (fdu-d2fn). This is the route of a directory
            // the reader declined, so the whole-path resolution is paid rarely.
            if !linux_dents::statx_unavailable() {
                crate::counters::bump(|c| c.stats += 1);
                if let Some(observed) = linux_dents::stat_path(&entry.path()) {
                    return missing_as_none(observed);
                }
                // `statx` has just been found unavailable: std answers, with `fstatat`.
            }
        }
        let Some(meta) = missing_as_none(metadata_for_fingerprint(entry))? else {
            return Ok(None);
        };
        Ok(Some((kind_from(&meta), attrs_from(Path::new(""), &meta)?)))
    }
}

/// The non-following observation of `path` itself, as [`observe`] reads it from
/// `symlink_metadata`, and on Linux one that never triggers an automount.
///
/// For a path a route holds as an entry and verifies by itself: a reconciliation's
/// subtree and the prefixes above it, a change the watch verifies, a control looked up
/// by name. The walk root is not one; [`root_device`] says why.
pub(crate) fn observe_path(path: &Path) -> std::io::Result<(EntryKind, Attrs)> {
    crate::counters::bump(|c| c.stats += 1);
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    if let Some(observed) = linux_dents::stat_path(path) {
        return observed;
    }
    let metadata = fs::symlink_metadata(path)?;
    observe(path, &metadata)
}

#[cfg(not(windows))]
fn kind_from(meta: &fs::Metadata) -> EntryKind {
    let file_type = meta.file_type();
    if file_type.is_symlink() {
        EntryKind::Symlink
    } else if file_type.is_dir() {
        EntryKind::Dir
    } else if file_type.is_file() {
        EntryKind::File
    } else {
        EntryKind::Other
    }
}

#[cfg(unix)]
#[allow(clippy::unnecessary_wraps)] // Windows observation is fallible; keep one call contract.
pub(crate) fn attrs_from(_path: &Path, meta: &fs::Metadata) -> std::io::Result<Attrs> {
    use std::os::unix::fs::MetadataExt;
    Ok(Attrs {
        size: meta.size(),
        // st_blocks is in 512-byte units by POSIX convention regardless of the
        // filesystem's own block size.
        allocated: meta.blocks().saturating_mul(512),
        mtime_ns: compose_ns(meta.mtime(), meta.mtime_nsec()),
        ctime_ns: compose_ns(meta.ctime(), meta.ctime_nsec()),
        inode: meta.ino(),
        dev: meta.dev(),
    })
}

#[cfg(unix)]
fn compose_ns(secs: i64, nanos: i64) -> i64 {
    secs.saturating_mul(1_000_000_000).saturating_add(nanos)
}

// Windows observation goes through `windows_metadata::observe` on every route; only a
// test still derives attributes from metadata alone.
#[cfg(all(windows, test))]
pub(crate) fn attrs_from(path: &Path, meta: &fs::Metadata) -> std::io::Result<Attrs> {
    windows_metadata::observe(path, || Ok(meta.clone())).map(|(_, attrs)| attrs)
}

#[cfg(not(any(unix, windows)))]
#[allow(clippy::unnecessary_wraps)] // Windows observation is fallible; keep one call contract.
pub(crate) fn attrs_from(_path: &Path, meta: &fs::Metadata) -> std::io::Result<Attrs> {
    let mtime_ns = meta.modified().map_or(0, system_time_ns);
    Ok(Attrs {
        size: meta.len(),
        // No allocated size without platform-specific calls; apparent size is the
        // honest fallback rather than a guess at block rounding.
        allocated: meta.len(),
        mtime_ns,
        // Windows has no ctime in the Unix sense. Leaving it zero means the fingerprint
        // degrades to size + mtime there, which is what every portable tool does.
        ctime_ns: 0,
        inode: 0,
        dev: 0,
    })
}

/// The device a walk's root is on, which bounds a one-filesystem walk.
///
/// Only the device is needed, and on Windows it is read without demanding a consistent
/// observation of the root's times, which change whenever a child is created or removed.
/// The device that bounds a `one_filesystem` walk from `root`, whose non-following
/// metadata is `meta`.
///
/// The walk root is resolved. The user named it and the listing that follows opens it,
/// and on Linux an open mounts an unmounted autofs trigger where a non-following stat
/// need not: `symlink_metadata` does on glibc (std's `statx` without `AT_NO_AUTOMOUNT`)
/// and does not on musl (`fstatat`). A trigger's own device would then exclude every
/// entry the listing finds under it, so on Linux the device is read from an opened
/// descriptor on every route and under either libc, and `meta`'s device answers only
/// when the open fails, as the listing then fails the same way. Every other stat of the
/// tree never mounts ([`observe_dir_entry`], [`observe_path`], `linux_dents`).
pub(crate) fn root_device(root: &Path, meta: &fs::Metadata) -> std::io::Result<u64> {
    #[cfg(windows)]
    {
        let _ = meta;
        windows_metadata::volume_serial(root)
    }
    #[cfg(target_os = "linux")]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        let opened = fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
            .open(root)
            .and_then(|directory| directory.metadata());
        attrs_from(root, opened.as_ref().unwrap_or(meta)).map(|attrs| attrs.dev)
    }
    #[cfg(not(any(windows, target_os = "linux")))]
    {
        attrs_from(root, meta).map(|attrs| attrs.dev)
    }
}

pub(crate) fn attrs_from_file(file: &fs::File, meta: &fs::Metadata) -> std::io::Result<Attrs> {
    #[cfg(windows)]
    {
        let _ = meta;
        windows_metadata::attrs_from_file(file)
    }
    #[cfg(not(windows))]
    {
        let _ = file;
        attrs_from(Path::new(""), meta)
    }
}

#[cfg(any(not(any(unix, windows)), test))]
fn system_time_ns(time: std::time::SystemTime) -> i64 {
    match time.duration_since(std::time::UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_nanos()).unwrap_or(i64::MAX),
        Err(error) => {
            i64::try_from(error.duration().as_nanos()).map_or(i64::MIN, i64::saturating_neg)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;

    fn write_file(path: &Path, contents: &[u8]) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("create parent");
        }
        let mut f = File::create(path).expect("create file");
        f.write_all(contents).expect("write");
    }

    fn sample_tree() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("a.txt"), b"hello");
        write_file(&dir.path().join("src/main.rs"), b"fn main() {}");
        write_file(&dir.path().join("src/deep/nested.rs"), b"// nested");
        crate::test_support::settle_allocations(dir.path());
        dir
    }

    /// A counter that silently reads zero is worse than a missing one, because a report
    /// full of zeroes invites the conclusion that the work did not happen.
    ///
    /// This has already gone wrong twice: once when the per-entry counter was added to
    /// the serial walk while the parallel walk went uninstrumented, and once when a
    /// clippy fix hoisted a `read_dir` out of a match scrutinee and took the counter
    /// with it. Both builds compiled, passed every other test, and reported zero. This
    /// asserts the relationships a real walk must satisfy, so the next such edit fails
    /// here instead of in a report someone believes.
    #[test]
    fn a_walk_moves_every_counter_it_should() {
        // Both walkers, because they are separate loops with separate call sites. The
        // first version of this test only exercised the parallel one, and deleting the
        // serial walker's counter still passed — a guard covering one path gives false
        // confidence about the other.
        let _serial = crate::counters::test_serial();
        crate::counters::enable(true);
        for threads in [Some(1), Some(4)] {
            let dir = sample_tree();
            let config = ScanConfig { threads, ..ScanConfig::default() };

            // Deltas around the scan, not absolute totals. The counters are
            // process-global, so a test running beside this one can add to them — and
            // `test_serial` cannot prevent that, since it only serializes tests that
            // take it, not every test that happens to walk a tree.
            let before = crate::counters::snapshot();
            let report = scan(dir.path(), &config, &mut |_| {}).expect("scan");
            crate::counters::flush_thread();
            let after = crate::counters::snapshot();
            let observed_entries = after.dir_entries - before.dir_entries;
            let observed_opens = after.dir_opens - before.dir_opens;
            let observed_stats = after.stats - before.stats;

            // `>=` rather than `==`, and the direction is the whole point: concurrent
            // work can only inflate these, never deflate them. So a counter that is too
            // low means a path ran uninstrumented, which is the failure worth catching
            // and the one that has actually happened — the macOS bulk reader reported
            // zero opens against three real ones. Equality would catch double-counting
            // too, and would be flaky for it.
            assert!(
                observed_entries >= report.entries,
                "every enumerated entry is counted at {threads:?}: {observed_entries} < {}",
                report.entries
            );
            assert!(
                observed_opens >= report.dirs_read,
                "every directory open is counted at {threads:?}: {observed_opens} < {}",
                report.dirs_read
            );
            assert!(
                observed_stats >= report.entries,
                "every entry is stated at {threads:?}: {observed_stats} < {}",
                report.entries
            );
            #[cfg(any(target_os = "macos", all(target_os = "linux", target_env = "gnu")))]
            {
                let observed_enum = after.dir_enumeration_calls - before.dir_enumeration_calls;
                // The serial walker is the portable `read_dir` path, which cannot see
                // getdents multiplicity. Enumeration calls are a native-backend fact.
                if threads != Some(1) {
                    assert!(
                        observed_enum >= report.dirs_read,
                        "every successful native directory issues at least one enumeration \
                         call at {threads:?}: {observed_enum} < {}",
                        report.dirs_read
                    );
                }
            }

            // Deliberately not asserted: `allocs` stays zero in a library test, because
            // allocation counting needs a binary to install `CountingAlloc` as its
            // global allocator and a test harness installs its own. The probe covers
            // that half; this covers the counters the library itself drives.
        }
        crate::counters::enable(false);
    }

    #[test]
    fn summary_fold_skips_stat_on_directories_and_symlinks() {
        let _serial = crate::counters::test_serial();
        crate::counters::enable(true);
        let dir = tempfile::tempdir().expect("tempdir");
        fs::create_dir(dir.path().join("src")).expect("directory");
        write_file(&dir.path().join("a.txt"), b"hi");
        #[cfg(unix)]
        std::os::unix::fs::symlink("a.txt", dir.path().join("link")).expect("symlink");
        let config = ScanConfig { threads: Some(1), read_controls: false, ..ScanConfig::default() };

        crate::counters::test_thread_reset();
        let scan_report = scan(dir.path(), &config, &mut |_| {}).expect("scan");
        let scan_stats = crate::counters::test_thread_snapshot().stats;

        crate::counters::test_thread_reset();
        let fold_report = scan_summary_fold(dir.path(), &config, &mut |_| {}).expect("fold");
        let fold_stats = crate::counters::test_thread_snapshot().stats;
        crate::counters::enable(false);

        assert_eq!(fold_report.entries, scan_report.entries);
        assert_eq!(fold_report.files_walked, scan_report.files_walked);
        assert_eq!(fold_report.bytes_walked, scan_report.bytes_walked);
        // Windows observes every listed entry through a fresh handle on both paths, so the
        // fold performs exactly the retained walk's observations there; the skip is a
        // non-Windows saving.
        #[cfg(unix)]
        assert!(
            fold_stats < scan_stats,
            "fold {fold_stats} should skip directory/symlink stats versus scan {scan_stats}"
        );
        // The fold stats `a.txt` and, when the listing yields `src` or `link` before it,
        // the first of those, whose stat proves the directory searchable
        // ([`Searchability`]); the others take their kind from the listing.
        #[cfg(not(windows))]
        let proof = u64::from(first_listed(dir.path()) != "a.txt");
        #[cfg(unix)]
        assert_eq!(scan_stats.saturating_sub(fold_stats), 2 - proof);
        #[cfg(not(any(unix, windows)))]
        assert_eq!(scan_stats.saturating_sub(fold_stats), 1 - proof);
        #[cfg(windows)]
        assert_eq!(fold_stats, scan_stats);
    }

    /// The name the filesystem lists first in `dir`, read rather than assumed: under the
    /// skip a listing stats its children until one stat succeeds ([`Searchability`]), so
    /// how many stats the fold saves depends on the enumeration order.
    #[cfg(not(windows))]
    fn first_listed(dir: &Path) -> std::ffi::OsString {
        fs::read_dir(dir).expect("listing").next().expect("an entry").expect("entry").file_name()
    }

    #[cfg(unix)]
    #[test]
    fn summary_fold_still_stats_directories_when_bound_to_one_filesystem() {
        let _serial = crate::counters::test_serial();
        crate::counters::enable(true);
        let dir = tempfile::tempdir().expect("tempdir");
        fs::create_dir(dir.path().join("src")).expect("directory");
        write_file(&dir.path().join("a.txt"), b"hi");
        std::os::unix::fs::symlink("a.txt", dir.path().join("link")).expect("symlink");
        let config = ScanConfig {
            threads: Some(1),
            read_controls: false,
            one_filesystem: true,
            ..ScanConfig::default()
        };

        crate::counters::test_thread_reset();
        let scan_report = scan(dir.path(), &config, &mut |_| {}).expect("scan");
        let scan_stats = crate::counters::test_thread_snapshot().stats;

        crate::counters::test_thread_reset();
        let fold_report = scan_summary_fold(dir.path(), &config, &mut |_| {}).expect("fold");
        let fold_stats = crate::counters::test_thread_snapshot().stats;
        crate::counters::enable(false);

        assert_eq!(fold_report.entries, scan_report.entries);
        // `src` and `a.txt` are stated on both routes; `link` takes its kind from the
        // listing only once one of them has been stated before it, which proves the
        // directory searchable ([`Searchability`]).
        let proof = u64::from(first_listed(dir.path()) == "link");
        assert_eq!(scan_stats.saturating_sub(fold_stats), 1 - proof);
    }

    #[test]
    fn summary_fold_reuses_cleared_recycled_batches() {
        // Four workers and a batch of three force StreamingEmission to send more than
        // once per worker on this tree. Without `recycled.clear()`, the next send
        // re-folds the previous ops and files/bytes/dirs double-count.
        const DIRS: usize = 16;
        const FILES_PER_DIR: usize = 40;
        let dir = tempfile::tempdir().expect("tempdir");
        let mut expected_bytes = 0u64;
        for directory in 0..DIRS {
            let child = dir.path().join(format!("d{directory:02}"));
            fs::create_dir(&child).expect("directory");
            for file in 0..FILES_PER_DIR {
                let size = directory * FILES_PER_DIR + file + 1;
                expected_bytes += size as u64;
                write_file(&child.join(format!("f{file:02}.dat")), &vec![b'x'; size]);
            }
        }
        let expected_files = (DIRS * FILES_PER_DIR) as u64;
        let expected_dirs = DIRS as u64;
        let expected_entries = expected_files + expected_dirs;
        let config = ScanConfig {
            threads: Some(4),
            batch_size: 3,
            read_controls: false,
            ..ScanConfig::default()
        };
        let mut files = 0u64;
        let mut bytes = 0u64;
        let mut dirs = 0u64;
        let mut ops = 0u64;
        let report = scan_summary_fold(dir.path(), &config, &mut |observed| {
            ops += 1;
            let Op::Upsert { kind, attrs, .. } = &observed.op else {
                return;
            };
            match kind {
                EntryKind::File => {
                    files += 1;
                    bytes += attrs.size;
                }
                EntryKind::Dir => dirs += 1,
                EntryKind::Symlink | EntryKind::Other => {}
            }
        })
        .expect("fold");
        assert_eq!(files, expected_files);
        assert_eq!(bytes, expected_bytes);
        assert_eq!(dirs, expected_dirs);
        assert_eq!(ops, report.entries);
        assert_eq!(report.entries, expected_entries);
        assert_eq!(report.files_walked, expected_files);
        assert_eq!(report.bytes_walked, expected_bytes);
    }

    /// Publish one listing through `emission` and receive what the consumer would.
    fn publish_detached(
        emission: &mut DetachedEmission,
        directory: DetachedDirectory,
        sender: &std::sync::mpsc::Sender<WalkMessage>,
        receiver: &std::sync::mpsc::Receiver<WalkMessage>,
    ) -> (Vec<DetachedDirectory>, std::sync::mpsc::Sender<Vec<DetachedDirectory>>) {
        emission.finish_directory(directory);
        let mut send_ns = 0;
        assert!(emission.publish_before_discovery(true, sender, &mut send_ns, None));
        match receiver.try_recv().expect("a published chunk") {
            WalkMessage::DetachedDirectories { directories, recycle } => (directories, recycle),
            _ => panic!("the detached walker publishes only listings"),
        }
    }

    /// H185: a folded index describes each directory once, by its own listing, so its
    /// directory and symlink entries carry the listing's default attributes, as the
    /// transient summary's do (H72); the full index keeps the parent's stat, which is the
    /// cache's freshness fingerprint. Under `--one-filesystem` descent reads each
    /// directory's device, so the folded walk keeps that stat too. macOS lists every
    /// child's attributes in bulk and Windows never takes the skip, so neither shows it.
    #[cfg(all(unix, not(target_os = "macos")))]
    #[test]
    fn a_folded_index_takes_directory_and_symlink_kinds_from_the_listing() {
        let root = tempfile::tempdir().expect("temp root");
        write_file(&root.path().join("dir/file.txt"), b"contents");
        write_file(&root.path().join("dir/nested/deep.txt"), b"more");
        write_file(&root.path().join("top.txt"), b"top");
        std::os::unix::fs::symlink("top.txt", root.path().join("link")).expect("symlink");
        let canonical = root.path().canonicalize().expect("canonical root");
        let retention = crate::execution::TreeRetention {
            largest_files: 100,
            size: crate::query::SizeMetric::Allocated,
        };
        let attrs_by_kind = |index: &Index| -> Vec<(EntryKind, bool)> {
            let mut seen = Vec::new();
            let mut stack = vec![(PathBuf::new(), crate::EntryId::ROOT)];
            while let Some((path, id)) = stack.pop() {
                let Some(children) = index.children_of(id) else { continue };
                for (name, child) in children {
                    let kind = index.kind_of(child).expect("live child");
                    let attrs = index.attrs_of(child).expect("live child");
                    seen.push((kind, *attrs == Attrs::default()));
                    if kind.is_dir() {
                        stack.push((path.join(name), child));
                    }
                }
            }
            seen.sort_by_key(|(kind, defaulted)| (*kind as u8, *defaulted));
            seen
        };

        for threads in [1, 4] {
            let config = ScanConfig { threads: Some(threads), ..ScanConfig::default() };
            let (folded, _, _) =
                scan_into_folded_index(&canonical, &config, retention, false).expect("folded");
            let (full, _) = scan_into_index(&canonical, &config).expect("full");
            for (kind, defaulted) in attrs_by_kind(&folded) {
                assert_eq!(
                    defaulted,
                    matches!(kind, EntryKind::Dir | EntryKind::Symlink),
                    "{threads} workers: a folded {kind:?} takes its kind from the listing"
                );
            }
            assert!(
                attrs_by_kind(&full).iter().all(|(_, defaulted)| !defaulted),
                "{threads} workers: the full index stats every entry"
            );

            let bound = ScanConfig { one_filesystem: true, ..config };
            let (folded, _, _) =
                scan_into_folded_index(&canonical, &bound, retention, false).expect("folded");
            for (kind, defaulted) in attrs_by_kind(&folded) {
                assert_eq!(
                    defaulted,
                    kind == EntryKind::Symlink,
                    "{threads} workers, one filesystem: directories keep their device"
                );
            }
        }
    }

    #[test]
    fn detached_emission_reuses_returned_listings_as_fresh_ones() {
        // H159: the consumer hands drained listings back to the worker that allocated
        // them. A reused listing must be indistinguishable from a fresh one, including
        // after the consumer returned it unapplied, as it does after a build error.
        let (sender, receiver) = std::sync::mpsc::channel();
        let mut emission = DetachedEmission::new(false);

        let mut skipped = emission.begin_directory(Path::new("a/much/longer/relative/path"));
        skipped.children.push(DetachedChild {
            name: OsString::from("stale.txt"),
            kind: EntryKind::File,
            attrs: Attrs::default(),
            position: 0,
        });
        skipped.control = Some(Op::ControlRemove { path: PathBuf::from("a/.gitignore") });
        let (directories, recycle) = publish_detached(&mut emission, skipped, &sender, &receiver);
        let returned_list = directories.as_ptr();
        let returned_children = directories[0].children.as_ptr();
        recycle.send(directories).expect("the worker still listens");

        // Returned listings are taken back at the next publish, so this one is fresh.
        let mut large = emission.begin_directory(Path::new("large"));
        assert_eq!(large.children.capacity(), 0);
        large.children.reserve_exact(DETACHED_SPARE_CHILD_CAPACITY + 1);
        let (directories, recycle) = publish_detached(&mut emission, large, &sender, &receiver);
        recycle.send(directories).expect("the worker still listens");

        let reused = emission.begin_directory(Path::new("b"));
        assert_eq!(reused.path.as_os_str(), OsStr::new("b"));
        assert!(reused.children.is_empty(), "a returned listing's children are dropped");
        assert!(reused.control.is_none(), "a returned listing's control is dropped");
        assert_eq!(reused.children.as_ptr(), returned_children, "the child buffer is reused");
        let (directories, _recycle) = publish_detached(&mut emission, reused, &sender, &receiver);
        assert_eq!(directories.as_ptr(), returned_list, "the published list is reused");

        // The large listing came back past the retention bound and was freed instead.
        let fresh = emission.begin_directory(Path::new("c"));
        assert_eq!(fresh.path.as_os_str(), OsStr::new("c"));
        assert_eq!(fresh.children.capacity(), 0);
    }

    /// A transient fold that reads `.gitignore` receives each directory's control, once,
    /// ahead of every entry in that directory, whatever the batch size, the worker count,
    /// or where `.gitignore` falls in the listing (fdu-1ovb). Its consumer classifies each
    /// entry as it arrives, so an entry folded before its directory's control would miss
    /// that control's rules. Batches smaller than a listing force the probe path; the
    /// default batch holds whole listings and moves the listed control.
    #[test]
    fn a_classifying_summary_fold_receives_each_control_ahead_of_its_entries() {
        const DIRS: usize = 12;
        const FILES_PER_DIR: usize = 30;
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        for directory in 0..DIRS {
            let child = dir.path().join(format!("d{directory:02}"));
            write_file(&child.join(".gitignore"), b"*.tmp\n");
            for file in 0..FILES_PER_DIR {
                write_file(&child.join(format!("f{file:02}.dat")), b"x");
            }
            write_file(&child.join("nested/n.dat"), b"n");
        }
        let default_batch = ScanConfig::default().batch_size;
        for (threads, batch_size) in [
            (Some(1), 1),
            (Some(4), 1),
            (Some(4), 3),
            (None, 7),
            (Some(4), 16),
            (None, default_batch),
        ] {
            let config = ScanConfig { batch_size, threads, ..ScanConfig::default() };
            assert!(config.read_controls, "observation is the default");
            // Per directory: the positions of its control observations and of its entries.
            let mut seen: std::collections::BTreeMap<PathBuf, (Vec<usize>, Vec<usize>)> =
                std::collections::BTreeMap::new();
            let mut position = 0;
            scan_summary_fold(dir.path(), &config, &mut |observed| {
                let (path, control) = match &observed.op {
                    Op::Upsert { path, .. } => (path, false),
                    Op::ControlUpsert { path, .. } | Op::ControlRemove { path } => (path, true),
                    other => panic!("a cold walk emitted {other:?}"),
                };
                let directory = path.parent().unwrap_or_else(|| Path::new("")).to_path_buf();
                let (controls, entries) = seen.entry(directory).or_default();
                if control { controls } else { entries }.push(position);
                position += 1;
            })
            .expect("fold");

            assert_eq!(seen.len(), 1 + 2 * DIRS, "the root, each child, and each nested");
            for (directory, (controls, entries)) in &seen {
                let label = format!("{directory:?} with {threads:?} workers, batch {batch_size}");
                let governed = directory.as_os_str().is_empty()
                    || directory.file_name().is_some_and(|name| name != "nested");
                assert_eq!(controls.len(), usize::from(governed), "{label}: one control read");
                if let (Some(last_control), Some(first_entry)) =
                    (controls.iter().max(), entries.iter().min())
                {
                    assert!(last_control < first_entry, "{label}: its control comes first");
                }
            }
        }
    }

    /// A directory's control is what a lookup of `<dir>/.gitignore` resolves to, as git
    /// opens it (fdu-0w1b). A listed `.GITIGNORE` reads exactly what that lookup finds,
    /// named by the canonical path: its rules where the directory is case-insensitive, and
    /// nothing where it is not. The probe a transient fold makes is that same lookup.
    #[test]
    fn a_directory_control_is_what_a_lookup_of_its_canonical_path_resolves_to() {
        use crate::test_support::CaseLookups;

        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("exact/.gitignore"), b"*.log\n");
        write_file(&dir.path().join("variant/.GITIGNORE"), b"*.tmp\n");
        fs::create_dir_all(dir.path().join("shape/.GitIgnore")).expect("a directory so named");
        write_file(&dir.path().join("absent/README"), b"no rules");
        let config = ScanConfig::default();
        let upsert = |path: &str, source: &[u8]| {
            Some(Op::ControlUpsert { path: PathBuf::from(path), source: source.to_vec() })
        };

        for (lookups, insensitive) in CaseLookups::on_this_host(dir.path()) {
            let _lookups = lookups.install(dir.path());
            let label = format!("{lookups:?} lookups");
            let lookup = |directory: &str| {
                read_directory_control(
                    &config,
                    dir.path(),
                    &Path::new(directory).join(".gitignore"),
                )
                .expect("lookup")
            };
            let listed = |path: &str, kind| {
                let path = Path::new(path);
                let read = read_control_op(&config, dir.path(), path, kind).expect("listed read");
                let name = path.file_name().expect("a listed name");
                assert_eq!(
                    read_named_control_op(&config, dir.path(), path, name, kind).expect("named"),
                    read,
                    "{label}: a walker's read by the listed name decides as the path's (H180)"
                );
                read
            };

            assert_eq!(lookup("exact"), upsert("exact/.gitignore", b"*.log\n"), "{label}");
            assert_eq!(listed("exact/.gitignore", EntryKind::File), lookup("exact"), "{label}");
            assert_eq!(
                lookup("variant"),
                if insensitive { upsert("variant/.gitignore", b"*.tmp\n") } else { None },
                "{label}"
            );
            assert_eq!(
                listed("variant/.GITIGNORE", EntryKind::File),
                lookup("variant"),
                "{label}: a listed variant reads what the lookup finds"
            );
            assert_eq!(
                listed("shape/.GitIgnore", EntryKind::Dir),
                insensitive.then(|| Op::ControlRemove { path: PathBuf::from("shape/.gitignore") }),
                "{label}: a directory is resolved to, and holds no rules"
            );
            assert_eq!(lookup("absent"), None, "{label}");
            assert_eq!(listed("absent/README", EntryKind::File), None, "{label}");

            let blind = ScanConfig { read_controls: false, ..ScanConfig::default() };
            assert_eq!(
                read_control_op(
                    &blind,
                    dir.path(),
                    Path::new("variant/.GITIGNORE"),
                    EntryKind::File
                )
                .expect("read"),
                None,
                "{label}: a scan that reads no rules looks nothing up"
            );
            assert_eq!(
                read_named_control_op(
                    &blind,
                    dir.path(),
                    Path::new("exact/.gitignore"),
                    OsStr::new(".gitignore"),
                    EntryKind::File
                )
                .expect("read"),
                None,
                "{label}: nor does a read by the listed name"
            );
        }
    }

    /// The walker's join makes [`Path::join`]'s path byte for byte, including under the
    /// root, whose relative directory is empty, and for a name longer than its directory
    /// (H180).
    #[test]
    fn a_listed_name_joins_as_path_join_does() {
        for (rel_dir, name) in [
            ("", "file"),
            ("", ".gitignore"),
            ("a", "b"),
            ("a/b", ".GITIGNORE"),
            ("node_modules/x", "a-name-longer-than-twice-its-directory.js"),
        ] {
            let joined = join_listed_name(Path::new(rel_dir), OsStr::new(name));
            assert_eq!(
                joined.as_os_str(),
                Path::new(rel_dir).join(name).as_os_str(),
                "{rel_dir:?} and {name:?}"
            );
        }
    }

    /// Every entry's kind and ignored classification, and every retained control source:
    /// what a route's index says about a tree's `.gitignore` rules.
    type Classification = (BTreeMap<PathBuf, (EntryKind, Option<bool>)>, Vec<(PathBuf, Vec<u8>)>);

    fn classification(index: &Index) -> Classification {
        let mut entries = BTreeMap::new();
        let mut pending = vec![PathBuf::new()];
        while let Some(directory) = pending.pop() {
            let children: Vec<(PathBuf, crate::EntryId)> = index
                .children(&directory)
                .into_iter()
                .flatten()
                .map(|(name, id)| (directory.join(name), id))
                .collect();
            for (path, id) in children {
                let kind = index.kind_of(id).expect("a live child");
                entries.insert(path.clone(), (kind, index.is_ignored(&path).expect("observed")));
                if kind.is_dir() {
                    pending.push(path);
                }
            }
        }
        let sources = index
            .controls()
            .expect("observed")
            .sources()
            .map(|(path, source)| (path, source.to_vec()))
            .collect();
        (entries, sources)
    }

    /// A tree whose `up` directory holds its rules only in a case variant of the control
    /// name, beside a root `.gitignore` those rules partly override.
    fn case_variant_tree() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("a.log"), b"root rule");
        write_file(&dir.path().join("keep.txt"), b"kept");
        write_file(&dir.path().join("up/.GITIGNORE"), b"*.tmp\n!keep.log\nbuild/\n");
        write_file(&dir.path().join("up/x.tmp"), b"variant rule");
        write_file(&dir.path().join("up/keep.log"), b"negated by the variant");
        write_file(&dir.path().join("up/y.log"), b"root rule");
        write_file(&dir.path().join("up/build/out.bin"), b"variant rule");
        write_file(&dir.path().join("up/deep/z.tmp"), b"variant rule");
        for file in 0..12 {
            write_file(&dir.path().join(format!("up/f{file:02}.dat")), b"unignored");
        }
        dir
    }

    /// What [`case_variant_tree`] classifies where its variant does and does not govern.
    fn assert_case_variant_classification(classified: &Classification, governs: bool, label: &str) {
        let (entries, sources) = classified;
        let ignored = |path: &str| entries.get(Path::new(path)).map(|(_, ignored)| *ignored);
        assert_eq!(ignored("a.log"), Some(Some(true)), "{label}");
        assert_eq!(ignored("up/y.log"), Some(Some(true)), "{label}");
        assert_eq!(ignored("up/x.tmp"), Some(Some(governs)), "{label}");
        assert_eq!(ignored("up/deep/z.tmp"), Some(Some(governs)), "{label}");
        assert_eq!(ignored("up/build"), Some(Some(governs)), "{label}");
        assert_eq!(ignored("up/build/out.bin"), Some(Some(governs)), "{label}");
        assert_eq!(ignored("up/keep.log"), Some(Some(!governs)), "{label}: negation");
        assert_eq!(ignored("up/f00.dat"), Some(Some(false)), "{label}");
        let governing: Vec<&Path> = sources.iter().map(|(path, _)| path.as_path()).collect();
        let expected: Vec<&Path> = if governs {
            vec![Path::new(".gitignore"), Path::new("up/.gitignore")]
        } else {
            vec![Path::new(".gitignore")]
        };
        assert_eq!(governing, expected, "{label}: rules are recorded by the canonical path");
    }

    /// The detached builder, the retained scanner stream (serial and concurrent), and the
    /// narrowed-population walks classify a tree whose rules sit in `.GITIGNORE` alike, and
    /// apply those rules exactly where a lookup of `.gitignore` resolves to it (fdu-0w1b).
    /// Hidden pruning keeps the variant a control signal, as it keeps `.gitignore` one.
    #[test]
    fn every_cold_route_classifies_a_case_variant_control_alike() {
        use crate::test_support::CaseLookups;

        let dir = case_variant_tree();
        let root = dir.path();
        let pruned = Some(std::sync::Arc::new(crate::HiddenPolicy::prune_hidden(Vec::<
            std::ffi::OsString,
        >::new())));
        for (lookups, governs) in CaseLookups::on_this_host(root) {
            let _lookups = lookups.install(root);
            let reference = ScanConfig { threads: Some(1), ..ScanConfig::default() };
            let (index, report) = scan_into_index(root, &reference).expect("detached scan");
            assert!(report.is_complete(), "{:?}", report.errors);
            let expected = classification(&index);
            assert_case_variant_classification(&expected, governs, &format!("{lookups:?}"));

            for threads in [Some(1), Some(4)] {
                for batch_size in [ScanConfig::default().batch_size, 1, 3] {
                    let config = ScanConfig { batch_size, threads, ..ScanConfig::default() };
                    let label = format!("{lookups:?}, {threads:?} workers, batch {batch_size}");
                    let (detached, _) = scan_into_index(root, &config).expect("detached");
                    assert_eq!(classification(&detached), expected, "{label}: detached");
                    let (streamed, _) = scan_into_index_via_scanner(root, &config).expect("stream");
                    assert_eq!(classification(&streamed), expected, "{label}: scanner stream");
                }
            }

            // Pruning hidden entries drops the variant's row, never its rules.
            let hidden = ScanConfig { hidden: pruned.clone(), ..ScanConfig::default() };
            let (without_hidden, _) = scan_into_index(root, &hidden).expect("hidden pruned");
            let (entries, sources) = classification(&without_hidden);
            assert_eq!(sources, expected.1, "{lookups:?}: hidden pruning keeps the rules");
            for (path, fact) in &entries {
                assert_eq!(expected.0.get(path), Some(fact), "{lookups:?}: {path:?}");
            }
            assert!(!entries.contains_key(Path::new("up/.GITIGNORE")), "{lookups:?}");

            // A narrowed population reads each control before listing its directory, which
            // is the lookup itself; it keeps every spelling's row, as it keeps `.gitignore`.
            let spelled = |path: &Path| crate::control::path_control_spelling(path).is_some();
            for population in
                [crate::query::IgnoredEntries::Exclude, crate::query::IgnoredEntries::Only]
            {
                let config = ScanConfig { population, ..ScanConfig::default() };
                let (narrowed, report) = scan_into_index(root, &config).expect("narrowed");
                assert!(report.is_complete(), "{:?}", report.errors);
                let (entries, sources) = classification(&narrowed);
                let label = format!("{lookups:?}, {population:?}");
                assert_eq!(sources, expected.1, "{label}");
                let files =
                    |entries: &BTreeMap<PathBuf, (EntryKind, Option<bool>)>| -> Vec<PathBuf> {
                        entries
                            .iter()
                            .filter(|(_, (kind, _))| *kind == EntryKind::File)
                            .map(|(path, _)| path.clone())
                            .collect()
                    };
                let wanted: BTreeMap<PathBuf, (EntryKind, Option<bool>)> = expected
                    .0
                    .iter()
                    .filter(|(path, (_, ignored))| {
                        spelled(path)
                            || match population {
                                crate::query::IgnoredEntries::Exclude => *ignored == Some(false),
                                _ => *ignored == Some(true),
                            }
                    })
                    .map(|(path, fact)| (path.clone(), *fact))
                    .collect();
                assert_eq!(files(&entries), files(&wanted), "{label}: retained files");
            }
        }
    }

    /// Reconciliation keeps a case-variant control exactly as a cold walk finds it through
    /// every change: a case-only rename of `.gitignore` to `.GITIGNORE`, an edit, a
    /// removal, and a refresh of the variant's own path after it is created and after it
    /// is gone. Serial and parallel reconciliation, and revalidation, agree with a cold
    /// walk after each (fdu-0w1b).
    ///
    /// The rename is the case a canonical path cannot follow on its own: the index still
    /// holds the old `.gitignore` entry, and removing an entry at the canonical path drops
    /// the rules it governs, which on a case-insensitive directory the variant still holds.
    #[test]
    fn reconciliation_follows_a_case_variant_control_through_every_change() {
        use crate::test_support::CaseLookups;

        let probe = tempfile::tempdir().expect("tempdir");
        for (lookups, governs) in CaseLookups::on_this_host(probe.path()) {
            for threads in [Some(1), Some(4)] {
                let dir = tempfile::tempdir().expect("tempdir");
                let root = dir.path().canonicalize().expect("canonical root");
                let _lookups = lookups.install(&root);
                let config = ScanConfig { threads, batch_size: 3, ..ScanConfig::default() };
                write_file(&root.join(".gitignore"), b"*.log\n");
                write_file(&root.join("up/.gitignore"), b"*.tmp\n");
                write_file(&root.join("up/x.tmp"), b"governed");
                write_file(&root.join("up/y.bin"), b"governed after the edit");
                for file in 0..8 {
                    write_file(&root.join(format!("up/f{file}.dat")), b"unignored");
                }
                let (mut index, _) = scan_into_index(&root, &config).expect("cold scan");
                let cold = |label: &str| {
                    let (cold, report) = scan_into_index(&root, &config).expect("cold");
                    assert!(report.is_complete(), "{label}: {:?}", report.errors);
                    classification(&cold)
                };
                let reconciled = |index: &mut Index, label: &str| {
                    let report = reconcile(index, &config, &mut |_| {}).expect("reconcile");
                    assert!(report.is_complete(), "{label}: {:?}", report.scan.errors);
                    assert_eq!(report.apply.stale, 0, "{label}: no observation lost a race");
                };
                let revalidated = |snapshot: &Index, label: &str| {
                    let mut revalidated = snapshot.clone();
                    let mut observations = Vec::new();
                    revalidate(&revalidated, &config, &mut |observation| {
                        observations.push(observation);
                    })
                    .expect("revalidate");
                    for observation in &observations {
                        let outcome = revalidated.apply(observation).expect("apply");
                        assert_eq!(outcome.stats.stale, 0, "{label}: revalidation lost a race");
                    }
                    classification(&revalidated)
                };
                let governed = |label: &str| {
                    let (entries, _) = cold(label);
                    entries.get(Path::new("up/x.tmp")).map(|(_, ignored)| *ignored)
                };

                let before_rename = index.clone();
                fs::rename(root.join("up/.gitignore"), root.join("up/.GITIGNORE")).expect("recase");
                let label = format!("{lookups:?}, {threads:?} workers: case-only rename");
                assert_eq!(governed(&label), Some(Some(governs)), "{label}");
                assert_eq!(
                    revalidated(&before_rename, &label),
                    cold(&label),
                    "{label}: revalidate"
                );
                reconciled(&mut index, &label);
                assert_eq!(classification(&index), cold(&label), "{label}");

                write_file(&root.join("up/.GITIGNORE"), b"*.bin\n");
                let label = format!("{lookups:?}, {threads:?} workers: edit");
                reconciled(&mut index, &label);
                assert_eq!(classification(&index), cold(&label), "{label}");

                fs::remove_file(root.join("up/.GITIGNORE")).expect("remove the variant");
                let label = format!("{lookups:?}, {threads:?} workers: removal");
                reconciled(&mut index, &label);
                assert_eq!(classification(&index), cold(&label), "{label}");

                // A refresh of the variant's own path looks the directory's control up
                // whether the variant is there or gone.
                write_file(&root.join("up/.GITIGNORE"), b"*.tmp\n");
                for (step, label) in [
                    (None, format!("{lookups:?}, {threads:?} workers: refresh of a new variant")),
                    (
                        Some(()),
                        format!("{lookups:?}, {threads:?} workers: refresh of a removed variant"),
                    ),
                ] {
                    if step.is_some() {
                        fs::remove_file(root.join("up/.GITIGNORE")).expect("remove");
                    }
                    let report = reconcile_subtree(
                        &mut index,
                        Path::new("up/.GITIGNORE"),
                        &config,
                        &mut |_| {},
                    )
                    .expect("refresh");
                    assert!(report.is_complete(), "{label}: {:?}", report.scan.errors);
                    assert_eq!(classification(&index), cold(&label), "{label}");
                }
            }
        }
    }

    /// Revalidate a copy of `index` and apply every observation it sends, none of which may
    /// lose a race.
    fn revalidated_copy(index: &Index, config: &ScanConfig, label: &str) -> Index {
        let mut revalidated = index.clone();
        let mut observations = Vec::new();
        let report = revalidate(&revalidated, config, &mut |observation| {
            observations.push(observation);
        })
        .expect("revalidate");
        assert!(report.is_complete(), "{label}: {:?}", report.errors);
        for observation in &observations {
            let outcome = revalidated.apply(observation).expect("apply");
            assert_eq!(outcome.stats.stale, 0, "{label}: revalidation lost a race");
        }
        revalidated
    }

    /// A narrowed population's reconciliation keeps a case-variant control through a
    /// case-only rename, as a cold walk finds it. Its lookup before the listing is what
    /// finds the variant's rules, and the listing shows the variant, so the sweep restates
    /// the rules its removal of the stale `.gitignore` entry drops (fdu-0w1b).
    #[test]
    fn a_narrowed_reconciliation_follows_a_case_only_rename() {
        use crate::test_support::CaseLookups;

        let probe = tempfile::tempdir().expect("tempdir");
        for (lookups, governs) in CaseLookups::on_this_host(probe.path()) {
            for population in
                [crate::query::IgnoredEntries::Exclude, crate::query::IgnoredEntries::Only]
            {
                let label = format!("{lookups:?}, {population:?}");
                let dir = tempfile::tempdir().expect("tempdir");
                let root = dir.path().canonicalize().expect("canonical root");
                let _lookups = lookups.install(&root);
                let config = ScanConfig { population, batch_size: 3, ..ScanConfig::default() };
                write_file(&root.join("up/.gitignore"), b"*.tmp\n");
                write_file(&root.join("up/x.tmp"), b"governed");
                for file in 0..4 {
                    write_file(&root.join(format!("up/f{file}.dat")), b"unignored");
                }
                let (mut index, _) = scan_into_index(&root, &config).expect("cold scan");
                fs::rename(root.join("up/.gitignore"), root.join("up/.GITIGNORE")).expect("recase");
                let (cold, report) = scan_into_index(&root, &config).expect("cold");
                assert!(report.is_complete(), "{label}: {:?}", report.errors);
                let cold = classification(&cold);
                assert_eq!(
                    cold.1.iter().any(|(path, _)| path == Path::new("up/.gitignore")),
                    governs,
                    "{label}: the variant governs exactly where the lookup resolves to it"
                );

                let revalidated = revalidated_copy(&index, &config, &label);
                assert_eq!(classification(&revalidated), cold, "{label}: revalidate");
                let report = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
                assert!(report.is_complete(), "{label}: {:?}", report.scan.errors);
                assert_eq!(report.apply.stale, 0, "{label}: no observation lost a race");
                assert_eq!(classification(&index), cold, "{label}: reconcile");
            }
        }
    }

    /// A narrowed population's reconciliation looks a directory's control up before
    /// listing it. When the `.gitignore` that lookup found is deleted before the listing,
    /// the sweep removes the stale entry, and the rules go with it: no case variant was
    /// listed to hold them, so nothing is restated, and the table is as bare as the
    /// directory. The next pass agrees with a cold walk.
    #[test]
    fn a_control_deleted_between_its_lookup_and_the_listing_leaves_no_rules() {
        for population in
            [crate::query::IgnoredEntries::Exclude, crate::query::IgnoredEntries::Only]
        {
            for revalidating in [true, false] {
                let label = format!("{population:?}, revalidating: {revalidating}");
                let dir = tempfile::tempdir().expect("tempdir");
                let root = dir.path().canonicalize().expect("canonical root");
                let config = ScanConfig { population, ..ScanConfig::default() };
                write_file(&root.join("up/.gitignore"), b"*.tmp\n");
                write_file(&root.join("up/x.tmp"), b"governed");
                write_file(&root.join("up/y.dat"), b"unignored");
                let control_path = Path::new("up/.gitignore");
                let (mut index, _) = scan_into_index(&root, &config).expect("cold scan");
                assert!(index.control_table().contains(control_path), "{label}");

                let control = root.join(control_path);
                let deleted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
                let hook_deleted = std::sync::Arc::clone(&deleted);
                let race = install_walk_hook(&root, move |point| {
                    if let WalkHookPoint::ControlLookup(looked_up) = point {
                        if looked_up == control && fs::remove_file(looked_up).is_ok() {
                            hook_deleted.store(true, std::sync::atomic::Ordering::SeqCst);
                        }
                    }
                    None
                });
                if revalidating {
                    index = revalidated_copy(&index, &config, &label);
                } else {
                    let report = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
                    assert!(report.is_complete(), "{label}: {:?}", report.scan.errors);
                }
                drop(race);
                assert!(
                    deleted.load(std::sync::atomic::Ordering::SeqCst),
                    "{label}: the lookup found the control before it was deleted"
                );
                assert_eq!(index.path_state(control_path), PathState::Absent, "{label}");
                assert!(
                    !index.control_table().contains(control_path),
                    "{label}: no rules remain for a file that is gone"
                );

                let report = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
                assert!(report.is_complete(), "{label}: {:?}", report.scan.errors);
                let (cold, _) = scan_into_index(&root, &config).expect("cold");
                assert_eq!(classification(&index), classification(&cold), "{label}");
            }
        }
    }

    /// The sweep restates what a lookup found only after removing the stale `.gitignore`
    /// entry of a listing that showed a case variant, the one spelling that can still hold
    /// the rules that removal drops. Without a listed variant the exact file is gone, and
    /// so are its rules.
    #[test]
    fn a_listing_restates_looked_up_rules_only_after_showing_a_case_variant() {
        let found =
            Op::ControlUpsert { path: PathBuf::from("up/.gitignore"), source: b"*.tmp\n".to_vec() };
        let exact = OsStr::new(".gitignore");

        let mut deleted = ListedControl::default();
        deleted.lookup(&Ok(Some(found.clone())));
        deleted.listed(OsStr::new("x.tmp"));
        assert_eq!(deleted.restatement_after_removing(exact), None, "the exact file is gone");

        let mut recased = ListedControl::default();
        recased.lookup(&Ok(Some(found.clone())));
        recased.listed(OsStr::new(".GITIGNORE"));
        assert_eq!(recased.restatement_after_removing(exact), Some(found.clone()));
        assert_eq!(
            recased.restatement_after_removing(OsStr::new(".GitIgnore")),
            None,
            "only removing the canonical entry drops rules"
        );
        assert_eq!(recased.restatement_after_removing(OsStr::new("x.tmp")), None);

        // An included population looks the control up through the listed variant itself.
        let mut read = ListedControl::default();
        read.listed(OsStr::new(".GitIgnore"));
        read.read(OsStr::new(".GitIgnore"), &Ok(Some(found.clone())));
        assert_eq!(read.restatement_after_removing(exact), Some(found));

        let mut missed = ListedControl::default();
        missed.lookup(&Ok(None));
        missed.listed(OsStr::new(".GITIGNORE"));
        assert_eq!(missed.restatement_after_removing(exact), None, "nothing was found");
    }

    /// Where a directory is case-sensitive it can list `.gitignore` beside `.GITIGNORE`,
    /// and only the exact name governs, on every route and through every change: the
    /// variant's lookup resolves to the exact file, and removing the variant leaves the
    /// rules while removing the exact name takes them (fdu-0w1b).
    #[test]
    fn a_case_sensitive_directory_listing_both_spellings_takes_only_the_exact_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path().canonicalize().expect("canonical root");
        write_file(&root.join(".gitignore"), b"*.log\n");
        write_file(&root.join(".GITIGNORE"), b"*.tmp\n");
        let listed = fs::read_dir(&root).expect("list").count();
        if listed != 2 {
            eprintln!(
                "skipped: the temporary directory is case-insensitive, so it cannot hold both \
                 spellings"
            );
            return;
        }
        write_file(&root.join("x.log"), b"exact rule");
        write_file(&root.join("y.tmp"), b"variant, not a rule here");
        let ignored =
            |index: &Index, path: &str| index.is_ignored(Path::new(path)).expect("observed");

        for threads in [Some(1), Some(4)] {
            let config = ScanConfig { threads, batch_size: 1, ..ScanConfig::default() };
            let (detached, _) = scan_into_index(&root, &config).expect("detached");
            let (streamed, _) = scan_into_index_via_scanner(&root, &config).expect("stream");
            for index in [&detached, &streamed] {
                assert_eq!(ignored(index, "x.log"), Some(true), "{threads:?}");
                assert_eq!(ignored(index, "y.tmp"), Some(false), "{threads:?}");
                assert_eq!(classification(index), classification(&detached), "{threads:?}");
            }
        }

        let config = ScanConfig::default();
        let (mut index, _) = scan_into_index(&root, &config).expect("cold");
        fs::remove_file(root.join(".GITIGNORE")).expect("remove the variant");
        reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
        assert_eq!(ignored(&index, "x.log"), Some(true), "the exact name still governs");
        write_file(&root.join(".GITIGNORE"), b"*.tmp\n");
        fs::remove_file(root.join(".gitignore")).expect("remove the exact name");
        reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
        assert_eq!(ignored(&index, "x.log"), Some(false), "no rules remain");
        assert_eq!(ignored(&index, "y.tmp"), Some(false), "the variant never governs here");
        let (cold, _) = scan_into_index(&root, &config).expect("cold");
        assert_eq!(classification(&index), classification(&cold));
    }

    /// A listing whose control was already probed does not read its `.gitignore` again:
    /// the entry is prepared with no control and, here, no error from a file that cannot
    /// be read, where reading it would have produced one.
    #[test]
    #[cfg(unix)]
    fn a_probed_listing_prepares_its_control_entry_without_reading_it() {
        use std::os::unix::fs::PermissionsExt;
        if !crate::test_support::require_permission_bits() {
            return;
        }
        let dir = tempfile::tempdir().expect("tempdir");
        let control = dir.path().join(".gitignore");
        write_file(&control, b"*.log\n");
        fs::set_permissions(&control, fs::Permissions::from_mode(0o000)).expect("deny");
        let config = ScanConfig::default();
        let prepare = |read_control| {
            prepare_walk_entry_reading(
                dir.path(),
                Path::new(""),
                0,
                OsStr::new(".gitignore"),
                EntryKind::File,
                Attrs::default(),
                0,
                &config,
                read_control,
            )
            .expect("admitted")
        };
        let read = prepare(true);
        let skipped = prepare(false);
        fs::set_permissions(&control, fs::Permissions::from_mode(0o600)).expect("restore");

        assert!(read.control.is_none() && read.control_error.is_some(), "the read was made");
        assert!(skipped.control.is_none() && skipped.control_error.is_none(), "no read");
        assert!(skipped.retained, "the entry is still a row");
    }

    /// An automatic walk too short to fill its calibration window must say so.
    ///
    /// The failure this guards is quiet: such a walk runs on its initial pool, which is
    /// indistinguishable in the artifacts from a walk that measured the filesystem and
    /// chose to hold — unless the undecided case is recorded separately. Reading the
    /// first as the second is how a policy with no evidence behind it comes to look
    /// like a policy with evidence behind it.
    #[test]
    fn a_short_automatic_walk_records_an_undecided_policy() {
        let _serial = crate::counters::test_serial();
        let available = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
        if automatic_worker_pool(available).calibration.is_none() {
            // A host reporting one processor has no reserve to unlock, so there is no
            // policy here to leave undecided.
            return;
        }

        crate::counters::enable(true);
        let dir = sample_tree();
        let config = ScanConfig { threads: None, ..ScanConfig::default() };
        let before = crate::counters::snapshot();
        scan(dir.path(), &config, &mut |_| {}).expect("scan");
        crate::counters::flush_thread();
        let after = crate::counters::snapshot();
        crate::counters::enable(false);

        // A strict increase, so a counter inflated by a test running beside this one
        // cannot turn the assertion into a false pass.
        assert!(
            after.adaptive_policy_undecided > before.adaptive_policy_undecided,
            "a three-file tree cannot fill a {ADAPTIVE_SCAN_CALIBRATION_ENTRIES}-entry window"
        );
    }

    #[test]
    fn diagnostics_make_a_fixed_pool_and_backend_choice_explicit() {
        let dir = sample_tree();
        let config = ScanConfig { threads: Some(1), ..ScanConfig::default() };

        let (report, diagnostics) =
            scan_with_diagnostics(dir.path(), &config, &mut |_| {}).expect("diagnostic scan");

        assert_eq!(diagnostics.schema, SCAN_DIAGNOSTICS_SCHEMA);
        assert_eq!(diagnostics.worker_policy.outcome, WorkerPolicyOutcome::Fixed);
        assert_eq!(diagnostics.worker_policy.initial_workers, 1);
        assert_eq!(diagnostics.worker_policy.maximum_workers, 1);
        assert_eq!(diagnostics.worker_policy.peak_active_workers, 1);
        assert!(diagnostics.worker_policy.windows.is_empty());
        assert!(!diagnostics.worker_policy.events_truncated);
        assert_eq!(diagnostics.worker_policy.ready_directories_at_finish, 0);
        assert_eq!(diagnostics.worker_policy.in_flight_directories_at_finish, 0);
        // On glibc the serial walk lists through the native reader too, and the Linux
        // backend fields count it: every attempt is a success or a fallback, and the
        // directories read are the native successes plus the portable reads.
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        {
            let backend = &diagnostics.backend;
            assert_eq!(backend.portable_attempts, backend.portable_directory_reads);
            assert!(
                backend.portable_directory_reads < report.dirs_read,
                "native listings are not portable reads: {backend:?}, {} read",
                report.dirs_read
            );
            let (Some(attempts), Some(successes), Some(fallbacks)) = (
                backend.linux_dents_attempts,
                backend.linux_dents_successes,
                backend.linux_dents_fallbacks,
            ) else {
                panic!("Linux native counts are present: {backend:?}");
            };
            assert_eq!(attempts, successes + fallbacks);
            assert!(successes > 0, "the serial walk lists natively: {backend:?}");
            assert_eq!(successes + backend.portable_directory_reads, report.dirs_read);
        }
        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
        assert_eq!(diagnostics.backend.portable_directory_reads, report.dirs_read);

        #[cfg(target_os = "macos")]
        {
            assert_eq!(diagnostics.backend.macos_bulk_attempts, Some(0));
            assert_eq!(diagnostics.backend.macos_bulk_successes, Some(0));
            assert_eq!(diagnostics.backend.macos_bulk_fallbacks, Some(0));
            assert!(diagnostics.backend.unavailable_reason.is_none());
        }
        #[cfg(not(target_os = "macos"))]
        {
            assert_eq!(diagnostics.backend.macos_bulk_attempts, None);
            assert_eq!(diagnostics.backend.macos_bulk_successes, None);
            assert_eq!(diagnostics.backend.macos_bulk_fallbacks, None);
            assert_eq!(
                diagnostics.backend.unavailable_reason,
                Some("macOS bulk directory enumeration is unavailable on this platform")
            );
        }

        // A parallel walk counts the same way, worker by worker.
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        {
            let config = ScanConfig { threads: Some(4), ..ScanConfig::default() };
            let (report, diagnostics) =
                scan_with_diagnostics(dir.path(), &config, &mut |_| {}).expect("diagnostic scan");
            let backend = &diagnostics.backend;
            assert!(report.is_complete(), "{:?}", report.errors);
            assert_eq!(backend.portable_attempts, backend.portable_directory_reads);
            assert!(
                backend.portable_directory_reads < report.dirs_read,
                "native listings are not portable reads: {backend:?}, {} read",
                report.dirs_read
            );
            assert_eq!(
                backend.unavailable_reason,
                Some("macOS bulk directory enumeration is unavailable on this platform")
            );
            let (Some(attempts), Some(successes), Some(fallbacks)) = (
                backend.linux_dents_attempts,
                backend.linux_dents_successes,
                backend.linux_dents_fallbacks,
            ) else {
                panic!("Linux native counts are present: {backend:?}");
            };
            assert_eq!(attempts, successes + fallbacks);
            assert!(successes > 0, "a parallel walk lists natively: {backend:?}");
            assert_eq!(successes + backend.portable_directory_reads, report.dirs_read);
        }
        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
        {
            assert_eq!(diagnostics.backend.linux_dents_attempts, None);
            assert_eq!(diagnostics.backend.linux_dents_successes, None);
            assert_eq!(diagnostics.backend.linux_dents_fallbacks, None);
        }
    }

    #[test]
    fn diagnostics_fail_closed_when_an_automatic_window_is_incomplete() {
        let available = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
        let pool = automatic_worker_pool(available);
        if pool.calibration.is_none() {
            return;
        }
        let dir = sample_tree();
        let config = ScanConfig { threads: None, ..ScanConfig::default() };

        let (report, diagnostics) =
            scan_with_diagnostics(dir.path(), &config, &mut |_| {}).expect("diagnostic scan");

        assert_eq!(diagnostics.worker_policy.outcome, WorkerPolicyOutcome::Undecided);
        assert_eq!(diagnostics.worker_policy.available_parallelism, available);
        assert_eq!(diagnostics.worker_policy.initial_workers, pool.initial);
        assert_eq!(diagnostics.worker_policy.maximum_workers, pool.maximum);
        assert_eq!(
            diagnostics.worker_policy.calibration_window_entries,
            Some(ADAPTIVE_SCAN_CALIBRATION_ENTRIES)
        );
        assert_eq!(
            diagnostics.worker_policy.slow_threshold_ns_per_entry,
            Some(ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY)
        );
        assert_eq!(diagnostics.worker_policy.windows.len(), 1);
        let window = &diagnostics.worker_policy.windows[0];
        assert_eq!(window.sequence, 0);
        assert_eq!(window.start_entry_ordinal, 0);
        assert_eq!(window.end_entry_ordinal, report.entries);
        assert_eq!(window.observed_entries, report.entries);
        assert_eq!(window.decision, WorkerPolicyDecision::Undecided);
        assert!(window.end_entry_ordinal < ADAPTIVE_SCAN_CALIBRATION_ENTRIES);
        assert!(window.active_workers <= diagnostics.worker_policy.peak_active_workers);
        assert_eq!(diagnostics.worker_policy.ready_directories_at_finish, 0);
        assert_eq!(diagnostics.worker_policy.in_flight_directories_at_finish, 0);
        assert!(diagnostics.worker_policy.handoff_backlog_high_water >= 1);
    }

    #[test]
    fn diagnostic_trace_is_bounded_and_marks_truncation() {
        let recorder = ScanDiagnosticsRecorder::new(
            WorkerPool::fixed(2),
            2,
            WorkerPolicyExperiment::ShippedOneShot,
        );
        for sequence in 0..=MAX_POLICY_TRACE_EVENTS {
            recorder.record_policy_window(PolicyWindowSnapshot {
                sequence: sequence as u64,
                start_entry_ordinal: sequence as u64,
                end_entry_ordinal: sequence as u64 + 1,
                observed_entries: 1,
                observed_chunks: 1,
                observed_work_ns: 10,
                ready_directories: 1,
                in_flight_directories: 1,
                active_workers: 1,
                handoff_backlog: 0,
                requested_workers: None,
                decision: WorkerPolicyDecision::Hold,
            });
        }

        let diagnostics = recorder.finish();
        assert_eq!(diagnostics.worker_policy.windows.len(), MAX_POLICY_TRACE_EVENTS);
        assert!(diagnostics.worker_policy.events_truncated);
    }

    #[test]
    fn diagnostic_trace_preserves_queue_order_when_recorders_arrive_out_of_order() {
        let pool =
            WorkerPool { initial: 2, maximum: 4, calibration: Some(WorkerCalibration::new(1, 1)) };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 2, WorkerPolicyExperiment::RepeatedWindows);
        let snapshot = |sequence, decision| PolicyWindowSnapshot {
            sequence,
            start_entry_ordinal: sequence,
            end_entry_ordinal: sequence + 1,
            observed_entries: 1,
            observed_chunks: 1,
            observed_work_ns: 1,
            ready_directories: 0,
            in_flight_directories: 0,
            active_workers: 1,
            handoff_backlog: 0,
            requested_workers: None,
            decision,
        };

        recorder.record_policy_window(snapshot(1, WorkerPolicyDecision::HoldNoUsefulWork));
        recorder.record_policy_window(snapshot(0, WorkerPolicyDecision::Hold));

        let diagnostics = recorder.finish();
        assert_eq!(
            diagnostics
                .worker_policy
                .windows
                .iter()
                .map(|window| window.sequence)
                .collect::<Vec<_>>(),
            vec![0, 1]
        );
        assert_eq!(diagnostics.worker_policy.outcome, WorkerPolicyOutcome::HeldNoUsefulWork);
    }

    #[test]
    fn diagnostic_policy_aggregates_cross_check_runtime_counters() {
        let _serial = crate::counters::test_serial();
        let pool = WorkerPool {
            initial: 2,
            maximum: 4,
            calibration: Some(WorkerCalibration::new(17, 100)),
        };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 2, WorkerPolicyExperiment::ShippedOneShot);

        crate::counters::enable(true);
        let before = crate::counters::snapshot();
        record_adaptive_calibration_chunk(Some(&recorder), 17, 2_100);
        record_adaptive_worker_expansion(Some(&recorder));
        crate::counters::flush_thread();
        let after = crate::counters::snapshot();
        crate::counters::enable(false);

        recorder.record_policy_window(PolicyWindowSnapshot {
            sequence: 0,
            start_entry_ordinal: 0,
            end_entry_ordinal: 17,
            observed_entries: 17,
            observed_chunks: 1,
            observed_work_ns: 2_100,
            ready_directories: 2,
            in_flight_directories: 2,
            active_workers: 2,
            handoff_backlog: 0,
            requested_workers: Some(4),
            decision: WorkerPolicyDecision::ScaleUp,
        });
        let diagnostics = recorder.finish();
        let policy = diagnostics.worker_policy;
        assert_eq!(policy.calibration_chunks, 1);
        assert_eq!(policy.calibration_entries, 17);
        assert_eq!(policy.calibration_work_ns, 2_100);
        assert_eq!(policy.worker_expansions, 1);
        assert_eq!(policy.windows[0].observed_chunks, policy.calibration_chunks);
        assert_eq!(policy.windows[0].observed_entries, policy.calibration_entries);
        assert_eq!(policy.windows[0].observed_work_ns, policy.calibration_work_ns);

        // Other tests can record while this process-global interval is enabled, so the
        // counter delta may be larger but must never be smaller than this run-scoped
        // trace. The shared helpers above make the two observations one event.
        assert!(
            after.adaptive_calibration_chunks - before.adaptive_calibration_chunks
                >= policy.calibration_chunks
        );
        assert!(
            after.adaptive_calibration_entries - before.adaptive_calibration_entries
                >= policy.calibration_entries
        );
        assert!(
            after.adaptive_calibration_work_us - before.adaptive_calibration_work_us
                >= policy.calibration_work_ns / 1_000
        );
        assert!(after.adaptive_scale_ups - before.adaptive_scale_ups >= policy.worker_expansions);
    }

    #[test]
    fn diagnostic_index_scan_preserves_the_regular_result() {
        let dir = branching_tree();
        let config = ScanConfig { threads: Some(4), ..ScanConfig::default() };
        let (plain, plain_report) = scan_into_index(dir.path(), &config).expect("plain scan");
        let (diagnostic, diagnostic_report, diagnostics) =
            scan_into_index_with_diagnostics(dir.path(), &config).expect("diagnostic scan");

        assert_eq!(index_fingerprint(&plain), index_fingerprint(&diagnostic));
        assert_eq!(plain_report.entries, diagnostic_report.entries);
        assert_eq!(diagnostics.worker_policy.outcome, WorkerPolicyOutcome::Fixed);
    }

    #[test]
    fn detached_bootstrap_matches_the_streaming_reducer_for_each_worker_count() {
        let dir = branching_tree();
        for threads in 1..=4 {
            let config = ScanConfig {
                read_controls: false,
                threads: Some(threads),
                ..ScanConfig::default()
            };
            let _ = detached_and_streaming_indexes(dir.path(), &config);
        }
    }

    #[test]
    fn detached_control_bootstrap_matches_the_streaming_reducer_for_each_worker_count() {
        let dir = controlled_branching_tree();
        for threads in 1..=4 {
            let config =
                ScanConfig { read_controls: true, threads: Some(threads), ..ScanConfig::default() };
            let _ = detached_and_streaming_indexes(dir.path(), &config);
        }
    }

    #[test]
    fn detached_bootstrap_preserves_the_exact_first_mutation() {
        let dir = branching_tree();
        let config = ScanConfig { read_controls: false, threads: Some(4), ..ScanConfig::default() };
        let (mut detached, mut streaming) = detached_and_streaming_indexes(dir.path(), &config);
        let created = dir.path().join("t3/m2/after-bootstrap.rs");
        write_file(&created, b"new fact");
        let attrs =
            attrs_from(&created, &fs::symlink_metadata(&created).expect("new file metadata"))
                .expect("observe new file");
        let observation = Observation::new(vec![Op::Upsert {
            path: PathBuf::from("t3/m2/after-bootstrap.rs"),
            kind: EntryKind::File,
            attrs,
        }]);

        let detached_outcome = detached.apply(&observation).expect("detached mutation");
        let streaming_outcome = streaming.apply(&observation).expect("streaming mutation");
        assert_eq!(detached_outcome, streaming_outcome);
        assert_indexes_equal(&detached, &streaming);
    }

    #[test]
    fn detached_control_bootstrap_preserves_the_exact_first_mutation() {
        let dir = controlled_branching_tree();
        let config = ScanConfig { read_controls: true, threads: Some(4), ..ScanConfig::default() };
        let (mut detached, mut streaming) = detached_and_streaming_indexes(dir.path(), &config);
        let observation = Observation::new(vec![Op::ControlUpsert {
            path: PathBuf::from(".gitignore"),
            source: b"leaf-2.dat\n".to_vec(),
        }]);

        let detached_outcome = detached.apply(&observation).expect("detached control mutation");
        let streaming_outcome = streaming.apply(&observation).expect("streaming control mutation");
        assert_eq!(detached_outcome, streaming_outcome);
        assert_indexes_equal(&detached, &streaming);
    }

    fn observed_coverage(index: &Index) -> crate::control::ControlObservation {
        match index.control_coverage() {
            crate::control::ControlCoverage::Observed(observation) => observation,
            crate::control::ControlCoverage::NotObserved => panic!("controls were observed"),
        }
    }

    /// Both bootstrap lanes refuse a line over the limit and a file over the budget, and
    /// neither ends the scan or makes it partial. Both refusals are order-independent, so
    /// the lanes agree on exactly which files they refused.
    #[test]
    fn both_bootstrap_lanes_refuse_over_bound_controls_without_ending_the_scan() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut long_line = b"*.log\n".to_vec();
        long_line.extend(std::iter::repeat_n(b'x', crate::control::DEFAULT_CONTROL_LINE_LIMIT + 1));
        write_file(&dir.path().join("guarded/.gitignore"), &long_line);
        write_file(&dir.path().join("guarded/kept.log"), b"guarded");
        write_file(
            &dir.path().join("huge/.gitignore"),
            &b"x\n".repeat(crate::control::DEFAULT_CONTROL_BUDGET / 2),
        );
        write_file(&dir.path().join("applied/.gitignore"), b"*.log\n");
        write_file(&dir.path().join("applied/dropped.log"), b"applied");
        let config = ScanConfig { read_controls: true, threads: Some(4), ..ScanConfig::default() };

        let (detached, _) = detached_and_streaming_indexes(dir.path(), &config);
        let (_, report) = scan_into_index(dir.path(), &config).expect("scan");

        assert!(report.is_complete(), "{:?}", report.errors);
        let coverage = observed_coverage(&detached);
        assert_eq!((coverage.applied, coverage.refused), (1, 2));
        assert_eq!(
            coverage.refusals,
            vec![
                crate::control::RefusedControl {
                    path: PathBuf::from("guarded/.gitignore"),
                    reason: crate::control::ControlRefusalReason::LineLimit,
                },
                crate::control::RefusedControl {
                    path: PathBuf::from("huge/.gitignore"),
                    reason: crate::control::ControlRefusalReason::Budget,
                },
            ]
        );
        assert_eq!(detached.is_ignored(Path::new("guarded/kept.log")).expect("observed"), None);
        assert_eq!(
            detached.is_ignored(Path::new("applied/dropped.log")).expect("observed"),
            Some(true)
        );
    }

    /// The control counters attribute what a scan's control state cost: files read, sources
    /// refused, and sources that shared a retained content instead of parsing their own.
    ///
    /// Off by default and compiled in, like every counter, so the numbers a speed check
    /// reads come from the shipped path rather than an instrumented build.
    #[test]
    fn control_counters_attribute_reads_refusals_and_sharing() {
        let _serial = crate::counters::test_serial();
        let dir = tempfile::tempdir().expect("tempdir");
        let shared = b"*.log\n".to_vec();
        write_file(&dir.path().join(".gitignore"), &shared);
        write_file(&dir.path().join("twin/.gitignore"), &shared);
        let mut long_line = b"*.tmp\n".to_vec();
        long_line.extend(std::iter::repeat_n(b'x', crate::control::DEFAULT_CONTROL_LINE_LIMIT + 1));
        write_file(&dir.path().join("guarded/.gitignore"), &long_line);
        let config = ScanConfig { read_controls: true, threads: Some(1), ..ScanConfig::default() };

        crate::counters::enable(true);
        // Deltas around the scan rather than absolute totals, for the reason
        // `a_walk_moves_every_counter_it_should` gives: the counters are process-global,
        // `test_serial` only serializes the tests that take it, and every report in this
        // binary now reads `.gitignore` by default, so a test running beside this one can
        // add control reads of its own.
        let before = crate::counters::snapshot();
        let (index, report) = scan_into_index(dir.path(), &config).expect("scan");
        crate::counters::flush_thread();
        let after = crate::counters::snapshot();
        crate::counters::enable(false);

        assert!(report.is_complete(), "{:?}", report.errors);
        assert_eq!(observed_coverage(&index).refused, 1);
        // `>=` in the one direction concurrency can move them. A count that is too low
        // means a path ran uninstrumented, which is the defect worth catching; too high
        // is another test's tree, which is not.
        for (label, observed, expected) in [
            ("one read per .gitignore", after.control_reads - before.control_reads, 3),
            ("the line over the limit", after.control_refused - before.control_refused, 1),
            (
                "the twin shares one parsed content",
                after.control_sources_shared - before.control_sources_shared,
                1,
            ),
        ] {
            assert!(observed >= expected, "{label}: counted {observed}, expected {expected}");
        }
    }

    /// Both limits are part of the scope, and each lifts only its own refusals: no budget
    /// still refuses a long line, and no line limit still refuses a file past the budget.
    #[test]
    fn each_control_limit_is_scope_and_lifts_only_its_own_refusals() {
        use crate::control::{ControlLimits, ControlRefusalReason, RefusedControl};

        let with = |limits| ScanConfig { control_limits: limits, ..ScanConfig::default() };
        let defaults = ControlLimits::default();
        let default = ScanConfig::default();
        let no_budget = with(ControlLimits { budget: None, ..defaults });
        let no_line_limit = with(ControlLimits { line_limit: None, ..defaults });
        let configs = [
            default.clone(),
            with(ControlLimits { budget: Some(16 * 1024 * 1024), ..defaults }),
            no_budget.clone(),
            with(ControlLimits { line_limit: Some(64 * 1024), ..defaults }),
            no_line_limit.clone(),
            with(ControlLimits { budget: None, line_limit: None }),
            // The same values in each other's places are a different scope.
            with(ControlLimits { budget: defaults.line_limit, line_limit: defaults.budget }),
        ];
        let scopes: Vec<ScanScope> = configs.iter().map(ScanConfig::scope).collect();
        for (index, scope) in scopes.iter().enumerate() {
            assert!(scope.observes_controls());
            assert!(scopes[index + 1..].iter().all(|other| other != scope), "{scopes:?}");
        }
        for config in &configs {
            let blind = ScanConfig { read_controls: false, ..config.clone() };
            assert_eq!(blind.scope().ignore_rules_fingerprint, 0, "unobserved has one scope");
        }

        let dir = tempfile::tempdir().expect("tempdir");
        let mut long_line = b"*.log\n".to_vec();
        long_line.extend(std::iter::repeat_n(b'x', crate::control::DEFAULT_CONTROL_LINE_LIMIT + 1));
        write_file(&dir.path().join("guarded/.gitignore"), &long_line);
        write_file(&dir.path().join("guarded/dropped.log"), b"log");
        write_file(
            &dir.path().join("huge/.gitignore"),
            &b"x\n".repeat(crate::control::DEFAULT_CONTROL_BUDGET / 2),
        );
        let refused = |path: &str, reason| RefusedControl { path: PathBuf::from(path), reason };
        let (bounded, _) = scan_into_index(dir.path(), &default).expect("default scan");
        assert_eq!(observed_coverage(&bounded).refused, 2);

        let (budget_lifted, _) = detached_and_streaming_indexes(dir.path(), &no_budget);
        let coverage = observed_coverage(&budget_lifted);
        assert_eq!(coverage.limits, no_budget.control_limits);
        assert_eq!(
            coverage.refusals,
            [refused("guarded/.gitignore", ControlRefusalReason::LineLimit)]
        );
        assert_eq!(
            budget_lifted.is_ignored(Path::new("guarded/dropped.log")).expect("observed"),
            None
        );

        let (line_limit_lifted, _) = detached_and_streaming_indexes(dir.path(), &no_line_limit);
        let coverage = observed_coverage(&line_limit_lifted);
        assert_eq!(coverage.refusals, [refused("huge/.gitignore", ControlRefusalReason::Budget)]);
        assert_eq!(
            line_limit_lifted.is_ignored(Path::new("guarded/dropped.log")).expect("observed"),
            Some(true)
        );
        assert_eq!(line_limit_lifted.scope(), no_line_limit.scope());
    }

    /// The synthetic tree that ended a cold scan (fdu-1onj): 1,105 directories, each with
    /// a distinct 510-byte `.gitignore` of short rules, plus one line over the limit. The
    /// scan completes with every size exact and names what it refused, on both lanes.
    #[test]
    fn a_tree_past_both_control_bounds_completes_with_exact_sizes() {
        const DIRECTORIES: usize = 1_105;
        let dir = tempfile::tempdir().expect("tempdir");
        for directory in 0..DIRECTORIES {
            let mut source = Vec::new();
            for line in 0..63 {
                source.extend(format!("p{directory:04}{line:02}\n").bytes());
            }
            source.extend(format!("q{directory:04}\n").bytes());
            assert_eq!(source.len(), 510);
            let root = dir.path().join(format!("d{directory:04}"));
            write_file(&root.join(".gitignore"), &source);
            write_file(&root.join("file.txt"), b"contents");
        }
        write_file(
            &dir.path().join("a-guard/.gitignore"),
            &vec![b'x'; crate::control::DEFAULT_CONTROL_LINE_LIMIT + 1],
        );
        crate::test_support::settle_allocations(dir.path());
        let observing =
            ScanConfig { read_controls: true, threads: Some(4), ..ScanConfig::default() };
        let blind = ScanConfig { read_controls: false, ..observing.clone() };

        let (unobserved, _) = scan_into_index(dir.path(), &blind).expect("controls-off scan");
        let canonical = dir.path().canonicalize().expect("canonical root");
        let lanes = [
            scan_into_index(dir.path(), &observing).expect("detached scan"),
            scan_into_index_via_scanner(&canonical, &observing).expect("streaming scan"),
        ];
        for (index, report) in &lanes {
            assert!(report.is_complete(), "{:?}", report.errors);
            assert_eq!(index.total(), unobserved.total(), "sizes do not depend on controls");
            let coverage = observed_coverage(index);
            assert!(coverage.refused > 1, "the budget refused sources: {coverage:?}");
            assert_eq!(
                coverage.applied + coverage.refused,
                u64::try_from(DIRECTORIES + 1).expect("small")
            );
            assert_eq!(coverage.refusals.len(), crate::MAX_RETAINED_ISSUES);
            assert!(!coverage.lists_every_refusal());
            assert_eq!(
                coverage.refusals[0],
                crate::control::RefusedControl {
                    path: PathBuf::from("a-guard/.gitignore"),
                    reason: crate::control::ControlRefusalReason::LineLimit,
                }
            );
            assert!(
                index.control_table().retained_cost() <= crate::control::DEFAULT_CONTROL_BUDGET
            );
        }
    }

    #[test]
    fn fingerprint_metadata_observes_mutation_after_directory_enumeration() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("changing.bin");
        write_file(&path, b"before");
        let entry = fs::read_dir(dir.path())
            .expect("read directory")
            .next()
            .expect("one entry")
            .expect("read entry");

        write_file(&path, b"after mutation");

        let metadata = metadata_for_fingerprint(&entry).expect("fresh metadata");
        assert_eq!(metadata.len(), b"after mutation".len() as u64);
    }

    /// A tree wide and deep enough that workers genuinely interleave.
    ///
    /// A three-file fixture would pass every one of these tests with a broken queue,
    /// because one worker would finish before another started.
    fn branching_tree() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        for top in 0..12 {
            for middle in 0..6 {
                for leaf in 0..7 {
                    write_file(
                        &dir.path().join(format!("t{top}/m{middle}/leaf-{leaf}.dat")),
                        &vec![b'x'; leaf * 13],
                    );
                }
            }
            // A deep chain alongside the wide fan-out, so depth and width are both
            // exercised by the same walk.
            write_file(&dir.path().join(format!("t{top}/a/b/c/d/e/deep.txt")), b"deep");
        }
        crate::test_support::settle_allocations(dir.path());
        dir
    }

    fn controlled_branching_tree() -> tempfile::TempDir {
        let dir = branching_tree();
        write_file(&dir.path().join(".gitignore"), b"leaf-1.dat\nt7/\n");
        write_file(&dir.path().join("t3/.gitignore"), b"!m2/leaf-1.dat\n*.tmp\n");
        write_file(&dir.path().join("t3/m2/generated.tmp"), b"ignored by nested control");
        write_file(&dir.path().join("t7/.gitignore"), b"!m0/leaf-1.dat\n");
        fs::create_dir_all(dir.path().join("t5/.gitignore")).expect("non-file control directory");
        write_file(&dir.path().join("t5/.gitignore/ordinary.txt"), b"ordinary child");
        crate::test_support::settle_allocations(dir.path());
        dir
    }

    fn index_fingerprint(index: &Index) -> Vec<(PathBuf, EntryKind, Attrs)> {
        let mut entries: Vec<(PathBuf, EntryKind, Attrs)> = Vec::new();
        let mut queue = vec![PathBuf::new()];
        while let Some(path) = queue.pop() {
            let Some(children) = index.children(&path) else {
                continue;
            };
            let names: Vec<PathBuf> = children.map(|(name, _id)| path.join(name)).collect();
            for child_path in names {
                let kind = index.kind(&child_path).expect("child has a kind");
                let attrs = *index.attrs(&child_path).expect("child has attrs");
                entries.push((child_path.clone(), kind, attrs));
                if kind.is_dir() {
                    queue.push(child_path);
                }
            }
        }
        entries.sort_by(|left, right| left.0.cmp(&right.0));
        entries
    }

    fn detached_and_streaming_indexes(root: &Path, config: &ScanConfig) -> (Index, Index) {
        let canonical = root.canonicalize().expect("canonical test root");
        let (streaming, streaming_report) =
            scan_into_index_via_scanner(&canonical, config).expect("streaming oracle");
        let (detached, detached_report) = scan_into_index(root, config).expect("detached scan");

        assert_eq!(detached_report.dirs_read, streaming_report.dirs_read);
        assert_eq!(detached_report.entries, streaming_report.entries);
        assert_eq!(detached_report.files_walked, streaming_report.files_walked);
        assert_eq!(detached_report.bytes_walked, streaming_report.bytes_walked);
        assert_eq!(
            detached_report.errors.iter().map(ToString::to_string).collect::<Vec<_>>(),
            streaming_report.errors.iter().map(ToString::to_string).collect::<Vec<_>>()
        );
        assert_indexes_equal(&detached, &streaming);
        (detached, streaming)
    }

    fn assert_indexes_equal(left: &Index, right: &Index) {
        assert_eq!(index_fingerprint(left), index_fingerprint(right));
        assert_eq!(left.total(), right.total());
        assert_eq!(left.partition_total().ok(), right.partition_total().ok());
        assert_eq!(left.scope(), right.scope());
        assert_eq!(left.freshness(), right.freshness());
        assert_eq!(left.state(), right.state());
        assert_eq!(left.clock(), right.clock());
        assert_eq!(left.len(), right.len());
        assert_eq!(left.issues(), right.issues());
        assert_eq!(left.observes_controls(), right.observes_controls());
        assert_eq!(left.control_coverage(), right.control_coverage());
        assert_eq!(
            left.control_table()
                .sources()
                .map(|(path, source)| (path, source.to_vec()))
                .collect::<Vec<_>>(),
            right
                .control_table()
                .sources()
                .map(|(path, source)| (path, source.to_vec()))
                .collect::<Vec<_>>()
        );
        for (path, _, _) in index_fingerprint(left) {
            assert_eq!(left.is_ignored(&path).ok(), right.is_ignored(&path).ok(), "{path:?}");
        }
    }

    /// A small tree whose mutation crosses every structural reconciliation boundary.
    fn reconciliation_transition_tree() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("changed.txt"), b"before");
        write_file(&dir.path().join("removed.txt"), b"remove me");
        write_file(&dir.path().join("directory-to-file/old.rs"), b"old child");
        write_file(&dir.path().join("file-to-directory"), b"old file");
        write_file(&dir.path().join("removed-tree/nested/gone.md"), b"gone");
        write_file(&dir.path().join("stable/deep/kept.rs"), b"kept");
        crate::test_support::settle_allocations(dir.path());
        dir
    }

    fn mutate_reconciliation_transition_tree(root: &Path) {
        write_file(&root.join("changed.txt"), b"after, with a distinct size");
        fs::remove_file(root.join("removed.txt")).expect("remove root file");

        fs::remove_dir_all(root.join("directory-to-file")).expect("remove old directory");
        write_file(&root.join("directory-to-file"), b"replacement file");

        fs::remove_file(root.join("file-to-directory")).expect("remove old file");
        write_file(&root.join("file-to-directory/new.txt"), b"replacement child");

        fs::remove_dir_all(root.join("removed-tree")).expect("remove nested tree");
        write_file(&root.join("added-tree/nested/new.md"), b"new nested file");
        crate::test_support::settle_allocations(root);
    }

    fn effective_ops(commits: &[Commit]) -> Vec<Op> {
        let mut operations: Vec<_> = commits
            .iter()
            .flat_map(|commit| commit.changes.iter())
            .filter_map(|change| match change {
                crate::EffectiveChange::Inserted { path, kind, attrs } => {
                    Some(Op::Upsert { path: path.clone(), kind: *kind, attrs: *attrs })
                }
                crate::EffectiveChange::Updated { path, kind, current, .. } => {
                    Some(Op::Upsert { path: path.clone(), kind: *kind, attrs: *current })
                }
                crate::EffectiveChange::Removed { path, .. } => {
                    Some(Op::Remove { path: path.clone() })
                }
                crate::EffectiveChange::Invalidated { path, reason } => {
                    Some(Op::InvalidateSubtree { path: path.clone(), reason: *reason })
                }
                crate::EffectiveChange::ControlUpdated { .. }
                | crate::EffectiveChange::ControlRefusalUpdated { .. }
                | crate::EffectiveChange::Reclassified { .. } => None,
            })
            .collect();
        operations.sort_by(|left, right| left.path().cmp(right.path()));
        operations
    }

    fn commit_touches(commit: &Commit, path: &Path) -> bool {
        commit.changes.iter().any(|change| change.path() == path)
    }

    #[test]
    fn parallel_and_serial_walks_produce_the_same_index() {
        let dir = branching_tree();
        let serial_config = ScanConfig { threads: Some(1), ..ScanConfig::default() };
        let (serial, serial_report) =
            scan_into_index(dir.path(), &serial_config).expect("serial scan");
        assert!(serial_report.is_complete());

        for threads in [2_usize, 3, 8] {
            let config = ScanConfig { threads: Some(threads), ..ScanConfig::default() };
            let (parallel, report) = scan_into_index(dir.path(), &config).expect("parallel scan");
            assert!(report.is_complete(), "{threads} threads reported errors");
            assert_eq!(report.entries, serial_report.entries, "{threads} threads");
            assert_eq!(report.dirs_read, serial_report.dirs_read, "{threads} threads");
            assert_eq!(report.files_walked, serial_report.files_walked, "{threads} threads");
            assert_eq!(report.bytes_walked, serial_report.bytes_walked, "{threads} threads");
            // Public roll-ups carry extension names even though the internal merge path
            // uses ids whose assignment order differs between serial and parallel walks.
            let (serial_total, parallel_total) = (serial.total(), parallel.total());
            assert_eq!(
                (
                    parallel_total.files,
                    parallel_total.dirs,
                    parallel_total.bytes,
                    parallel_total.allocated,
                    parallel_total.newest_mtime_ns,
                ),
                (
                    serial_total.files,
                    serial_total.dirs,
                    serial_total.bytes,
                    serial_total.allocated,
                    serial_total.newest_mtime_ns,
                ),
                "{threads} threads roll-up"
            );
            assert_eq!(
                parallel_total.by_ext, serial_total.by_ext,
                "{threads} threads per-extension roll-up"
            );
            assert_eq!(
                index_fingerprint(&parallel),
                index_fingerprint(&serial),
                "{threads} threads produced a different index"
            );
        }
    }

    #[test]
    fn parallel_walk_emits_every_entry_exactly_once() {
        let dir = branching_tree();
        let config = ScanConfig { threads: Some(4), batch_size: 16, ..ScanConfig::default() };
        let mut seen: BTreeMap<PathBuf, usize> = BTreeMap::new();
        let report = scan(dir.path(), &config, &mut |observation| {
            for op in &observation.ops {
                if let Op::Upsert { path, .. } = &op.op {
                    *seen.entry(path.clone()).or_default() += 1;
                }
            }
        })
        .expect("parallel scan");

        assert!(report.is_complete());
        assert_eq!(seen.len() as u64, report.entries, "entry count disagrees with the report");
        let duplicated: Vec<_> =
            seen.iter().filter(|(_path, count)| **count != 1).map(|(path, _)| path).collect();
        assert!(duplicated.is_empty(), "paths emitted more than once: {duplicated:?}");
    }

    #[test]
    fn parallel_walk_honours_max_depth() {
        let dir = branching_tree();
        for threads in [1_usize, 4] {
            let config =
                ScanConfig { threads: Some(threads), max_depth: Some(2), ..ScanConfig::default() };
            let (index, report) = scan_into_index(dir.path(), &config).expect("scan");
            assert!(report.is_complete());
            for (path, _kind, _attrs) in index_fingerprint(&index) {
                assert!(
                    path.components().count() <= 2,
                    "{threads} threads kept {path:?} past the depth limit"
                );
            }
        }
    }

    #[test]
    fn scan_order_never_changes_the_resulting_index() {
        let dir = branching_tree();
        let depth_first =
            ScanConfig { order: ScanOrder::DepthFirst, threads: Some(1), ..ScanConfig::default() };
        let (expected, expected_report) =
            scan_into_index(dir.path(), &depth_first).expect("depth-first scan");

        for (order, threads) in
            [(ScanOrder::BreadthFirst, 1), (ScanOrder::BreadthFirst, 4), (ScanOrder::DepthFirst, 4)]
        {
            let config = ScanConfig { order, threads: Some(threads), ..ScanConfig::default() };
            let (index, report) = scan_into_index(dir.path(), &config).expect("scan");
            assert_eq!(report.entries, expected_report.entries, "{order:?}/{threads}");
            assert_eq!(report.dirs_read, expected_report.dirs_read, "{order:?}/{threads}");
            // Public roll-ups resolve internal ids, so their named maps are stable even
            // when traversal order changes id assignment.
            let (totals, expected_totals) = (index.total(), expected.total());
            assert_eq!(
                (totals.files, totals.dirs, totals.bytes, totals.allocated),
                (
                    expected_totals.files,
                    expected_totals.dirs,
                    expected_totals.bytes,
                    expected_totals.allocated
                ),
                "{order:?}/{threads} roll-up"
            );
            assert_eq!(
                totals.newest_mtime_ns, expected_totals.newest_mtime_ns,
                "{order:?}/{threads} newest mtime"
            );
            assert_eq!(
                totals.by_ext, expected_totals.by_ext,
                "{order:?}/{threads} extension tallies"
            );
            assert_eq!(
                index_fingerprint(&index),
                index_fingerprint(&expected),
                "{order:?}/{threads} produced a different index"
            );
        }
    }

    #[test]
    fn a_single_worker_breadth_first_walk_is_strictly_level_ordered() {
        // The strict guarantee, which holds only with one worker. With several, the
        // queue is ordered but the claims are not: a fast worker can enqueue and claim
        // depth d+2 while a slow worker still holds depth d+1. See
        // `breadth_first_starts_every_top_level_subtree_early` for the property the
        // default configuration actually provides, which is the one consumers rely on.
        let dir = branching_tree();
        let config = ScanConfig {
            order: ScanOrder::BreadthFirst,
            threads: Some(1),
            batch_size: 1,
            ..ScanConfig::default()
        };
        let mut depths_in_order: Vec<usize> = Vec::new();
        scan(dir.path(), &config, &mut |observation| {
            for op in &observation.ops {
                if let Op::Upsert { path, kind, .. } = &op.op {
                    if kind.is_dir() {
                        depths_in_order.push(path.components().count());
                    }
                }
            }
        })
        .expect("scan");

        assert!(depths_in_order.len() > 10, "fixture should have many directories");
        assert!(
            depths_in_order.windows(2).all(|pair| pair[0] <= pair[1]),
            "directory depths were not non-decreasing: {depths_in_order:?}"
        );
    }

    /// How many of the fixture's twelve top-level subtrees have received any file by
    /// the time half the files have been emitted.
    ///
    /// This is the product metric — "is a mid-scan ranking meaningful?" — rather than
    /// first-touch, which cannot distinguish the orders at all: reading the root
    /// enumerates all twelve children at once either way. What a ranking needs is that
    /// the subtrees grow *together*.
    fn subtrees_started_at_halfway(order: ScanOrder, threads: usize, dir: &Path) -> usize {
        let config =
            ScanConfig { order, batch_size: 1, threads: Some(threads), ..ScanConfig::default() };

        let mut files: Vec<PathBuf> = Vec::new();
        scan(dir, &config, &mut |observation| {
            for op in &observation.ops {
                if let Op::Upsert { path, kind, .. } = &op.op {
                    if !kind.is_dir() {
                        files.push(path.clone());
                    }
                }
            }
        })
        .expect("scan");

        let halfway = files.len() / 2;
        let mut started: BTreeSet<PathBuf> = BTreeSet::new();
        for path in files.iter().take(halfway) {
            if let Some(top) = path.components().next() {
                started.insert(PathBuf::from(top.as_os_str()));
            }
        }
        started.len()
    }

    #[test]
    fn a_parallel_walk_accounts_for_where_its_time_went() {
        // The attribution identity: every named cause is a disjoint slice of worker
        // wall time, so the parts can never exceed the whole, and the counters that
        // amortization depends on are actually incremented. This is the instrument
        // the scheduler experiments will read; if it drifts, they measure noise.
        let dir = branching_tree();
        let config = ScanConfig { threads: Some(4), batch_size: 64, ..ScanConfig::default() };
        let report = scan(dir.path(), &config, &mut |_| {}).expect("scan");
        let a = report.attribution;

        assert!(a.claims > 0, "a parallel walk claims chunks: {a:?}");
        assert!(a.work_ns > 0, "reading directories takes time: {a:?}");
        assert!(a.wall_ns > 0);
        // claim() locks at least once per successful claim, and release() locks once
        // per claim cycle too.
        assert!(a.lock_ops >= a.claims * 2, "lock ops out of step with claims: {a:?}");
        assert!(
            a.accounted_ns() <= a.wall_ns,
            "attributed slices are disjoint intervals inside worker wall: {a:?}"
        );
    }

    #[test]
    fn a_serial_walk_has_no_coordination_to_attribute() {
        // Serial semantics: wall is the loop, "send" is the inline sink (the consumer
        // actually running), work is the rest — and the coordination counters stay
        // zero because there is no queue lock and no channel.
        let dir = branching_tree();
        let config = ScanConfig { threads: Some(1), batch_size: 64, ..ScanConfig::default() };
        let mut observations = 0usize;
        let report = scan(dir.path(), &config, &mut |_| observations += 1).expect("scan");
        let a = report.attribution;

        assert!(observations > 0, "the sink ran, so send_ns measured something real");
        assert!(a.work_ns > 0 && a.wall_ns >= a.work_ns);
        assert_eq!(
            (a.claims, a.lock_ops, a.lock_contended, a.starved_ns, a.lock_wait_ns),
            (0, 0, 0, 0, 0),
            "no queue, no lock, nothing to wait on: {a:?}"
        );
    }

    /// Twelve top-level subtrees, each a branching tree several levels deep.
    ///
    /// Branching matters: an earlier fixture gave every level exactly one child, which
    /// pinned the frontier at twelve directories and made both orders behave
    /// identically — a LIFO cannot dive when there is nothing to dive into. With two
    /// children per level, depth-first pushes siblings and immediately descends into
    /// the last one, which is the behaviour that leaves other subtrees behind.
    ///
    /// It is also deliberately uniform. A version using one deep spur beside shallow
    /// siblings made the result depend on whether `readdir` returned the spur early:
    /// it passed on APFS and failed on ext4.
    fn deep_forest() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        for top in 0..12 {
            let mut level: Vec<PathBuf> = vec![dir.path().join(format!("t{top}"))];
            for _ in 0..5 {
                let mut next = Vec::new();
                for parent in &level {
                    for child in 0..2 {
                        let path = parent.join(format!("c{child}"));
                        for file in 0..3 {
                            write_file(&path.join(format!("f{file}.dat")), b"xxxxxxxxxx");
                        }
                        next.push(path);
                    }
                }
                level = next;
            }
        }
        dir
    }

    /// Files accumulated by the *least advanced* top-level subtree in the first
    /// quarter of the walk.
    ///
    /// Counting subtrees merely *started* cannot discriminate on a tree whose root
    /// fans out twelve ways: every scheduler touches all twelve immediately, because
    /// reading the root enumerates them. What differs is whether they then advance
    /// together, so the question is how far behind the laggard is.
    fn leanest_subtree_early(order: ScanOrder, threads: usize, dir: &Path) -> usize {
        let config =
            ScanConfig { order, batch_size: 1, threads: Some(threads), ..ScanConfig::default() };
        let mut files: Vec<PathBuf> = Vec::new();
        scan(dir, &config, &mut |observation| {
            for op in &observation.ops {
                if let Op::Upsert { path, kind, .. } = &op.op {
                    if !kind.is_dir() {
                        files.push(path.clone());
                    }
                }
            }
        })
        .expect("scan");

        let quarter = files.len() / 4;
        let mut per_top: BTreeMap<PathBuf, usize> = BTreeMap::new();
        for path in files.iter().take(quarter) {
            if let Some(top) = path.components().next() {
                *per_top.entry(PathBuf::from(top.as_os_str())).or_default() += 1;
            }
        }
        (0..12)
            .map(|top| per_top.get(&PathBuf::from(format!("t{top}"))).copied().unwrap_or(0))
            .min()
            .unwrap_or(0)
    }

    #[test]
    fn deep_subtrees_do_not_delay_their_siblings() {
        // The orientation property, and the reason breadth-first is the default: when
        // every top-level subtree is deep, depth-first pours its early effort down
        // whichever ones it picked up and leaves the rest at zero, while the region
        // scheduler advances all twelve together. A user watching the top level fill
        // in sees a meaningful ranking in the first case and a misleading one in the
        // second.
        //
        // Asserted at one worker only, and that bound is deliberate. This metric reads
        // *emission* order, and under several workers emission reflects which worker
        // finished first as much as which region was claimed — so it varies with core
        // count. Measured on a six-core machine the margin is wide (33-37 files against
        // 6); on a CI runner with fewer cores both orders can report zero. That makes it
        // a benchmark-grade observation, recorded in exp-013, not a unit-test assertion.
        //
        // The scheduling property itself *is* asserted deterministically, against the
        // queue rather than through a walk, by
        // `the_region_scheduler_spreads_workers_over_distinct_subtrees`.
        let dir = deep_forest();
        let breadth = leanest_subtree_early(ScanOrder::BreadthFirst, 1, dir.path());
        let depth = leanest_subtree_early(ScanOrder::DepthFirst, 1, dir.path());
        assert!(
            breadth > depth,
            "breadth-first should leave its least advanced top-level subtree further \
             along: {breadth} files against {depth}"
        );
    }

    #[test]
    fn the_region_scheduler_spreads_workers_over_distinct_subtrees() {
        // The scheduler invariant, checked directly on the queue rather than through a
        // walk: consecutive claims by *different* workers must land in different
        // regions while several regions have work. This is what the round-robin ready
        // ring buys, and it is the thing a global FIFO could not promise.
        let queue = DirectoryQueue::new((PathBuf::new(), 0), ScanOrder::BreadthFirst, None, None);
        let mut timing = WalkAttribution::default();

        // Bootstrap: drain the root, then seed four top-level regions.
        let mut claimed = Vec::new();
        let root = queue.claim(&mut claimed, &mut timing).expect("root is claimable");
        claimed.clear();
        queue.extend(
            (0..4).map(|top| (PathBuf::from(format!("t{top}")), 1, RegionId::UNASSIGNED)),
            &mut timing,
        );
        assert!(root.release(0, 0, &mut timing).is_none());

        // Four workers with no affinity must each be handed a different region. The
        // claims are held for the whole loop, as four concurrent workers would hold
        // them, because releasing between them would let one worker take every region.
        let mut regions = BTreeSet::new();
        let mut held = Vec::new();
        for _ in 0..4 {
            let mut claimed = Vec::new();
            held.push(queue.claim(&mut claimed, &mut timing).expect("a region has work"));
            regions.insert(claimed[0].2.0);
            assert_eq!(claimed.len(), 1, "one directory per region so far");
        }
        assert_eq!(regions.len(), 4, "each claim took a distinct region: {regions:?}");
    }

    #[test]
    fn breadth_first_spreads_early_work_across_top_level_subtrees() {
        // The justification for making breadth-first the default: at the halfway point
        // more of the tree's top-level subtrees have started filling, so a consumer
        // ranking by size mid-scan is comparing partial values rather than a mix of
        // final values and zeros.
        //
        // Pinned with one worker, where the ordering guarantee is strict and the result
        // is deterministic. The multi-worker case is deliberately NOT asserted here:
        // measured on this fixture the advantage disappears under the default worker
        // count (both orders start 7-8 subtrees, run to run), because emission order is
        // then dominated by worker scheduling rather than by queue order. That is a
        // real limitation of the current design, recorded in the plan and tracked
        // rather than papered over with a test tuned until it passed.
        let dir = branching_tree();
        let breadth = subtrees_started_at_halfway(ScanOrder::BreadthFirst, 1, dir.path());
        let depth = subtrees_started_at_halfway(ScanOrder::DepthFirst, 1, dir.path());

        assert!(
            breadth > depth,
            "breadth-first should have more top-level subtrees underway at the halfway \
             point, but started {breadth} against depth-first's {depth}"
        );
    }

    #[test]
    fn scan_order_does_not_change_the_cache_scope() {
        // Order is operational, like the worker count: it changes when observations
        // appear, never which ones, so it must not be able to invalidate a snapshot.
        let breadth = ScanConfig { order: ScanOrder::BreadthFirst, ..ScanConfig::default() };
        let depth = ScanConfig { order: ScanOrder::DepthFirst, ..ScanConfig::default() };
        assert_eq!(breadth.scope(), depth.scope());
    }

    #[test]
    fn worker_threads_are_bounded_and_never_zero() {
        let zero = ScanConfig { threads: Some(0), ..ScanConfig::default() };
        assert_eq!(zero.worker_threads(), 1, "zero threads must fall back to the serial walk");
        let absurd = ScanConfig { threads: Some(usize::MAX), ..ScanConfig::default() };
        assert_eq!(absurd.worker_threads(), MAX_SCAN_THREADS);
        // The automatic choice is capped well below what a caller may request, because
        // the measured knee is far below the core count on a large machine.
        let automatic = ScanConfig { threads: None, ..ScanConfig::default() };
        assert!((1..=DEFAULT_SCAN_THREADS_CAP).contains(&automatic.worker_threads()));
    }

    #[test]
    fn automatic_worker_pool_keeps_a_conservative_start_and_bounded_reserve() {
        assert_eq!(automatic_worker_pool(1), WorkerPool::fixed(1));
        assert_eq!(
            automatic_worker_pool(4),
            WorkerPool {
                initial: 4,
                maximum: 8,
                calibration: Some(WorkerCalibration::new(
                    ADAPTIVE_SCAN_CALIBRATION_ENTRIES,
                    ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY,
                )),
            }
        );
        assert_eq!(
            automatic_worker_pool(10),
            WorkerPool {
                initial: DEFAULT_SCAN_THREADS_CAP,
                maximum: ADAPTIVE_SCAN_THREADS_CAP,
                calibration: Some(WorkerCalibration::new(
                    ADAPTIVE_SCAN_CALIBRATION_ENTRIES,
                    ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY,
                )),
            }
        );
    }

    #[test]
    fn an_abandoned_claim_does_not_strand_the_other_workers() {
        // The liveness property behind `DirectoryClaim`. A worker that stops mid-chunk
        // — consumer gone, or a panic unwinding through the directory read — still owes
        // the queue its claim, and `claim` parks everyone else until `outstanding`
        // reaches zero. Before the claim was an RAII guard both of those exits skipped
        // the release, and every remaining worker waited on the condvar forever while
        // the scoped join waited on them.
        let queue = std::sync::Arc::new(DirectoryQueue::new(
            (PathBuf::new(), 0),
            ScanOrder::BreadthFirst,
            None,
            None,
        ));
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();

        // One worker takes the root and abandons it without publishing anything.
        drop(queue.claim(&mut claimed, &mut timing).expect("root is claimable"));

        // A second worker must now be told the walk is over rather than parking.
        let waiter = queue.clone();
        let (done, finished) = std::sync::mpsc::sync_channel(1);
        std::thread::spawn(move || {
            let mut timing = WalkAttribution::default();
            let mut claimed = Vec::new();
            let outcome = waiter.claim(&mut claimed, &mut timing).is_some();
            done.send(outcome).expect("publish the claim outcome");
        });

        assert_eq!(
            finished.recv_timeout(std::time::Duration::from_secs(5)),
            Ok(false),
            "the queue must report the walk finished instead of parking the worker"
        );
    }

    #[test]
    fn automatic_queue_activates_its_reserve_only_for_slow_initial_work() {
        let slow = WorkerCalibration::new(3, 10);
        let queue =
            DirectoryQueue::new((PathBuf::new(), 0), ScanOrder::BreadthFirst, Some(slow), None);
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();

        let claim = queue.claim(&mut claimed, &mut timing).expect("root is claimable");
        queue.extend([(PathBuf::from("child"), 1, RegionId::UNASSIGNED)].into_iter(), &mut timing);
        assert!(claim.release(2, 20, &mut timing).is_none());

        claimed.clear();
        let claim = queue.claim(&mut claimed, &mut timing).expect("child is claimable");
        queue.extend([(PathBuf::from("grandchild"), 2, claimed[0].2)].into_iter(), &mut timing);
        assert_eq!(claim.release(1, 10, &mut timing), Some(2));

        let fast = WorkerCalibration::new(3, 11);
        let queue =
            DirectoryQueue::new((PathBuf::new(), 0), ScanOrder::BreadthFirst, Some(fast), None);
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();
        let claim = queue.claim(&mut claimed, &mut timing).expect("root is claimable");
        assert!(claim.release(3, 30, &mut timing).is_none());
        assert!(queue.lock().controller.is_none(), "calibration decides only once");
    }

    #[test]
    fn repeated_windows_reconsider_a_late_slow_phase_in_entry_order() {
        let calibration = WorkerCalibration::new(4, 10);
        let mut controller =
            WorkerController::new(calibration, WorkerPolicyExperiment::RepeatedWindows);

        let fast = controller.observe(4, 20).expect("first complete window");
        let slow = controller.observe(4, 80).expect("second complete window");

        assert!(!fast.slow);
        assert!(slow.slow);
        assert_eq!((fast.start_entry_ordinal, fast.end_entry_ordinal), (0, 4));
        assert_eq!((slow.start_entry_ordinal, slow.end_entry_ordinal), (4, 8));
    }

    #[test]
    fn shipped_trace_retains_post_decision_windows_without_changing_policy() {
        let calibration = WorkerCalibration::new(2, 10);
        let pool = WorkerPool { initial: 2, maximum: 4, calibration: Some(calibration) };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 2, WorkerPolicyExperiment::ShippedOneShot);
        let queue = DirectoryQueue::new_with_policy(
            (PathBuf::new(), 0),
            ScanOrder::BreadthFirst,
            Some(calibration),
            Some(recorder.clone()),
            pool.initial,
            pool.maximum,
            WorkerPolicyExperiment::ShippedOneShot,
        );
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();

        let first = queue.claim(&mut claimed, &mut timing).expect("first window");
        queue.extend([(PathBuf::from("late"), 1, RegionId::UNASSIGNED)].into_iter(), &mut timing);
        assert_eq!(first.release(2, 10, &mut timing), None, "fast prefix holds");

        claimed.clear();
        let late = queue.claim(&mut claimed, &mut timing).expect("late phase");
        queue.extend([(PathBuf::from("tail"), 2, RegionId::UNASSIGNED)].into_iter(), &mut timing);
        assert_eq!(late.release(2, 40, &mut timing), None, "shadow cannot scale");

        let diagnostics = recorder.finish();
        assert_eq!(diagnostics.worker_policy.outcome, WorkerPolicyOutcome::Held);
        assert_eq!(
            diagnostics
                .worker_policy
                .windows
                .iter()
                .map(|window| window.decision)
                .collect::<Vec<_>>(),
            vec![WorkerPolicyDecision::Hold, WorkerPolicyDecision::ObserveSlow]
        );
    }

    #[test]
    fn staged_controller_requires_a_useful_frontier_then_stays_bounded() {
        let calibration = WorkerCalibration::new(1, 10);
        let pool = WorkerPool { initial: 2, maximum: 8, calibration: Some(calibration) };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 4, WorkerPolicyExperiment::StagedGatedWindows);
        let queue = DirectoryQueue::new_with_policy(
            (PathBuf::new(), 0),
            ScanOrder::BreadthFirst,
            Some(calibration),
            Some(recorder.clone()),
            pool.initial,
            pool.maximum,
            WorkerPolicyExperiment::StagedGatedWindows,
        );
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();

        let root = queue.claim(&mut claimed, &mut timing).expect("root");
        queue.extend([(PathBuf::from("narrow"), 1, RegionId::UNASSIGNED)].into_iter(), &mut timing);
        assert_eq!(root.release(1, 20, &mut timing), None);

        claimed.clear();
        let narrow = queue.claim(&mut claimed, &mut timing).expect("narrow child");
        queue.extend(
            (0..9).map(|index| (PathBuf::from(format!("wide-{index}")), 2, RegionId::UNASSIGNED)),
            &mut timing,
        );
        assert_eq!(narrow.release(1, 20, &mut timing), Some(4));

        claimed.clear();
        let wide = queue.claim(&mut claimed, &mut timing).expect("wide claim");
        queue.extend(
            (0..9).map(|index| (PathBuf::from(format!("wider-{index}")), 3, RegionId::UNASSIGNED)),
            &mut timing,
        );
        assert_eq!(wide.release(1, 20, &mut timing), Some(8));

        let diagnostics = recorder.finish();
        let decisions: Vec<_> = diagnostics
            .worker_policy
            .windows
            .iter()
            .map(|window| (window.decision, window.requested_workers))
            .collect();
        assert_eq!(
            decisions,
            vec![
                (WorkerPolicyDecision::HoldInsufficientFrontier, None),
                (WorkerPolicyDecision::ScaleUp, Some(4)),
                (WorkerPolicyDecision::ScaleUp, Some(8)),
            ]
        );
        assert!(
            diagnostics
                .worker_policy
                .windows
                .windows(2)
                .all(|pair| pair[0].end_entry_ordinal <= pair[1].start_entry_ordinal)
        );
        assert!(diagnostics.worker_policy.windows.iter().all(|window| {
            window.requested_workers.is_none_or(|workers| workers <= pool.maximum)
        }));
    }

    #[test]
    fn staged_controller_does_not_add_producers_to_a_delayed_handoff() {
        let calibration = WorkerCalibration::new(1, 10);
        let pool = WorkerPool { initial: 2, maximum: 8, calibration: Some(calibration) };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 4, WorkerPolicyExperiment::StagedGatedWindows);
        recorder.handoff_sent();
        recorder.handoff_sent();
        let queue = DirectoryQueue::new_with_policy(
            (PathBuf::new(), 0),
            ScanOrder::BreadthFirst,
            Some(calibration),
            Some(recorder.clone()),
            pool.initial,
            pool.maximum,
            WorkerPolicyExperiment::StagedGatedWindows,
        );
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();
        let claim = queue.claim(&mut claimed, &mut timing).expect("root");
        queue.extend(
            (0..9).map(|index| (PathBuf::from(format!("ready-{index}")), 1, RegionId::UNASSIGNED)),
            &mut timing,
        );

        assert_eq!(claim.release(1, 20, &mut timing), None);
        recorder.handoff_received();
        recorder.handoff_received();
        let diagnostics = recorder.finish();
        assert_eq!(
            diagnostics.worker_policy.windows[0].decision,
            WorkerPolicyDecision::HoldHandoffBacklog
        );
    }

    #[test]
    fn candidate_retains_post_expansion_shadow_history() {
        let calibration = WorkerCalibration::new(1, 10);
        let pool = WorkerPool { initial: 2, maximum: 4, calibration: Some(calibration) };
        let recorder =
            ScanDiagnosticsRecorder::new(pool, 4, WorkerPolicyExperiment::RepeatedWindows);
        let queue = DirectoryQueue::new_with_policy(
            (PathBuf::new(), 0),
            ScanOrder::BreadthFirst,
            Some(calibration),
            Some(recorder.clone()),
            pool.initial,
            pool.maximum,
            WorkerPolicyExperiment::RepeatedWindows,
        );
        let mut timing = WalkAttribution::default();
        let mut claimed = Vec::new();

        let slow = queue.claim(&mut claimed, &mut timing).expect("slow prefix");
        queue.extend(
            (0..4).map(|index| (PathBuf::from(format!("fast-{index}")), 1, RegionId::UNASSIGNED)),
            &mut timing,
        );
        assert_eq!(slow.release(1, 20, &mut timing), Some(4));

        claimed.clear();
        let fast = queue.claim(&mut claimed, &mut timing).expect("fast suffix");
        queue.extend([(PathBuf::from("tail"), 2, RegionId::UNASSIGNED)].into_iter(), &mut timing);
        assert_eq!(fast.release(1, 1, &mut timing), None);

        let diagnostics = recorder.finish();
        assert_eq!(
            diagnostics
                .worker_policy
                .windows
                .iter()
                .map(|window| window.decision)
                .collect::<Vec<_>>(),
            vec![WorkerPolicyDecision::ScaleUp, WorkerPolicyDecision::ObserveFast]
        );
    }

    #[test]
    fn every_experimental_controller_preserves_exactness_and_shutdown() {
        let dir = branching_tree();
        let serial = ScanConfig { threads: Some(1), ..ScanConfig::default() };
        let (reference, _) = scan_into_index(dir.path(), &serial).expect("serial reference");
        let automatic = ScanConfig { threads: None, ..ScanConfig::default() };

        for policy in [
            WorkerPolicyExperiment::ShippedOneShot,
            WorkerPolicyExperiment::RepeatedWindows,
            WorkerPolicyExperiment::StagedGatedWindows,
        ] {
            let (index, report, diagnostics) =
                scan_into_index_with_policy_diagnostics(dir.path(), &automatic, policy)
                    .expect("candidate scan finishes");
            assert!(report.is_complete(), "{policy:?}: {:?}", report.errors);
            assert_eq!(index_fingerprint(&reference), index_fingerprint(&index), "{policy:?}");
            assert_eq!(diagnostics.worker_policy.ready_directories_at_finish, 0);
            assert_eq!(diagnostics.worker_policy.in_flight_directories_at_finish, 0);
            assert_eq!(diagnostics.worker_policy.handoff_backlog_at_finish, 0);
            assert!(
                diagnostics.worker_policy.workers_spawned
                    <= diagnostics.worker_policy.maximum_workers
            );
        }
    }

    /// A deterministic model of the automatic worker policy under *completion* order.
    ///
    /// The scaling decision is driven by chunk releases, and chunks complete in whatever
    /// order the filesystem and the workers produce them — not in traversal order. On a
    /// homogeneous tree that distinction is invisible, because every prefix looks like
    /// every other. On a heterogeneous one it decides the answer.
    ///
    /// These tests exist because the alternative is a stopwatch on a real tree, which
    /// measures one host on one day and cannot separate a policy defect from ambient
    /// noise. Replaying an explicit completion order through the shipped calibration
    /// isolates the policy exactly, and does so identically on every platform.
    ///
    /// They characterize behavior; they do not endorse a replacement. Which controller
    /// is *faster* is a question only the held-out Apple Silicon/APFS matrix can answer.
    mod completion_order {
        use super::{ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, WorkerCalibration};

        /// One chunk release: entries observed and worker time spent observing them.
        #[derive(Clone, Copy, Debug)]
        struct Chunk {
            entries: u64,
            work_ns: u64,
        }

        impl Chunk {
            /// A run of `entries` entries costing `per_entry_ns` each.
            const fn at(entries: u64, per_entry_ns: u64) -> Self {
                Self { entries, work_ns: entries.saturating_mul(per_entry_ns) }
            }
        }

        /// What a policy concluded over one completion order.
        #[derive(Debug, PartialEq, Eq)]
        enum Outcome {
            /// The policy found the filesystem slow and expanded the reserve.
            ScaledUp { after_chunks: usize },
            /// The policy found the filesystem fast and held the initial pool.
            Held { after_chunks: usize },
            /// The walk ended before the policy observed enough to conclude anything.
            ///
            /// Distinct from [`Outcome::Held`] on purpose: nothing was measured, so a
            /// held pool here is an absence of evidence rather than a decision.
            Undecided,
        }

        /// Mean cost per entry over a whole trace, which is what the threshold *means*.
        fn whole_trace_ns_per_entry(trace: &[Chunk]) -> u64 {
            let entries: u64 = trace.iter().map(|chunk| chunk.entries).sum();
            let work_ns: u64 = trace.iter().map(|chunk| chunk.work_ns).sum();
            assert!(entries > 0, "a trace must observe entries");
            work_ns / entries
        }

        /// Replay a completion order through the *shipped* calibration.
        ///
        /// This drives [`WorkerCalibration::observe`] itself rather than restating its
        /// arithmetic, so the model cannot quietly drift from the policy it is evidence
        /// about. The loop mirrors `DirectoryQueue::release`: fold each chunk in, and
        /// stop at the first one that produces a verdict.
        fn shipped(window: u64, threshold_ns: u64, trace: &[Chunk]) -> Outcome {
            let mut calibration = WorkerCalibration::new(window, threshold_ns);
            for (index, chunk) in trace.iter().enumerate() {
                if let Some(slow) = calibration.observe(chunk.entries, chunk.work_ns) {
                    let after_chunks = index + 1;
                    return if slow {
                        Outcome::ScaledUp { after_chunks }
                    } else {
                        Outcome::Held { after_chunks }
                    };
                }
            }
            Outcome::Undecided
        }

        /// Entries per chunk in the traces below. Four fill the 16,384-entry window.
        const CHUNK: u64 = 4_096;
        /// A shallow, cache-warm phase: metadata already resident.
        const FAST: Chunk = Chunk::at(CHUNK, 2_000);
        /// A deep, cold phase: the latency-bound regime the reserve exists to hide.
        const SLOW: Chunk = Chunk::at(CHUNK, 90_000);

        #[test]
        fn completion_order_alone_flips_the_shipped_decision() {
            // The defect, stated as an experiment: hold the *tree* constant and vary
            // only the order its chunks complete in. Both traces contain the same four
            // fast and four slow chunks, so they describe the same filesystem work.
            let fast_phase_first = [FAST, FAST, FAST, FAST, SLOW, SLOW, SLOW, SLOW];
            let interleaved = [SLOW, FAST, SLOW, FAST, SLOW, FAST, SLOW, FAST];

            let window = 4 * CHUNK;
            let threshold = ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY;

            // Whole-walk truth is identical, and by the policy's own threshold both
            // walks are latency-bound: 46 µs per entry against a 30 µs trigger.
            let truth = whole_trace_ns_per_entry(&fast_phase_first);
            assert_eq!(truth, whole_trace_ns_per_entry(&interleaved));
            assert!(
                truth >= threshold,
                "both traces are slow walks by the shipped threshold: {truth} < {threshold}"
            );

            // Yet the decision depends entirely on which chunks happened to finish
            // first. One walk hides latency; the other runs the whole slow phase on the
            // starting pool, having concluded from an unrepresentative prefix.
            assert_eq!(
                shipped(window, threshold, &fast_phase_first),
                Outcome::Held { after_chunks: 4 },
                "a fast prefix holds the pool for a walk that is slow overall"
            );
            assert_eq!(
                shipped(window, threshold, &interleaved),
                Outcome::ScaledUp { after_chunks: 4 },
                "the same tree scales up when its slow chunks land in the window"
            );
        }

        #[test]
        fn a_slow_phase_after_the_window_is_never_reconsidered() {
            // The heterogeneous-tree case from the field report. A small fast region
            // fills the window, and everything after it is slow — but the calibration
            // is already gone, so no amount of later evidence can reopen the decision.
            let mut trace = vec![FAST; 4];
            trace.extend(std::iter::repeat_n(SLOW, 400));

            let observed = whole_trace_ns_per_entry(&trace);
            assert!(
                observed >= 2 * ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY,
                "the walk is overwhelmingly latency-bound: {observed} ns per entry"
            );

            assert_eq!(
                shipped(4 * CHUNK, ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, &trace),
                Outcome::Held { after_chunks: 4 },
                "1% of the walk decided the worker policy for the other 99%"
            );
        }

        #[test]
        fn slow_in_flight_work_is_censored_by_fast_completions() {
            // Four slow chunks have already been claimed, but their filesystem calls
            // remain in flight while four cache-warm chunks complete. Completion-order
            // calibration cannot see owed work: the fast completions close the window
            // and permanently hold before any slow claim returns.
            let completed_before_slow_returns = [FAST, FAST, FAST, FAST];
            assert_eq!(
                shipped(
                    4 * CHUNK,
                    ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY,
                    &completed_before_slow_returns,
                ),
                Outcome::Held { after_chunks: 4 }
            );

            let mut eventual_completions = completed_before_slow_returns.to_vec();
            eventual_completions.extend([SLOW, SLOW, SLOW, SLOW]);
            assert!(
                whole_trace_ns_per_entry(&eventual_completions)
                    >= ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY
            );
            assert_eq!(
                shipped(4 * CHUNK, ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, &eventual_completions,),
                Outcome::Held { after_chunks: 4 }
            );
        }

        #[test]
        fn a_slow_prefix_can_scale_a_walk_that_is_fast_overall() {
            // The mirror-image error. A one-way expansion reacts correctly to the
            // prefix by its local threshold, but the prefix is under 1% of this walk
            // and the whole trace is firmly in the fast regime. A repeated trigger
            // alone cannot undo an expansion; staged growth limits exposure but does
            // not make reversible parking unnecessary.
            let mut trace = vec![SLOW; 4];
            trace.extend(std::iter::repeat_n(FAST, 400));
            let observed = whole_trace_ns_per_entry(&trace);
            assert!(observed < ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY);
            assert_eq!(
                shipped(4 * CHUNK, ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, &trace),
                Outcome::ScaledUp { after_chunks: 4 }
            );
            assert_eq!(
                sliding(4 * CHUNK, ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, &trace),
                Outcome::ScaledUp { after_chunks: 4 }
            );
        }

        #[test]
        fn a_walk_shorter_than_the_window_decides_nothing() {
            // Fails closed rather than reporting a held pool: a walk this short never
            // observed enough to have an opinion, and an artifact that recorded `Held`
            // would claim a measurement that was never taken.
            let trace = [FAST, SLOW];
            assert_eq!(
                shipped(4 * CHUNK, ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY, &trace),
                Outcome::Undecided
            );
        }

        /// A screening-only candidate: a window that slides instead of closing once.
        ///
        /// Present as *evidence about a design*, not as a proposed change. It keeps the
        /// shipped trigger and pool bounds and alters only when the question is asked,
        /// which is the narrowest edit that could address the order sensitivity above.
        /// Whether it is faster on a real tree is unmeasured here and unmeasurable in a
        /// virtualized non-APFS environment; selecting it would need the held-out Apple
        /// Silicon matrix that this workstream has not yet been able to run.
        struct SlidingWindow {
            window_entries: u64,
            threshold_ns: u64,
            recent: std::collections::VecDeque<Chunk>,
            entries: u64,
            work_ns: u64,
        }

        impl SlidingWindow {
            fn new(window_entries: u64, threshold_ns: u64) -> Self {
                Self {
                    window_entries,
                    threshold_ns,
                    recent: std::collections::VecDeque::new(),
                    entries: 0,
                    work_ns: 0,
                }
            }

            /// Fold in a chunk and re-ask the question over the trailing window.
            fn observe(&mut self, chunk: Chunk) -> Option<bool> {
                self.recent.push_back(chunk);
                self.entries = self.entries.saturating_add(chunk.entries);
                self.work_ns = self.work_ns.saturating_add(chunk.work_ns);

                // Drop from the front while the window stays full without the oldest
                // chunk, so the answer describes recent work rather than the whole walk.
                while let Some(oldest) = self.recent.front().copied() {
                    if self.entries - oldest.entries < self.window_entries {
                        break;
                    }
                    self.recent.pop_front();
                    self.entries -= oldest.entries;
                    self.work_ns -= oldest.work_ns;
                }

                (self.entries >= self.window_entries)
                    .then(|| self.work_ns / self.entries >= self.threshold_ns)
            }
        }

        /// Replay a completion order through the candidate, stopping at its first
        /// scale-up. The shipped pool only grows, so a later verdict cannot undo one.
        fn sliding(window: u64, threshold_ns: u64, trace: &[Chunk]) -> Outcome {
            let mut policy = SlidingWindow::new(window, threshold_ns);
            let mut decided = None;
            for (index, chunk) in trace.iter().enumerate() {
                if let Some(slow) = policy.observe(*chunk) {
                    let after_chunks = index + 1;
                    if slow {
                        return Outcome::ScaledUp { after_chunks };
                    }
                    decided.get_or_insert(Outcome::Held { after_chunks });
                }
            }
            decided.unwrap_or(Outcome::Undecided)
        }

        #[test]
        fn screening_a_sliding_window_against_the_order_sensitivity() {
            let window = 4 * CHUNK;
            let threshold = ADAPTIVE_SCAN_SLOW_WORK_NS_PER_ENTRY;

            // The pair that splits the shipped policy reaches one answer here, and it
            // is the answer the whole-trace mean supports in both orders.
            let fast_phase_first = [FAST, FAST, FAST, FAST, SLOW, SLOW, SLOW, SLOW];
            let interleaved = [SLOW, FAST, SLOW, FAST, SLOW, FAST, SLOW, FAST];
            // Both reach the same verdict; they differ only in how long the fast prefix
            // delays it, which is the behavior a trailing window is supposed to have.
            assert_eq!(
                sliding(window, threshold, &fast_phase_first),
                Outcome::ScaledUp { after_chunks: 6 }
            );
            assert_eq!(
                sliding(window, threshold, &interleaved),
                Outcome::ScaledUp { after_chunks: 4 }
            );

            // And the late slow phase is reached rather than missed: two slow chunks
            // after the window closes are enough to pull the trailing mean over.
            let mut late = vec![FAST; 4];
            late.extend(std::iter::repeat_n(SLOW, 400));
            assert_eq!(sliding(window, threshold, &late), Outcome::ScaledUp { after_chunks: 6 });

            // A genuinely fast tree must still hold the pool: the candidate has to keep
            // the property the shipped policy gets right, or it is not a candidate.
            let uniformly_fast = vec![FAST; 40];
            assert_eq!(
                sliding(window, threshold, &uniformly_fast),
                Outcome::Held { after_chunks: 4 }
            );

            // A short walk still decides nothing, for the same reason as above.
            assert_eq!(sliding(window, threshold, &[FAST, SLOW]), Outcome::Undecided);
        }
    }

    #[test]
    fn thread_count_does_not_change_the_cache_scope() {
        // Threads are an operational choice. If they leaked into the scope, changing
        // the pool size would invalidate every snapshot on disk.
        let serial = ScanConfig { threads: Some(1), ..ScanConfig::default() };
        let parallel = ScanConfig { threads: Some(8), ..ScanConfig::default() };
        assert_eq!(serial.scope(), parallel.scope());
    }

    #[test]
    fn scan_populates_an_index_end_to_end() {
        let dir = sample_tree();
        let (index, report) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");

        assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
        let total = index.total();
        assert_eq!(total.files, 3);
        assert_eq!(total.dirs, 2);
        assert_eq!(total.bytes, 5 + 12 + 9);
        assert_eq!(total.by_ext[".rs"].files, 2);
        assert_eq!(total.by_ext[".txt"].files, 1);

        let src = index.rollup(Path::new("src")).expect("src");
        assert_eq!(src.files, 2);
        assert_eq!(src.dirs, 1);
    }

    #[test]
    fn cold_scan_routes_control_sources_through_both_walkers() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("debug.log"), b"ignored");
        write_file(&dir.path().join("keep.rs"), b"visible");

        for threads in [1, 4] {
            let config =
                ScanConfig { read_controls: true, threads: Some(threads), ..ScanConfig::default() };
            let (index, report) = scan_into_index(dir.path(), &config).expect("scan");

            assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
            assert!(
                index
                    .controls()
                    .expect("control state observed")
                    .source_is(Path::new(".gitignore"), b"*.log\n")
            );
            assert_eq!(
                index.is_ignored(Path::new("debug.log")).expect("control state observed"),
                Some(true)
            );
            assert_eq!(
                index.is_ignored(Path::new("keep.rs")).expect("control state observed"),
                Some(false)
            );
            let partitions = index.partition_total().expect("control state observed");
            assert_eq!(partitions.all.files, 3);
            assert_eq!(partitions.unignored.files, 2);
        }
    }

    #[cfg(unix)]
    #[test]
    fn raced_fifo_control_source_is_rejected_without_blocking() {
        let dir = tempfile::tempdir().expect("tempdir");
        let control = dir.path().join(".gitignore");
        let status = match std::process::Command::new("mkfifo").arg(&control).status() {
            Ok(status) => status,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
            Err(error) => panic!("create fifo: {error}"),
        };
        assert!(status.success(), "mkfifo exited with {status}");

        let root = dir.path().to_path_buf();
        let (sender, receiver) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let result = read_control_op_unconditional(
                &root,
                Path::new(".gitignore"),
                EntryKind::File,
                Some(crate::control::DEFAULT_CONTROL_BUDGET),
            );
            sender.send(result).ok();
        });
        let result = receiver
            .recv_timeout(std::time::Duration::from_secs(1))
            .expect("a raced FIFO must not block the scan worker")
            .expect("the non-regular replacement is a normal control removal");

        assert!(matches!(result, Some(Op::ControlRemove { .. })));
    }

    #[test]
    fn hidden_admission_keeps_exact_allowlist_and_control_signals_only() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("debug.log"), b"ignored");
        write_file(&dir.path().join(".secret/token"), b"hidden");
        write_file(&dir.path().join(".github/workflows/check.yml"), b"visible");
        let hidden = std::sync::Arc::new(crate::HiddenPolicy::prune_hidden([".github"]));

        for threads in [1, 4] {
            let config = ScanConfig {
                hidden: Some(std::sync::Arc::clone(&hidden)),
                threads: Some(threads),
                read_controls: true,
                ..ScanConfig::default()
            };
            let (mut index, report) = scan_into_index(dir.path(), &config).expect("scan");

            assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
            assert!(index.lookup(Path::new(".gitignore")).is_none());
            assert!(index.lookup(Path::new(".secret")).is_none());
            assert!(index.lookup(Path::new(".secret/token")).is_none());
            assert!(index.lookup(Path::new(".github/workflows/check.yml")).is_some());
            assert!(
                index
                    .controls()
                    .expect("control state observed")
                    .source_is(Path::new(".gitignore"), b"*.log\n")
            );
            assert_eq!(
                index.is_ignored(Path::new("debug.log")).expect("control state observed"),
                Some(true)
            );

            fs::remove_file(dir.path().join(".gitignore")).expect("remove control");
            if threads > 1 {
                fs::create_dir(dir.path().join(".gitignore")).expect("replace with directory");
            }
            let reconciled = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
            assert!(reconciled.is_complete());
            assert!(index.controls().expect("control state observed").is_empty());
            if threads > 1 {
                fs::remove_dir(dir.path().join(".gitignore")).expect("remove directory");
            }
            write_file(&dir.path().join(".gitignore"), b"*.log\n");
        }
    }

    #[test]
    fn excluded_ignored_directory_is_not_enumerated_and_rule_edits_reconcile_it() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join(".gitignore"), b"target/\n");
        write_file(&root.path().join("target/deep/file.rs"), b"code");
        write_file(&root.path().join("keep.rs"), b"kept");
        let config = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            threads: Some(4),
            ..ScanConfig::default()
        };

        let (mut index, cold) = scan_into_index(root.path(), &config).expect("cold scan");
        assert!(cold.is_complete(), "{:?}", cold.errors);
        assert_eq!(cold.dirs_read, 1, "ignored target was not opened");
        assert!(index.lookup(Path::new("target")).is_none());
        assert!(index.lookup(Path::new("keep.rs")).is_some());

        write_file(&root.path().join(".gitignore"), b"");
        let exposed = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile exposure");
        assert!(exposed.is_complete(), "{:?}", exposed.scan.errors);
        assert!(index.lookup(Path::new("target/deep/file.rs")).is_some());
        assert!(exposed.scan.dirs_read >= 3);

        write_file(&root.path().join(".gitignore"), b"target/\n");
        let excluded = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile exclusion");
        assert!(excluded.is_complete(), "{:?}", excluded.scan.errors);
        assert!(index.lookup(Path::new("target")).is_none());
        assert_eq!(excluded.scan.dirs_read, 1, "ignored target was not reopened");
    }

    #[test]
    fn excluded_subtree_refresh_keeps_ignored_file_and_directory_out_of_scope() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join(".gitignore"), b"target/\n*.log\n");
        write_file(&root.path().join("target/deep/file.rs"), b"code");
        write_file(&root.path().join("debug.log"), b"ignored");
        let config = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            ..ScanConfig::default()
        };
        let (mut index, cold) = scan_into_index(root.path(), &config).expect("cold scan");
        assert!(cold.is_complete());
        assert!(index.lookup(Path::new("target")).is_none());
        assert!(index.lookup(Path::new("debug.log")).is_none());

        for path in ["target", "debug.log"] {
            let refresh = reconcile_subtree(&mut index, Path::new(path), &config, &mut |_| {})
                .expect("subtree refresh");
            assert!(refresh.is_complete(), "{path}: {:?}", refresh.scan.errors);
            assert!(index.lookup(Path::new(path)).is_none(), "{path} is outside scope");
        }
        assert_eq!(index.total().dirs, 0);
    }

    #[test]
    fn handled_subtree_refresh_recovers_pruned_ancestry_after_control_edit() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join(".gitignore"), b"target/\n");
        write_file(&root.path().join("target/deep/file.rs"), b"code");
        let config = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            ..ScanConfig::default()
        };
        let (index, cold) = scan_into_index(root.path(), &config).expect("cold scan");
        assert!(cold.is_complete());
        let handle = IndexHandle::new(index);

        let hidden = reconcile_subtree_handle(
            &handle,
            Path::new("target/deep/file.rs"),
            &config,
            &mut |_| {},
        )
        .expect("refresh pruned descendant");
        assert!(hidden.is_complete());
        assert!(
            !handle
                .read_with(|index| index.lookup(Path::new("target")).is_some())
                .expect("read after hidden refresh")
        );

        write_file(&root.path().join(".gitignore"), b"");
        let exposed = reconcile_subtree_handle(&handle, Path::new("target"), &config, &mut |_| {})
            .expect("refresh changed control");
        assert!(exposed.is_complete());
        assert!(
            handle
                .read_with(|index| index.lookup(Path::new("target/deep/file.rs")).is_some())
                .expect("read after control recovery")
        );

        write_file(&root.path().join(".gitignore"), b"target/\n");
        let hidden_again =
            reconcile_subtree_handle(&handle, Path::new("target"), &config, &mut |_| {})
                .expect("refresh restored control");
        assert!(hidden_again.is_complete());
        assert!(
            !handle
                .read_with(|index| index.lookup(Path::new("target")).is_some())
                .expect("read after restored control")
        );
    }

    #[cfg(unix)]
    #[test]
    fn targeted_refresh_keeps_unknown_population_below_unreadable_ancestor_control() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }
        let root = tempfile::tempdir().expect("root");
        let control = root.path().join(".gitignore");
        write_file(&control, b"*.log\n");
        write_file(&root.path().join("a/keep.rs"), b"unknown membership");
        let config =
            ScanConfig { population: crate::query::IgnoredEntries::Only, ..ScanConfig::default() };
        fs::set_permissions(&control, fs::Permissions::from_mode(0o000)).expect("unreadable");
        let (mut index, cold) = scan_into_index(root.path(), &config).expect("cold scan");
        assert!(!cold.is_complete());
        assert!(index.lookup(Path::new("a/keep.rs")).is_some());
        assert_eq!(index.ignored_classification(Path::new("a/keep.rs")), None);

        let refreshed = reconcile_subtree(&mut index, Path::new("a/keep.rs"), &config, &mut |_| {});
        fs::set_permissions(&control, fs::Permissions::from_mode(0o644)).expect("restore control");
        let refreshed = refreshed.expect("targeted refresh");
        assert!(!refreshed.is_complete(), "unreadable governing control was not visited");
        assert!(index.lookup(Path::new("a/keep.rs")).is_some(), "unknown must stay retained");
        assert_eq!(index.ignored_classification(Path::new("a/keep.rs")), None);
    }

    #[test]
    fn exclusion_honors_nested_negation_and_refused_rule_changes() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join("nested/.gitignore"), b"*.log\n!keep.log\n");
        write_file(&root.path().join("nested/keep.log"), b"negated");
        write_file(&root.path().join("nested/drop.log"), b"ignored");
        let config = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            control_limits: crate::control::ControlLimits {
                line_limit: Some(20),
                ..crate::control::ControlLimits::default()
            },
            ..ScanConfig::default()
        };
        let (mut index, cold) = scan_into_index(root.path(), &config).expect("cold");
        assert!(cold.is_complete(), "{:?}", cold.errors);
        assert!(index.lookup(Path::new("nested/keep.log")).is_some());
        assert!(index.lookup(Path::new("nested/drop.log")).is_none());

        write_file(&root.path().join("nested/.gitignore"), b"this-line-is-over-the-limit\n");
        let changed =
            reconcile(&mut index, &config, &mut |_| {}).expect("reconcile refused source");
        assert!(changed.is_complete(), "{:?}", changed.scan.errors);
        assert!(index.lookup(Path::new("nested/drop.log")).is_some(), "unknown cannot be pruned");
        assert_eq!(index.ignored_classification(Path::new("nested/drop.log")), None);
    }

    #[test]
    fn only_population_skips_nonignored_content_candidates_and_refusals_are_unknown() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join(".gitignore"), b"*.log\n");
        write_file(&root.path().join("keep.rs"), b"code");
        write_file(&root.path().join("debug.log"), b"ignored");
        write_file(&root.path().join("nested/keep.rs"), b"kept");
        write_file(&root.path().join("nested/debug.log"), b"ignored below nonignored dir");
        let only =
            ScanConfig { population: crate::query::IgnoredEntries::Only, ..ScanConfig::default() };
        let (index, report) = scan_into_index(root.path(), &only).expect("scan");
        assert!(report.is_complete());
        assert!(index.lookup(Path::new("keep.rs")).is_none());
        assert!(index.lookup(Path::new("nested")).is_some());
        assert!(index.lookup(Path::new("nested/keep.rs")).is_none());
        assert!(index.lookup(Path::new("nested/debug.log")).is_some());
        let candidates = index.analysis_candidates(crate::content::AnalysisSet::NONE.with_lines());
        assert_eq!(candidates.len(), 2);
        assert!(
            candidates.iter().any(|candidate| candidate.relative_path == Path::new("debug.log"))
        );
        assert!(
            candidates
                .iter()
                .any(|candidate| candidate.relative_path == Path::new("nested/debug.log"))
        );

        let refused = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            control_limits: crate::control::ControlLimits {
                line_limit: Some(1),
                ..crate::control::ControlLimits::default()
            },
            ..ScanConfig::default()
        };
        let (index, report) = scan_into_index(root.path(), &refused).expect("refused scan");
        assert!(report.is_complete());
        assert!(index.lookup(Path::new("debug.log")).is_some(), "unknown is not pruned");
        assert_eq!(index.ignored_classification(Path::new("debug.log")), None);
        assert!(
            index.analysis_candidates(crate::content::AnalysisSet::NONE.with_lines()).is_empty()
        );
    }

    #[test]
    fn only_population_content_is_complete_with_retained_control_file() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join(".gitignore"), b"vendor/\n");
        write_file(&root.path().join("main.rs"), b"fn main() {}\n");
        write_file(&root.path().join("vendor/lib.rs"), b"fn lib() {}\n");
        let config =
            ScanConfig { population: crate::query::IgnoredEntries::Only, ..ScanConfig::default() };
        let (mut index, scan) = scan_into_index(root.path(), &config).expect("scan");
        assert!(scan.is_complete());
        let profile = crate::content::AnalysisSet::NONE.with_lines().with_code();
        let analyzed = crate::content::analyze_index(
            &mut index,
            crate::content::AnalysisRequest {
                profile,
                ..crate::content::AnalysisRequest::default()
            },
        );
        assert!(analyzed.is_complete(), "{analyzed:?}");
        assert_eq!(analyzed.candidates, 1);
        assert!(!index.content_has_pending(profile));
    }

    #[test]
    fn only_population_reconciles_rule_changes_without_losing_traversal() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join("nested/.gitignore"), b"*.log\n");
        write_file(&root.path().join("nested/first.log"), b"first");
        write_file(&root.path().join("nested/second.txt"), b"second");
        let config =
            ScanConfig { population: crate::query::IgnoredEntries::Only, ..ScanConfig::default() };
        let (mut index, cold) = scan_into_index(root.path(), &config).expect("cold");
        assert!(cold.is_complete());
        assert!(index.lookup(Path::new("nested")).is_some());
        assert!(index.lookup(Path::new("nested/first.log")).is_some());
        assert!(index.lookup(Path::new("nested/second.txt")).is_none());

        write_file(&root.path().join("nested/.gitignore"), b"*.txt\n");
        let changed = reconcile(&mut index, &config, &mut |_| {}).expect("rule change");
        assert!(changed.is_complete(), "{:?}", changed.scan.errors);
        assert!(index.lookup(Path::new("nested/first.log")).is_none());
        assert!(index.lookup(Path::new("nested/second.txt")).is_some());
    }

    #[cfg(unix)]
    #[test]
    fn excluded_special_objects_never_enter_cold_or_reconciled_facts() {
        use std::os::unix::net::UnixListener;

        let dir = tempfile::tempdir().expect("tempdir");
        let socket_path = dir.path().join("service.sock");
        let _listener = UnixListener::bind(&socket_path).expect("bind socket");
        write_file(&dir.path().join("replacement"), b"ordinary");
        crate::test_support::settle_allocations(dir.path());
        let (kept, kept_report) =
            scan_into_index(dir.path(), &ScanConfig::default()).expect("default scan");
        assert!(kept_report.is_complete());
        assert_eq!(kept.kind(Path::new("service.sock")), Some(EntryKind::Other));

        let serial_config =
            ScanConfig { exclude_special: true, threads: Some(1), ..ScanConfig::default() };
        let parallel_config =
            ScanConfig { exclude_special: true, threads: Some(4), ..ScanConfig::default() };
        let (mut serial, serial_report) =
            scan_into_index(dir.path(), &serial_config).expect("serial scan");
        let (mut parallel, parallel_report) =
            scan_into_index(dir.path(), &parallel_config).expect("parallel scan");

        for (index, report) in [(&serial, &serial_report), (&parallel, &parallel_report)] {
            assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
            assert!(index.lookup(Path::new("service.sock")).is_none());
            assert!(index.lookup(Path::new("replacement")).is_some());
        }

        fs::remove_file(dir.path().join("replacement")).expect("remove file");
        let _replacement =
            UnixListener::bind(dir.path().join("replacement")).expect("bind replacement socket");
        let serial_reconciled =
            reconcile(&mut serial, &serial_config, &mut |_| {}).expect("serial reconcile");
        let parallel_reconciled =
            reconcile(&mut parallel, &parallel_config, &mut |_| {}).expect("parallel reconcile");

        assert!(serial_reconciled.is_complete());
        assert!(parallel_reconciled.is_complete());
        assert!(serial.lookup(Path::new("replacement")).is_none());
        assert!(parallel.lookup(Path::new("replacement")).is_none());
        assert_eq!(index_fingerprint(&serial), index_fingerprint(&parallel));
    }

    #[test]
    fn control_sources_respect_a_single_operation_batch_bound() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("debug.log"), b"ignored");

        for threads in [1, 4] {
            let config = ScanConfig {
                read_controls: true,
                threads: Some(threads),
                batch_size: 1,
                ..ScanConfig::default()
            };
            let mut largest = 0;
            let report = scan(dir.path(), &config, &mut |observation| {
                largest = largest.max(observation.len());
            })
            .expect("scan");

            assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
            assert_eq!(largest, 1);
        }
    }

    #[test]
    fn cold_scan_matches_the_metabrowser_nested_control_fixture() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"node_modules/\n*.pyc\n");
        write_file(&dir.path().join("src/app.py"), b"x");
        write_file(&dir.path().join("src/thing.pyc"), b"x");
        write_file(&dir.path().join("src/generated/.gitignore"), b"*.gen\n");
        write_file(&dir.path().join("src/generated/out.gen"), b"x");
        write_file(&dir.path().join("node_modules/.gitignore"), b"!keep-me.py\n");
        write_file(&dir.path().join("node_modules/keep-me.py"), b"x");

        let (index, report) = scan_into_index(
            dir.path(),
            &ScanConfig { read_controls: true, threads: Some(4), ..ScanConfig::default() },
        )
        .expect("scan fixture");

        assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
        assert_eq!(
            index.is_ignored(Path::new("src/app.py")).expect("control state observed"),
            Some(false)
        );
        assert_eq!(
            index.is_ignored(Path::new("src/thing.pyc")).expect("control state observed"),
            Some(true)
        );
        assert_eq!(
            index.is_ignored(Path::new("src/generated")).expect("control state observed"),
            Some(false)
        );
        assert_eq!(
            index.is_ignored(Path::new("src/generated/out.gen")).expect("control state observed"),
            Some(true)
        );
        assert_eq!(
            index.is_ignored(Path::new("node_modules")).expect("control state observed"),
            Some(true)
        );
        assert_eq!(
            index.is_ignored(Path::new("node_modules/keep-me.py")).expect("control state observed"),
            Some(true)
        );
    }

    #[test]
    fn reconciliation_observes_same_metadata_control_edits_and_last_deletion() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("debug.log"), b"ignored");
        let config = ScanConfig { read_controls: true, threads: Some(1), ..ScanConfig::default() };
        let (mut index, report) = scan_into_index(dir.path(), &config).expect("scan");
        assert!(report.is_complete());
        assert_eq!(
            index.is_ignored(Path::new("debug.log")).expect("control state observed"),
            Some(true)
        );

        // Same-length content proves control identity is not inferred from stat-tier
        // metadata, which can remain unchanged on coarse filesystems.
        write_file(&dir.path().join(".gitignore"), b"*.tmp\n");
        let edited = reconcile(&mut index, &config, &mut |_| {}).expect("edit reconcile");
        assert!(edited.is_complete());
        assert_eq!(edited.apply.controls, 1);
        assert_eq!(edited.apply.reclassified, 1);
        assert!(
            index
                .controls()
                .expect("control state observed")
                .source_is(Path::new(".gitignore"), b"*.tmp\n")
        );
        assert_eq!(
            index.is_ignored(Path::new("debug.log")).expect("control state observed"),
            Some(false)
        );

        fs::remove_file(dir.path().join(".gitignore")).expect("remove control");
        let removed = reconcile(&mut index, &config, &mut |_| {}).expect("remove reconcile");
        assert!(removed.is_complete());
        assert_eq!(removed.apply.controls, 1);
        assert!(index.controls().expect("control state observed").is_empty());
        let partitions = index.partition_total().expect("control state observed");
        assert_eq!(partitions.all, partitions.unignored);
    }

    #[cfg(unix)]
    #[test]
    fn directory_entry_metadata_does_not_follow_symlinks() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().expect("root");
        let outside = tempfile::tempdir().expect("outside");
        write_file(&outside.path().join("must-not-be-scanned.txt"), b"outside");
        symlink(outside.path(), root.path().join("link")).expect("symlink");

        let (index, report) = scan_into_index(root.path(), &ScanConfig::default()).expect("scan");

        assert!(report.is_complete(), "unexpected errors: {:?}", report.errors);
        assert_eq!(index.kind(Path::new("link")), Some(EntryKind::Symlink));
        assert!(index.lookup(Path::new("link/must-not-be-scanned.txt")).is_none());
        assert_eq!(index.total().files, 0);
    }

    #[test]
    fn cold_scan_establishes_a_baseline_without_change_history() {
        let dir = sample_tree();
        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");

        assert_eq!(index.clock(), crate::Clock::ZERO);
        assert!(index.since(crate::Clock::ZERO).commits.is_empty());
    }

    #[test]
    fn max_depth_stops_descent() {
        let dir = sample_tree();
        let config = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (index, _) = scan_into_index(dir.path(), &config).expect("scan");

        assert!(index.lookup(Path::new("src")).is_some());
        assert!(index.lookup(Path::new("src/main.rs")).is_none());
    }

    #[test]
    fn zero_max_depth_keeps_only_the_index_root() {
        let dir = sample_tree();
        let config = ScanConfig { max_depth: Some(0), ..ScanConfig::default() };
        let (index, report) = scan_into_index(dir.path(), &config).expect("scan");

        assert!(index.is_empty());
        assert_eq!(report.entries, 0);
        assert_eq!(report.dirs_read, 0);
    }

    #[test]
    fn direct_scan_records_the_canonical_root() {
        let dir = sample_tree();
        let aliased = dir.path().join(".");
        let (index, _) = scan_into_index(&aliased, &ScanConfig::default()).expect("scan");

        assert_eq!(index.root_path(), dir.path().canonicalize().expect("canonical root"));
    }

    #[test]
    fn unsupported_symlink_following_is_rejected_on_cold_and_warm_paths() {
        let dir = sample_tree();
        let unsupported = ScanConfig { follow_symlinks: true, ..ScanConfig::default() };
        assert!(matches!(
            scan_into_index(dir.path(), &unsupported),
            Err(Error::UnsupportedScanConfig(_))
        ));

        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        assert!(matches!(
            revalidate(&index, &unsupported, &mut |_| {}),
            Err(Error::UnsupportedScanConfig(_))
        ));
    }

    #[test]
    fn revalidation_uses_the_same_depth_boundary_as_cold_scan() {
        let dir = sample_tree();
        let config = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");
        write_file(&dir.path().join("src/added-after-scan.txt"), b"new");

        let mut observations = Vec::new();
        revalidate(&index, &config, &mut |observation| observations.push(observation))
            .expect("revalidate");
        for observation in &observations {
            index.apply_ok(observation);
        }

        assert!(index.lookup(Path::new("src/added-after-scan.txt")).is_none());
    }

    #[test]
    fn zero_depth_revalidation_prunes_cached_root_children() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = ScanConfig { max_depth: Some(0), ..ScanConfig::default() };
        let mut index = Index::new_with_scope(dir.path(), config.scope());
        index.apply_baseline_ok(&Observation::new(vec![Op::Upsert {
            path: PathBuf::from("stale.txt"),
            kind: EntryKind::File,
            attrs: Attrs::default(),
        }]));

        let mut observations = Vec::new();
        let report = revalidate(&index, &config, &mut |observation| {
            observations.push(observation);
        })
        .expect("revalidate");
        for observation in &observations {
            index.apply_ok(observation);
        }

        assert!(index.is_empty());
        assert_eq!(report.dirs_read, 0);
    }

    #[test]
    fn zero_depth_applying_reconciliation_prunes_cached_root_children() {
        let dir = tempfile::tempdir().expect("tempdir");
        let config = ScanConfig { max_depth: Some(0), ..ScanConfig::default() };
        let mut index = Index::new_with_scope(dir.path(), config.scope());
        index.apply_baseline_ok(&Observation::new(vec![Op::Upsert {
            path: PathBuf::from("stale.txt"),
            kind: EntryKind::File,
            attrs: Attrs::default(),
        }]));

        let report = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");

        assert!(index.is_empty());
        assert_eq!(report.scan.dirs_read, 0);
    }

    #[test]
    fn filesystem_boundary_is_part_of_the_shared_descent_policy() {
        let config = ScanConfig { one_filesystem: true, ..ScanConfig::default() };
        let attrs = Attrs { dev: 22, ..Attrs::default() };
        assert!(!should_descend(EntryKind::Dir, attrs, 0, 11, &config));
        assert!(should_descend(EntryKind::Dir, Attrs { dev: 11, ..attrs }, 0, 11, &config,));
    }

    /// A cold scan's index records its own pass start, the stamp a snapshot of it writes:
    /// never earlier than an instant taken before the scan, so it is not a stale or zero
    /// stamp, and never later than one taken after it. The builder constructs the index,
    /// and so takes the stamp, before the walk begins.
    #[test]
    fn a_cold_scan_stamps_its_own_pass_start() {
        let nanos = || {
            i64::try_from(
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .expect("after the epoch")
                    .as_nanos(),
            )
            .expect("nanoseconds")
        };
        let dir = sample_tree();
        let before = nanos();
        let (index, report) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let after = nanos();
        assert!(report.is_complete() && report.entries > 0, "{report:?}");
        let stamp = index.writing_pass_started_at_ns();
        assert!(before <= stamp && stamp <= after, "{before} <= {stamp} <= {after}");
    }

    #[test]
    fn scanning_a_file_is_an_error_not_a_panic() {
        let dir = sample_tree();
        let err = scan_into_index(&dir.path().join("a.txt"), &ScanConfig::default());
        assert!(err.is_err());
    }

    #[test]
    fn deltas_arrive_in_batches_of_the_configured_size() {
        let dir = tempfile::tempdir().expect("tempdir");
        for i in 0..25 {
            write_file(&dir.path().join(format!("f{i}.txt")), b"x");
        }
        let config = ScanConfig { batch_size: 10, ..ScanConfig::default() };
        let mut sizes = Vec::new();
        scan(dir.path(), &config, &mut |d| sizes.push(d.len())).expect("scan");

        assert!(sizes.len() >= 3, "expected several batches, got {sizes:?}");
        assert!(sizes.iter().all(|&n| n <= 10));
        assert_eq!(sizes.iter().sum::<usize>(), 25);
    }

    #[test]
    fn invalid_batch_sizes_are_rejected_before_allocation() {
        let zero = ScanConfig { batch_size: 0, ..ScanConfig::default() };
        let unbounded = ScanConfig { batch_size: usize::MAX, ..ScanConfig::default() };

        assert!(matches!(zero.validate(), Err(Error::UnsupportedScanConfig(_))));
        assert!(matches!(unbounded.validate(), Err(Error::UnsupportedScanConfig(_))));
    }

    #[test]
    fn reconciliation_scope_budget_publishes_before_returning_retry() {
        let directory = tempfile::tempdir().expect("root");
        let config = ScanConfig::default();
        let (index, _) = scan_into_index(directory.path(), &config).expect("scan root-only tree");
        let handle = IndexHandle::new(index);
        let mut started = false;
        let mut published_partial = false;
        let report = reconcile_handle(&handle, &config, &mut |commit| {
            if !started {
                started = true;
                // No entries are added: distinct absent children must not grow history
                // for the paused root pass without bound.
                for child in ["missing-a", "missing-b", "missing-c"] {
                    let nested = reconcile_subtree_handle(&handle, Path::new(child), &config, &mut |_| {}).expect("newer absent scope");
                    assert!(nested.is_complete());
                }
            }
            if commit.state.iter().any(|state| matches!(state,
                crate::StateTransition::IndexState { current, .. }
                    if current.coverage == crate::Coverage::Partial(crate::CoverageReason::Inaccessible))) {
                assert_eq!(handle.read_with(Index::state).expect("coherent state").coverage,
                    crate::Coverage::Partial(crate::CoverageReason::Inaccessible));
                published_partial = true;
            }
        }).expect("interrupted pass returns retryable report");
        assert!(!report.is_complete());
        assert!(report.retry_required);
        assert!(published_partial, "the transition precedes the caller's retry result");
        let recovered = reconcile_handle(&handle, &config, &mut |_| {}).expect("retry");
        assert!(recovered.is_complete());
        assert_eq!(
            handle.read_with(Index::state).expect("recovered state").coverage,
            crate::Coverage::Complete
        );
    }

    #[test]
    fn stale_arbitration_keeps_a_reconciliation_incomplete() {
        let report = ReconcileReport {
            scan: ScanReport::default(),
            apply: ApplyStats { stale: 1, ..ApplyStats::default() },
            observations: 1,
            ..ReconcileReport::default()
        };

        assert!(!report.is_complete());
    }

    #[test]
    fn portable_system_time_conversion_preserves_pre_epoch_values() {
        let before_epoch = std::time::UNIX_EPOCH
            // Windows timestamps have 100 ns granularity, so use a duration that every
            // supported platform can represent without rounding back to the epoch.
            .checked_sub(std::time::Duration::from_secs(1))
            .expect("represent pre-epoch fixture");

        assert_eq!(system_time_ns(before_epoch), -1_000_000_000);
        assert_eq!(system_time_ns(std::time::UNIX_EPOCH), 0);
    }

    #[cfg(not(unix))]
    #[test]
    fn one_filesystem_fails_when_device_identity_is_unavailable() {
        let config = ScanConfig { one_filesystem: true, ..ScanConfig::default() };

        assert!(matches!(config.validate(), Err(Error::UnsupportedScanConfig(_))));
    }

    #[test]
    fn revalidate_is_a_no_op_against_an_unchanged_tree() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let before = index.total();

        let mut deltas = Vec::new();
        revalidate(&index, &ScanConfig::default(), &mut |d| deltas.push(d)).expect("revalidate");
        let mut unchanged = 0;
        for delta in &deltas {
            unchanged += index.apply_ok(delta).unchanged;
        }

        assert_eq!(unchanged, 5, "3 files + 2 dirs all already known");
        assert_eq!(index.total(), before);
    }

    #[cfg(windows)]
    #[test]
    fn windows_reconcile_detects_same_size_rewrite_with_preserved_mtime() {
        let root = tempfile::tempdir().expect("tempdir");
        let path = root.path().join("same.txt");
        write_file(&path, b"first");
        let modified = fs::metadata(&path).expect("metadata").modified().expect("mtime");
        let (mut index, _) =
            scan_into_index(root.path(), &ScanConfig::default()).expect("initial scan");
        let before = *index.attrs(Path::new("same.txt")).expect("initial attrs");

        // NTFS stamps change time from the system clock, which advances in ticks of up to
        // 15.625 ms, so a rewrite stamped in the same tick as the first write is
        // indistinguishable from it. Wait for the clock to leave that tick rather than for
        // a fixed interval; the precise clock `SystemTime` reads runs at most one tick ahead.
        let stamped = std::time::UNIX_EPOCH
            + std::time::Duration::from_nanos(
                u64::try_from(before.ctime_ns).expect("change time after the epoch"),
            );
        while std::time::SystemTime::now() <= stamped + std::time::Duration::from_millis(20) {
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        write_file(&path, b"other");
        File::options()
            .write(true)
            .open(&path)
            .expect("open rewritten file")
            .set_times(std::fs::FileTimes::new().set_modified(modified))
            .expect("restore mtime");
        reconcile(&mut index, &ScanConfig::default(), &mut |_| {}).expect("reconcile");

        let after = *index.attrs(Path::new("same.txt")).expect("rewritten attrs");
        assert_eq!((after.size, after.mtime_ns), (before.size, before.mtime_ns));
        assert_ne!(after.ctime_ns, before.ctime_ns, "change time detects the rewrite");
        assert_ne!(after.fingerprint(), before.fingerprint());
    }

    #[cfg(windows)]
    #[test]
    fn windows_reconcile_detects_path_identity_replacement() {
        let root = tempfile::tempdir().expect("tempdir");
        let path = root.path().join("replace.txt");
        let displaced = root.path().join("displaced.txt");
        write_file(&path, b"first");
        let modified = fs::metadata(&path).expect("metadata").modified().expect("mtime");
        let (mut index, _) =
            scan_into_index(root.path(), &ScanConfig::default()).expect("initial scan");
        let before = *index.attrs(Path::new("replace.txt")).expect("initial attrs");

        fs::rename(&path, &displaced).expect("retain old file identity");
        write_file(&path, b"other");
        File::options()
            .write(true)
            .open(&path)
            .expect("open replacement")
            .set_times(std::fs::FileTimes::new().set_modified(modified))
            .expect("restore mtime");
        reconcile(&mut index, &ScanConfig::default(), &mut |_| {}).expect("reconcile");

        let after = *index.attrs(Path::new("replace.txt")).expect("replacement attrs");
        assert_eq!((after.size, after.mtime_ns), (before.size, before.mtime_ns));
        assert_ne!(
            (after.dev, after.inode),
            (before.dev, before.inode),
            "volume serial and file index identify the replacement"
        );
        assert_ne!(after.fingerprint(), before.fingerprint());
    }

    #[test]
    fn direct_reconciliation_counts_unchanged_entries_and_publishes_state_commits() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let before_total = index.total();
        let before_clock = index.clock();
        let mut commits = Vec::new();

        let report = reconcile(&mut index, &ScanConfig::default(), &mut |commit| {
            commits.push(commit.clone());
        })
        .expect("reconcile");

        assert!(report.is_complete());
        assert_eq!(report.apply.unchanged, 5, "3 files + 2 dirs all already known");
        assert_eq!(commits.len(), 2);
        assert!(commits.iter().all(|commit| commit.changes.is_empty()));
        assert_eq!(
            index.clock(),
            crate::Clock(before_clock.0 + 2),
            "start and finish are state commits"
        );
        let commits = index.since(before_clock).commits;
        assert_eq!(commits.len(), 2);
        assert!(commits.iter().all(|commit| commit.changes.is_empty()));
        assert_eq!(index.total(), before_total);
    }

    #[test]
    fn parallel_and_serial_reconciliation_produce_the_same_index() {
        let dir = sample_tree();
        let portable_config =
            ScanConfig { threads: Some(1), batch_size: 2, ..ScanConfig::default() };
        let (mut portable, _) =
            scan_into_index(dir.path(), &portable_config).expect("portable baseline");
        let mut bulk = portable.clone();

        fs::remove_file(dir.path().join("a.txt")).expect("remove file");
        write_file(&dir.path().join("src/main.rs"), b"fn main() { much longer }");
        write_file(&dir.path().join("src/added.md"), b"new file");
        crate::test_support::settle_allocations(dir.path());

        let portable_report = reconcile(&mut portable, &portable_config, &mut |_| {})
            .expect("portable reconciliation");
        let bulk_config = ScanConfig { threads: Some(2), ..portable_config };
        let bulk_report =
            reconcile(&mut bulk, &bulk_config, &mut |_| {}).expect("bulk reconciliation");

        assert!(portable_report.is_complete());
        assert!(bulk_report.is_complete());
        assert_eq!(bulk_report.scan.attribution, WalkAttribution::default());
        assert_eq!(bulk_report.scan.entries, portable_report.scan.entries);
        assert_eq!(bulk_report.scan.dirs_read, portable_report.scan.dirs_read);
        assert_eq!(bulk_report.apply, portable_report.apply);
        assert_eq!(index_fingerprint(&bulk), index_fingerprint(&portable));
        assert_eq!(bulk.total(), portable.total());
    }

    #[test]
    fn parallel_reconciliation_workers_publish_directory_counters() {
        let _serial = crate::counters::test_serial();
        let dir = sample_tree();
        let baseline = ScanConfig { threads: Some(1), ..ScanConfig::default() };
        let (mut index, scan) = scan_into_index(dir.path(), &baseline).expect("baseline scan");
        assert!(scan.is_complete());

        crate::counters::enable(true);
        crate::counters::reset();
        let config = ScanConfig { threads: Some(4), ..baseline };
        let report = reconcile(&mut index, &config, &mut |_| {}).expect("reconciliation");
        crate::counters::flush_thread();
        let counts = crate::counters::snapshot();
        crate::counters::reset();
        crate::counters::enable(false);

        assert!(report.is_complete());
        assert!(
            counts.dir_opens >= report.scan.dirs_read,
            "parallel worker directory opens were folded: {counts:?}, report={report:?}"
        );
    }

    #[test]
    fn parallel_reconciliation_matches_serial_across_structural_transitions() {
        for max_depth in [None, Some(1), Some(2)] {
            for order in [ScanOrder::BreadthFirst, ScanOrder::DepthFirst] {
                let dir = reconciliation_transition_tree();
                let reference_config = ScanConfig {
                    order,
                    max_depth,
                    threads: Some(1),
                    batch_size: 2,
                    ..ScanConfig::default()
                };
                let (baseline, baseline_report) =
                    scan_into_index(dir.path(), &reference_config).expect("baseline scan");
                assert!(baseline_report.is_complete());
                mutate_reconciliation_transition_tree(dir.path());

                let mut serial = baseline.clone();
                let mut serial_commits = Vec::new();
                let serial_report = reconcile(&mut serial, &reference_config, &mut |commit| {
                    serial_commits.push(commit.clone());
                })
                .expect("serial reconciliation");
                let (fresh, fresh_report) =
                    scan_into_index(dir.path(), &reference_config).expect("fresh oracle");
                assert!(serial_report.is_complete(), "serial {order:?}/{max_depth:?}");
                assert!(fresh_report.is_complete(), "fresh {order:?}/{max_depth:?}");
                assert_eq!(
                    index_fingerprint(&serial),
                    index_fingerprint(&fresh),
                    "serial did not converge to a fresh scan for {order:?}/{max_depth:?}"
                );

                for workers in [2, 4] {
                    let mut parallel = baseline.clone();
                    let config = ScanConfig { threads: Some(workers), ..reference_config.clone() };
                    let mut parallel_commits = Vec::new();
                    let report = reconcile(&mut parallel, &config, &mut |commit| {
                        parallel_commits.push(commit.clone());
                    })
                    .expect("parallel reconciliation");
                    let context = format!("{order:?}/{max_depth:?}/{workers} workers");

                    assert!(report.is_complete(), "{context}: unexpected partial report");
                    assert_eq!(report.scan.entries, serial_report.scan.entries, "{context}");
                    assert_eq!(report.scan.dirs_read, serial_report.scan.dirs_read, "{context}");
                    assert_eq!(report.apply, serial_report.apply, "{context}");
                    assert_eq!(
                        effective_ops(&parallel_commits),
                        effective_ops(&serial_commits),
                        "{context}: effective delta differs"
                    );
                    assert_eq!(
                        index_fingerprint(&parallel),
                        index_fingerprint(&serial),
                        "{context}: final index differs"
                    );
                    let (parallel_total, serial_total) = (parallel.total(), serial.total());
                    assert_eq!(
                        (
                            parallel_total.files,
                            parallel_total.dirs,
                            parallel_total.bytes,
                            parallel_total.allocated,
                            parallel_total.newest_mtime_ns,
                        ),
                        (
                            serial_total.files,
                            serial_total.dirs,
                            serial_total.bytes,
                            serial_total.allocated,
                            serial_total.newest_mtime_ns,
                        ),
                        "{context}: roll-up differs"
                    );
                    assert_eq!(
                        parallel_total.by_ext, serial_total.by_ext,
                        "{context}: extension roll-up differs"
                    );
                }
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn revalidation_metadata_errors_do_not_delete_enumerated_entries() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }

        let dir = sample_tree();
        let config = ScanConfig::default();
        let (mut index, baseline_report) =
            scan_into_index(dir.path(), &config).expect("baseline scan");
        assert!(baseline_report.is_complete());
        let before = index_fingerprint(&index);
        let original_permissions = fs::metadata(dir.path()).expect("root metadata").permissions();

        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o400))
            .expect("remove search permission");
        let mut observations = Vec::new();
        let outcome = revalidate(&index, &config, &mut |observation| {
            observations.push(observation);
        });
        fs::set_permissions(dir.path(), original_permissions).expect("restore permissions");

        let report = outcome.expect("operational metadata errors are a partial report");
        assert!(!report.errors.is_empty(), "the fixture did not induce metadata errors");
        for observation in &observations {
            index.apply_ok(observation);
        }
        assert_eq!(index_fingerprint(&index), before);
        assert!(index.attrs(Path::new("a.txt")).is_some(), "existing entry was removed");
    }

    #[cfg(unix)]
    #[test]
    fn reconciliation_metadata_errors_drop_unverified_entries_like_a_cold_scan() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }

        // macOS's parallel path may satisfy the whole directory through
        // getattrlistbulk even without search permission. One worker pins the portable
        // fallback there; Linux also exercises the parallel portable worker.
        let worker_counts = if cfg!(target_os = "macos") { vec![1] } else { vec![1, 2] };
        for workers in worker_counts {
            let dir = sample_tree();
            let config =
                ScanConfig { threads: Some(workers), batch_size: 2, ..ScanConfig::default() };
            let (mut index, baseline_report) =
                scan_into_index(dir.path(), &config).expect("baseline scan");
            assert!(baseline_report.is_complete());
            let before = index_fingerprint(&index);
            let original_permissions =
                fs::metadata(dir.path()).expect("root metadata").permissions();

            // Reading names requires read permission; looking up their metadata also
            // requires search permission. This makes enumeration succeed and each
            // metadata lookup fail, the boundary where an encountered name used to be
            // misclassified as a deletion.
            fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o400))
                .expect("remove search permission");
            let outcome = reconcile(&mut index, &config, &mut |_| {});
            let cold = scan_into_index(dir.path(), &config);
            fs::set_permissions(dir.path(), original_permissions).expect("restore permissions");

            let report = outcome.expect("operational metadata errors are a partial report");
            let (cold, cold_report) = cold.expect("cold partial scan");
            assert!(!report.scan.errors.is_empty(), "the fixture did not induce metadata errors");
            assert!(!report.is_complete());
            assert!(!cold_report.is_complete());
            assert_eq!(index_fingerprint(&index), index_fingerprint(&cold));
            assert!(
                index_fingerprint(&index).is_empty(),
                "neither warm nor cold may retain attributes it could not verify"
            );
            assert_eq!(index.directory_complete(Path::new("")), Some(false));
            assert_eq!(cold.directory_complete(Path::new("")), Some(false));
            assert!(!before.is_empty(), "the fixture began with retained facts");
        }
    }

    #[cfg(unix)]
    #[test]
    fn failed_listing_withdraws_retained_completeness_and_recovers() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }
        for workers in [1, 2] {
            let dir = tempfile::tempdir().expect("root");
            write_file(&dir.path().join("ancestor/blocked/unknown.txt"), b"unknown");
            write_file(&dir.path().join("healthy/known.txt"), b"known");
            let config = ScanConfig { threads: Some(workers), ..ScanConfig::default() };
            let (mut warm, baseline) = scan_into_index(dir.path(), &config).expect("baseline");
            assert!(baseline.is_complete());
            let blocked = dir.path().join("ancestor/blocked");
            fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("deny listing");
            let probe = fs::read_dir(&blocked);
            let mut commits = Vec::new();
            let refreshed =
                reconcile(&mut warm, &config, &mut |commit| commits.push(commit.clone()));
            let cold = scan_into_index(dir.path(), &config);
            fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700)).expect("restore");
            assert_eq!(
                probe.expect_err("real denied listing").kind(),
                std::io::ErrorKind::PermissionDenied
            );
            assert!(!refreshed.expect("partial refresh").is_complete());
            let (cold, report) = cold.expect("partial cold scan");
            assert!(!report.is_complete());
            for index in [&warm, &cold] {
                for path in ["", "ancestor", "healthy"] {
                    assert_eq!(
                        index.directory_complete(Path::new(path)),
                        Some(true),
                        "workers={workers}: {path}"
                    );
                }
                assert_eq!(index.directory_complete(Path::new("ancestor/blocked")), Some(false));
                assert_eq!(index.freshness_at(Path::new("ancestor")), crate::Freshness::Partial);
            }
            assert!(commits.iter().flat_map(|commit| &commit.state).any(|state| matches!(state,
                crate::StateTransition::IndexState { current, .. } if current.coverage != crate::Coverage::Complete
            )), "failure is published");
            assert!(reconcile(&mut warm, &config, &mut |_| {}).expect("recovery").is_complete());
            assert_eq!(warm.directory_complete(Path::new("ancestor/blocked")), Some(true));
            assert_eq!(warm.state().coverage, crate::Coverage::Complete);
        }
    }

    #[test]
    fn unreadable_directory_warm_answer_matches_cold_verified_tree() {
        for workers in [1, 2] {
            let dir = tempfile::tempdir().expect("tempdir");
            write_file(&dir.path().join("blocked/old.txt"), b"old");
            write_file(&dir.path().join("verified.txt"), b"verified");
            crate::test_support::settle_allocations(dir.path());
            let config = ScanConfig { threads: Some(workers), ..ScanConfig::default() };
            let (mut warm, baseline) = scan_into_index(dir.path(), &config).expect("baseline");
            assert!(baseline.is_complete());

            let blocked = dir.path().join("blocked").canonicalize().expect("blocked path");
            let hook = install_child_metadata_hook(dir.path(), move |path| {
                (path == blocked)
                    .then(|| std::io::Error::from(std::io::ErrorKind::PermissionDenied))
            });
            let warm_report = reconcile(&mut warm, &config, &mut |_| {}).expect("warm partial");
            let (cold, cold_report) = scan_into_index(dir.path(), &config).expect("cold partial");
            drop(hook);

            assert!(!warm_report.is_complete(), "workers={workers}");
            assert!(!cold_report.is_complete(), "workers={workers}");
            assert!(warm.lookup(Path::new("blocked")).is_none(), "workers={workers}");
            assert!(warm.lookup(Path::new("blocked/old.txt")).is_none(), "workers={workers}");
            assert_eq!(index_fingerprint(&warm), index_fingerprint(&cold), "workers={workers}");
            assert!(warm.lookup(Path::new("verified.txt")).is_some(), "workers={workers}");
        }
    }

    #[test]
    fn deferred_change_overflow_retries_without_applying_a_partial_wave() {
        let dir = sample_tree();
        let config = ScanConfig { threads: Some(2), batch_size: 2, ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &config).expect("baseline");
        let before = index_fingerprint(&index);

        fs::remove_file(dir.path().join("a.txt")).expect("remove file");
        write_file(&dir.path().join("added.md"), b"new file");
        write_file(&dir.path().join("src/main.rs"), b"fn main() { much longer }");
        crate::test_support::settle_allocations(dir.path());

        let root = index.root_path().to_path_buf();
        let root_meta = {
            crate::counters::bump(|c| c.stats += 1);
            fs::symlink_metadata(&root)
        }
        .expect("root metadata");
        let mut commits = Vec::new();
        let outcome = reconcile_direct_parallel(
            &mut index,
            &root,
            root_device(&root, &root_meta).expect("root device"),
            &config,
            1,
            &mut |commit| commits.push(commit.clone()),
        )
        .expect("parallel attempt");
        let DirectParallelOutcome::RetrySerial { prefix, remaining } = outcome else {
            panic!("the deliberately tiny deferred budget must trigger the retry");
        };

        assert_eq!(prefix.apply, ApplyStats::default());
        assert_eq!(remaining, VecDeque::from([(PathBuf::new(), 0)]));
        assert!(commits.is_empty());
        assert_eq!(index_fingerprint(&index), before);

        let serial = ScanConfig { threads: Some(1), ..config };
        let report = reconcile(&mut index, &serial, &mut |_| {}).expect("serial retry");
        let (expected, expected_report) = scan_into_index(dir.path(), &serial).expect("oracle");
        assert!(report.is_complete());
        assert!(expected_report.is_complete());
        assert_eq!(index_fingerprint(&index), index_fingerprint(&expected));
        assert_eq!(index.total().files, expected.total().files);
        assert_eq!(index.total().dirs, expected.total().dirs);
        assert_eq!(index.total().bytes, expected.total().bytes);
        assert_eq!(index.total().allocated, expected.total().allocated);
        assert_eq!(index.total().newest_mtime_ns, expected.total().newest_mtime_ns);
        assert_eq!(index.total().by_ext, expected.total().by_ext);
    }

    #[test]
    fn late_overflow_resumes_without_double_counting_completed_waves() {
        let dir = tempfile::tempdir().expect("tempdir");
        // The root wave discovers more than one full wave of directories. A change in
        // the second wave then forces the serial fallback only after the first wave's
        // unchanged entries have already been counted.
        for directory in 0..=RECONCILE_WAVE_DIRECTORIES {
            write_file(&dir.path().join(format!("d{directory:04}/file.txt")), b"unchanged");
        }
        let parallel = ScanConfig { threads: Some(2), ..ScanConfig::default() };
        let (baseline, _) = scan_into_index(dir.path(), &parallel).expect("baseline");
        let mut candidate = baseline.clone();
        let mut serial_oracle = baseline;

        for directory in 0..=RECONCILE_WAVE_DIRECTORIES {
            write_file(
                &dir.path().join(format!("d{directory:04}/file.txt")),
                b"changed after the first wave",
            );
        }
        crate::test_support::settle_allocations(dir.path());

        let candidate_report = reconcile_target_inner(
            &mut ReconcileTarget::Direct(&mut candidate),
            Path::new(""),
            0,
            &parallel,
            0,
            &mut |_| {},
        )
        .expect("late-overflow reconciliation");
        let serial = ScanConfig { threads: Some(1), ..parallel };
        let oracle_report =
            reconcile(&mut serial_oracle, &serial, &mut |_| {}).expect("serial oracle");

        assert_eq!(candidate_report.apply, oracle_report.apply);
        assert_eq!(candidate_report.scan.entries, oracle_report.scan.entries);
        assert_eq!(candidate_report.scan.dirs_read, oracle_report.scan.dirs_read);
        assert_eq!(index_fingerprint(&candidate), index_fingerprint(&serial_oracle));
    }

    /// The four counts a walk reports, in the order [`crate::ProgressSnapshot`] shows them.
    fn walked(report: &ScanReport) -> (u64, u64, u64, u64) {
        (report.dirs_read, report.files_walked, report.bytes_walked, report.allocated_walked)
    }

    fn reported(progress: &crate::Progress) -> (u64, u64, u64, u64) {
        let snapshot = progress.snapshot();
        (snapshot.directories, snapshot.files, snapshot.bytes, snapshot.allocated)
    }

    /// Each walker is a separate loop with its own reporting sites, so each is checked:
    /// the detached cold walk, the streaming walk, the transient summary fold, the
    /// reference revalidation, exclusive reconciliation serial and in parallel waves,
    /// and shared-handle reconciliation. The tree is wide enough that every parallel
    /// walker claims several chunks and the small batch size fills several batches, so a
    /// walker that reported only its final state would still fail on the counts a
    /// mid-walk chunk added twice or not at all.
    #[test]
    fn every_walker_reports_exactly_what_its_report_counts() {
        let dir = tempfile::tempdir().expect("tempdir");
        for directory in 0..12 {
            for file in 0..5 {
                write_file(
                    &dir.path().join(format!("d{directory}/f{file}.txt")),
                    &vec![b'x'; directory * 5 + file + 1],
                );
            }
        }
        for threads in [1, 4] {
            let context = format!("threads={threads}");
            let progress = crate::Progress::new();
            let cold_config = ScanConfig {
                threads: Some(threads),
                batch_size: 4,
                progress: Some(progress.clone()),
                ..ScanConfig::default()
            };
            let (mut index, cold) = scan_into_index(dir.path(), &cold_config).expect("cold scan");
            assert_eq!(cold.dirs_read, 13, "{context}: the root and twelve children");
            assert_eq!(
                progress.snapshot().phase,
                crate::ProgressPhase::Indexing,
                "{context}: the detached walk ends by assembling the index"
            );
            assert_eq!(reported(&progress), walked(&cold), "{context}: detached cold walk");

            let progress = crate::Progress::new();
            let config = ScanConfig { progress: Some(progress.clone()), ..cold_config.clone() };
            let streamed = scan(dir.path(), &config, &mut |_| {}).expect("streaming scan");
            assert_eq!(walked(&streamed), walked(&cold), "{context}");
            assert_eq!(reported(&progress), walked(&streamed), "{context}: streaming walk");

            let progress = crate::Progress::new();
            let config = ScanConfig {
                read_controls: false,
                progress: Some(progress.clone()),
                ..cold_config.clone()
            };
            let folded = scan_summary_fold(dir.path(), &config, &mut |_| {}).expect("fold");
            assert_eq!(walked(&folded), walked(&cold), "{context}");
            assert_eq!(reported(&progress), walked(&folded), "{context}: summary fold");

            let progress = crate::Progress::new();
            let config = ScanConfig { progress: Some(progress.clone()), ..cold_config.clone() };
            let revalidated = revalidate(&index, &config, &mut |_| {}).expect("revalidate");
            assert_eq!(progress.snapshot().phase, crate::ProgressPhase::Revalidating, "{context}");
            assert_eq!(reported(&progress), walked(&revalidated), "{context}: revalidate");

            // Changes, so reconciliation defers and applies operations rather than
            // discarding every entry as unchanged.
            write_file(&dir.path().join(format!("d0/new{threads}.txt")), b"added");
            fs::remove_file(dir.path().join(format!("d1/f{}.txt", threads - 1))).expect("remove");
            write_file(&dir.path().join("d2/f0.txt"), &vec![b'y'; 40 + threads]);
            // An independent walk of the changed tree. The handle and the reconcile's own
            // report both come from the walker's counts, so agreeing with each other
            // would not show that the walker counted anything; agreeing with this does.
            let (_, fresh) = scan_into_index(dir.path(), &ScanConfig::default()).expect("fresh");
            let progress = crate::Progress::new();
            let config = ScanConfig { progress: Some(progress.clone()), ..cold_config.clone() };
            let reconciled = reconcile(&mut index, &config, &mut |_| {}).expect("reconcile");
            assert!(reconciled.apply.mutated(), "{context}: the changes were applied");
            assert_eq!(progress.snapshot().phase, crate::ProgressPhase::Revalidating, "{context}");
            assert_eq!(reported(&progress), walked(&reconciled.scan), "{context}: reconcile");
            assert_eq!(walked(&reconciled.scan), walked(&fresh), "{context}: the whole tree");

            let handle = crate::IndexHandle::new(index);
            let progress = crate::Progress::new();
            let config = ScanConfig { progress: Some(progress.clone()), ..cold_config };
            let shared = reconcile_handle(&handle, &config, &mut |_| {}).expect("shared");
            assert_eq!(reported(&progress), walked(&shared.scan), "{context}: shared handle");
        }
    }

    /// A wave that overflows its deferred-operation budget is thrown away and rewalked
    /// serially. The report counts each directory once, as the logical pass does, and
    /// progress counts the wave's reads both times, as the filesystem did them: work
    /// done, not the answer. This is the one walker relation that is not equality, and
    /// the difference is exactly the rewalked wave.
    #[test]
    fn progress_counts_a_rewalked_wave_twice_where_the_report_counts_it_once() {
        let dir = tempfile::tempdir().expect("tempdir");
        for directory in 0..=RECONCILE_WAVE_DIRECTORIES {
            write_file(&dir.path().join(format!("d{directory:04}/file.txt")), b"unchanged");
        }
        // A file in the wave that completes, so the serial rewalk has counts of that wave
        // to carry forward as already added rather than add again.
        write_file(&dir.path().join("root.txt"), b"counted by the wave that completes");
        let parallel = ScanConfig { threads: Some(2), ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &parallel).expect("baseline");
        // Larger than any filesystem stores inline in the inode, so each copy occupies
        // blocks of its own wherever the test runs.
        let changed = &vec![b'c'; 8_193];
        for directory in 0..=RECONCILE_WAVE_DIRECTORIES {
            write_file(&dir.path().join(format!("d{directory:04}/file.txt")), changed);
        }
        crate::test_support::settle_allocations(dir.path());

        let progress = crate::Progress::new();
        let observed = ScanConfig { progress: Some(progress.clone()), ..parallel };
        let report = reconcile_target_inner(
            &mut ReconcileTarget::Direct(&mut index),
            Path::new(""),
            0,
            &observed,
            0,
            &mut |_| {},
        )
        .expect("late-overflow reconciliation");

        // The root wave changes nothing and completes; the second wave holds exactly
        // one full wave of changed directories, overflows, and is rewalked with the one
        // directory the wave left behind.
        let rewalked = u64::try_from(RECONCILE_WAVE_DIRECTORIES).expect("fits");
        let snapshot = progress.snapshot();
        assert_eq!(snapshot.directories, report.scan.dirs_read + rewalked);
        assert_eq!(snapshot.files, report.scan.files_walked + rewalked);
        assert_eq!(
            snapshot.bytes,
            report.scan.bytes_walked + rewalked * u64::try_from(changed.len()).expect("fits")
        );
        let allocated = index.attrs(Path::new("d0000/file.txt")).expect("indexed").allocated;
        assert!(allocated > 0, "a file with content occupies blocks");
        assert_eq!(snapshot.allocated, report.scan.allocated_walked + rewalked * allocated);
    }

    /// Several invalidated roots are reconciled one at a time and their reports summed,
    /// so every walked count has to survive the sum, allocated bytes included.
    #[test]
    fn a_multi_root_reconcile_sums_every_walked_count() {
        let dir = tempfile::tempdir().expect("tempdir");
        for directory in ["a", "b", "c"] {
            for file in 0..3 {
                write_file(&dir.path().join(format!("{directory}/f{file}.txt")), b"before");
            }
        }
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        for directory in ["a", "b"] {
            write_file(&dir.path().join(format!("{directory}/f0.txt")), &vec![b'x'; 5_000]);
        }
        index.apply_ok(&Observation::new(
            ["a", "b"]
                .into_iter()
                .map(|directory| Op::InvalidateSubtree {
                    path: PathBuf::from(directory),
                    reason: crate::InvalidateReason::Requested,
                })
                .collect(),
        ));
        let report =
            reconcile_pending(&mut index, &ScanConfig::default(), &mut |_| {}).expect("reconcile");

        let attrs: Vec<Attrs> = ["a", "b"]
            .into_iter()
            .flat_map(|directory| (0..3).map(move |file| format!("{directory}/f{file}.txt")))
            .map(|path| *index.attrs(Path::new(&path)).expect("indexed"))
            .collect();
        assert_eq!(report.scan.files_walked, 6, "the two roots' files, and not c's");
        assert_eq!(report.scan.bytes_walked, attrs.iter().map(|attrs| attrs.size).sum::<u64>());
        assert_eq!(
            report.scan.allocated_walked,
            attrs.iter().map(|attrs| attrs.allocated).sum::<u64>()
        );
    }

    #[test]
    fn shared_reconciliation_retains_conditional_no_op_arbitration() {
        let dir = sample_tree();
        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let handle = crate::IndexHandle::new(index);
        let before_clock = handle.clock().expect("clock");
        let mut commits = Vec::new();

        let report = reconcile_handle(&handle, &ScanConfig::default(), &mut |commit| {
            commits.push(commit.clone());
        })
        .expect("reconcile");

        assert!(report.is_complete());
        assert_eq!(report.apply.unchanged, 5, "3 files + 2 dirs all already known");
        assert_eq!(commits.len(), 2);
        assert!(commits.iter().all(|commit| commit.changes.is_empty()));
        assert_eq!(
            handle.clock().expect("clock"),
            crate::Clock(before_clock.0 + 2),
            "start and finish are state commits"
        );
        let commits = handle.since(before_clock).expect("state commits").commits;
        assert_eq!(commits.len(), 2);
        assert!(commits.iter().all(|commit| commit.changes.is_empty()));
    }

    #[test]
    fn revalidate_detects_additions_edits_and_deletions() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");

        fs::remove_file(dir.path().join("a.txt")).expect("remove");
        write_file(&dir.path().join("src/main.rs"), b"fn main() { longer }");
        write_file(&dir.path().join("added.md"), b"new");

        let mut deltas = Vec::new();
        revalidate(&index, &ScanConfig::default(), &mut |d| deltas.push(d)).expect("revalidate");
        let mut stats = crate::index::ApplyStats::default();
        for delta in &deltas {
            let s = index.apply_ok(delta);
            stats.inserted += s.inserted;
            stats.updated += s.updated;
            stats.removed += s.removed;
        }

        assert_eq!(stats.inserted, 1, "added.md");
        assert_eq!(stats.updated, 1, "main.rs grew");
        assert_eq!(stats.removed, 1, "a.txt is gone");

        let total = index.total();
        assert_eq!(total.files, 3);
        assert_eq!(total.bytes, 20 + 9 + 3);
        assert!(!total.by_ext.contains_key(".txt"));
        assert_eq!(total.by_ext[".md"].files, 1);
    }

    #[test]
    fn revalidate_removes_a_whole_vanished_directory() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        fs::remove_dir_all(dir.path().join("src")).expect("remove dir");

        let mut deltas = Vec::new();
        revalidate(&index, &ScanConfig::default(), &mut |d| deltas.push(d)).expect("revalidate");
        for delta in &deltas {
            index.apply_ok(delta);
        }

        let total = index.total();
        assert_eq!(total.files, 1);
        assert_eq!(total.dirs, 0);
        assert!(index.lookup(Path::new("src")).is_none());
    }

    #[test]
    fn pending_invalidation_reconciles_the_requested_subtree() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        write_file(&dir.path().join("src/added.rs"), b"new");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::from("src"),
            reason: crate::InvalidateReason::Requested,
        }]));
        assert_eq!(index.freshness_at(Path::new("src")), crate::Freshness::Stale);

        let mut applied = Vec::new();
        let report = reconcile_pending(&mut index, &ScanConfig::default(), &mut |delta| {
            applied.push(delta.clone());
        })
        .expect("reconcile pending");

        assert!(report.is_complete());
        assert!(index.lookup(Path::new("src/added.rs")).is_some());
        assert_eq!(index.freshness_at(Path::new("src")), crate::Freshness::Fresh);
        assert!(index.take_pending_invalidations().is_empty());
        assert!(applied.iter().any(|commit| commit_touches(commit, Path::new("src/added.rs"))));
    }

    /// A retained `.gitignore` reconciled as the root of its own walk re-reads its rules.
    /// A file does not descend, so the subtree-root branch was the only place that could
    /// read them, and it did not: the table kept `*.log` while the pass reported complete.
    #[test]
    fn reconciling_a_retained_control_file_as_the_subtree_root_rereads_its_rules() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join(".gitignore"), b"*.log\n");
        write_file(&dir.path().join("a.log"), b"log");
        let config = ScanConfig { read_controls: true, ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");
        assert_eq!(
            index.is_ignored(Path::new("a.log")).expect("control state observed"),
            Some(true)
        );

        write_file(&dir.path().join(".gitignore"), b"# nothing is ignored now\n");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::from(".gitignore"),
            reason: crate::InvalidateReason::Requested,
        }]));
        let report = reconcile_pending(&mut index, &config, &mut |_| {}).expect("reconcile");

        assert!(report.is_complete(), "{:?}", report.scan.errors);
        assert_eq!(index.freshness_at(Path::new(".gitignore")), crate::Freshness::Fresh);
        assert_eq!(
            index.is_ignored(Path::new("a.log")).expect("control state observed"),
            Some(false)
        );
    }

    /// A control file the pass cannot verify contributes neither stale rules nor an entry.
    #[cfg(unix)]
    #[test]
    fn reconciling_an_unreadable_control_file_root_drops_its_rules_and_stays_partial() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }

        let dir = tempfile::tempdir().expect("tempdir");
        let control = dir.path().join(".gitignore");
        write_file(&control, b"*.log\n");
        write_file(&dir.path().join("a.log"), b"log");
        let config = ScanConfig { read_controls: true, ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");

        write_file(&control, b"# rewritten, then made unreadable\n");
        fs::set_permissions(&control, fs::Permissions::from_mode(0o000)).expect("chmod");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::from(".gitignore"),
            reason: crate::InvalidateReason::Requested,
        }]));
        let report = reconcile_pending(&mut index, &config, &mut |_| {});
        fs::set_permissions(&control, fs::Permissions::from_mode(0o644)).expect("restore");
        let report = report.expect("reconcile");

        assert!(!report.is_complete());
        assert_eq!(report.scan.errors.len(), 1, "{:?}", report.scan.errors);
        assert_eq!(index.freshness_at(Path::new(".gitignore")), crate::Freshness::Partial);
        assert!(
            !index.controls().expect("control state observed").contains(Path::new(".gitignore"))
        );
        assert_eq!(index.is_ignored(Path::new("a.log")).expect("control state observed"), None);
    }

    #[cfg(unix)]
    #[test]
    fn unreadable_control_keeps_new_excluded_file_unknown_and_out_of_analysis() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }
        let dir = tempfile::tempdir().expect("tempdir");
        let control = dir.path().join(".gitignore");
        write_file(&control, b"*.log\n");
        write_file(&dir.path().join("keep.rs"), b"code");
        let config = ScanConfig {
            population: crate::query::IgnoredEntries::Exclude,
            ..ScanConfig::default()
        };
        let (mut index, cold) = scan_into_index(dir.path(), &config).expect("cold");
        assert!(cold.is_complete());
        write_file(&dir.path().join("debug.log"), b"must not analyze");
        fs::set_permissions(&control, fs::Permissions::from_mode(0o000)).expect("chmod");
        let report = reconcile(&mut index, &config, &mut |_| {});
        fs::set_permissions(&control, fs::Permissions::from_mode(0o644)).expect("restore");
        let report = report.expect("reconcile");
        assert!(!report.is_complete());
        assert!(index.lookup(Path::new("debug.log")).is_some(), "unknown is retained");
        assert_eq!(index.ignored_classification(Path::new("debug.log")), None);
        assert!(!index.ignored_classification_complete_below(Path::new("")));
        let candidates = index.analysis_candidates(crate::content::AnalysisSet::NONE.with_lines());
        assert!(
            candidates.iter().all(|candidate| candidate.relative_path != Path::new("debug.log"))
        );
        let repaired =
            reconcile(&mut index, &config, &mut |_| {}).expect("reconcile repaired control");
        assert!(repaired.is_complete(), "{:?}", repaired.scan.errors);
        assert!(index.ignored_classification_complete_below(Path::new("")));
        assert!(index.lookup(Path::new("debug.log")).is_none(), "known ignored file is pruned");
    }

    #[test]
    fn handle_reconciliation_publishes_after_each_delta_is_applied() {
        let dir = sample_tree();
        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let handle = crate::IndexHandle::new(index);
        let reader = handle.clone();
        write_file(&dir.path().join("added.md"), b"new");

        let mut observed_after_apply = false;
        reconcile_handle(&handle, &ScanConfig::default(), &mut |commit| {
            if commit_touches(commit, Path::new("added.md")) {
                observed_after_apply =
                    reader.kind(Path::new("added.md")).expect("query index").is_some();
            }
        })
        .expect("reconcile handle");

        assert!(observed_after_apply);
    }

    /// Delete `name` under `root` from inside its own metadata lookup, after the listing
    /// returned it, on whichever thread performs the lookup.
    fn delete_between_listing_and_stat(root: &Path, name: &'static str) -> WalkHookGuard {
        install_child_metadata_hook(root, move |path| {
            delete_if_named(path, name);
            None
        })
    }

    /// As [`delete_between_listing_and_stat`], and every reconciliation listing under `root`
    /// also ends in an error, so none of them is complete.
    fn delete_between_listing_and_stat_in_a_failing_listing(
        root: &Path,
        name: &'static str,
    ) -> WalkHookGuard {
        install_walk_hook(root, move |point| match point {
            WalkHookPoint::ChildMetadata(path) => {
                delete_if_named(path, name);
                None
            }
            WalkHookPoint::ListingEnd => Some(std::io::Error::other("injected listing error")),
            WalkHookPoint::ControlLookup(_) => None,
        })
    }

    fn delete_if_named(path: &Path, name: &str) {
        if path.file_name() == Some(OsStr::new(name)) {
            fs::remove_file(path).expect("delete between listing and stat");
        }
    }

    /// A name the listing returned that is gone by the time it is stat'd was deleted, on
    /// the serial path and on the parallel waves a full-root pass takes by default. The
    /// walk removes it; recorded as an error, it would settle as a phantom entry with
    /// permanent partial freshness.
    #[test]
    fn a_child_deleted_between_listing_and_stat_is_removed_rather_than_reported() {
        for threads in [1, 4] {
            let dir = tempfile::tempdir().expect("tempdir");
            write_file(&dir.path().join("keep.txt"), b"keep");
            write_file(&dir.path().join("gone.txt"), b"gone");
            let config = ScanConfig { threads: Some(threads), ..ScanConfig::default() };
            let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");
            assert!(index.lookup(Path::new("gone.txt")).is_some());

            index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
                path: PathBuf::new(),
                reason: crate::InvalidateReason::Requested,
            }]));
            let hook = delete_between_listing_and_stat(dir.path(), "gone.txt");
            let report = reconcile_pending(&mut index, &config, &mut |_| {});
            drop(hook);
            let report = report.expect("reconcile");

            assert!(report.is_complete(), "threads {threads}: {:?}", report.scan.errors);
            assert_eq!(report.apply.removed, 1, "threads {threads}");
            assert!(index.lookup(Path::new("gone.txt")).is_none(), "threads {threads}");
            assert!(index.lookup(Path::new("keep.txt")).is_some(), "threads {threads}");
            assert_eq!(index.freshness(), crate::Freshness::Fresh, "threads {threads}");
        }
    }

    /// A vanished control file takes its rules with it on both reconcile paths, even when the
    /// rest of its listing fails: the stat's `NotFound` is the evidence. A retained file's
    /// rules go with its entry's removal; a hidden-pruned one has no entry to remove, so
    /// without its own removal its rules would go on ignoring its siblings.
    #[test]
    fn a_control_file_deleted_between_listing_and_stat_takes_its_rules_with_it() {
        for prune_hidden in [false, true] {
            for (threads, listing_fails) in [(1, false), (4, false), (1, true), (4, true)] {
                let case = format!(
                    "prune hidden {prune_hidden}, threads {threads}, listing fails {listing_fails}"
                );
                let dir = tempfile::tempdir().expect("tempdir");
                write_file(&dir.path().join(".gitignore"), b"*.log\n");
                write_file(&dir.path().join("a.log"), b"log");
                let config = ScanConfig {
                    read_controls: true,
                    threads: Some(threads),
                    hidden: prune_hidden
                        .then(|| std::sync::Arc::new(crate::HiddenPolicy::prune_hidden([""; 0]))),
                    ..ScanConfig::default()
                };
                let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");
                assert_eq!(
                    index.is_ignored(Path::new("a.log")).expect("control state observed"),
                    Some(true),
                    "{case}"
                );

                index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
                    path: PathBuf::new(),
                    reason: crate::InvalidateReason::Requested,
                }]));
                let hook = if listing_fails {
                    delete_between_listing_and_stat_in_a_failing_listing(dir.path(), ".gitignore")
                } else {
                    delete_between_listing_and_stat(dir.path(), ".gitignore")
                };
                let report = reconcile_pending(&mut index, &config, &mut |_| {});
                drop(hook);
                let report = report.expect("reconcile");

                assert_eq!(
                    report.is_complete(),
                    !listing_fails,
                    "{case}: {:?}",
                    report.scan.errors
                );
                assert!(index.lookup(Path::new(".gitignore")).is_none(), "{case}");
                assert!(
                    !index
                        .controls()
                        .expect("control state observed")
                        .contains(Path::new(".gitignore")),
                    "{case}"
                );
                assert_eq!(
                    index.is_ignored(Path::new("a.log")).expect("control state observed"),
                    Some(false),
                    "{case}"
                );
            }
        }
    }

    /// A cold walk records a name gone by its stat as it records a name the listing never
    /// returned: not at all, and without an error that would make the walk partial.
    #[test]
    fn a_cold_walk_omits_a_child_deleted_between_listing_and_stat() {
        for threads in [1, 4] {
            let dir = tempfile::tempdir().expect("tempdir");
            write_file(&dir.path().join("keep.txt"), b"keep");
            write_file(&dir.path().join("gone.txt"), b"gone");
            let config = ScanConfig { threads: Some(threads), ..ScanConfig::default() };

            let hook = delete_between_listing_and_stat(dir.path(), "gone.txt");
            let scanned = scan_into_index_via_scanner(dir.path(), &config);
            drop(hook);
            let (index, report) = scanned.expect("scan");

            assert!(report.is_complete(), "threads {threads}: {:?}", report.errors);
            assert!(index.lookup(Path::new("gone.txt")).is_none(), "threads {threads}");
            assert!(index.lookup(Path::new("keep.txt")).is_some(), "threads {threads}");
        }
    }

    /// Revalidation emits the removal a reconciliation would apply.
    #[test]
    fn revalidation_removes_a_child_deleted_between_listing_and_stat() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("keep.txt"), b"keep");
        write_file(&dir.path().join("gone.txt"), b"gone");
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");

        let hook = delete_between_listing_and_stat(dir.path(), "gone.txt");
        let mut observations = Vec::new();
        let report = revalidate(&index, &ScanConfig::default(), &mut |observation| {
            observations.push(observation);
        });
        drop(hook);
        let report = report.expect("revalidate");
        for observation in &observations {
            index.apply_ok(observation);
        }

        assert!(report.is_complete(), "{:?}", report.errors);
        assert!(index.lookup(Path::new("gone.txt")).is_none());
        assert!(index.lookup(Path::new("keep.txt")).is_some());
    }

    /// Revalidation emits the same rules removal when the rest of the listing fails.
    #[test]
    fn revalidation_removes_the_rules_of_a_control_file_deleted_in_a_failing_listing() {
        for prune_hidden in [false, true] {
            let dir = tempfile::tempdir().expect("tempdir");
            write_file(&dir.path().join(".gitignore"), b"*.log\n");
            write_file(&dir.path().join("a.log"), b"log");
            let config = ScanConfig {
                read_controls: true,
                hidden: prune_hidden
                    .then(|| std::sync::Arc::new(crate::HiddenPolicy::prune_hidden([""; 0]))),
                ..ScanConfig::default()
            };
            let (mut index, _) = scan_into_index(dir.path(), &config).expect("scan");
            assert_eq!(
                index.is_ignored(Path::new("a.log")).expect("control state observed"),
                Some(true)
            );

            let hook =
                delete_between_listing_and_stat_in_a_failing_listing(dir.path(), ".gitignore");
            let mut observations = Vec::new();
            let report = revalidate(&index, &config, &mut |observation| {
                observations.push(observation);
            });
            drop(hook);
            let report = report.expect("revalidate");
            for observation in &observations {
                index.apply_ok(observation);
            }

            assert!(!report.is_complete(), "prune hidden {prune_hidden}");
            assert!(index.lookup(Path::new(".gitignore")).is_none(), "prune hidden {prune_hidden}");
            assert!(
                !index
                    .controls()
                    .expect("control state observed")
                    .contains(Path::new(".gitignore")),
                "prune hidden {prune_hidden}"
            );
            assert_eq!(
                index.is_ignored(Path::new("a.log")).expect("control state observed"),
                Some(false),
                "prune hidden {prune_hidden}"
            );
        }
    }

    #[test]
    fn reconciliation_does_not_clear_a_newer_invalidation() {
        let dir = sample_tree();
        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let handle = crate::IndexHandle::new(index);
        write_file(&dir.path().join("added.md"), b"new");

        let invalidator = handle.clone();
        let mut saw_reconciling = false;
        reconcile_handle(&handle, &ScanConfig::default(), &mut |commit| {
            if commit_touches(commit, Path::new("added.md")) {
                saw_reconciling =
                    invalidator.freshness().expect("query") == crate::Freshness::Reconciling;
                invalidator
                    .apply(&Observation::new(vec![Op::InvalidateSubtree {
                        path: PathBuf::new(),
                        reason: crate::InvalidateReason::WatchOverflow,
                    }]))
                    .expect("new invalidation");
            }
        })
        .expect("reconcile handle");

        assert!(saw_reconciling);
        assert_eq!(handle.freshness().expect("query"), crate::Freshness::Stale);
    }

    #[test]
    fn failed_reconciliation_marks_the_scope_partial() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        fs::remove_dir_all(dir.path()).expect("remove root");

        assert!(reconcile(&mut index, &ScanConfig::default(), &mut |_| {}).is_err());
        assert_eq!(index.freshness(), crate::Freshness::Partial);
    }

    #[test]
    fn successful_subtree_retry_restores_complete_root_coverage() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("blocked/known.txt"), b"known");
        let config = ScanConfig::default();
        let (mut index, report) = scan_into_index(dir.path(), &config).expect("scan");
        assert!(report.is_complete());
        let blocked = dir.path().join("blocked");
        let fault = install_walk_hook(&blocked, |_| {
            Some(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "deterministic subtree refusal",
            ))
        });

        let failed = reconcile_subtree(&mut index, Path::new("blocked"), &config, &mut |_| {})
            .expect("partial");
        assert!(!failed.scan.is_complete());
        assert_eq!(
            index.state().coverage,
            crate::Coverage::Partial(crate::CoverageReason::Inaccessible)
        );
        drop(fault);

        let recovered = reconcile_subtree(&mut index, Path::new("blocked"), &config, &mut |_| {})
            .expect("retry");

        assert!(recovered.scan.is_complete());
        assert_eq!(index.state().coverage, crate::Coverage::Complete);
    }

    #[test]
    fn failed_pending_reconciliation_remains_queued_for_retry() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::new(),
            reason: crate::InvalidateReason::Requested,
        }]));
        fs::remove_dir_all(dir.path()).expect("remove root");

        assert!(reconcile_pending(&mut index, &ScanConfig::default(), &mut |_| {}).is_err());
        assert_eq!(
            index.take_pending_invalidations(),
            vec![(PathBuf::new(), crate::InvalidateReason::Requested)]
        );
        assert_eq!(index.freshness(), crate::Freshness::Partial);
    }

    #[cfg(unix)]
    #[test]
    fn partial_cold_scan_keeps_verified_siblings_complete() {
        use std::os::unix::fs::PermissionsExt;
        if !crate::test_support::require_permission_bits() {
            return;
        }
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join("blocked/unknown.txt"), b"unread");
        write_file(&root.path().join("healthy/nested/known.txt"), b"known");
        let blocked = root.path().join("blocked");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("deny reads");
        let scan = ScanConfig::default();
        let detached = scan_into_index(root.path(), &scan);
        let streamed = scan_into_index_via_scanner(root.path(), &scan);
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700)).expect("restore reads");
        for result in [detached, streamed] {
            let (index, report) = result.expect("partial scan still returns its facts");
            assert!(!report.is_complete(), "permission fixture must fail the blocked listing");
            assert!(
                index
                    .issues()
                    .iter()
                    .any(|issue| issue.path.as_deref() == Some(Path::new("blocked")))
            );
            assert_eq!(index.freshness_at(Path::new("")), crate::Freshness::Partial);
            assert_eq!(index.directory_complete(Path::new("")), Some(true));
            assert_eq!(index.directory_complete(Path::new("blocked")), Some(false));
            assert_eq!(index.freshness_at(Path::new("blocked")), crate::Freshness::Partial);
            assert!(index.lookup(Path::new("blocked/unknown.txt")).is_none());
            for sibling in ["healthy", "healthy/nested"] {
                assert_eq!(index.directory_complete(Path::new(sibling)), Some(true), "{sibling}");
                assert_eq!(
                    index.freshness_at(Path::new(sibling)),
                    crate::Freshness::Fresh,
                    "{sibling}"
                );
            }
            assert!(index.lookup(Path::new("healthy/nested/known.txt")).is_some());
            assert!(
                !crate::stored_state::entries_writable(&index),
                "partial root cannot persist metadata"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn partial_pending_reconciliation_remains_queued_for_retry() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("blocked/known.txt"), b"known");
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let blocked = dir.path().join("blocked");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("deny reads");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::from("blocked"),
            reason: crate::InvalidateReason::VerificationFailed,
        }]));

        let report = reconcile_pending(&mut index, &ScanConfig::default(), &mut |_| {})
            .expect("permission failure is a partial report");
        let pending = index.take_pending_invalidations();
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700)).expect("restore reads");
        assert!(!report.is_complete(), "permission fixture must make reconciliation partial");
        assert_eq!(
            pending,
            vec![(PathBuf::from("blocked"), crate::InvalidateReason::VerificationFailed)]
        );
        assert_eq!(index.freshness_at(Path::new("blocked")), crate::Freshness::Partial);
    }

    /// The shared API settles an unreadable subtree instead of queueing it again.
    ///
    /// Its per-event driver, `Watcher::apply_next`, drains after every event, so a retry
    /// re-walked the same unreadable subtree on each unrelated event, forever. The subtree
    /// stays partial and the report still names the error, once.
    #[cfg(unix)]
    #[test]
    fn partial_shared_pending_reconciliation_settles_instead_of_retrying() {
        use std::os::unix::fs::PermissionsExt;

        if !crate::test_support::require_permission_bits() {
            return;
        }
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("blocked/known.txt"), b"known");
        let (index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        let handle = crate::IndexHandle::new(index);
        let blocked = dir.path().join("blocked");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).expect("deny reads");
        handle
            .apply(&Observation::new(vec![Op::InvalidateSubtree {
                path: PathBuf::from("blocked"),
                reason: crate::InvalidateReason::VerificationFailed,
            }]))
            .expect("invalidate");

        let report = reconcile_pending_handle(&handle, &ScanConfig::default(), &mut |_| {})
            .expect("permission failure is a partial report");
        let pending = handle.take_pending_invalidations().expect("pending");
        let freshness = handle.freshness_at(Path::new("blocked")).expect("freshness");
        fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700)).expect("restore reads");
        assert!(!report.is_complete(), "permission fixture must make reconciliation partial");
        assert!(pending.is_empty(), "{pending:?}");
        assert_eq!(freshness, crate::Freshness::Partial);
        assert!(!report.scan.errors.is_empty());
    }

    #[test]
    fn pending_scope_mismatch_does_not_drain_the_retry_queue() {
        let dir = tempfile::tempdir().expect("tempdir");
        let shallow = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &shallow).expect("scan");
        index.apply_ok(&Observation::new(vec![Op::InvalidateSubtree {
            path: PathBuf::new(),
            reason: crate::InvalidateReason::Requested,
        }]));

        let error = reconcile_pending(&mut index, &ScanConfig::default(), &mut |_| {})
            .expect_err("mismatched scope must fail");

        assert!(matches!(error, Error::ScanScopeMismatch { .. }));
        assert_eq!(
            index.take_pending_invalidations(),
            vec![(PathBuf::new(), crate::InvalidateReason::Requested)]
        );
    }

    #[test]
    fn reconciliation_rejects_a_scope_mismatch_before_mutating() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("deep/nested.txt"), b"nested");
        let shallow = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &shallow).expect("scan");
        assert!(index.lookup(Path::new("deep/nested.txt")).is_none());

        let error = reconcile(&mut index, &ScanConfig::default(), &mut |_| {})
            .expect_err("mismatched scope must fail");

        assert!(matches!(error, Error::ScanScopeMismatch { .. }));
        assert!(index.lookup(Path::new("deep/nested.txt")).is_none());
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[test]
    fn subtree_reconciliation_rejects_a_path_beyond_the_depth_scope() {
        let dir = tempfile::tempdir().expect("tempdir");
        write_file(&dir.path().join("deep/nested.txt"), b"nested");
        let shallow = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (mut index, _) = scan_into_index(dir.path(), &shallow).expect("scan");

        let result =
            reconcile_subtree(&mut index, Path::new("deep/nested.txt"), &shallow, &mut |_| {});

        assert!(matches!(result, Err(Error::SubtreeOutsideScanScope { .. })));
        assert!(index.lookup(Path::new("deep/nested.txt")).is_none());
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[cfg(unix)]
    #[test]
    fn subtree_reconciliation_does_not_follow_an_ancestor_symlink() {
        use std::os::unix::fs::symlink;

        let root = tempfile::tempdir().expect("root");
        let outside = tempfile::tempdir().expect("outside");
        write_file(&outside.path().join("secret.txt"), b"secret");
        symlink(outside.path(), root.path().join("link")).expect("symlink");
        let config = ScanConfig::default();
        let (mut index, _) = scan_into_index(root.path(), &config).expect("scan");

        let result =
            reconcile_subtree(&mut index, Path::new("link/secret.txt"), &config, &mut |_| {});

        assert!(matches!(result, Err(Error::SubtreeOutsideScanScope { .. })));
        assert!(index.lookup(Path::new("link/secret.txt")).is_none());
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[test]
    fn subtree_reconciliation_widens_to_a_non_directory_ancestor() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join("parent/child.txt"), b"old");
        let config = ScanConfig::default();
        let (mut index, _) = scan_into_index(root.path(), &config).expect("scan");
        fs::remove_dir_all(root.path().join("parent")).expect("remove directory");
        write_file(&root.path().join("parent"), b"replacement");

        let report =
            reconcile_subtree(&mut index, Path::new("parent/child.txt"), &config, &mut |_| {})
                .expect("reconcile widened ancestor");

        assert!(report.is_complete());
        assert_eq!(index.kind(Path::new("parent")), Some(EntryKind::File));
        assert!(index.lookup(Path::new("parent/child.txt")).is_none());
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[test]
    fn subtree_reconciliation_widens_to_a_missing_ancestor() {
        let root = tempfile::tempdir().expect("root");
        write_file(&root.path().join("parent/child.txt"), b"old");
        let config = ScanConfig::default();
        let (mut index, _) = scan_into_index(root.path(), &config).expect("scan");
        fs::remove_dir_all(root.path().join("parent")).expect("remove directory");

        let report =
            reconcile_subtree(&mut index, Path::new("parent/child.txt"), &config, &mut |_| {})
                .expect("reconcile widened ancestor");

        assert!(report.is_complete());
        assert!(index.lookup(Path::new("parent")).is_none());
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[test]
    fn observation_only_revalidation_rejects_a_scope_mismatch() {
        let dir = tempfile::tempdir().expect("tempdir");
        let shallow = ScanConfig { max_depth: Some(1), ..ScanConfig::default() };
        let (index, _) = scan_into_index(dir.path(), &shallow).expect("scan");
        let mut observations = Vec::new();

        let error = revalidate(&index, &ScanConfig::default(), &mut |observation| {
            observations.push(observation);
        })
        .expect_err("mismatched scope must fail");

        assert!(matches!(error, Error::ScanScopeMismatch { .. }));
        assert!(observations.is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn a_new_filesystem_boundary_prunes_cached_descendants() {
        use std::os::unix::fs::MetadataExt;

        let root = Path::new("/");
        let root_dev = {
            crate::counters::bump(|c| c.stats += 1);
            fs::symlink_metadata(root)
        }
        .expect("stat root")
        .dev();
        let Some(mount) = [Path::new("/dev"), Path::new("/proc"), Path::new("/sys")]
            .into_iter()
            .find(|candidate| {
                fs::symlink_metadata(candidate)
                    .is_ok_and(|metadata| metadata.is_dir() && metadata.dev() != root_dev)
            })
        else {
            return; // This host exposes no convenient cross-device directory.
        };
        let relative = mount.strip_prefix(root).expect("mount is below root");
        let stale_child = relative.join(".fdu-stale-snapshot-entry");
        let config = ScanConfig { one_filesystem: true, ..ScanConfig::default() };
        let mount_meta = fs::symlink_metadata(mount).expect("stat mount");
        let mut index = Index::new_with_scope(root, config.scope());
        index.apply_baseline_ok(&Observation::new(vec![
            Op::Upsert {
                path: relative.to_path_buf(),
                kind: EntryKind::Dir,
                attrs: attrs_from(mount, &mount_meta).expect("mount attrs"),
            },
            Op::Upsert {
                path: stale_child.clone(),
                kind: EntryKind::File,
                attrs: Attrs { size: 10, allocated: 10, ..Attrs::default() },
            },
        ]));

        let error = reconcile_subtree(&mut index, &stale_child, &config, &mut |_| {})
            .expect_err("a descendant below the mount boundary is outside scope");
        assert!(matches!(error, Error::SubtreeOutsideScanScope { .. }));
        assert!(index.lookup(&stale_child).is_some());

        reconcile_subtree(&mut index, relative, &config, &mut |_| {}).expect("reconcile mount");

        assert!(index.lookup(relative).is_some(), "the mount point itself stays visible");
        assert!(index.lookup(&stale_child).is_none(), "out-of-scope descendants are pruned");
    }

    #[test]
    fn subtree_reconciliation_rejects_paths_outside_the_root() {
        let dir = sample_tree();
        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");

        assert!(matches!(
            reconcile_subtree(
                &mut index,
                Path::new("../outside"),
                &ScanConfig::default(),
                &mut |_| {},
            ),
            Err(Error::PathEscapesRoot(_))
        ));
        assert_eq!(index.freshness(), crate::Freshness::Fresh);
    }

    #[test]
    fn normalized_walk_errors_keep_index_and_one_shot_status_in_lockstep() {
        let root = Path::new("/root");
        let mut order: Vec<_> = (0..66).rev().collect();
        order.push(65);
        let mut errors = order
            .into_iter()
            .map(|number| {
                Error::io(
                    root.join(format!("file-{number:02}")),
                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
                )
            })
            .collect::<Vec<_>>();

        normalize_walk_errors(root, &mut errors);
        assert_eq!(errors.len(), 66, "the repeated cause is removed once");

        let mut index = crate::Index::new(root);
        index.record_walk_errors(&mut errors);
        let status = crate::query::TreeStatus::of_walk(
            root,
            &mut ScanReport { errors, ..ScanReport::default() },
        );

        assert_eq!(status.errors, index.issues());
        assert_eq!(status.errors_omitted, index.state().issues.omitted);
        assert_eq!(status.errors.len(), crate::MAX_RETAINED_ISSUES);
        assert_eq!(status.errors_omitted, 2);
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let first = PathBuf::from(OsString::from_vec(vec![b'n', 0x80]));
        let second = PathBuf::from(OsString::from_vec(vec![b'n', 0x81]));
        write_file(&dir.path().join(&first), b"a");
        write_file(&dir.path().join(&second), b"bb");

        let (mut index, _) = scan_into_index(dir.path(), &ScanConfig::default()).expect("scan");
        assert_eq!(index.total().files, 2);
        assert_eq!(index.total().bytes, 3);

        fs::remove_file(dir.path().join(&first)).expect("remove first");
        let mut observations = Vec::new();
        revalidate(&index, &ScanConfig::default(), &mut |observation| {
            observations.push(observation);
        })
        .expect("revalidate");
        for observation in &observations {
            index.apply_ok(observation);
        }
        assert!(index.lookup(&first).is_none());
        assert!(index.lookup(&second).is_some());
        assert_eq!(index.total().bytes, 2);
    }
}