ant-node 0.24.0

Pure quantum-proof network node for the Autonomi decentralized network
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
//! One immutable file per chunk, content-addressed, with the filesystem as the
//! only authority.
//!
//! ```text
//! {root}/chunks/                     store root
//! {root}/chunks/layout.json          versioned layout marker
//! {root}/chunks/.lock                advisory single-process guard
//! {root}/chunks/<xy>/<64-hex>        xy = the LAST two hex characters of the address
//! {root}/chunks/<xy>/.tmp.<pid>.<n>  an in-flight write, in the destination directory
//! ```
//!
//! # Why the *last* two hex characters
//!
//! A node holds keys for which it is among the [`CLOSE_GROUP_SIZE`] closest, so its
//! holdings share roughly `log2(N / CLOSE_GROUP_SIZE)` leading bits with its own node
//! ID, and that shared prefix grows as the network grows. Sharding on a prefix therefore
//! does not degrade, it collapses: at ~800 nodes a two-hex prefix already resolves to
//! about two distinct directories, and past a million nodes even a four-hex prefix
//! resolves to one. Close-group membership constrains the leading bits and places no
//! constraint at all on the trailing ones, and the address is a BLAKE3 output, so the
//! last byte is uniform by construction at every network size.
//!
//! 256 shards keeps a 24 GiB node at ~23 files per directory and a 1 TiB node at ~977,
//! for 1 MiB of directory inodes. The scheme and depth are recorded in `layout.json` at
//! creation so a future layout can be detected rather than silently misread.
//!
//! # Why lowercase hex names
//!
//! NTFS and default APFS fold case. Under an encoding with both cases (base64url,
//! base58) two distinct 32-byte keys can share one case-folded filename, which is a
//! silent overwrite. Hex has one case-folded form per key, and no hex string can ever
//! spell a reserved Windows device name (`CON`, `NUL`, `AUX`, `COM1`, ...) because none
//! of those letters is in `0-9a-f`. The full 64-character key stays in the filename, so
//! a `find` over the tree recovers the whole store even if the directory layer is lost.
//!
//! [`CLOSE_GROUP_SIZE`]: crate::ant_protocol::CLOSE_GROUP_SIZE

use crate::ant_protocol::{XorName, MAX_CHUNK_SIZE, XORNAME_LEN};
use crate::error::{Error, Result};
use crate::logging::{debug, info, trace, warn};
use crate::storage::StorageStats;
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::fs::{File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Notify;
use tokio::task::spawn_blocking;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;

/// Directory under the node root that holds the chunk files.
pub const CHUNKS_DIR_NAME: &str = "chunks";

/// Name of the layout marker written once at store creation.
pub const LAYOUT_FILE_NAME: &str = "layout.json";

/// Name of the advisory single-process lock file.
const LOCK_FILE_NAME: &str = ".lock";

/// Prefix that marks an in-flight write. Never a valid chunk name (chunk names are
/// exactly [`CHUNK_NAME_LEN`] lowercase hex characters, and `.` is not hex).
const TEMP_PREFIX: &str = ".tmp.";

/// Number of shard directories. One level, `00` through `ff`.
const SHARD_COUNT: usize = 256;

/// Length of a chunk filename: the full address in lowercase hex.
const CHUNK_NAME_LEN: usize = XORNAME_LEN * 2;

/// How often to re-query available disk space, in seconds.
const DISK_CHECK_INTERVAL_SECS: u64 = 5;

/// Allocation granularity assumed when charging a pending write against free space.
///
/// Every filesystem we support allocates in units of at least 4 KiB, so a write of
/// `n` bytes consumes at least `ceil(n / 4096) * 4096`. One extra unit covers the
/// directory entry and inode.
const ALLOC_UNIT: u64 = 4096;

/// How many times a publish retries a transient Windows sharing violation.
const RENAME_RETRY_ATTEMPTS: u32 = 5;

/// Base backoff between those retries; the wait grows linearly with the attempt.
const RENAME_RETRY_BACKOFF: Duration = Duration::from_millis(20);

/// Longest absolute path a chunk file may need, checked once at open.
///
/// Windows caps a non-verbatim path at `MAX_PATH` (260) including the terminating NUL.
/// Rust's standard library transparently switches to the `\\?\` verbatim form for long
/// absolute paths, so this is a warning rather than a hard failure, but an operator who
/// buries the node root ten directories deep should hear about it before the first write
/// fails rather than after.
#[cfg(windows)]
const WINDOWS_PATH_WARN_LEN: usize = 240;

/// The on-disk layout marker.
///
/// Written once when the store directory is created and read on every subsequent open.
/// Nothing in this survey of comparable stores (IPFS flatfs, Storj, borgbackup) shipped
/// an in-place re-sharder, and all three paid for it. Recording the scheme costs one
/// small file and is the difference between changing the default later and never being
/// able to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoreLayout {
    /// Marker schema version. A store written by a newer schema is refused.
    pub schema: u32,
    /// How a chunk address maps to a shard directory.
    pub scheme: String,
    /// How many hex characters of the address name the shard directory.
    pub shard_chars: u8,
    /// How many directory levels of sharding.
    pub depth: u8,
    /// How a chunk address maps to a filename.
    pub name_encoding: String,
}

/// Marker schema this build writes and understands.
const LAYOUT_SCHEMA: u32 = 1;
/// Shard scheme this build implements: the trailing hex characters of the address.
const LAYOUT_SCHEME_SUFFIX_HEX: &str = "suffix-hex";
/// Filename encoding this build implements.
const LAYOUT_NAME_LOWER_HEX: &str = "lower-hex";

impl Default for StoreLayout {
    fn default() -> Self {
        Self {
            schema: LAYOUT_SCHEMA,
            scheme: LAYOUT_SCHEME_SUFFIX_HEX.to_string(),
            shard_chars: 2,
            depth: 1,
            name_encoding: LAYOUT_NAME_LOWER_HEX.to_string(),
        }
    }
}

impl StoreLayout {
    /// Return an error unless this build can read a store written with this layout.
    fn check_supported(&self) -> Result<()> {
        if self.schema > LAYOUT_SCHEMA {
            return Err(Error::Storage(format!(
                "Chunk store layout schema {} is newer than this build understands ({LAYOUT_SCHEMA}). \
                 Refusing to open rather than misread the store.",
                self.schema
            )));
        }
        if self.scheme != LAYOUT_SCHEME_SUFFIX_HEX {
            return Err(Error::Storage(format!(
                "Chunk store uses shard scheme '{}', this build implements '{LAYOUT_SCHEME_SUFFIX_HEX}'",
                self.scheme
            )));
        }
        if self.shard_chars != 2 || self.depth != 1 {
            return Err(Error::Storage(format!(
                "Chunk store uses {} shard characters at depth {}, this build implements 2 at depth 1",
                self.shard_chars, self.depth
            )));
        }
        if self.name_encoding != LAYOUT_NAME_LOWER_HEX {
            return Err(Error::Storage(format!(
                "Chunk store names files with '{}', this build implements '{LAYOUT_NAME_LOWER_HEX}'",
                self.name_encoding
            )));
        }
        Ok(())
    }
}

/// What the store can say about free space right now.
///
/// Three answers, because deciding how long to stand down needs the distinction: a full
/// disk is a standing condition worth waiting minutes on, while a failed query may have
/// cleared by the next attempt and must not be treated as one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CapacityVerdict {
    /// Available space is at or above the configured reserve. That is what the query
    /// establishes, and possibly from the TTL cache, not a promise the next write succeeds.
    Writable,
    /// Available space is below the configured reserve.
    Full,
    /// The query itself failed, so nothing is known about available space.
    Unknown,
}

/// Free and total bytes on the partition holding the record store.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiskSpace {
    /// Bytes free to this process, less what writes have already charged
    /// against them.
    pub available: u64,
    /// Size of the partition less the blocks reserved for the root user, so
    /// `available / total` reads as `df` reads it.
    pub total: u64,
}

/// Configuration for [`ChunkStore`].
#[derive(Debug, Clone)]
pub struct ChunkStoreConfig {
    /// Node root directory. The store lives at `{root_dir}/chunks/`.
    pub root_dir: PathBuf,
    /// Verify `BLAKE3(content) == address` on read.
    pub verify_on_read: bool,
    /// Free bytes to keep on the storage partition. Writes are refused below this.
    pub disk_reserve: u64,
}

impl Default for ChunkStoreConfig {
    fn default() -> Self {
        Self {
            root_dir: PathBuf::from(".ant/chunks"),
            verify_on_read: true,
            disk_reserve: crate::storage::DEFAULT_DISK_RESERVE,
        }
    }
}

impl ChunkStoreConfig {
    /// The shipped defaults with the disk reserve removed, for tests on small volumes.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub fn test_default() -> Self {
        Self {
            disk_reserve: 0,
            ..Self::default()
        }
    }
}

/// Outcome of a single write attempt, used to keep the duplicate accounting honest.
enum PutOutcome {
    /// The chunk was newly published.
    New,
    /// The chunk was already on disk.
    Duplicate,
}

/// Snapshot of free space, plus what has been written since it was taken.
#[derive(Debug)]
struct CapacitySnapshot {
    /// When `available` was measured. `None` means never.
    measured_at: Option<Instant>,
    /// Free bytes reported by the filesystem at `measured_at`.
    available: u64,
    /// Bytes published since `measured_at`, charged against `available`.
    ///
    /// Cleared by a fresh measurement, which already accounts for them.
    written_since: u64,
    /// Bytes reserved by writes that have not landed yet.
    ///
    /// Deliberately **not** cleared by a measurement: a `statvfs` taken while writes are
    /// in flight reports space those writes are about to consume, so forgetting their
    /// reservations at that moment would hand the same bytes out twice. That is precisely
    /// the over-admission the reservation exists to prevent.
    in_flight: u64,
}

/// Size-aware free-space predicate with a short-lived cache.
///
/// Free bytes alone stopped being a sufficient answer the moment chunks became files:
/// a caller wants to know whether *this* write fits, not whether the disk is non-empty.
/// The cache keeps the common case at one `statvfs` per interval while staying correct
/// under a burst, because bytes written since the measurement are charged against it.
#[derive(Debug)]
struct CapacityGuard {
    /// Directory whose partition is measured.
    dir: PathBuf,
    /// Free bytes to keep unused.
    reserve: u64,
    /// The cached measurement.
    snapshot: parking_lot::Mutex<CapacitySnapshot>,
}

impl CapacitySnapshot {
    /// Free bytes, less everything written or promised since the measurement.
    fn free_estimate(&self) -> u64 {
        self.available
            .saturating_sub(self.written_since)
            .saturating_sub(self.in_flight)
    }
}

impl CapacityGuard {
    /// Create a guard over the partition hosting `dir`.
    fn new(dir: PathBuf, reserve: u64) -> Self {
        Self {
            dir,
            reserve,
            snapshot: parking_lot::Mutex::new(CapacitySnapshot {
                measured_at: None,
                available: 0,
                written_since: 0,
                in_flight: 0,
            }),
        }
    }

    /// Bytes actually consumed on disk by a payload of `len` bytes.
    fn charge(len: u64) -> u64 {
        // Round the payload up to the allocation unit, then add one unit for the
        // directory entry and inode.
        len.div_ceil(ALLOC_UNIT)
            .saturating_mul(ALLOC_UNIT)
            .saturating_add(ALLOC_UNIT)
    }

    /// Free bytes right now, or why the question could not be answered.
    ///
    /// Deliberately separate from [`Self::check`], which folds a failure into an error
    /// the caller cannot tell from "below the reserve". Callers poll this, so it leaves
    /// logging a failure to them.
    fn measure_available(&self) -> Result<u64> {
        let mut snapshot = self.snapshot.lock();
        self.measure(&mut snapshot)?;
        Ok(snapshot.free_estimate())
    }

    /// Query the filesystem and refresh the snapshot.
    fn measure(&self, snapshot: &mut CapacitySnapshot) -> Result<()> {
        let available = fs2::available_space(&self.dir)
            .map_err(|e| Error::Storage(format!("Failed to query available disk space: {e}")))?;
        snapshot.available = available;
        // Reservations survive: their bytes are not on the platter yet, so the fresh
        // measurement does not include them.
        snapshot.written_since = 0;
        snapshot.measured_at = Some(Instant::now());
        Ok(())
    }

    /// Test `needed` against the snapshot, refreshing it if it is stale or short.
    ///
    /// Only *passing* results are cached, so a low-space condition is rechecked on every
    /// call and freed space is noticed promptly.
    fn admit(&self, snapshot: &mut CapacitySnapshot, needed: u64) -> Result<()> {
        let want = self.reserve.saturating_add(Self::charge(needed));

        let cache_fresh = snapshot
            .measured_at
            .is_some_and(|t| t.elapsed().as_secs() < DISK_CHECK_INTERVAL_SECS);
        if cache_fresh && snapshot.free_estimate() >= want {
            return Ok(());
        }

        self.measure(snapshot)?;
        if snapshot.free_estimate() < want {
            // Do not cache a failing result: `measured_at` is left set so the next call
            // still re-measures, because the branch above only short-circuits a pass.
            return Err(Error::Storage(format!(
                "Insufficient disk space: {:.2} GiB available, {:.2} GiB reserve required. \
                 Free disk space or increase the partition to continue storing chunks.",
                bytes_to_gib(snapshot.free_estimate()),
                bytes_to_gib(self.reserve),
            )));
        }
        Ok(())
    }

    /// Drop the cached measurement so the next question hits the filesystem.
    fn invalidate(&self) {
        let mut snapshot = self.snapshot.lock();
        snapshot.measured_at = None;
        snapshot.written_since = 0;
    }

    /// Return `Ok(())` if a write of `needed` bytes would fit. Charges nothing.
    fn check(&self, needed: u64) -> Result<()> {
        let mut snapshot = self.snapshot.lock();
        self.admit(&mut snapshot, needed)
    }

    /// Admit a write of `needed` bytes and charge it in the same critical section.
    ///
    /// Checking and charging separately is the bug this exists to prevent: dozens of
    /// protocol handlers can each pass against the same cached measurement before any of
    /// them has written a byte, and collectively cross the reserve.
    ///
    /// The returned [`Reservation`] settles itself when dropped, so a caller whose future
    /// is dropped mid-write cannot strand it. Nothing else ever decrements the in-flight
    /// count, so a stranded reservation would be permanent, and enough of them would make
    /// an empty disk look full until the process restarted.
    fn reserve(self: &Arc<Self>, needed: u64) -> Result<Reservation> {
        {
            let mut snapshot = self.snapshot.lock();
            self.admit(&mut snapshot, needed)?;
            snapshot.in_flight = snapshot.in_flight.saturating_add(Self::charge(needed));
        }
        Ok(Reservation {
            capacity: Arc::clone(self),
            bytes: needed,
            settled: false,
        })
    }

    /// Give back a reservation whose write did not happen.
    fn release(&self, needed: u64) {
        let mut snapshot = self.snapshot.lock();
        snapshot.in_flight = snapshot.in_flight.saturating_sub(Self::charge(needed));
    }

    /// Turn a reservation into bytes that are now on disk.
    fn commit_reservation(&self, needed: u64) {
        let charge = Self::charge(needed);
        let mut snapshot = self.snapshot.lock();
        snapshot.in_flight = snapshot.in_flight.saturating_sub(charge);
        snapshot.written_since = snapshot.written_since.saturating_add(charge);
    }

    /// Credit a completed delete back to the cached measurement.
    fn record_removed(&self, len: u64) {
        let mut snapshot = self.snapshot.lock();
        snapshot.written_since = snapshot.written_since.saturating_sub(Self::charge(len));
    }

    /// The two accounting counters, for tests that need to prove a charge was
    /// settled one way rather than the other.
    #[cfg(test)]
    fn counters(&self) -> (u64, u64) {
        let snapshot = self.snapshot.lock();
        (snapshot.written_since, snapshot.in_flight)
    }
}

/// A charged, unsettled write.
///
/// Held by whatever is actually doing the write, so the charge is released even if the
/// caller's future is dropped and only the blocking closure survives.
pub struct Reservation {
    /// The guard this was taken from.
    capacity: Arc<CapacityGuard>,
    /// Payload size, before rounding.
    bytes: u64,
    /// Whether it has already been accounted for.
    settled: bool,
}

impl Reservation {
    /// The write landed: move the charge from in-flight to written.
    pub(crate) fn commit(mut self) {
        self.capacity.commit_reservation(self.bytes);
        self.settled = true;
    }
}

impl Drop for Reservation {
    fn drop(&mut self) {
        if !self.settled {
            self.capacity.release(self.bytes);
        }
    }
}

/// Environment variable naming a failpoint: stop after the temp file, before the rename.
#[cfg(any(test, feature = "test-utils"))]
pub const HALT_BEFORE_PUBLISH: &str = "ANT_HALT_BEFORE_PUBLISH";

/// Park forever at a named failpoint, once a marker says the process has reached it.
///
/// For crash tests, which need a process to die *inside* an operation rather than at
/// whatever point a sleep in another process happened to land. The variable holds a path:
/// this writes it, so the parent knows the child is exactly here, and then waits to be
/// killed.
///
/// Costs one environment read per write when the feature is compiled in, and the feature
/// is not in a release build.
#[cfg(any(test, feature = "test-utils"))]
pub(crate) fn halt_here_if_asked(variable: &str, reached: &Path) {
    let Ok(marker) = std::env::var(variable) else {
        return;
    };
    // Let the first few through. A test that stops the very first write leaves a store
    // with nothing successfully in it, and an assertion over what it holds then passes by
    // iterating nothing. Letting some land first means the crash happens to a store that
    // has real chunks in it, which is the situation worth checking.
    let skip: u64 = std::env::var(HALT_AFTER)
        .ok()
        .and_then(|raw| raw.parse().ok())
        .unwrap_or(0);
    if HALTS_SEEN.fetch_add(1, std::sync::atomic::Ordering::AcqRel) < skip {
        return;
    }
    if let Err(e) = std::fs::write(&marker, reached.as_os_str().as_encoded_bytes()) {
        // The parent waits for this file. Saying so on the way past is the difference
        // between a test that fails and one that hangs until the job times out.
        eprintln!("failpoint could not write its marker {marker}: {e}");
        return;
    }
    loop {
        std::thread::sleep(Duration::from_hours(1));
    }
}

/// How many writes to let through before the failpoint fires.
#[cfg(any(test, feature = "test-utils"))]
pub const HALT_AFTER: &str = "ANT_HALT_AFTER";

/// How many times the failpoint has been reached in this process.
#[cfg(any(test, feature = "test-utils"))]
static HALTS_SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Clears a write's registration when the work finishes, however it finishes.
///
/// Held by the blocking closure rather than by the caller, so a dropped future cannot
/// leave an entry behind, and a panic in the work cannot either.
struct WriteInFlight {
    writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
    finished: Arc<tokio::sync::Notify>,
    address: XorName,
}

impl Drop for WriteInFlight {
    fn drop(&mut self) {
        let was_last = {
            let mut writing = self.writing.lock();
            match writing.get_mut(&self.address) {
                Some(count) if *count > 1 => {
                    *count -= 1;
                    false
                }
                _ => {
                    writing.remove(&self.address);
                    true
                }
            }
        };
        // Only when this was the last one. Waking a waiter while another write for the
        // same key is still queued is exactly what the count exists to prevent.
        if was_last {
            self.finished.notify_waiters();
        }
    }
}

/// What is behind a chunk's name on disk.
///
/// Four answers, not two, because "could not read it" must never be treated as "wrong":
/// replacing a chunk is destructive, and off Unix it truncates the file in place, so a
/// transient fault would turn a healthy sole copy into an empty one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StoredBytes {
    /// The bytes are there and hash to the name.
    Good,
    /// The bytes are there and do not.
    Wrong,
    /// There is nothing behind the name.
    Absent,
    /// The question could not be answered this time.
    Unreadable,
}

/// Convert a byte count to GiB for human-readable log messages.
#[allow(clippy::cast_precision_loss)] // display only — sub-byte precision is irrelevant
fn bytes_to_gib(bytes: u64) -> f64 {
    bytes as f64 / (1024.0 * 1024.0 * 1024.0)
}

/// Most chunks that may be waiting for a corruption recheck at once, counting the one
/// being rechecked.
///
/// Enough for everything a single round-1 proof can report: a proof covers at most
/// `max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT)` leaves, the square root of the largest
/// legal commitment rounded up to a power of two. That function is not `const`, so a test
/// checks this stays at least that large. A key reported while this is full is dropped
/// rather than waited for: it is still on disk and still committed, so the next audit
/// that reads it reports it again.
const MAX_CORRUPT_REPORTS: usize = 1024;

/// Chunks found not to hash to their address, waiting for
/// [`ChunkStore::run_corrupt_rechecks`].
#[derive(Debug, Default)]
struct CorruptReports {
    /// Waiting to be rechecked, oldest first.
    waiting: VecDeque<XorName>,
    /// Everything in `waiting` plus the key being rechecked now, so a chunk reported again
    /// before its recheck has finished is not queued twice.
    queued: HashSet<XorName>,
}

impl CorruptReports {
    /// Queue each key not already queued or being rechecked, while there is room.
    ///
    /// Returns how many were queued, and how many were dropped for want of room.
    fn add(&mut self, keys: &[XorName]) -> (usize, usize) {
        let mut added = 0;
        let mut dropped = 0;
        for key in keys {
            if self.queued.contains(key) {
                continue;
            }
            if self.queued.len() >= MAX_CORRUPT_REPORTS {
                dropped += 1;
                continue;
            }
            self.queued.insert(*key);
            self.waiting.push_back(*key);
            added += 1;
        }
        (added, dropped)
    }
}

/// Content-addressed store holding one immutable file per chunk.
///
/// The filesystem is the sole authority. The in-memory index is a cache of what the
/// directory tree already contains, rebuilt from directory entries at every open, and
/// every mutation of it mirrors a filesystem operation that has *already* completed.
/// Bitcask's issue #114 is the cautionary tale for the opposite order: an index that is
/// rebuilt at startup and then mutated in anticipation drifts, and the drift is silent.
#[derive(Debug)]
pub struct ChunkStore {
    /// Store configuration.
    config: ChunkStoreConfig,
    /// `{root_dir}/chunks`.
    chunks_dir: PathBuf,
    /// Every address whose file is published, in ascending order.
    ///
    /// `BTreeSet` rather than a hash set because `all_keys()` must be sorted (the
    /// commitment builder truncates with `take(cap)` *before* the Merkle tree sorts, so
    /// an unstable order would make the node's published commitment depend on iteration
    /// luck), and because it never spikes memory while growing.
    index: Arc<parking_lot::RwLock<BTreeSet<XorName>>>,
    /// One mutex per shard, serialising writers of the same address.
    ///
    /// `put` must be exactly-once, so the duplicate test and the publish have to be one
    /// step. Two threads publishing the same address would otherwise both see an absent
    /// file, both rename, and both report "newly stored",
    /// double-counting the chunk. The lane is indexed by the address's LAST byte for the
    /// same reason the shard is: a node's keys share their leading bytes, so lanes keyed
    /// on the first byte would all collapse into one.
    write_lanes: Arc<Vec<parking_lot::Mutex<()>>>,

    /// One lock per shard, held across a whole logical transition for a key.
    ///
    /// Not the same thing as the write lanes above, which are taken inside a blocking
    /// closure and make one file write atomic. These are held across await points, which is
    /// what the races that matter need: a delete has to exclude a read that is deciding
    /// whether to accept an offered copy, and both span an await. Without it a prune can
    /// remove the file between that read and its answer, and the caller is told the chunk
    /// is already held while the copy that would have replaced it is discarded.
    ///
    /// Indexed by the address's LAST byte, for the reason the shard is: a node's keys share
    /// their leading bytes, so lanes keyed on the first would collapse into one.
    key_locks: Arc<Vec<tokio::sync::Mutex<()>>>,
    /// Operation counters.
    stats: parking_lot::RwLock<StorageStats>,
    /// Which of the 256 shard directories are known to exist, so a steady-state write
    /// does not pay a `create_dir_all` syscall.
    shards_present: Arc<parking_lot::Mutex<[bool; SHARD_COUNT]>>,
    /// Indexed chunks this store currently cannot read.
    ///
    /// Held back from everything the node says it has, while the files themselves are
    /// left alone. See [`Self::mark_suspect`].
    suspect: Arc<parking_lot::RwLock<HashSet<XorName>>>,
    /// Indexed chunks a read has proven do not match their name.
    ///
    /// Separate from the above because they clear differently. Not being able to read a
    /// file is a question a later read answers; bytes that are wrong stay wrong however
    /// often they are read, and only a repair or a removal settles it. A raw read that
    /// does not hash anything must not take a chunk out of this set.
    known_wrong: Arc<parking_lot::RwLock<HashSet<XorName>>>,
    /// Addresses this store is part-way through writing.
    ///
    /// Every mutation registers here before it spawns its blocking work and clears the
    /// entry *inside* that work, so a caller whose future is dropped cannot skip the
    /// clearing while the write itself goes on to land. That is the difference that
    /// matters: the blocking half is not cancelled with the future, so anything the
    /// future was going to do afterwards is not a record of what happened.
    ///
    /// It lets a delete queue behind the exact write it would otherwise race, rather than
    /// behind every write this store has in flight.
    ///
    /// Counted, not a set. Cancellation can release `put`'s key lock while the
    /// blocking half survives, so a second write for the same key can start behind the
    /// first. With one entry between them, whichever finished first would remove it and a
    /// waiter would be told the key is free while the other was still queued.
    writing: Arc<parking_lot::Mutex<HashMap<XorName, usize>>>,
    /// Woken when [`Self::writing`] loses its last entry for a key.
    write_finished: Arc<tokio::sync::Notify>,
    /// Size-aware free-space predicate.
    capacity: Arc<CapacityGuard>,
    /// Monotonic counter that makes temp filenames unique within this store.
    temp_seq: AtomicU64,
    /// Random per-instance discriminator for temp filenames.
    nonce: u32,
    /// Held for the store's lifetime. Startup fails without it.
    ///
    /// Shared rather than owned so the blocking work that depends on it can hold a lease
    /// of its own: that work outlives the future that spawned it, and a cancelled caller
    /// releasing the lock would leave it writing into a directory another process had
    /// just been let into.
    lock: Arc<File>,
    /// Tracks every blocking task, so [`ChunkStore::wait_idle`] can wait for writes that
    /// outlived their awaiting future.
    blocking_tracker: TaskTracker,
    /// Chunks [`Self::report_corrupt`] has queued for the recheck worker.
    corrupt: parking_lot::Mutex<CorruptReports>,
    /// Wakes the recheck worker when a report queues something.
    corrupt_reported: Notify,
    /// Test-only gate read-acquired at the top of the put blocking closure.
    ///
    /// Tests hold the write half to park an in-flight write on the blocking pool, which
    /// is the shape a `select!` losing to a shutdown token leaves behind.
    ///
    /// Compiled under `test-utils` too, unlike the gate below, because the browser devnet
    /// harness parks a real write through it. What that costs a write in a `test-utils`
    /// build is an uncontended read taken on the blocking thread, not an await.
    #[cfg(any(test, feature = "test-utils"))]
    test_put_gate: Arc<parking_lot::RwLock<()>>,
    /// Test-only: what [`Self::disk_space`] reports instead of measuring.
    #[cfg(any(test, feature = "test-utils"))]
    test_disk_space: parking_lot::RwLock<Option<DiskSpace>>,

    /// Test-only: parks a put after it has taken the key's lane and before it registers
    /// itself as in flight.
    ///
    /// Asynchronous, unlike the gate above. That one is taken inside a blocking closure on
    /// its own thread; this one is taken on the runtime, so a synchronous lock here would
    /// block the executor and the test would deadlock instead of observing anything.
    ///
    /// A separate gate from the one above, because that one sits inside the blocking
    /// closure, which is after registration. The window this opens is the one the key lane
    /// exists for: a put that a delete's wait cannot see yet, because there is nothing to
    /// see. Without a hook here, a test cannot tell a delete blocked by the lane from a
    /// delete blocked by the wait, and so cannot show the lane is doing anything.
    #[cfg(test)]
    test_pre_registration_gate: Arc<tokio::sync::RwLock<()>>,

    /// Test-only: how many puts have reached that gate.
    ///
    /// So a test can wait for the put to be parked rather than sleeping and hoping. A sleep
    /// makes the staging a guess, and a guess in a test that is meant to be deterministic
    /// is a flake waiting for a loaded machine.
    #[cfg(test)]
    test_reached_pre_registration: Arc<std::sync::atomic::AtomicU64>,
}

impl ChunkStore {
    /// Open (or create) the store at `{root_dir}/chunks/`.
    ///
    /// Sweeps orphaned temp files, then rebuilds the index from directory entries.
    /// The scan reads names only: it never `stat`s an entry and never reads a chunk.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the directory cannot be created, the layout marker
    /// is unreadable or describes a layout this build does not implement, or the scan
    /// fails.
    pub async fn new(config: ChunkStoreConfig) -> Result<Self> {
        // Deliberately nothing about the old chunk store here. Clearing up after the storage
        // migration happens once, in `NodeBuilder::build`, and only after this constructor
        // has succeeded: what it deletes are directories retirement cleared because every
        // chunk the node kept is in this store, so it may not run until this store is open. Asking here as well would put that
        // decision in front of itself.

        let chunks_dir = config.root_dir.join(CHUNKS_DIR_NAME);
        std::fs::create_dir_all(&chunks_dir).map_err(|e| {
            Error::Storage(format!(
                "Failed to create chunk store directory {}: {e}",
                chunks_dir.display()
            ))
        })?;

        check_path_budget(&chunks_dir);

        let layout = read_or_write_layout(&chunks_dir)?;
        layout.check_supported()?;

        // Startup fails without it, so from here this process is the only one using this
        // directory and an interrupted write can only be its own.
        let lock = acquire_store_lock(&chunks_dir)?;

        let scan_dir = chunks_dir.clone();
        // The scan holds the lease itself. It sweeps interrupted writes on the strength of
        // being alone here, and it runs on a thread that outlives this future: a
        // cancelled startup that released the lock would leave it sweeping a directory
        // another process had just been let into.
        let scan_lease = Arc::clone(&lock);
        // Only the chunk tree. Its scan sweeps interrupted writes under `chunks/`, which
        // covers the layout marker's temporary because that lives there too. Nothing in the
        // node root is this store's to remove.
        let scan = spawn_blocking(move || {
            let _lease = scan_lease;
            scan_store(&scan_dir)
        })
        .await
        .map_err(|e| Error::Storage(format!("Chunk store scan task failed: {e}")))??;

        let ScanResult {
            keys,
            shards_present,
            swept_temps,
            skipped,
        } = scan;

        let key_count = keys.len();
        // Build from a sorted vector: bulk-building packs every B-tree node to its
        // capacity, where repeated `insert` converges on ~68% fill for the same keys.
        let index: BTreeSet<XorName> = keys.into_iter().collect();

        if swept_temps > 0 {
            info!("Chunk store: removed {swept_temps} orphaned temporary file(s) from interrupted writes");
        }
        if skipped > 0 {
            warn!("Chunk store: ignored {skipped} directory entr(ies) that are not chunk files");
        }
        info!(
            "Chunk store open at {} ({key_count} chunks)",
            chunks_dir.display()
        );

        let capacity = Arc::new(CapacityGuard::new(chunks_dir.clone(), config.disk_reserve));

        Ok(Self {
            config,
            chunks_dir,
            index: Arc::new(parking_lot::RwLock::new(index)),
            key_locks: Arc::new(
                std::iter::repeat_with(|| tokio::sync::Mutex::new(()))
                    .take(SHARD_COUNT)
                    .collect(),
            ),
            write_lanes: Arc::new(
                std::iter::repeat_with(|| parking_lot::Mutex::new(()))
                    .take(SHARD_COUNT)
                    .collect(),
            ),
            stats: parking_lot::RwLock::new(StorageStats::default()),
            shards_present: Arc::new(parking_lot::Mutex::new(shards_present)),
            suspect: Arc::new(parking_lot::RwLock::new(HashSet::new())),
            known_wrong: Arc::new(parking_lot::RwLock::new(HashSet::new())),
            writing: Arc::new(parking_lot::Mutex::new(HashMap::new())),
            write_finished: Arc::new(tokio::sync::Notify::new()),
            capacity,
            temp_seq: AtomicU64::new(0),
            nonce: rand::random(),
            lock,
            blocking_tracker: TaskTracker::new(),
            corrupt: parking_lot::Mutex::new(CorruptReports::default()),
            corrupt_reported: Notify::new(),
            #[cfg(any(test, feature = "test-utils"))]
            test_put_gate: Arc::new(parking_lot::RwLock::new(())),
            #[cfg(any(test, feature = "test-utils"))]
            test_disk_space: parking_lot::RwLock::new(None),
            #[cfg(test)]
            test_pre_registration_gate: Arc::new(tokio::sync::RwLock::new(())),
            #[cfg(test)]
            test_reached_pre_registration: Arc::new(std::sync::atomic::AtomicU64::new(0)),
        })
    }

    /// Store a chunk.
    ///
    /// On Unix, publishing is a rename within the destination directory, so the final name
    /// can never appear on partial content: the name *is* the hash, and the content is
    /// fully written and flushed before the name exists. Off Unix there is no rename, for
    /// the reason `publish_in_place` gives (it is compiled only on those platforms, so this
    /// is not a link), and a partial file can wear a real name; that
    /// is why a duplicate is read and compared rather than trusted.
    ///
    /// # Returns
    ///
    /// `true` if the chunk was newly stored, `false` if it was already present.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the content does not hash to `address`, the disk
    /// is too full, or the write fails.
    pub async fn put(&self, address: &XorName, content: &[u8]) -> Result<bool> {
        // The key's whole transition, not just the part that touches the disk. Registering
        // the write is what a delete waits for, and everything before that registration
        // happens outside it: validation, the duplicate read, the capacity reservation. A
        // put that got that far before a delete arrived would otherwise be invisible to the
        // delete's wait, register while the delete was already committed to going ahead,
        // and publish afterwards. The node would then hold a chunk it had decided to prune.
        let _lane = self.key_lock(address).await;
        let computed = crate::client::compute_address(content);
        if computed != *address {
            return Err(Error::Storage(format!(
                "Content address mismatch: expected {}, computed {}",
                hex::encode(address),
                hex::encode(computed)
            )));
        }
        // The read path refuses anything over the ceiling, so writing one would create a
        // file the store could never read back and could never repair.
        if content.len() > MAX_CHUNK_SIZE {
            return Err(Error::Storage(format!(
                "Chunk {} is {} bytes, over the {MAX_CHUNK_SIZE} byte maximum",
                hex::encode(address),
                content.len()
            )));
        }

        // An indexed name is not proof of the bytes under it. The index is built from
        // names, by the startup scan and by a completed publish, and a name can outlive
        // what it points at: off Unix a chunk is created under its final name before its
        // bytes are written, so a crash leaves a short file wearing a real name, and rot
        // leaves a full-length one. Answering "already have it" to the copy that would fix
        // either is how a node discards its own repair and is never offered another.
        //
        // So the bytes decide. Checked before the reservation below, so re-storing a chunk
        // this node already holds stays a no-op on a full disk.
        if self.index.read().contains(address) {
            if let Some(answer) = self.settle_indexed_duplicate(address, content).await {
                return answer;
            }
        }

        let len = content.len() as u64;
        // Reserved after the duplicate test so re-storing an existing chunk stays a
        // harmless no-op on a full disk.
        let reservation = self.capacity.reserve(len)?;

        let shard = self.chunks_dir.join(shard_name(address));
        let final_path = shard.join(hex::encode(address));
        let temp_path = shard.join(self.next_temp_name());
        let payload = content.to_vec();
        let lanes = Arc::clone(&self.write_lanes);
        let index = Arc::clone(&self.index);
        let shards_present = Arc::clone(&self.shards_present);
        let chunks_dir = self.chunks_dir.clone();
        let lane = shard_index(address);
        let key = *address;
        #[cfg(any(test, feature = "test-utils"))]
        let test_put_gate = Arc::clone(&self.test_put_gate);
        // Registered before the work is spawned and cleared by the work itself, so a
        // caller that goes away cannot leave a delete free to race this publish.
        // Test-only: the window between taking the lane and being visible to a delete.
        #[cfg(test)]
        {
            self.test_reached_pre_registration
                .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
            drop(self.test_pre_registration_gate.read().await);
        }
        let in_flight = self.begin_write(address);
        // And the lease, for the same reason the scan holds it: this thread writes into a
        // directory whose exclusivity the lock is what establishes, and it can outlive
        // the last owner of the store.
        let lease = Arc::clone(&self.lock);
        let known_wrong = Arc::clone(&self.known_wrong);
        let suspect = Arc::clone(&self.suspect);

        let outcome = self
            .blocking_tracker
            .spawn_blocking(move || -> Result<PutOutcome> {
                let _in_flight = in_flight;
                let _lease = lease;
                // Test-only: parks here while a test holds the write half.
                #[cfg(any(test, feature = "test-utils"))]
                let _test_put_gate = test_put_gate.read();
                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
                // `mkdir` plus a directory flush are syscalls, so they belong here and
                // not on a runtime worker.
                ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
                let outcome = match publish(&temp_path, &final_path, &payload, &shard) {
                    Ok(outcome) => outcome,
                    Err(PublishFailed { error, left_behind }) => {
                        // A publish that failed can still have left the bytes there: off
                        // Unix the chunk is created under its final name, and if the write
                        // or the flush then fails, the cleanup that removes it can fail
                        // too. Releasing the reservation would hand back a charge for a
                        // file that is on the disk.
                        //
                        // The publish says so rather than this deciding from a later
                        // `is_file`. Asking the filesystem afterwards infers ownership from
                        // a name being occupied, which is true under the store lock and the
                        // shard lane and not true against anything out of band, and this
                        // file spends a lot of its length arguing that a name is not
                        // evidence. A bit set by the code that created the file is.
                        if left_behind {
                            reservation.commit();
                        }
                        return Err(error);
                    }
                };
                // Placed, not yet durable. A failure from here on leaves the bytes on the
                // disk: the chunk is rightly not reported as stored, because a chunk that is
                // not durable must not be reported as stored, but the space is spent
                // all the same. Dropping the reservation would hand that charge back and
                // admit the next write against room that is already gone.
                //
                // Only for a chunk this call published. `Duplicate` means the file was
                // already there and was charged by whoever wrote it, so charging it again
                // here would count one file twice and shrink the store's idea of its own
                // disk on every retry.
                if let Err(e) = flush_publication(&final_path, &shard) {
                    if matches!(outcome, PutOutcome::New) {
                        reservation.commit();
                    }
                    return Err(e);
                }
                // Index inside the lane, and only after the rename has returned. A
                // concurrent delete of the same address therefore cannot interleave
                // between publishing the file and admitting the key.
                //
                // Only for a chunk this call actually published. `Duplicate` says a file
                // already wears the name, and a name is not evidence about the bytes under
                // it: the four-way answer that decides whether they are good, wrong, absent
                // or unreadable runs after the await below, and a caller whose future is
                // dropped never reaches it. Admitting the key here would leave the node
                // claiming, advertising and committing to bytes nothing has read, with no
                // suspect or known-wrong mark to hold it back, and the sharpest case is a
                // name the startup scan deliberately refused because what wears it is a
                // fifo, a socket or a directory. The duplicate arm admits the key itself,
                // once a read has proven the bytes.
                if matches!(outcome, PutOutcome::New) {
                    index.write().insert(key);
                    // With the marks that would otherwise hold the key back. These bytes
                    // were hashed against their own name on the way in, so an older
                    // instance proven wrong or merely unreadable has just been replaced by
                    // a good one. Cleared here rather than after the await for the same
                    // reason the insert is here: a cancelled caller would leave the key
                    // indexed and suppressed at once, so a chunk this node really does hold
                    // would stay hidden from `exists` and `all_keys` until some later read
                    // happened to settle it.
                    known_wrong.write().remove(&key);
                    suspect.write().remove(&key);
                    // Settled here, inside the work, so a dropped awaiter cannot strand it.
                    reservation.commit();
                }
                Ok(outcome)
            })
            .await
            .map_err(|e| Error::Storage(format!("Chunk store put task failed: {e}")))??;

        match outcome {
            PutOutcome::Duplicate => self.settle_duplicate(address, content).await,
            PutOutcome::New => {
                // Freshly published bytes that were checked against their own name on the
                // way in. The marks were already cleared inside the work, where a dropped
                // caller cannot skip them; what is left here is only what a caller who is
                // still waiting should see.
                let mut stats = self.stats.write();
                stats.chunks_stored = stats.chunks_stored.saturating_add(1);
                stats.bytes_stored = stats.bytes_stored.saturating_add(len);
                drop(stats);
                debug!("Stored chunk {} ({len} bytes)", hex::encode(address));
                Ok(true)
            }
        }
    }

    /// Decide what a name that was already taken actually means.
    ///
    /// Split out of [`Self::put`] because it is a different question. `put` puts bytes on
    /// a disk; this reads bytes back to find out whether the ones already there are the
    /// ones the caller is offering, which is the only thing that makes a duplicate safe to
    /// report as stored.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] when the existing file is absent or could not be read,
    /// both of which mean this node must not report the chunk as held.
    async fn settle_duplicate(&self, address: &XorName, content: &[u8]) -> Result<bool> {
        // The file was already on disk, and its name is not evidence its contents
        // are right. The startup scan indexes by name without reading anything,
        // and on Windows a crash mid-write leaves a partial file under a real
        // chunk name. Trusting the name here would acknowledge a chunk that was
        // never stored, and then discard the good copy arriving to repair it.
        // Every answer handled, because three of the four must not report the
        // chunk as stored. A caller that hears success acts on it: a client drops
        // its own copy and replication marks the key held.
        match self.stored_bytes_match(address).await {
            StoredBytes::Good => {
                // Admitted here, which is the first moment the bytes behind the
                // name have been read and shown to hash to it. Idempotent: the
                // ordinary case is a key the startup scan already indexed.
                self.index.write().insert(*address);
                {
                    let mut stats = self.stats.write();
                    stats.duplicates = stats.duplicates.saturating_add(1);
                }
                Ok(false)
            }
            StoredBytes::Wrong => {
                warn!(
                    "Chunk {} was already on disk but its contents are wrong; \
                     replacing it with the copy just offered",
                    hex::encode(address)
                );
                self.repair_holding_the_lane(address, content)
                    .await
                    .map(|()| true)
            }
            // The name was taken a moment ago and is not now, or was never a
            // readable chunk file. Either way nothing holds these bytes, so say so
            // rather than reporting a chunk that is not there.
            StoredBytes::Absent => Err(Error::Storage(format!(
                "Chunk {} was reported already on disk but nothing is there. Not \
                 reporting it as stored.",
                hex::encode(address)
            ))),
            // Replacing on an unanswered question would destroy a healthy copy,
            // and reporting success would discard the offered one. The index entry
            // stays: the file is still there, and dropping the entry would leave
            // a chunk on disk that this store no longer answers for. Removing an
            // entry is the quarantine path's
            // job, and it removes the file with it, after a read that succeeded
            // and proved the bytes wrong.
            StoredBytes::Unreadable => Err(Error::Storage(format!(
                "Chunk {} is on disk but could not be read to check it. Not \
                 replacing it, and not reporting it as stored.",
                hex::encode(address)
            ))),
        }
    }

    /// Take the critical section for one key.
    ///
    /// Held across await points, unlike the write lanes, so a whole logical transition for
    /// a key excludes another. `None` only if the table were empty, which it is not.
    async fn key_lock(&self, address: &XorName) -> Option<tokio::sync::MutexGuard<'_, ()>> {
        let lane = address.last().copied().unwrap_or(0) as usize;
        match self.key_locks.get(lane) {
            Some(lock) => Some(lock.lock().await),
            None => None,
        }
    }

    /// The address content hashes to.
    ///
    /// A convenience the old facade offered and callers still use, so it stays with the
    /// store rather than making every one of them reach for the client module.
    #[must_use]
    pub fn compute_address(content: &[u8]) -> XorName {
        crate::client::compute_address(content)
    }

    /// Does this store already hold exactly these bytes under this address?
    ///
    /// Asked by the protocol handler before it accepts a client's PUT, so the answer has
    /// to be about the bytes and not about the name. A name on disk is not evidence: the
    /// startup scan indexes by name without reading anything, and a partial file can wear a
    /// real chunk name. Answering yes on a name would acknowledge a chunk that was never
    /// stored and then discard the good copy that had just arrived to replace it.
    ///
    /// A chunk that is on disk with the wrong bytes is repaired from what the caller
    /// offered rather than turned away, because the caller has already checked those bytes
    /// against the address. A chunk that cannot be read this time is not claimed as held
    /// and not replaced either: the offer goes through the ordinary write path instead,
    /// which never truncates a healthy file on the strength of an unanswered question.
    pub async fn holds_verified(&self, address: &XorName, content: &[u8]) -> bool {
        // The key's critical section for the whole check, so the answer is a linearizable
        // statement about the store: at the moment this returns, the chunk was held and its
        // bytes were these.
        //
        // It does not follow the answer out to the caller. The handler turns a `true` into
        // an `AlreadyExists` and sends it afterwards, outside this lock, so a prune landing
        // in between still means a peer is told to drop a copy of a chunk this node no
        // longer has. Closing that would mean holding a per-key lock across a network
        // response, which trades a narrow window for a much worse one. Replication finds
        // the key missing and re-offers it.
        let _lane = self.key_lock(address).await;

        if !self.is_indexed(address) {
            return false;
        }
        // No cheap length pre-check. `metadata` failing is not the same as a length that
        // does not match, and off Unix replacing a chunk truncates it in place, so acting
        // on an unanswered question would empty a healthy sole copy. The read below
        // distinguishes them.
        match self.get_raw(address).await {
            // Byte-for-byte what the caller has, and the caller checked those bytes against
            // the address before getting here. Nothing is wrong with this file.
            Ok(Some(stored)) if stored == content => {
                self.note_bytes_proven_good(address);
                true
            }
            Ok(_) => {
                warn!(
                    "Chunk {} is on disk but its contents are wrong; replacing it with the \
                     copy just offered",
                    hex::encode(address)
                );
                // Recorded before the repair is attempted, not after it succeeds. A repair
                // can fail for capacity or I/O, and a chunk proven wrong that goes on
                // looking healthy is one the node keeps answering for.
                self.note_known_wrong(address);
                self.repair_holding_the_lane(address, content).await.is_ok()
            }
            // Unanswerable this time. Not claimed as held, so the offer goes through the
            // ordinary path, which writes it rather than replacing anything.
            Err(_) => false,
        }
    }

    /// Decide what to do about a write of a chunk the index already names.
    ///
    /// `None` means the index was wrong and there is nothing on disk, so the caller
    /// publishes it as new. Everything else is the answer.
    async fn settle_indexed_duplicate(
        &self,
        address: &XorName,
        content: &[u8],
    ) -> Option<Result<bool>> {
        match self.stored_bytes_match(address).await {
            StoredBytes::Good => {
                trace!("Chunk {} already exists", hex::encode(address));
                {
                    let mut stats = self.stats.write();
                    stats.duplicates = stats.duplicates.saturating_add(1);
                }
                Some(Ok(false))
            }
            StoredBytes::Wrong => {
                warn!(
                    "Chunk {} is indexed but its bytes are wrong; replacing it with the \
                     copy just offered",
                    hex::encode(address)
                );
                Some(
                    self.repair_holding_the_lane(address, content)
                        .await
                        .map(|()| true),
                )
            }
            // Indexed but gone: publish it fresh rather than replacing something that is
            // not there.
            StoredBytes::Absent => None,
            // Unanswerable this time. Do not touch what is there, and do not tell the
            // caller the chunk is safely stored either: a client would take that as an
            // acknowledgement and drop the only other copy. The index entry stays, for
            // the reason given on the same case after publication.
            StoredBytes::Unreadable => Some(Err(Error::Storage(format!(
                "Chunk {} is indexed but could not be read to check it. Not replacing it, \
                 and not reporting it as stored.",
                hex::encode(address)
            )))),
        }
    }

    /// Whether the file already stored under `address` really hashes to it.
    async fn stored_bytes_match(&self, address: &XorName) -> StoredBytes {
        match self.get_raw(address).await {
            Ok(Some(bytes)) if crate::client::compute_address(&bytes) == *address => {
                // A read that hashed. It settles both questions.
                self.clear_suspect(address);
                self.clear_known_wrong(address);
                StoredBytes::Good
            }
            Ok(Some(_)) => {
                self.mark_known_wrong(address);
                StoredBytes::Wrong
            }
            Ok(None) => StoredBytes::Absent,
            // NOT the same as wrong. A file that could not be read this once may be
            // perfectly good, and off Unix replacing it means opening it with `truncate`,
            // which would destroy a healthy sole copy on the strength of a transient
            // fault. Say so and let the caller leave it alone.
            Err(e) => {
                debug!("Could not read {} to check it: {e}", hex::encode(address));
                self.mark_suspect(address);
                StoredBytes::Unreadable
            }
        }
    }

    /// Replace the file behind an address with bytes that hash to it.
    ///
    /// Unlike [`Self::put`], this deliberately publishes **over** an existing name, for
    /// repairing a file whose bytes no longer hash to their own. Doing it as
    /// delete-then-put would leave a window with no copy at all.
    ///
    /// **Only call this once a read has shown the existing bytes are wrong.** On Unix the
    /// replacement is atomic and a failure leaves the old file untouched. Off Unix it is
    /// not: there is no durable rename there, so the existing file is truncated and
    /// rewritten in place, and a crash part-way leaves a mixture. That is tolerable when
    /// the bytes being replaced were already known to be wrong, and is data loss when they
    /// were not. Nothing enforces the precondition, which is why it is stated here.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if `content` does not hash to `address`, or the write
    /// fails.
    pub async fn repair(&self, address: &XorName, content: &[u8]) -> Result<()> {
        let _lane = self.key_lock(address).await;
        self.repair_holding_the_lane(address, content).await
    }

    /// The body of [`Self::repair`], for callers that already hold the key's lane.
    ///
    /// Split because the lane is a `tokio::sync::Mutex` and so is not reentrant: every
    /// internal caller reaches this while holding it, and taking it again would deadlock
    /// the task on itself.
    async fn repair_holding_the_lane(&self, address: &XorName, content: &[u8]) -> Result<()> {
        // The same ceiling `put` enforces. Without it a repair can install bytes the read
        // path will refuse for ever, which is a chunk that verifies as present and can
        // never be served.
        if content.len() > MAX_CHUNK_SIZE {
            return Err(Error::Storage(format!(
                "Refusing to repair {} with {} bytes, over the {MAX_CHUNK_SIZE} byte \
                 maximum",
                hex::encode(address),
                content.len()
            )));
        }
        let computed = crate::client::compute_address(content);
        if computed != *address {
            return Err(Error::Storage(format!(
                "Refusing to repair {} with content that hashes to {}",
                hex::encode(address),
                hex::encode(computed)
            )));
        }
        // The replacement exists alongside the original until the rename, so the room for
        // it has to be there first. Reserved rather than merely checked: a plain check
        // passes against a cached measurement, so concurrent repairs and PUTs can each be
        // admitted against the same headroom and cross the reserve together.
        // Moved into the work below, so it is released when the write finishes rather
        // than when its caller stops waiting. A caller that goes away otherwise frees
        // room that the detached write is still about to consume.
        let reservation = self.capacity.reserve(content.len() as u64)?;

        let shard = self.chunks_dir.join(shard_name(address));
        let final_path = shard.join(hex::encode(address));
        let temp_path = shard.join(self.next_temp_name());
        let payload = content.to_vec();
        let lanes = Arc::clone(&self.write_lanes);
        let index = Arc::clone(&self.index);
        let shards_present = Arc::clone(&self.shards_present);
        let chunks_dir = self.chunks_dir.clone();
        let lane = shard_index(address);
        let key = *address;
        let in_flight = self.begin_write(address);
        let lease = Arc::clone(&self.lock);
        let capacity = Arc::clone(&self.capacity);
        let suspect = Arc::clone(&self.suspect);
        let known_wrong = Arc::clone(&self.known_wrong);

        self.blocking_tracker
            .spawn_blocking(move || -> Result<()> {
                let _in_flight = in_flight;
                let _lease = lease;
                let _reservation = reservation;
                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
                ensure_shard_dir(&chunks_dir, &shard, lane, &shards_present)?;
                write_and_replace(&temp_path, &final_path, &payload, &shard)?;
                index.write().insert(key);
                // Settled here rather than after the await. The replacement has landed
                // and hashes to its own name, so nothing is wrong with this chunk any
                // more; a caller that stopped waiting would otherwise leave a healthy
                // file excluded from everything the node claims to hold, and the
                // measurement believing the store is a chunk smaller than it is.
                suspect.write().remove(&key);
                known_wrong.write().remove(&key);
                capacity.invalidate();
                Ok(())
            })
            .await
            .map_err(|e| Error::Storage(format!("Chunk store repair task failed: {e}")))??;

        // Everything the success means was recorded by the work that succeeded: the
        // reservation released, the marks cleared, the measurement thrown away. Released
        // rather than committed because a repair is not a new chunk, and the measurement
        // discarded rather than adjusted because the file it replaced may have been
        // shorter, which is exactly the case a repair fixes.
        debug!("Repaired chunk {}", hex::encode(address));
        Ok(())
    }

    /// Retrieve a chunk, verifying it against its address when configured to.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] on an I/O failure, or when verification fails. A
    /// chunk whose bytes do not hash to its name is removed and dropped from the index
    /// before the error is returned, so it leaves `all_keys()` and ordinary replication
    /// repairs it.
    pub async fn get(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
        let Some(content) = self.read_file(address).await? else {
            trace!("Chunk {} not found", hex::encode(address));
            return Ok(None);
        };

        if self.config.verify_on_read {
            let computed = crate::client::compute_address(&content);
            if computed != *address {
                {
                    let mut stats = self.stats.write();
                    stats.verification_failures = stats.verification_failures.saturating_add(1);
                }
                warn!(
                    "Chunk verification failed: expected {}, computed {}",
                    hex::encode(address),
                    hex::encode(computed)
                );
                // Said before it is acted on. Removing the file can fail or be cancelled,
                // and a chunk proven wrong that goes on looking healthy is one the node
                // keeps committing to and keeps being audited for.
                self.mark_known_wrong(address);
                self.quarantine_corrupt(address).await;
                return Err(Error::Storage(format!(
                    "Chunk verification failed for {}",
                    hex::encode(address)
                )));
            }
        }

        if self.config.verify_on_read {
            // The bytes hashed to their name. Whatever this store thought was wrong with
            // them is not wrong with them, and a mark that outlives the fault it
            // describes means the node can serve a chunk it will not claim, commit or
            // offer.
            self.clear_known_wrong(address);
        }

        let len = content.len() as u64;
        {
            let mut stats = self.stats.write();
            stats.chunks_retrieved = stats.chunks_retrieved.saturating_add(1);
            stats.bytes_retrieved = stats.bytes_retrieved.saturating_add(len);
        }
        debug!("Retrieved chunk {} ({len} bytes)", hex::encode(address));
        Ok(Some(content))
    }

    /// Retrieve raw chunk bytes without content-address verification.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] on an I/O failure.
    pub async fn get_raw(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
        self.read_file(address).await
    }

    /// Queue keys whose raw bytes were found not to hash to them, for
    /// [`Self::run_corrupt_rechecks`] to take out of service.
    ///
    /// [`Self::get_raw`] does not verify, and it is the read that answers audits, so a
    /// rotted or torn file is never noticed there: the node goes on committing the key
    /// and failing every audit that lands on it, and only a fetch of that exact key
    /// would ever repair it. A caller that has hashed raw bytes anyway and found them
    /// wrong reports the key here.
    ///
    /// Never waits. Rechecking here instead would let every audit that reads a rotted
    /// chunk start a recheck of its own, outside every responder limit, and while a
    /// quarantine waits on its shard's write lane each of those would hold a blocking
    /// thread. A key already queued or being rechecked is not queued again, and one that
    /// does not fit under [`MAX_CORRUPT_REPORTS`] is dropped.
    pub(crate) fn report_corrupt(&self, keys: &[XorName]) {
        let (added, dropped) = self.corrupt.lock().add(keys);
        if added > 0 {
            self.corrupt_reported.notify_one();
        }
        if dropped > 0 {
            warn!(
                "{dropped} chunk(s) found rotted were not queued for a recheck, because \
                 {MAX_CORRUPT_REPORTS} already are; the next audit that reads them will \
                 report them again"
            );
        }
    }

    /// Take the keys [`Self::report_corrupt`] queued out of service, one at a time and
    /// oldest first, until `stop` is cancelled.
    ///
    /// The node runs exactly one of these, on the replication engine, so however many
    /// audits report rot, and however long a quarantine waits for its shard's write lane,
    /// the rechecks hold at most one blocking thread between them. `stop` is raced only
    /// against waiting for work, never against a recheck: the verifying read settles a
    /// chunk's marks only after its quarantine attempt reports back, so a recheck dropped
    /// part-way could leave a chunk held out of service that a repair put right between
    /// the failing read and the mark. Keys still queued when it stops are left there: each is
    /// still on disk and still committed, so after a restart the next audit that reads it
    /// reports it again.
    pub(crate) async fn run_corrupt_rechecks(&self, stop: &CancellationToken) {
        // A worker stopped part-way through a recheck leaves that key marked as queued
        // with nothing left to finish it; clear it so the key can be reported again.
        {
            let mut reports = self.corrupt.lock();
            reports.queued = reports.waiting.iter().copied().collect();
        }
        loop {
            if stop.is_cancelled() {
                return;
            }
            let next = self.corrupt.lock().waiting.pop_front();
            let Some(key) = next else {
                tokio::select! {
                    biased;
                    () = stop.cancelled() => return,
                    () = self.corrupt_reported.notified() => {}
                }
                continue;
            };
            self.recheck_corrupt(&key).await;
            self.corrupt.lock().queued.remove(&key);
        }
    }

    /// Take a key out of service if its bytes really do not hash to it.
    ///
    /// The verifying read does this exactly as it does for a fetch: it re-reads the file
    /// under the write lane, removes it only if it is still wrong, and stops the node
    /// claiming the key, so its next commitment leaves it out and replication brings a
    /// good copy back.
    ///
    /// Follows the node's `verify_on_read` setting, like every other verifying read.
    async fn recheck_corrupt(&self, address: &XorName) {
        match self.get(address).await {
            Ok(Some(_)) => debug!("Chunk {} reads back intact", hex::encode(address)),
            Ok(None) => debug!("Chunk {} is no longer stored", hex::encode(address)),
            Err(e) => debug!(
                "Chunk {} taken out of service after a failed check: {e}",
                hex::encode(address)
            ),
        }
    }

    /// Check whether a chunk is stored.
    ///
    /// An in-memory lookup: no syscall, no I/O.
    ///
    /// # Errors
    ///
    /// Never fails. It returns a `Result` because callers treat an error as "assume
    /// absent".
    pub fn exists(&self, address: &XorName) -> Result<bool> {
        if self.is_unservable(address) {
            return Ok(false);
        }
        Ok(self.is_indexed(address))
    }

    /// Is this chunk one the node must not answer for?
    #[must_use]
    fn is_unservable(&self, address: &XorName) -> bool {
        self.suspect.read().contains(address) || self.known_wrong.read().contains(address)
    }

    /// Is this chunk in the index, whether or not it can currently be read?
    ///
    /// The physical question, as against [`Self::exists`]'s question about what the node
    /// is willing to claim.
    #[must_use]
    pub fn is_indexed(&self, address: &XorName) -> bool {
        self.index.read().contains(address)
    }

    /// Delete a chunk, returning whether it was present.
    ///
    /// `unlink` returns the blocks to the filesystem immediately. That is the whole
    /// point of this store: no free list, no compaction, no free space required to
    /// reclaim space.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the file exists but cannot be removed. The index
    /// keeps the key in that case, because the bytes are still on disk.
    pub async fn delete(&self, address: &XorName) -> Result<bool> {
        // The key's whole critical section, held across the wait below and the unlink.
        let _lane = self.key_lock(address).await;
        // Behind whatever is already writing this key, and only this key. A write's
        // blocking half outlives the future that started it, so one landing after this
        // would put back a chunk the node had decided to prune, and the next thing to look
        // would find it in a store that no longer claims it.
        self.wait_for_write(address).await;

        let path = self.chunk_path(address);
        let lanes = Arc::clone(&self.write_lanes);
        let index = Arc::clone(&self.index);
        let lane = shard_index(address);
        let key = *address;
        // Carried into the closure for the reason `put`, `repair` and the startup scan
        // carry it: this work outlives the future that started it, so a cancelled caller
        // that drops the last `ChunkStore` would otherwise release the directory to another
        // process while an unlink is still queued against it. Deleting is the operation
        // where that matters most.
        let lease = Arc::clone(&self.lock);

        let (existed, freed) = self
            .blocking_tracker
            .spawn_blocking(move || -> Result<(bool, u64)> {
                let _lease = lease;
                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
                let len = std::fs::metadata(&path).map_or(0, |m| m.len());
                let removed = match std::fs::remove_file(&path) {
                    Ok(()) => {
                        // Without this a crash can resurrect the entry on ext4, XFS,
                        // btrfs and APFS: the unlink is in the page cache, the directory
                        // is not.
                        if let Some(shard) = path.parent() {
                            fsync_dir_best_effort(shard);
                        }
                        true
                    }
                    // Already gone: the index was stale. Still a successful delete as
                    // far as the caller is concerned.
                    Err(e) if e.kind() == ErrorKind::NotFound => false,
                    Err(e) => {
                        return Err(Error::Storage(format!(
                            "Failed to delete chunk file {}: {e}",
                            path.display()
                        )))
                    }
                };
                // Index only after the filesystem operation has succeeded. On the error
                // path above the entry stays, because the bytes are still on disk.
                let was_indexed = index.write().remove(&key);
                Ok((removed || was_indexed, if removed { len } else { 0 }))
            })
            .await
            .map_err(|e| Error::Storage(format!("Chunk store delete task failed: {e}")))??;

        if freed > 0 {
            self.capacity.record_removed(freed);
            debug!("Deleted chunk {}", hex::encode(address));
        }
        Ok(existed)
    }

    /// Return every stored key, in ascending order.
    ///
    /// The order is a correctness requirement, not a convenience: the commitment
    /// builder truncates the responsible subset with `take(cap)` before the Merkle tree
    /// sorts it, so an unstable order would make the node's published commitment depend
    /// on iteration luck.
    ///
    /// # Errors
    ///
    /// Never fails. It returns a `Result` for callers that treat an error as absent.
    // Async without awaiting anything, deliberately: the whole point of this store is
    // that the key set is already in memory. Callers are spread across the replication
    // engine and cannot all be de-async'd in this change.
    //
    // Two lint names because they were renamed between toolchains, and `unknown_lints`
    // so whichever one the compiler in use has never heard of stays quiet.
    #[allow(unknown_lints)]
    #[allow(clippy::unused_async, clippy::unused_async_trait_impl)]
    pub async fn all_keys(&self) -> Result<Vec<XorName>> {
        // Copied out first so neither lock is held while the other is taken, and so the
        // usual case, where nothing is suspect, costs one clone of an empty set.
        let mut unservable: HashSet<XorName> = self.suspect.read().clone();
        unservable.extend(self.known_wrong.read().iter().copied());
        let keys = self.index.read().clone();
        if unservable.is_empty() {
            return Ok(keys.into_iter().collect());
        }
        Ok(keys
            .into_iter()
            .filter(|key| !unservable.contains(key))
            .collect())
    }

    /// Stop answering for a chunk this store could not read.
    ///
    /// The file stays. It may be perfectly good and unreadable only for the moment, and
    /// deleting it, or dropping it from the index, would lose it.
    ///
    /// What does change is what the node says about it. A chunk it cannot read is one it
    /// cannot serve, and claiming it anyway puts the key in signed commitments, answers
    /// presence probes with a yes, suppresses the replication that would repair it, and
    /// earns a penalty at the next commitment-bound audit.
    fn mark_suspect(&self, address: &XorName) {
        if self.suspect.write().insert(*address) {
            warn!(
                "Chunk {} is on disk but could not be read; this node stops answering for \
                 it until a read succeeds",
                hex::encode(address)
            );
        }
    }

    /// Stop answering for a chunk a read has proven wrong.
    ///
    /// Unlike a chunk that merely could not be read, a later read does not clear this.
    /// The bytes are wrong, and reading them again says the same thing; only replacing
    /// them or removing them settles it.
    ///
    /// For callers outside this module that have proven it themselves.
    pub fn note_known_wrong(&self, address: &XorName) {
        self.mark_known_wrong(address);
    }

    /// Stop answering for a chunk a read has proven wrong.
    fn mark_known_wrong(&self, address: &XorName) {
        if self.known_wrong.write().insert(*address) {
            warn!(
                "Chunk {} does not match its name; this node stops answering for it until \
                 it is repaired or removed",
                hex::encode(address)
            );
        }
    }

    /// A caller outside this module has proven the stored bytes are right.
    pub fn note_bytes_proven_good(&self, address: &XorName) {
        self.clear_known_wrong(address);
        self.clear_suspect(address);
    }

    /// Answer for a chunk again, after it has been replaced or removed.
    fn clear_known_wrong(&self, address: &XorName) {
        self.known_wrong.write().remove(address);
    }

    /// Answer for a chunk again, after a read that worked.
    fn clear_suspect(&self, address: &XorName) {
        if !self.suspect.read().contains(address) {
            return;
        }
        if self.suspect.write().remove(address) {
            info!(
                "Chunk {} could be read again; this node answers for it once more",
                hex::encode(address)
            );
        }
    }

    /// Number of chunks currently stored.
    ///
    /// The physical count: every name in the index, including chunks the node has stopped
    /// answering for because a read found them wrong or could not read them at all. It is
    /// deliberately not the same number as `all_keys().len()`, which is what the node is
    /// willing to claim and so leaves those out.
    ///
    /// Anything asking "how much is on this disk" wants this one, and that is what its
    /// callers ask: the storage stats, the quoting metrics, and the size an audit is built
    /// for. Anything asking "what will this node answer for" wants `all_keys`. Quietly
    /// filtering this one would move all three of those without saying so, which is why the difference is written down
    /// here rather than removed.
    ///
    /// # Errors
    ///
    /// Never fails. It returns a `Result` for callers that treat an error as absent.
    pub fn current_chunks(&self) -> Result<u64> {
        Ok(self.index.read().len() as u64)
    }

    /// Operation statistics, with the live chunk count filled in.
    #[must_use]
    pub fn stats(&self) -> StorageStats {
        let mut stats = self.stats.read().clone();
        stats.current_chunks = self.index.read().len() as u64;
        stats
    }

    /// The node root directory this store was configured with.
    #[must_use]
    pub fn root_dir(&self) -> &Path {
        &self.config.root_dir
    }

    /// The directory holding the shard tree.
    #[must_use]
    pub fn chunks_dir(&self) -> &Path {
        &self.chunks_dir
    }

    /// Free and total bytes on the partition holding this store, or `None` if
    /// the filesystem could not say.
    ///
    /// The pointer store keeps its files on this partition too, so this is the
    /// one measurement both record kinds' retention decides by (ADR-0028).
    #[must_use]
    pub fn disk_space(&self) -> Option<DiskSpace> {
        #[cfg(any(test, feature = "test-utils"))]
        {
            let reported = *self.test_disk_space.read();
            if reported.is_some() {
                return reported;
            }
        }
        let available = match self.capacity.measure_available() {
            Ok(available) => available,
            Err(e) => {
                warn!("Cannot measure free space, so nothing is erased: {e}");
                return None;
            }
        };
        let total = self.usable_disk_total()?;
        Some(DiskSpace { available, total })
    }

    /// [`DiskSpace::total`] for this store's partition.
    fn usable_disk_total(&self) -> Option<u64> {
        let measured = || -> std::io::Result<u64> {
            let total = fs2::total_space(&self.chunks_dir)?;
            let free = fs2::free_space(&self.chunks_dir)?;
            let available = fs2::available_space(&self.chunks_dir)?;
            Ok(total.saturating_sub(free.saturating_sub(available)))
        };
        match measured() {
            Ok(total) => Some(total),
            Err(e) => {
                warn!("Cannot measure the record store's partition, so nothing is erased: {e}");
                None
            }
        }
    }

    /// Free bytes this store keeps unused: below them it refuses writes.
    #[must_use]
    pub fn disk_reserve(&self) -> u64 {
        self.capacity.reserve
    }

    /// Reject work early when the disk cannot take another chunk at all.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] when free space is below the configured reserve.
    pub fn check_capacity(&self) -> Result<()> {
        self.capacity.check(0)
    }

    /// Three-way answer to "can this store take a write right now".
    ///
    /// Kept distinct from [`Self::check_capacity`] because a failed free-space query and a
    /// genuinely full disk are not the same thing, and the replication verification cycle
    /// depends on the difference: a full disk is a standing condition worth minutes of
    /// backoff, while a `statvfs` that failed says nothing about available space and may
    /// well succeed on the next pass.
    #[must_use]
    pub fn capacity_verdict(&self) -> crate::storage::CapacityVerdict {
        match self.capacity.measure_available() {
            Ok(available) if available < self.capacity.reserve => {
                crate::storage::CapacityVerdict::Full
            }
            Ok(_) => crate::storage::CapacityVerdict::Writable,
            Err(_) => crate::storage::CapacityVerdict::Unknown,
        }
    }

    /// Reject work early when the disk cannot take `bytes` more.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] when the write would not fit above the reserve.
    pub fn check_capacity_for(&self, bytes: u64) -> Result<()> {
        self.capacity.check(bytes)
    }

    /// Charge `bytes` against the disk before writing them, releasing the charge if the
    /// write does not happen.
    ///
    /// For the pointer store, which keeps its own files on this disk. Checking capacity
    /// and then writing is a race [`CapacityGuard::reserve`] exists to close: concurrent
    /// writers all pass one cached measurement and cross the reserve together.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the disk cannot take `bytes` more.
    pub(crate) fn reserve(&self, bytes: u64) -> Result<Reservation> {
        self.capacity.reserve(bytes)
    }

    /// Credit `bytes` deleted from the pointer store back to the disk budget.
    ///
    /// The counterpart of [`Self::reserve`]: a record the pointer store removes
    /// gives its charge back, as a deleted chunk does.
    pub(crate) fn release(&self, bytes: u64) {
        self.capacity.record_removed(bytes);
    }

    /// `(written_since, in_flight)` from the capacity guard. Tests only: it is
    /// how a released charge is told apart from a stranded one.
    #[cfg(test)]
    pub(crate) fn capacity_counters(&self) -> (u64, u64) {
        self.capacity.counters()
    }

    /// What a payload of `bytes` actually costs the disk, rounded to the
    /// allocation unit. Tests only, so they can assert exact counter deltas
    /// rather than "it went up" — which a charge of one allocation unit would
    /// satisfy for several payloads at once.
    #[cfg(test)]
    pub(crate) fn capacity_charge_for(bytes: u64) -> u64 {
        CapacityGuard::charge(bytes)
    }

    /// Test-only: make [`Self::disk_space`] report `space` instead of measuring
    /// the partition, or measure it again with `None`.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn set_test_disk_space(&self, space: Option<DiskSpace>) {
        *self.test_disk_space.write() = space;
    }

    /// Test-only handle to the put gate.
    ///
    /// Hold the write half to park the next write inside its blocking closure, for
    /// example to prove that shutdown waits for a write whose awaiter was dropped.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub fn test_put_gate(&self) -> Arc<parking_lot::RwLock<()>> {
        Arc::clone(&self.test_put_gate)
    }

    /// Test-only handle to the gate that parks a put before it registers itself.
    #[cfg(test)]
    fn test_pre_registration_gate(&self) -> Arc<tokio::sync::RwLock<()>> {
        Arc::clone(&self.test_pre_registration_gate)
    }

    /// Test-only: how many puts have reached the pre-registration gate.
    #[cfg(test)]
    fn test_reached_pre_registration(&self) -> u64 {
        self.test_reached_pre_registration
            .load(std::sync::atomic::Ordering::Acquire)
    }

    /// Test-only handle to the write lanes, and the index of the one `address` is
    /// written, repaired and quarantined under.
    ///
    /// Holding that lane stalls every write, repair and quarantine in the shard the way a
    /// hung disk would. [`Self::test_put_gate`] cannot stand in for it: a put parks there
    /// before it takes its lane.
    #[cfg(test)]
    pub(crate) fn test_write_lane(
        &self,
        address: &XorName,
    ) -> (Arc<Vec<parking_lot::Mutex<()>>>, usize) {
        (Arc::clone(&self.write_lanes), shard_index(address))
    }

    /// Test-only path of the file a chunk is (or would be) stored in, so tests
    /// can damage or remove it without re-deriving the store's layout.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub fn test_chunk_path(&self, address: &XorName) -> PathBuf {
        self.chunk_path(address)
    }

    /// Register a write of `address` and hand back the token that clears it.
    ///
    /// The token must be moved into the blocking closure that does the work, so the entry
    /// is cleared by the thread that finishes rather than by a caller that may be gone.
    fn begin_write(&self, address: &XorName) -> WriteInFlight {
        *self.writing.lock().entry(*address).or_insert(0) += 1;
        WriteInFlight {
            writing: Arc::clone(&self.writing),
            finished: Arc::clone(&self.write_finished),
            address: *address,
        }
    }

    /// Wait until nothing is part-way through writing `address`.
    ///
    /// For callers that must be last: a delete whose key still has a write in flight
    /// would be undone by that write landing afterwards.
    pub async fn wait_for_write(&self, address: &XorName) {
        loop {
            // Registered before the check, so a clear between the two is not missed.
            let waiting = self.write_finished.notified();
            if !self.writing.lock().contains_key(address) {
                return;
            }
            waiting.await;
        }
    }

    /// How many blocking tasks this store currently has in flight. Tests only.
    ///
    /// Lets a test wait for work to have actually started rather than guessing at a
    /// delay, which is the difference between a test that proves something and one that
    /// passes because the machine was quick.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub(crate) fn tasks_in_flight(&self) -> usize {
        self.blocking_tracker.len()
    }

    /// Test-only count of running or queued blocking operations, for harnesses outside
    /// this crate.
    #[cfg(any(test, feature = "test-utils"))]
    #[must_use]
    pub fn test_file_tasks_in_flight(&self) -> usize {
        self.tasks_in_flight()
    }

    /// Wait until every blocking task this store spawned has finished.
    ///
    /// Dropping the awaiting future does not cancel a `spawn_blocking` closure, so
    /// shutdown has to wait for the closure itself.
    pub async fn wait_idle(&self) {
        self.blocking_tracker.close();
        self.blocking_tracker.wait().await;
        self.blocking_tracker.reopen();
    }

    /// Absolute path of a chunk file.
    fn chunk_path(&self, address: &XorName) -> PathBuf {
        self.chunks_dir
            .join(shard_name(address))
            .join(hex::encode(address))
    }

    /// A temp name unique to this store instance, and distinguishable from a chunk name.
    ///
    /// The nonce matters: two `ChunkStore`s on one root in one process share a PID, and a
    /// recycled PID collides with an age-gated leftover. Either way `create_new` would
    /// fail and surface as a spurious write error.
    fn next_temp_name(&self) -> String {
        let seq = self.temp_seq.fetch_add(1, Ordering::Relaxed);
        format!(
            "{TEMP_PREFIX}{}.{:08x}.{seq}",
            std::process::id(),
            self.nonce
        )
    }

    /// Read a chunk file, dropping the index entry if the file has vanished.
    async fn read_file(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
        let path = self.chunk_path(address);
        let read = self
            .blocking_tracker
            .spawn_blocking(move || -> Result<Option<Vec<u8>>> {
                match open_regular(&path) {
                    Ok(Some(f)) => read_bounded(f, &path).map(Some),
                    Ok(None) => Ok(None),
                    Err(e) => Err(e),
                }
            })
            .await
            .map_err(|e| Error::Storage(format!("Chunk store read task failed: {e}")))?;

        // Every read decides the question, not only the ones that were checking. A read
        // that failed means this chunk cannot be served, whoever asked; a read that
        // worked means it can be, whoever asked. Doing this anywhere else leaves a key
        // stuck unadvertised after the fault has cleared, or advertised after it has not.
        let read = match read {
            Ok(read) => {
                self.clear_suspect(address);
                read
            }
            Err(e) => {
                self.mark_suspect(address);
                return Err(e);
            }
        };

        if read.is_none() && self.forget_if_absent(address).await {
            // The file went away underneath us. Stop advertising the key so the close
            // group notices the shortfall and replication puts it back.
            warn!(
                "Chunk {} is indexed but its file is missing; dropped from the index so \
                 replication can repair it",
                hex::encode(address)
            );
        }
        Ok(read)
    }

    /// Drop an index entry whose file is genuinely gone.
    ///
    /// Re-checks under the address's write lane, so a chunk republished between the
    /// failing read and this call keeps its entry.
    async fn forget_if_absent(&self, address: &XorName) -> bool {
        // Not suspect any more: it is not unreadable, it is not there.
        self.clear_suspect(address);
        let path = self.chunk_path(address);
        let lanes = Arc::clone(&self.write_lanes);
        let index = Arc::clone(&self.index);
        let lane = shard_index(address);
        let key = *address;
        self.blocking_tracker
            .spawn_blocking(move || {
                let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
                if path.exists() {
                    return false;
                }
                index.write().remove(&key)
            })
            .await
            .unwrap_or(false)
    }

    /// Remove a chunk whose bytes do not match its name, and stop advertising it.
    ///
    /// Re-reads and re-verifies under the address's write lane first. A read that failed
    /// verification is rare enough that paying for one extra read is worth never
    /// discarding a chunk that a concurrent write had already repaired.
    async fn quarantine_corrupt(&self, address: &XorName) {
        let path = self.chunk_path(address);
        let lanes = Arc::clone(&self.write_lanes);
        let index = Arc::clone(&self.index);
        let lane = shard_index(address);
        let key = *address;
        // For the reason given on `forget_if_absent`: this closure outlives its awaiter,
        // and the change it makes has to be announced by the same thread that makes it.
        // And the store-lock lease, for the reason `put`, `repair`, `delete` and the
        // startup scan carry it: this closure outlives its awaiter, so without it a
        // cancelled verification whose caller dropped the last `ChunkStore` would unlink
        // inside a directory a second process had already been handed.
        let lease = Arc::clone(&self.lock);
        let outcome =
            self.blocking_tracker
                .spawn_blocking(move || -> std::io::Result<bool> {
                    let _lease = lease;
                    let _lane = lanes.get(lane).map(parking_lot::Mutex::lock);
                    // Nothing is thrown away without proof. A re-read that fails says the
                    // question could not be answered this time, not that the bytes are wrong,
                    // and a repair may have published a good copy since the read that brought
                    // us here. Treating either as corruption deletes a chunk this node has.
                    let buf = match open_regular(&path) {
                        Ok(Some(f)) => read_bounded(f, &path)
                            .map_err(|e| std::io::Error::other(e.to_string()))?,
                        Ok(None) => {
                            index.write().remove(&key);
                            return Ok(true);
                        }
                        Err(e) => return Err(std::io::Error::other(e.to_string())),
                    };
                    if crate::client::compute_address(&buf) == key {
                        // Repaired between the failing read and now. Leave it alone.
                        return Ok(false);
                    }
                    std::fs::remove_file(&path)?;
                    // The same flush the ordinary delete does, for the same reason: an
                    // unlink that has not reached the directory can be undone by a power
                    // loss, and here the entry that comes back is one this node has proven
                    // wrong. The startup scan would re-index it by name, and the
                    // known-wrong mark that would otherwise hold it back lives only in
                    // memory and does not survive the restart, so the node would go back to
                    // claiming and committing to a chunk it already knows is bad.
                    if let Some(shard) = path.parent() {
                        fsync_dir_best_effort(shard);
                    }
                    index.write().remove(&key);
                    Ok(true)
                })
                .await;
        match outcome {
            Ok(Ok(true)) => {
                self.clear_known_wrong(address);
                self.clear_suspect(address);
                warn!(
                    "Removed corrupt chunk file {}; replication will repair it",
                    hex::encode(address)
                );
            }
            Ok(Ok(false)) => {
                // The re-read hashed and matched: a repair landed between the failing
                // read and this one.
                self.clear_known_wrong(address);
                self.clear_suspect(address);
                debug!(
                    "Chunk {} verified on re-read; leaving it in place",
                    hex::encode(address)
                );
            }
            // Still indexed, so it must not still be claimed: the read that brought us
            // here proved the bytes wrong, and the node would otherwise go on committing
            // to a chunk it knows it cannot serve.
            Ok(Err(e)) => {
                self.mark_suspect(address);
                warn!(
                    "Corrupt chunk {} could not be removed: {e}. It stays on disk, and \
                     this node stops answering for it.",
                    hex::encode(address)
                );
            }
            Err(e) => {
                self.mark_suspect(address);
                warn!("Corrupt-chunk removal task failed: {e}");
            }
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Free functions
// ────────────────────────────────────────────────────────────────────────────

/// Create the destination shard directory if this store has not seen it yet.
///
/// A newly created directory entry is only durable once its parent is flushed; without
/// that a crash could take the directory and the chunk inside it together.
fn ensure_shard_dir(
    chunks_dir: &Path,
    dir: &Path,
    shard: usize,
    present: &parking_lot::Mutex<[bool; SHARD_COUNT]>,
) -> Result<()> {
    if present.lock().get(shard).copied().unwrap_or(false) {
        return Ok(());
    }
    std::fs::create_dir_all(dir).map_err(|e| {
        Error::Storage(format!(
            "Failed to create shard directory {}: {e}",
            dir.display()
        ))
    })?;
    // Load-bearing, like the flush that publishes a chunk into this directory. Until the
    // parent is flushed the shard's own entry can be lost, and losing it loses every chunk
    // inside it. Reporting the shard present anyway would let the very first chunk written
    // into it count as durably stored.
    fsync_dir(chunks_dir).map_err(|e| {
        Error::Storage(format!(
            "Created shard directory {} but could not flush {}: {e}. Not marking the shard \
             usable, because a directory that is not durable cannot hold a chunk that is.",
            dir.display(),
            chunks_dir.display()
        ))
    })?;
    if let Some(slot) = present.lock().get_mut(shard) {
        *slot = true;
    }
    Ok(())
}

/// Shard directory index for an address: its last byte.
fn shard_index(address: &XorName) -> usize {
    address.last().copied().unwrap_or(0) as usize
}

/// Shard directory name for an address: the last two characters of its hex form.
fn shard_name(address: &XorName) -> String {
    format!("{:02x}", shard_index(address))
}

/// True for a string of hex digits in either case.
fn is_hex_any_case(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// Move an entry aside under a name that can never be read as a chunk.
fn quarantine_entry(path: &Path) {
    let aside = path.with_extension("not-a-chunk");
    match std::fs::rename(path, &aside) {
        Ok(()) => warn!(
            "Chunk store: moved {} aside to {}; a name that differs from a chunk name only \
             by case collides with it on Windows and macOS",
            path.display(),
            aside.display()
        ),
        Err(e) => warn!(
            "Chunk store: {} collides with a chunk name by case folding and could not be \
             moved aside: {e}. Rename or delete it.",
            path.display()
        ),
    }
}

/// True for a string of lowercase hex digits only.
fn is_lower_hex(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// Decode a filename back into the address it names, or `None` if it is not one.
///
/// Rejects uppercase deliberately. On a case-folding filesystem (NTFS, default APFS)
/// accepting both cases would let one file answer to two index entries.
fn decode_chunk_name(name: &str) -> Option<XorName> {
    if name.len() != CHUNK_NAME_LEN || !is_lower_hex(name) {
        return None;
    }
    let bytes = hex::decode(name).ok()?;
    XorName::try_from(bytes.as_slice()).ok()
}

/// Flush a directory so a rename or creation inside it survives power loss.
///
/// Best effort by design. Linux and XFS require it, macOS accepts it with undocumented
/// effect, and Windows offers no way to do it at all through the standard library. The
/// content is content-addressed and re-replicable, so a lost directory entry costs a
/// refetch rather than data. Pretending otherwise in the code would be dishonest.
#[cfg(unix)]
fn fsync_dir_best_effort(path: &Path) {
    if let Err(e) = fsync_dir(path) {
        debug!("Directory flush of {} failed: {e}", path.display());
    }
}

/// Flush a directory, reporting whether it worked.
///
/// Used where the answer is load-bearing: a published chunk is only durable once its
/// directory entry is, and a chunk reported as stored is what lets a client drop its own
/// copy.
#[cfg(unix)]
fn fsync_dir(path: &Path) -> std::io::Result<()> {
    File::open(path)?.sync_all()
}

/// Off Unix there is no way to flush a directory through the standard library, so this
/// reports success without being able to promise anything.
///
/// That is why the publish path off Unix does not use a rename at all: it creates the
/// chunk under its final name and flushes the file, which Microsoft documents as flushing
/// the creation metadata with it. Directory creation has no equivalent, so a power loss soon
/// after a shard directory is created can lose it and the chunks published into it, after the
/// puts had reported success. The startup scan then does not find them and the node does not
/// claim them; it gets them back only if a peer offers them while it is still responsible for
/// them. Other replicas are untouched. This is the state the store has shipped in, and ADR-0022
/// names it as not fixed here.
///
/// Returns a `Result` so the callers that must handle a flush failure on Unix read the
/// same on every platform.
#[cfg(not(unix))]
#[allow(clippy::unnecessary_wraps)]
fn fsync_dir(_path: &Path) -> std::io::Result<()> {
    Ok(())
}

/// No-op on platforms with no way to flush a directory handle.
#[cfg(not(unix))]
fn fsync_dir_best_effort(_path: &Path) {}

/// Warn if the deepest chunk path this store can produce is close to `MAX_PATH`.
#[cfg(windows)]
fn check_path_budget(chunks_dir: &Path) {
    // Measured absolute, because that is what the filesystem sees. A relative root is the
    // case that still fails hard at MAX_PATH, since the standard library's long-path
    // handling only applies to paths it resolves as absolute.
    let absolute = if chunks_dir.is_absolute() {
        chunks_dir.to_path_buf()
    } else {
        std::env::current_dir()
            .map_or_else(|_| chunks_dir.to_path_buf(), |cwd| cwd.join(chunks_dir))
    };
    // `{chunks_dir}\{xy}\{64 hex}` — two separators, two shard characters, 64 name
    // characters.
    let deepest = absolute.as_os_str().len() + 1 + 2 + 1 + CHUNK_NAME_LEN;
    if deepest > WINDOWS_PATH_WARN_LEN {
        warn!(
            "Chunk file paths will be {deepest} characters, close to the {} character \
             Windows limit. Move the node root closer to the drive letter if writes start \
             failing.",
            WINDOWS_PATH_WARN_LEN
        );
    }
}

/// No-op where path length is not a practical constraint.
#[cfg(not(windows))]
fn check_path_budget(_chunks_dir: &Path) {}

/// Write `bytes` to `path` so a reader sees either the old content or the new.
fn write_file_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
    let Some(dir) = path.parent() else {
        return Err(Error::Storage(format!(
            "Refusing to write {} — it has no parent directory",
            path.display()
        )));
    };
    let temp = dir.join(format!(
        "{TEMP_PREFIX}{}.{:08x}.marker",
        std::process::id(),
        rand::random::<u32>()
    ));
    write_temp(&temp, bytes)?;
    // Through the retry, because on Windows a scanner holding a handle for a few
    // milliseconds turns an ordinary rename into a hard failure.
    rename_with_retry(&temp, path).map_err(|e| {
        let _ = std::fs::remove_file(&temp);
        Error::Storage(format!("Failed to publish {}: {e}", path.display()))
    })?;
    fsync_dir_best_effort(dir);
    Ok(())
}

/// Read the layout marker, writing the current one if the store is new.
fn read_or_write_layout(chunks_dir: &Path) -> Result<StoreLayout> {
    let path = chunks_dir.join(LAYOUT_FILE_NAME);
    match read_small_file(&path) {
        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| {
            Error::Storage(format!(
                "Chunk store layout marker {} is unreadable: {e}. Refusing to open rather \
                 than guess the layout.",
                path.display()
            ))
        }),
        Err(e) if e.kind() == ErrorKind::NotFound => {
            if store_has_entries(chunks_dir) {
                warn!(
                    "Chunk store at {} has data but no layout marker. Adopting it under \
                     the current scheme, which is the only one this build implements. If \
                     it was written by a build with a different layout its chunks will \
                     appear to be missing.",
                    chunks_dir.display()
                );
            }
            let layout = StoreLayout::default();
            let bytes = serde_json::to_vec_pretty(&layout)
                .map_err(|e| Error::Storage(format!("Failed to encode chunk store layout: {e}")))?;
            write_file_atomic(&path, &bytes)?;
            debug!("Wrote chunk store layout marker to {}", path.display());
            Ok(layout)
        }
        Err(e) => Err(Error::Storage(format!(
            "Failed to read chunk store layout marker {}: {e}",
            path.display()
        ))),
    }
}

/// Whether the store directory already holds at least one shard.
fn store_has_entries(chunks_dir: &Path) -> bool {
    let Ok(entries) = std::fs::read_dir(chunks_dir) else {
        return false;
    };
    entries.filter_map(std::result::Result::ok).any(|e| {
        e.file_name()
            .to_str()
            .is_some_and(|n| n.len() == 2 && is_lower_hex(n))
    })
}

/// Largest a metadata marker may be before it is treated as corrupt.
const MAX_MARKER_BYTES: u64 = 64 * 1024;

/// Read a small metadata file, refusing an implausibly large one.
///
/// The chunk path is bounded for exactly this reason; the markers live in the same data
/// directory and deserve the same ceiling.
///
/// # Errors
///
/// Returns an I/O error, including `NotFound`, so callers can distinguish "no marker yet".
pub fn read_small_file(path: &Path) -> std::io::Result<Vec<u8>> {
    let file = File::open(path)?;
    let mut bytes = Vec::new();
    let read = file.take(MAX_MARKER_BYTES + 1).read_to_end(&mut bytes)?;
    if read as u64 > MAX_MARKER_BYTES {
        return Err(std::io::Error::other(format!(
            "{} is larger than the {MAX_MARKER_BYTES} byte limit for a marker file",
            path.display()
        )));
    }
    Ok(bytes)
}

/// Take the store lock, or refuse to open the store.
///
/// Both failures are refusals, deliberately. Two of these stores on one directory keep
/// independent in-memory indices and independent views of what is in flight: both would
/// report the same write as new and each would keep serving keys the other had deleted. A
/// node that cannot create the lock file has no way to know it is alone.
///
/// The lock is an [`Arc`] so the work that relies on it can hold a lease. The startup
/// scan sweeps interrupted writes on the strength of being alone in the directory, and it
/// runs on a thread that outlives the future that started it.
///
/// # Errors
///
/// Returns [`Error::Storage`] when another process owns the directory, or when the lock
/// file cannot be created.
fn acquire_store_lock(chunks_dir: &Path) -> Result<Arc<File>> {
    let path = chunks_dir.join(LOCK_FILE_NAME);
    let file = match OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
    {
        Ok(f) => f,
        // Not a warning and carry on. Without this lock two processes can open the same
        // directory, each with its own index and its own view of what is in flight. A node
        // that cannot take it has no way to know it is alone.
        Err(e) => {
            return Err(Error::Storage(format!(
                "Could not create the chunk store lock {}: {e}. Refusing to start: \
                 without it this node cannot tell whether another is using the same data \
                 directory. Fix the permissions on that path, or remove a stale lock file \
                 left by a different user.",
                path.display()
            )))
        }
    };
    match file.try_lock_exclusive() {
        Ok(()) => Ok(Arc::new(file)),
        Err(e) => Err(Error::Storage(format!(
            "Another process already has the chunk store at {} open ({e}). Two nodes \
             cannot share one data directory: each keeps its own index and they would \
             disagree about what is stored. Stop the other node first.",
            chunks_dir.display()
        ))),
    }
}

/// What a startup scan found.
struct ScanResult {
    /// Every published address, ascending.
    keys: Vec<XorName>,
    /// Which shard directories already exist.
    shards_present: [bool; SHARD_COUNT],
    /// Orphaned temp files removed.
    swept_temps: usize,
    /// Entries that were neither a chunk nor one of ours.
    skipped: usize,
}

/// Rebuild the key set from directory entries.
///
/// Reads names only. A `stat` per entry costs about ten times the enumeration on Linux
/// and macOS and fifty to sixty times on Windows, and buys nothing: the filename is the
/// key, and the content is verified on read.
fn scan_store(chunks_dir: &Path) -> Result<ScanResult> {
    let mut result = ScanResult {
        keys: Vec::new(),
        shards_present: [false; SHARD_COUNT],
        swept_temps: 0,
        skipped: 0,
    };

    let top = std::fs::read_dir(chunks_dir).map_err(|e| {
        Error::Storage(format!(
            "Failed to enumerate chunk store {}: {e}",
            chunks_dir.display()
        ))
    })?;

    for entry in top {
        let entry = entry.map_err(|e| {
            Error::Storage(format!(
                "Failed to read an entry of {}: {e}",
                chunks_dir.display()
            ))
        })?;
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            result.skipped = result.skipped.saturating_add(1);
            continue;
        };
        if name == LAYOUT_FILE_NAME || name == LOCK_FILE_NAME {
            continue;
        }
        if name.starts_with(TEMP_PREFIX) {
            if sweep_temp(&entry.path()) {
                result.swept_temps = result.swept_temps.saturating_add(1);
            }
            continue;
        }
        if name.len() != 2 || !is_lower_hex(name) {
            warn!(
                "Chunk store: ignoring unexpected entry {name} in {}",
                chunks_dir.display()
            );
            result.skipped = result.skipped.saturating_add(1);
            continue;
        }
        let Ok(shard) = u8::from_str_radix(name, 16) else {
            result.skipped = result.skipped.saturating_add(1);
            continue;
        };
        // `shards_present` is set inside `scan_shard`, on success only. Setting it from
        // the name alone would make a stray regular file called `ab` look like a shard
        // that already exists, and every write to that shard would then fail with a
        // misleading error until the node was restarted.
        scan_shard(&entry.path(), shard, &mut result)?;
    }

    result.keys.sort_unstable();
    result.keys.dedup();
    Ok(result)
}

/// Scan one shard directory into `result`.
fn scan_shard(dir: &Path, shard: u8, result: &mut ScanResult) -> Result<()> {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        // A stray file named like a shard, or a directory removed between the two reads.
        // Neither is fatal, and neither marks the shard as present.
        Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
            warn!(
                "Chunk store: {} is not a shard directory ({e}); ignoring it",
                dir.display()
            );
            result.skipped = result.skipped.saturating_add(1);
            return Ok(());
        }
        // Anything else is a real fault: a permission problem, exhausted descriptors, or
        // failing hardware. Opening with a shard's worth of keys silently missing would
        // make the node under-claim in its published commitment and stop serving chunks
        // it still holds and is answerable for, so refuse to open at all.
        Err(e) => {
            return Err(Error::Storage(format!(
                "Failed to enumerate shard {}: {e}. Refusing to open with an incomplete \
                 key set.",
                dir.display()
            )))
        }
    };
    if let Some(slot) = result.shards_present.get_mut(shard as usize) {
        *slot = true;
    }

    for entry in entries {
        let entry =
            entry.map_err(|e| Error::Storage(format!("Failed to read {}: {e}", dir.display())))?;
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            result.skipped = result.skipped.saturating_add(1);
            continue;
        };
        if name.starts_with(TEMP_PREFIX) {
            if sweep_temp(&entry.path()) {
                result.swept_temps = result.swept_temps.saturating_add(1);
            }
            continue;
        }
        let Some(key) = decode_chunk_name(name) else {
            if name.len() == CHUNK_NAME_LEN && is_hex_any_case(name) {
                // A case-folded twin of a real chunk name. On NTFS and default APFS the
                // existence check in the write path folds onto it, so a paid write would
                // be answered "already stored" and its bytes dropped. Move it aside.
                quarantine_entry(&entry.path());
            } else {
                warn!(
                    "Chunk store: ignoring non-chunk entry {name} in {}",
                    dir.display()
                );
            }
            result.skipped = result.skipped.saturating_add(1);
            continue;
        };
        // `file_type` comes from the directory entry itself on Linux and macOS and from
        // the enumeration on Windows, so this is not the per-entry `stat` the scan
        // deliberately avoids. A pipe, socket, device or directory wearing a chunk name
        // must never enter the index: nothing downstream can read it, and it would sit in
        // the published commitment forever.
        match entry.file_type() {
            Ok(kind) if kind.is_file() => {}
            Ok(_) => {
                warn!(
                    "Chunk store: {name} in {} is not a regular file; ignoring it",
                    dir.display()
                );
                result.skipped = result.skipped.saturating_add(1);
                continue;
            }
            // Not the same as knowing it is not a file. Treating an unanswered question
            // as a no would drop a real chunk from the index and from the commitment
            // while its bytes sit on disk, and the node would not serve it again until
            // some later restart happened to succeed. Fail the scan instead: an index
            // that is missing keys must never be published as this node's key set.
            Err(e) => {
                return Err(Error::Storage(format!(
                    "Could not tell what {name} in {} is: {e}. Refusing to publish an \
                     index that may be missing chunks.",
                    dir.display()
                )));
            }
        }
        // A file in the wrong shard is unreachable through `chunk_path`, so indexing it
        // would make the index claim a key the read path cannot find.
        if shard_index(&key) != shard as usize {
            warn!(
                "Chunk store: {name} is filed under shard {shard:02x} but belongs in {:02x}; \
                 ignoring it. Move it or delete it.",
                shard_index(&key)
            );
            result.skipped = result.skipped.saturating_add(1);
            continue;
        }
        result.keys.push(key);
    }
    Ok(())
}

/// Remove one orphaned temp file. Returns whether it went.
///
/// Always removed. The scan that calls this runs only after the store lock has been taken,
/// so by then any temp file is an interrupted write of a previous run and there is no other
/// process that could be writing it. This used to describe a second, gentler mode for the
/// unlocked case; there was never any such branch and there is no caller that would need
/// one.
fn sweep_temp(path: &Path) -> bool {
    match std::fs::remove_file(path) {
        Ok(()) => {
            debug!("Removed orphaned temporary file {}", path.display());
            true
        }
        Err(e) => {
            debug!("Could not remove {}: {e}", path.display());
            false
        }
    }
}

/// Open a chunk file, refusing anything that is not a regular file.
///
/// `Ok(None)` means the file is not there. A named pipe wearing a valid chunk name would
/// otherwise block the opening thread forever: `open` on a FIFO with no writer does not
/// return, and enough of them would exhaust the blocking pool and stall every file and
/// database operation in the process. `O_NOFOLLOW` refuses a symlink for the same reason,
/// and both are checked on the handle rather than the path, so nothing can be swapped
/// underneath between the check and the open.
fn open_regular(path: &Path) -> Result<Option<File>> {
    #[cfg(unix)]
    let opened = {
        use std::os::unix::fs::OpenOptionsExt;
        OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW)
            .open(path)
    };
    #[cfg(not(unix))]
    let opened = OpenOptions::new().read(true).open(path);

    let file = match opened {
        Ok(f) => f,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(Error::Storage(format!(
                "Failed to open chunk file {}: {e}",
                path.display()
            )))
        }
    };
    let is_regular = file.metadata().is_ok_and(|m| m.file_type().is_file());
    if !is_regular {
        return Err(Error::Storage(format!(
            "{} is not a regular file; refusing to read it as a chunk",
            path.display()
        )));
    }
    Ok(Some(file))
}

/// Read a chunk file, refusing anything larger than a chunk can legitimately be.
///
/// A corrupt, sparse, or locally planted file wearing a valid 64-hex name would
/// otherwise be read straight into memory, so a single bad entry could exhaust the node
/// during an ordinary GET or an audit response.
fn read_bounded(file: File, path: &Path) -> Result<Vec<u8>> {
    let ceiling = MAX_CHUNK_SIZE as u64;
    // Sized from the file, so a chunk lands in an exactly-sized buffer: grown from
    // empty, a full chunk ended in twice its size, held for as long as the bytes are
    // served or offered. Capped at the ceiling, so a planted oversized file still
    // cannot make this allocate more than a chunk up front.
    let expected = file.metadata().map_or(0, |m| m.len()).min(ceiling);
    let mut buf = Vec::with_capacity(usize::try_from(expected).unwrap_or(0));
    let read = file.take(ceiling + 1).read_to_end(&mut buf).map_err(|e| {
        Error::Storage(format!("Failed to read chunk file {}: {e}", path.display()))
    })?;
    if read as u64 > ceiling {
        return Err(Error::Storage(format!(
            "Chunk file {} is larger than the {ceiling} byte maximum; refusing to read it",
            path.display()
        )));
    }
    Ok(buf)
}

/// Whether a Windows error is one a scanner or indexer holding a handle would produce.
///
/// `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION`, `ERROR_LOCK_VIOLATION`. Every other
/// failure is deterministic and retrying it only burns a blocking thread.
fn is_windows_sharing_violation(e: &std::io::Error) -> bool {
    matches!(e.raw_os_error(), Some(5 | 32 | 33))
}

/// Publish `temp_path` as `final_path`, retrying a transient sharing violation.
///
/// On Windows an antivirus scanner or the search indexer can hold a handle to either
/// file for a few milliseconds after it is created, and `MoveFileEx` fails outright
/// rather than queueing. Retrying a bounded number of times turns that from a failed
/// write into a short pause. Every other error returns immediately.
///
/// # Errors
///
/// Returns the rename's error: at once for anything but a Windows sharing violation, and
/// the last one after the bounded retries for that.
pub fn rename_with_retry(temp_path: &Path, final_path: &Path) -> std::io::Result<()> {
    let mut last = match std::fs::rename(temp_path, final_path) {
        Ok(()) => return Ok(()),
        Err(e) => e,
    };
    if !cfg!(windows) || !is_windows_sharing_violation(&last) {
        return Err(last);
    }
    for attempt in 1..=RENAME_RETRY_ATTEMPTS {
        std::thread::sleep(RENAME_RETRY_BACKOFF * attempt);
        match std::fs::rename(temp_path, final_path) {
            Ok(()) => return Ok(()),
            Err(e) => last = e,
        }
    }
    Err(last)
}

/// Write `payload` and publish it as `final_path`, replacing whatever is there.
///
/// Success here means the bytes are durable, not merely written. The repair path this
/// serves replaces bytes a read has proven wrong with bytes that hash to the address, and
/// a replacement that a power loss can undo would leave the wrong bytes in place while the
/// node believes the chunk repaired.
fn write_and_replace(
    temp_path: &Path,
    final_path: &Path,
    payload: &[u8],
    shard: &Path,
) -> Result<()> {
    // Unix: an intra-directory rename is atomic, so a reader sees the old content or the
    // new one and never an absence, and the directory flush is what makes it durable.
    #[cfg(unix)]
    {
        write_temp(temp_path, payload)?;
        if let Err(e) = rename_with_retry(temp_path, final_path) {
            let _ = std::fs::remove_file(temp_path);
            return Err(Error::Storage(format!(
                "Failed to replace chunk {}: {e}",
                final_path.display()
            )));
        }
        fsync_dir(shard).map_err(|e| {
            Error::Storage(format!(
                "Replaced {} but could not flush {}: {e}. Not reporting the repair as \
                 done, because a power loss could still undo it.",
                final_path.display(),
                shard.display()
            ))
        })?;
        Ok(())
    }
    // Everywhere else, Windows included: there is no way to flush a directory through the
    // standard library, so a rename cannot be shown to be durable at return. Overwriting
    // the existing file changes no directory entry at all, and `sync_all` (FlushFileBuffers
    // on Windows) is documented to flush the file's data, so a successful return is
    // durable under a documented contract.
    //
    // The cost is that this is not atomic: a crash part-way leaves the file holding a mix
    // of old and new bytes.
    //
    // The argument for accepting that does not depend on a second copy: every caller
    // reaches this only after a read has proven the bytes under that name
    // wrong. A crash part-way therefore leaves wrong bytes where wrong bytes already were,
    // which is not a loss, and the next verified read finds them and repairs again. What it
    // is NOT safe for is replacing bytes that were good, so this must not be reached on any
    // path that has not established otherwise. In this crate that holds: the two
    // `StoredBytes::Wrong` arms get there from a read that hashed and disagreed, and
    // `holds_verified` gets there from a read that returned bytes which were not the
    // caller's. The public entry point makes no such check and says so.
    //
    // A temporary and a rename would make it atomic, at the cost of a directory entry
    // change that cannot be flushed here. That trade is worth revisiting on a platform
    // where it can actually be tested; it is not worth making blind.
    #[cfg(not(unix))]
    {
        let _ = temp_path;
        let _ = shard;
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(final_path)
            .map_err(|e| {
                Error::Storage(format!(
                    "Failed to open {} for replacement: {e}",
                    final_path.display()
                ))
            })?;
        file.write_all(payload).map_err(|e| {
            Error::Storage(format!("Failed to rewrite {}: {e}", final_path.display()))
        })?;
        file.sync_all().map_err(|e| {
            Error::Storage(format!(
                "Rewrote {} but could not flush it: {e}. Not reporting the repair as \
                 done, because a power loss could still undo it.",
                final_path.display()
            ))
        })?;
        Ok(())
    }
}

/// Create `temp_path`, write `payload` into it, and flush it.
///
/// Flushed before any rename. On ext4 `auto_da_alloc` only orders the data before the
/// rename's own commit; it does not make the data durable, and btrfs has been observed
/// reordering. A name must never become visible on bytes that are not on the platter.
fn write_temp(temp_path: &Path, payload: &[u8]) -> Result<()> {
    let mut f = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(temp_path)
        .map_err(|e| {
            Error::Storage(format!(
                "Failed to create temporary file {}: {e}",
                temp_path.display()
            ))
        })?;
    if let Err(e) = f.write_all(payload) {
        let _ = std::fs::remove_file(temp_path);
        return Err(Error::Storage(format!(
            "Failed to write {}: {e}",
            temp_path.display()
        )));
    }
    if let Err(e) = f.sync_all() {
        let _ = std::fs::remove_file(temp_path);
        return Err(Error::Storage(format!(
            "Failed to flush {}: {e}",
            temp_path.display()
        )));
    }
    Ok(())
}

/// Write `payload` and publish it under `final_path`.
///
/// The temp lives in the destination directory, so the publish is an intra-directory
/// rename: atomic on every filesystem we support, and needing only that one directory
/// Put `payload` on disk as `final_path`, durably.
///
/// Returns [`PutOutcome::Duplicate`] when the name is already taken. The name is a hash
/// of the content, so that is not treated as proof the bytes are right: the caller
/// re-reads and verifies them.
#[cfg(unix)]
fn publish(
    temp_path: &Path,
    final_path: &Path,
    payload: &[u8],
    shard: &Path,
) -> std::result::Result<PutOutcome, PublishFailed> {
    // On Unix nothing is ever created under the final name by a failing path: the bytes go
    // to a temporary and only a successful rename gives them the real name. So every
    // failure here leaves the name as it found it.
    publish_via_rename(temp_path, final_path, payload, shard)
        .map_err(PublishFailed::nothing_written)
}

/// Put `payload` on disk as `final_path`, durably. See [`publish_in_place`] for why this
/// takes a different route off Unix.
#[cfg(not(unix))]
fn publish(
    temp_path: &Path,
    final_path: &Path,
    payload: &[u8],
    shard: &Path,
) -> std::result::Result<PutOutcome, PublishFailed> {
    let _ = temp_path;
    let _ = shard;
    publish_in_place(final_path, payload)
}

/// Create the chunk under its final name and flush it. Everywhere but Unix.
///
/// There is no way to flush a directory through the standard library, and Microsoft does
/// not document `MoveFileEx` as durable at return unless it is called with
/// `MOVEFILE_WRITE_THROUGH`, which std does not use. So off Unix a rename cannot be
/// relied on to have reached the disk when a put reports success.
///
/// Creating the file under its final name sidesteps the rename entirely. Microsoft
/// documents that creation metadata is cached and that `FlushFileBuffers`, which
/// `sync_all` calls on Windows, is the way to flush it. So a successful create, write and
/// flush is a durable publication under a documented contract, with no directory flush
/// and no rename involved.
///
/// The cost is that a crash mid-write leaves a partial file wearing a real chunk name.
/// That is why a duplicate re-reads and verifies rather than trusting the name.
#[cfg(not(unix))]
fn publish_in_place(
    final_path: &Path,
    payload: &[u8],
) -> std::result::Result<PutOutcome, PublishFailed> {
    // Test-only, and here rather than after the write so that it means the same thing on
    // both platforms: the chunk's name does not exist on disk yet. On Unix the equivalent
    // point is the temporary file written and the rename not yet made. Stopping after the
    // write instead would put the file under its real name already, and it could not
    // demonstrate anything about the missing flush either:
    // killing a process does not empty the page cache, so the bytes are still there to be
    // read. Only losing power loses them, which no test that kills a process can stage.
    #[cfg(any(test, feature = "test-utils"))]
    halt_here_if_asked(HALT_BEFORE_PUBLISH, final_path);
    let mut file = match OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(final_path)
    {
        Ok(f) => f,
        // Someone got there first. Immutable content under a content-addressed name, so
        // the caller verifies what is already there rather than assuming it is right.
        Err(e) if e.kind() == ErrorKind::AlreadyExists => return Ok(PutOutcome::Duplicate),
        Err(e) => {
            // Nothing was created, so nothing was spent.
            return Err(PublishFailed::nothing_written(Error::Storage(format!(
                "Failed to create chunk {}: {e}",
                final_path.display()
            ))));
        }
    };
    if let Err(e) = file.write_all(payload) {
        drop(file);
        // Taken back if it can be. Whether it could is what the caller needs: the file
        // was created by this call, so if it is still there the space is spent.
        let left_behind = std::fs::remove_file(final_path).is_err();
        return Err(PublishFailed {
            error: Error::Storage(format!("Failed to write {}: {e}", final_path.display())),
            left_behind,
        });
    }
    if let Err(e) = file.sync_all() {
        drop(file);
        // Taken back if it can be. Whether it could is what the caller needs: the file
        // was created by this call, so if it is still there the space is spent.
        let left_behind = std::fs::remove_file(final_path).is_err();
        return Err(PublishFailed {
            error: Error::Storage(format!("Failed to flush {}: {e}", final_path.display())),
            left_behind,
        });
    }
    Ok(PutOutcome::New)
}

/// Write a temp beside the target and rename it into place. Unix only.
///
/// Places the bytes and nothing more. Making the name durable is
/// [`flush_publication`]'s job, kept separate so a caller can tell a publish that spent no
/// space from one that spent it and could not be reported.
#[cfg(unix)]
fn publish_via_rename(
    temp_path: &Path,
    final_path: &Path,
    payload: &[u8],
    _shard: &Path,
) -> Result<PutOutcome> {
    // Content is immutable and the name is its hash, so an existing file already holds
    // exactly these bytes. Skipping the write is both cheaper and safer than replacing
    // it: on Windows a rename over a file another thread has open fails outright.
    //
    // The caller flushes either way. A name that is already there is not proof it is
    // durable: the write that put it there may have been this store's own previous attempt,
    // whose rename landed and whose directory flush then failed. That attempt returned an
    // error, so nobody acted on it, but if this call reported a durable duplicate without
    // flushing, the retry would silently launder an unflushed rename into a chunk reported
    // as stored.
    let outcome = if final_path.exists() {
        PutOutcome::Duplicate
    } else {
        write_temp(temp_path, payload)?;
        // Test-only: the one moment a complete chunk exists on disk under a name nothing
        // looks for. A crash test needs to die at a named point rather than wherever a
        // sleep in another process happened to land.
        #[cfg(any(test, feature = "test-utils"))]
        halt_here_if_asked(HALT_BEFORE_PUBLISH, temp_path);
        match rename_with_retry(temp_path, final_path) {
            Ok(()) => PutOutcome::New,
            Err(e) => {
                let _ = std::fs::remove_file(temp_path);
                // Another writer of the same address won the race, or the destination was
                // open. Either way the bytes are already published.
                if !final_path.exists() {
                    return Err(Error::Storage(format!(
                        "Failed to publish chunk {}: {e}",
                        final_path.display()
                    )));
                }
                PutOutcome::Duplicate
            }
        }
    };

    Ok(outcome)
}

/// A publish that failed, and whether it left its bytes on the disk.
///
/// The second half is the point. A failure before anything was created has spent nothing;
/// one that created the file and then could not remove it again has spent the space, and
/// whoever is accounting for free space has to know which happened. Only the code that did
/// the creating can say.
struct PublishFailed {
    error: Error,
    left_behind: bool,
}

impl PublishFailed {
    /// A failure that created nothing.
    fn nothing_written(error: Error) -> Self {
        Self {
            error,
            left_behind: false,
        }
    }
}

/// Make a publication durable by flushing the directory its name lives in.
///
/// Separate from placing the bytes, because the caller has to tell the two failures apart.
/// A publish that fails before the bytes land has spent nothing; one that fails here has
/// spent the space and must not be reported as stored, so whoever is accounting for free
/// space has to charge it while whoever is accounting for chunks must not count it.
///
/// NOT best effort. The directory flush is what makes the rename durable, and a chunk
/// reported as stored is what lets a client drop its own copy. Swallowing the failure would
/// let a power loss discard the directory entry after that copy was gone.
///
/// # Errors
///
/// Returns [`Error::Storage`] if the directory cannot be flushed.
#[cfg(unix)]
fn flush_publication(final_path: &Path, shard: &Path) -> Result<()> {
    fsync_dir(shard).map_err(|e| {
        Error::Storage(format!(
            "Published {} but could not flush {}: {e}. Not reporting this chunk as stored, \
             because a chunk that is not durable must not be reported as stored.",
            final_path.display(),
            shard.display()
        ))
    })
}

/// Nothing to do off Unix, where the chunk is created under its final name and flushed
/// with `sync_all`, which is documented to carry its creation metadata with it, and where
/// there is no way to flush a directory at all.
#[cfg(not(unix))]
fn flush_publication(_final_path: &Path, _shard: &Path) -> Result<()> {
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::replication::commitment::MAX_COMMITMENT_KEY_COUNT;
    use crate::replication::subtree::max_subtree_leaves;
    use std::collections::HashSet;
    use std::sync::mpsc::{self, Sender};
    use std::thread::JoinHandle;

    /// A directory flush that fails must say so.
    ///
    /// The quiet version of this function is only used where the answer does not change
    /// what happens next. On the publish path it does.
    #[cfg(unix)]
    #[test]
    fn flushing_a_directory_that_is_not_there_reports_the_failure() {
        let dir = TempDir::new().expect("temp dir");
        assert!(fsync_dir(dir.path()).is_ok());
        assert!(fsync_dir(&dir.path().join("no-such-shard")).is_err());
    }

    /// A chunk whose directory entry was never flushed is not reported as stored.
    ///
    /// A chunk reported as stored lets the client drop its own copy, so a published file
    /// whose directory flush failed, and which can vanish on power loss, must not be counted.
    /// The file staying on disk afterwards is fine: a later put of the same chunk verifies
    /// and keeps it.
    #[cfg(unix)]
    #[test]
    fn a_publish_whose_directory_flush_fails_is_not_reported_as_stored() {
        let dir = TempDir::new().expect("temp dir");
        let temp_path = dir.path().join("chunk.tmp");
        let final_path = dir.path().join("chunk");
        let unflushable = dir.path().join("shard-that-does-not-exist");

        // Asserted in two steps, not chained. Chaining them means a regression in placing
        // the bytes also produces an error, and the test passes without the flush ever
        // being reached: it would be checking that something went wrong rather than that
        // this went wrong.
        let placed = publish_via_rename(&temp_path, &final_path, b"payload", &unflushable);
        assert!(
            placed.is_ok(),
            "the bytes must be placed before this can be about the flush: {:?}",
            placed.err()
        );
        let outcome = flush_publication(&final_path, &unflushable);

        assert!(
            outcome.is_err(),
            "an unflushed publication must not be reported as stored"
        );
        assert!(
            !temp_path.exists(),
            "the temp file must not be left behind either way"
        );
    }

    use tempfile::TempDir;

    /// Open a store on a fresh temp directory with the disk reserve disabled.
    async fn test_store() -> (ChunkStore, TempDir) {
        let dir = TempDir::new().expect("temp dir");
        let store = ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: 0,
        })
        .await
        .expect("open store");
        (store, dir)
    }

    /// Open a store on an existing directory, as a restart would.
    async fn reopen(dir: &TempDir) -> ChunkStore {
        ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: 0,
        })
        .await
        .expect("reopen store")
    }

    /// An ordinary read settles whether the node answers for a chunk.
    ///
    /// Not only the reads that were checking something. A read that failed means the
    /// chunk cannot be served, whoever asked; a read that worked means it can be. Deciding
    /// this anywhere else leaves a key stuck unadvertised after the fault has cleared, or
    /// advertised after it has not.
    #[cfg(unix)]
    #[tokio::test]
    async fn an_ordinary_read_decides_whether_the_node_answers_for_a_chunk() {
        use std::os::unix::fs::PermissionsExt;

        let (store, dir) = test_store().await;
        let (addr, content) = addressed("read-decides");
        store.put(&addr, &content).await.expect("put");
        let path = store.chunk_path(&addr);

        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o000);
        std::fs::set_permissions(&path, perms).expect("chmod");

        assert!(store.get(&addr).await.is_err(), "the read must fail");
        assert!(
            !store.exists(&addr).expect("exists"),
            "and a plain read that failed must stop the node answering for it"
        );

        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o600);
        std::fs::set_permissions(&path, perms).expect("chmod back");

        assert_eq!(
            store.get(&addr).await.expect("get").expect("present"),
            content
        );
        assert!(
            store.exists(&addr).expect("exists"),
            "and a plain read that worked must start it answering again"
        );
        drop(dir);
    }

    /// Two writes for one key: waiting means waiting for both.
    ///
    /// Cancellation releases the caller's lane while the blocking half survives, so a
    /// second write for the same key can start behind the first. If the registry only
    /// recorded that *something* was writing, whichever finished first would clear it and
    /// a delete would be told the key was free while the other was still queued, then be
    /// undone by it.
    #[tokio::test]
    async fn waiting_for_a_key_waits_for_every_write_of_it() {
        let (store, dir) = test_store().await;
        let store = Arc::new(store);
        let (addr, content) = addressed("two-writers");

        // Two registrations, as two overlapping writes would make.
        let first = store.begin_write(&addr);
        let second = store.begin_write(&addr);

        let waiting = {
            let store = Arc::clone(&store);
            tokio::spawn(async move { store.wait_for_write(&addr).await })
        };
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(!waiting.is_finished());

        // One finishes. The other has not, so the wait must continue.
        drop(first);
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(
            !waiting.is_finished(),
            "one write finishing does not mean the key is free"
        );

        drop(second);
        waiting
            .await
            .expect("the wait ends once both have finished");

        // And the store is still usable afterwards.
        store.put(&addr, &content).await.expect("put");
        assert!(store.exists(&addr).expect("exists"));
        drop(dir);
    }

    /// A chunk this store cannot read is kept but not claimed.
    ///
    /// Both halves matter. Deleting it, or dropping it from the index, would lose a chunk
    /// that may be readable again in a moment. Claiming it anyway puts the key in signed
    /// commitments and answers presence probes with a yes for a chunk the node cannot serve,
    /// and the audit that catches that penalises.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_chunk_that_cannot_be_read_is_kept_but_not_claimed() {
        use std::os::unix::fs::PermissionsExt;

        let (store, dir) = test_store().await;
        let (addr, content) = addressed("unreadable-for-now");
        store.put(&addr, &content).await.expect("put");
        assert!(store.exists(&addr).expect("exists"));

        let path = store.chunk_path(&addr);
        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o000);
        std::fs::set_permissions(&path, perms).expect("chmod");

        // Offering the same bytes again must not be acknowledged, and must not replace
        // what is there on the strength of a read that did not happen.
        assert!(
            store.put(&addr, &content).await.is_err(),
            "an unreadable chunk must not be reported as stored"
        );
        assert!(path.exists(), "and the file must be left alone");
        assert!(
            !store.exists(&addr).expect("exists"),
            "but the node must stop claiming it"
        );
        assert!(!store.all_keys().await.expect("keys").contains(&addr));

        // Readable again: the node answers for it once more.
        let mut perms = std::fs::metadata(&path).expect("meta").permissions();
        perms.set_mode(0o600);
        std::fs::set_permissions(&path, perms).expect("chmod back");
        assert!(!store.put(&addr, &content).await.expect("put again"));
        assert!(store.exists(&addr).expect("exists"));
        assert!(store.all_keys().await.expect("keys").contains(&addr));
        drop(dir);
    }

    /// Content plus the address it hashes to.
    /// Every path under `root`, sorted, so a test can say the disk did not change.
    fn tree_under(root: &Path) -> Vec<std::path::PathBuf> {
        let mut found = Vec::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if entry.file_type().is_ok_and(|t| t.is_dir()) {
                    stack.push(path.clone());
                }
                found.push(path);
            }
        }
        found.sort();
        found
    }

    fn addressed(seed: &str) -> (XorName, Vec<u8>) {
        let content = format!("chunk-content-{seed}").into_bytes();
        (crate::client::compute_address(&content), content)
    }

    /// A value over the ceiling is not a chunk, and this build will not hold one anywhere.
    ///
    /// The 4 MB ceiling is what makes a chunk a chunk, and every released ingress enforces it
    /// before anything is stored: the protocol handler on a paid store, and replication on
    /// both the receive and the fetch path. So no over-ceiling value ever entered this network
    /// as a chunk, and one found on a disk is not data to be preserved — it is not a chunk at
    /// all.
    ///
    /// There was exactly one way to get one onto a disk, and it was ours, not the network's.
    /// The bridge's `put` wrote to the legacy environment FIRST — LMDB has no size ceiling —
    /// and only then offered the same bytes to the file store, which refused them. It then
    /// recorded the key as legacy-only so the copier would retry it, and the copier's own
    /// size arm deleted it. A local caller of the public `ChunkStore::put` was the whole of
    /// the exposure.
    ///
    /// That path is gone with the bridge. There is one store, its `put` refuses over the
    /// ceiling, and it refuses BEFORE it writes anything, so there is no half-written state
    /// to reason about and nothing for a later pass to find and have to decide about. This is
    /// why the release preserves no such value and grows no sidecar to put one in: there is
    /// no valid chunk to lose, and building a place to keep invalid ones would be building
    /// for a case this release makes unreachable.
    #[tokio::test]
    async fn a_value_over_the_ceiling_is_refused_before_anything_is_written() {
        let (store, dir) = test_store().await;

        // Addressed to its own bytes, so the content-address arm passes and the refusal is
        // the size one. Checking the wrong arm would pass this test while the ceiling was
        // gone.
        let content = vec![0xAB; MAX_CHUNK_SIZE + 1];
        let address = crate::client::compute_address(&content);

        // Every path under the store before the call, so "nothing was written" is asserted
        // about the whole tree and not only about the name this chunk would have had. A
        // regression that wrote a temporary somewhere else and tidied it up again would pass
        // the narrower check.
        let before = tree_under(dir.path());

        let err = store
            .put(&address, &content)
            .await
            .expect_err("a value over the ceiling is not a chunk and must be refused");
        let message = format!("{err}");
        assert!(
            message.contains("byte maximum"),
            "refused for the wrong reason, so this proves nothing about the ceiling: {message}"
        );

        assert!(
            !store.exists(&address).expect("exists"),
            "the node must not claim a value it refused"
        );
        assert!(!store.all_keys().await.expect("keys").contains(&address));
        assert!(
            !store.chunk_path(&address).exists(),
            "nothing may be left on disk: the refusal comes before the write"
        );
        assert_eq!(
            tree_under(dir.path()),
            before,
            "the refusal touched the disk; it is supposed to come before anything is written"
        );

        // And a restart cannot find one either, which is what says the refusal left no
        // partial file for a startup scan to index by name. The store holds its directory
        // lock for as long as it lives, so it goes first: two of them on one root is refused,
        // which is a different failure and would prove nothing about the ceiling.
        drop(store);
        let reopened = reopen(&dir).await;
        assert!(!reopened.exists(&address).expect("exists"));
        assert_eq!(
            reopened.current_chunks().expect("count"),
            0,
            "a refused value must not survive as a name the scan believes"
        );
    }

    #[tokio::test]
    async fn put_then_get_returns_the_same_bytes() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("a");

        assert!(store.put(&addr, &content).await.expect("put"));
        let got = store.get(&addr).await.expect("get").expect("present");
        assert_eq!(got, content);
    }

    #[tokio::test]
    async fn a_second_put_of_the_same_chunk_reports_not_new() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("b");

        assert!(store.put(&addr, &content).await.expect("first put"));
        assert!(!store.put(&addr, &content).await.expect("second put"));
        assert_eq!(store.current_chunks().expect("count"), 1);
        assert_eq!(store.stats().duplicates, 1);
    }

    #[tokio::test]
    async fn get_of_an_unknown_address_is_none() {
        let (store, _dir) = test_store().await;
        let (addr, _) = addressed("missing");
        assert!(store.get(&addr).await.expect("get").is_none());
    }

    #[tokio::test]
    async fn exists_tracks_the_store() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("c");

        assert!(!store.exists(&addr).expect("exists"));
        store.put(&addr, &content).await.expect("put");
        assert!(store.exists(&addr).expect("exists"));
        store.delete(&addr).await.expect("delete");
        assert!(!store.exists(&addr).expect("exists"));
    }

    #[tokio::test]
    async fn delete_unlinks_the_file_and_returns_the_space() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("d");
        store.put(&addr, &content).await.expect("put");

        let path = store.chunk_path(&addr);
        assert!(path.exists(), "the chunk file should be on disk");

        assert!(store.delete(&addr).await.expect("delete"));
        assert!(!path.exists(), "delete must actually unlink the file");
        assert_eq!(store.current_chunks().expect("count"), 0);

        // Deleting again is a no-op that reports nothing was there.
        assert!(!store.delete(&addr).await.expect("second delete"));
    }

    #[tokio::test]
    async fn content_that_does_not_hash_to_its_address_is_rejected() {
        let (store, _dir) = test_store().await;
        let (addr, _) = addressed("e");
        let err = store
            .put(&addr, b"different content")
            .await
            .expect_err("must reject");
        assert!(
            format!("{err}").contains("Content address mismatch"),
            "unexpected error: {err}"
        );
        assert_eq!(store.current_chunks().expect("count"), 0);
    }

    #[tokio::test]
    async fn a_chunk_is_filed_under_the_last_two_hex_characters_of_its_address() {
        let (store, dir) = test_store().await;
        let (addr, content) = addressed("f");
        store.put(&addr, &content).await.expect("put");

        let name = hex::encode(addr);
        let expected_shard = name
            .get(name.len() - 2..)
            .expect("64-character name")
            .to_string();
        let path = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(&expected_shard)
            .join(&name);
        assert!(path.exists(), "expected the chunk at {}", path.display());
    }

    #[tokio::test]
    async fn the_index_is_rebuilt_from_the_filesystem_on_restart() {
        let (store, dir) = test_store().await;
        let mut written = Vec::new();
        for i in 0..64 {
            let (addr, content) = addressed(&format!("restart-{i}"));
            store.put(&addr, &content).await.expect("put");
            written.push(addr);
        }
        drop(store);

        let reopened = reopen(&dir).await;
        assert_eq!(reopened.current_chunks().expect("count"), 64);
        for addr in &written {
            assert!(reopened.exists(addr).expect("exists"), "lost a key");
        }
    }

    #[tokio::test]
    async fn all_keys_is_sorted_ascending() {
        let (store, dir) = test_store().await;
        for i in 0..128 {
            let (addr, content) = addressed(&format!("sorted-{i}"));
            store.put(&addr, &content).await.expect("put");
        }

        let keys = store.all_keys().await.expect("all_keys");
        let mut sorted = keys.clone();
        sorted.sort_unstable();
        assert_eq!(keys, sorted, "all_keys() must be ordered");

        // And the order has to survive a restart, because the commitment builder
        // truncates the responsible subset before the Merkle tree sorts it.
        drop(store);
        let reopened = reopen(&dir).await;
        assert_eq!(reopened.all_keys().await.expect("all_keys"), keys);
    }

    #[tokio::test]
    async fn get_raw_skips_verification() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("raw");
        store.put(&addr, &content).await.expect("put");

        // Corrupt the file behind the store's back.
        std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");

        let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
        assert_eq!(raw, b"tampered");
    }

    /// A delete waits for a put that is already under way for the same key.
    ///
    /// The narrower ordering, and the one waiting for registered writes does not cover. A
    /// put does a lot before it registers itself: it checks the address, reads to see
    /// whether the name is taken, and reserves capacity. A delete arriving in that window
    /// would see nothing registered, wait for nothing, and go ahead; the put would register
    /// and publish afterwards, and the node would keep a chunk it had decided to prune.
    ///
    /// Staged deterministically rather than by racing two tasks. A put parked inside its
    /// own closure is holding the key's lane, so the delete must not be able to finish
    /// while it is parked. An earlier version of this test started both and accepted either
    /// ordering, which the bug also satisfies: it proved nothing.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn a_delete_waits_for_a_put_already_under_way() {
        let dir = TempDir::new().expect("temp dir");
        let store = Arc::new(reopen(&dir).await);
        let content = b"a chunk the pruner has decided to drop".to_vec();
        let addr = crate::client::compute_address(&content);

        // Park the put in the window that matters: it has taken the key's lane and has NOT
        // yet registered itself, so a delete's wait for in-flight writes would see nothing.
        // Parking it later, inside its closure, cannot show the lane doing anything: the
        // delete would block on the wait instead and the test would pass either way.
        let gate = store.test_pre_registration_gate();
        let held = gate.write().await;
        let writing = {
            let store = Arc::clone(&store);
            let content = content.clone();
            tokio::spawn(async move { store.put(&addr, &content).await })
        };
        // Waited for, not slept at. A sleep makes the staging a guess, and on a loaded
        // machine the guess is wrong and the test fails for the wrong reason.
        let deadline = std::time::Instant::now() + Duration::from_secs(30);
        while store.test_reached_pre_registration() == 0 {
            assert!(
                std::time::Instant::now() < deadline,
                "the put never reached the gate"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }

        // The delete must not get past the lane while that put holds it. Without the lane
        // on `put` this finishes immediately, which is the regression.
        let deleting = {
            let store = Arc::clone(&store);
            tokio::spawn(async move { store.delete(&addr).await })
        };
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert!(
            !deleting.is_finished(),
            "the delete finished while a put for the same key was still under way"
        );

        // Released: the put completes, then the delete runs. The delete is the later
        // decision, so the chunk must be gone.
        drop(held);
        let _ = writing.await.expect("the put task must not panic");
        let _ = deleting.await.expect("the delete task must not panic");
        store.wait_idle().await;

        assert!(
            !store.is_indexed(&addr),
            "the put landed after the delete and put {} back",
            hex::encode(addr)
        );
        assert!(
            !store.chunk_path(&addr).exists(),
            "and left its file behind"
        );
    }

    /// A delete outlasts a write nobody waited for.
    ///
    /// A write's blocking half outlives the future that started it, deliberately, so the
    /// work is never left half done. That means a cancelled put can still be queued when a
    /// delete arrives, and if the delete does not wait for it the write lands afterwards
    /// and puts back a chunk the node had decided to prune. The key is then in a store that
    /// no longer claims it, which is what the next verification has to clean up.
    ///
    /// This ordering had a regression test before the migration facade was deleted, and the
    /// test went with the facade even though the requirement did not.
    #[tokio::test]
    // The gate is held across awaits deliberately: holding it is what parks the put, which
    // is the state the delete has to be ordered against.
    #[allow(clippy::await_holding_lock)]
    async fn a_delete_outlasts_a_write_nobody_waited_for() {
        let dir = TempDir::new().expect("temp dir");
        let store = Arc::new(reopen(&dir).await);
        let content = b"a chunk that is about to be pruned".to_vec();
        let addr = crate::client::compute_address(&content);

        // Park the put inside its closure, then drop the future waiting on it.
        let gate = store.test_put_gate();
        let held = gate.write();
        let put = {
            let store = Arc::clone(&store);
            let content = content.clone();
            tokio::spawn(async move { store.put(&addr, &content).await })
        };
        let deadline = std::time::Instant::now() + Duration::from_secs(30);
        while store.tasks_in_flight() == 0 {
            assert!(
                std::time::Instant::now() < deadline,
                "the put never reached the closure"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        put.abort();
        let _ = put.await;

        // The delete must not finish ahead of that write. Released after the delete has
        // had time to be waiting, so if it does not wait, it wins the race and the test
        // catches it.
        let deleting = {
            let store = Arc::clone(&store);
            tokio::spawn(async move { store.delete(&addr).await })
        };
        tokio::time::sleep(Duration::from_millis(100)).await;
        drop(held);
        let _ = deleting
            .await
            .expect("the delete task itself must not fail");
        store.wait_idle().await;

        assert!(
            !store.is_indexed(&addr),
            "the write landed after the delete and put {} back",
            hex::encode(addr)
        );
        assert!(
            !store.chunk_path(&addr).exists(),
            "and left its file on disk"
        );
    }

    /// A put whose caller goes away does not admit a key on bytes nothing has read.
    ///
    /// The blocking half of a put outlives the future that started it, deliberately, so
    /// the work is never left half done. That makes anything it writes to memory a claim
    /// the node keeps whether or not the caller is still there to finish checking it.
    ///
    /// For a chunk this call published the claim is earned: the bytes were hashed against
    /// their own name on the way in. For a name that was already taken it is not. The
    /// check that decides whether those bytes are good runs after the await, and a dropped
    /// future skips it, so admitting the key in the closure claims a chunk nobody read.
    ///
    /// Staged with a fifo, which is the sharpest case and a real one: the startup scan
    /// refuses non-regular entries by design, so this is a key the store has already
    /// decided it must not claim, walked in through the back door.
    #[cfg(unix)]
    #[tokio::test]
    // The gate is held across an await deliberately: holding it is what parks the put
    // inside its closure, which is the state under test. Dropping it before awaiting would
    // let the put finish and there would be nothing to cancel.
    #[allow(clippy::await_holding_lock)]
    async fn a_cancelled_put_does_not_admit_a_key_whose_bytes_were_never_read() {
        let dir = TempDir::new().expect("temp dir");
        let store = Arc::new(reopen(&dir).await);

        // A name a real chunk would use, wearing something that is not a chunk.
        let content = b"the bytes that belong under this name".to_vec();
        let addr = crate::client::compute_address(&content);
        let shard = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(format!("{:02x}", addr[31]));
        std::fs::create_dir_all(&shard).expect("mkdir");
        let path = shard.join(hex::encode(addr));
        let name = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
            .expect("a path with no interior nul");
        // SAFETY: `name` is a valid NUL-terminated C string that outlives the call, and the
        // mode is a constant. `mkfifo` reads the pointer and returns; nothing is retained.
        #[allow(clippy::undocumented_unsafe_blocks, unsafe_code)]
        let made = unsafe { libc::mkfifo(name.as_ptr(), 0o644) };
        assert_eq!(made, 0, "could not make the fifo this test needs");

        // Hold the gate so the put parks inside the closure, then drop the future while it
        // is parked. That is a caller going away mid-put, which is what a cancelled
        // request, a client disconnect or a shutdown all look like from in here.
        let gate = store.test_put_gate();
        let held = gate.write();
        let put = {
            let store = Arc::clone(&store);
            let content = content.clone();
            tokio::spawn(async move { store.put(&addr, &content).await })
        };
        // Waited for rather than slept at. A sleep proves nothing: if the put had not
        // reached the gated closure yet, aborting would cancel it before it ever got
        // there and the test would pass having staged nothing.
        let deadline = std::time::Instant::now() + Duration::from_secs(30);
        while store.tasks_in_flight() == 0 {
            assert!(
                std::time::Instant::now() < deadline,
                "the put never reached the closure, so there was nothing to cancel"
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        put.abort();
        let _ = put.await;
        drop(held);
        store.wait_idle().await;

        assert!(
            !store.is_indexed(&addr),
            "a cancelled put admitted {} on bytes nothing read; the fifo under that name \
             would then be advertised, committed to, and audited against",
            hex::encode(addr)
        );
        assert!(
            !store.exists(&addr).unwrap_or(true),
            "and the node must not claim it either"
        );
    }

    /// Opening the store removes nothing from the node root.
    ///
    /// The release before this one swept the root for its migration marker's temporaries.
    /// This build neither writes nor reads that marker, and markers already on disk are left
    /// where they are. The root holds a node's identity and whatever its operator put there,
    /// so nothing in it is this store's to remove, whatever its name looks like.
    #[tokio::test]
    async fn opening_the_store_leaves_the_node_root_alone() {
        let dir = TempDir::new().expect("temp dir");
        let root = dir.path();
        let untouched = [
            root.join("migration-state.json"),
            root.join(format!("{TEMP_PREFIX}1234.abcdef01.marker")),
            root.join(format!("{TEMP_PREFIX}1234.abcdef01.chunk")),
            root.join("notes.txt"),
        ];
        for path in &untouched {
            std::fs::write(path, b"keep me").expect("plant");
        }

        let store = reopen(&dir).await;
        drop(store);

        for path in &untouched {
            assert!(
                path.exists(),
                "{} was removed from the node root",
                path.display()
            );
        }
    }

    #[tokio::test]
    async fn a_corrupt_chunk_is_removed_so_replication_can_repair_it() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("corrupt");
        store.put(&addr, &content).await.expect("put");
        std::fs::write(store.chunk_path(&addr), b"tampered").expect("tamper");

        let err = store.get(&addr).await.expect_err("verification must fail");
        assert!(format!("{err}").contains("verification failed"), "{err}");

        assert!(!store.chunk_path(&addr).exists(), "corrupt file must go");
        assert!(!store.exists(&addr).expect("exists"));
        assert!(
            !store.all_keys().await.expect("all_keys").contains(&addr),
            "a corrupt chunk must stop being advertised"
        );
        assert_eq!(store.stats().verification_failures, 1);
    }

    #[tokio::test]
    async fn a_file_removed_underneath_the_store_drops_out_of_the_index() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("vanished");
        store.put(&addr, &content).await.expect("put");

        std::fs::remove_file(store.chunk_path(&addr)).expect("remove behind our back");

        assert!(store.get(&addr).await.expect("get").is_none());
        assert!(!store.exists(&addr).expect("exists"));
        assert_eq!(store.current_chunks().expect("count"), 0);
    }

    #[tokio::test]
    async fn interrupted_writes_are_swept_at_startup() {
        let (store, dir) = test_store().await;
        let (addr, content) = addressed("sweep");
        store.put(&addr, &content).await.expect("put");
        let shard = store
            .chunk_path(&addr)
            .parent()
            .expect("shard")
            .to_path_buf();
        drop(store);

        let orphan = shard.join(format!("{TEMP_PREFIX}999.7"));
        std::fs::write(&orphan, b"half a chunk").expect("write orphan");
        let stray_root = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(format!("{TEMP_PREFIX}999.8"));
        std::fs::write(&stray_root, b"half a marker").expect("write stray");

        let reopened = reopen(&dir).await;
        assert!(!orphan.exists(), "an interrupted write must not survive");
        assert!(!stray_root.exists(), "nor one at the store root");
        assert_eq!(reopened.current_chunks().expect("count"), 1);
    }

    #[tokio::test]
    async fn concurrent_writers_of_one_address_store_it_exactly_once() {
        let (store, _dir) = test_store().await;
        let store = Arc::new(store);
        let (addr, content) = addressed("racing");

        let mut tasks = Vec::new();
        for _ in 0..16 {
            let store = Arc::clone(&store);
            let content = content.clone();
            tasks.push(tokio::spawn(
                async move { store.put(&addr, &content).await },
            ));
        }

        let mut new_count = 0;
        for task in tasks {
            if task.await.expect("join").expect("put") {
                new_count += 1;
            }
        }
        assert_eq!(new_count, 1, "exactly one writer may report a new chunk");
        assert_eq!(store.current_chunks().expect("count"), 1);
        assert_eq!(
            store.get(&addr).await.expect("get").expect("present"),
            content
        );
    }

    #[tokio::test]
    async fn names_that_are_not_lowercase_hex_are_ignored_by_the_scan() {
        let (store, dir) = test_store().await;
        let (addr, content) = addressed("scan");
        store.put(&addr, &content).await.expect("put");
        let shard = store
            .chunk_path(&addr)
            .parent()
            .expect("shard")
            .to_path_buf();
        drop(store);

        // Uppercase is deliberately rejected: on a case-folding filesystem accepting it
        // would let one file answer to two index entries.
        let upper = shard.join(hex::encode_upper(addressed("upper").0));
        std::fs::write(&upper, b"x").expect("write upper");
        std::fs::write(shard.join("not-a-chunk"), b"x").expect("write junk");
        std::fs::write(shard.join("deadbeef"), b"x").expect("write short");

        let reopened = reopen(&dir).await;
        assert_eq!(reopened.current_chunks().expect("count"), 1);
    }

    #[tokio::test]
    async fn a_chunk_filed_in_the_wrong_shard_is_not_indexed() {
        let (store, dir) = test_store().await;
        let (addr, content) = addressed("misfiled");
        store.put(&addr, &content).await.expect("put");
        drop(store);

        // Move it one shard over: the read path would never find it there, so indexing
        // it would make the store advertise a key it cannot serve.
        let correct = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(shard_name(&addr))
            .join(hex::encode(addr));
        let wrong_shard_index = (shard_index(&addr) + 1) % SHARD_COUNT;
        let wrong_dir = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(format!("{wrong_shard_index:02x}"));
        std::fs::create_dir_all(&wrong_dir).expect("mkdir");
        std::fs::rename(&correct, wrong_dir.join(hex::encode(addr))).expect("misfile");

        let reopened = reopen(&dir).await;
        assert_eq!(reopened.current_chunks().expect("count"), 0);
        assert!(!reopened.exists(&addr).expect("exists"));
    }

    #[tokio::test]
    async fn the_layout_marker_is_written_once_and_checked_on_reopen() {
        let (store, dir) = test_store().await;
        drop(store);

        let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
        let layout: StoreLayout =
            serde_json::from_slice(&std::fs::read(&marker).expect("read marker"))
                .expect("parse marker");
        assert_eq!(layout, StoreLayout::default());

        // A store written by a future build must be refused, not misread.
        let future = StoreLayout {
            schema: LAYOUT_SCHEMA + 1,
            ..StoreLayout::default()
        };
        std::fs::write(&marker, serde_json::to_vec(&future).expect("encode")).expect("write");
        let err = ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: 0,
        })
        .await
        .expect_err("must refuse a newer layout");
        assert!(format!("{err}").contains("newer than this build"), "{err}");
    }

    #[tokio::test]
    async fn an_unknown_shard_scheme_is_refused() {
        let (store, dir) = test_store().await;
        drop(store);
        let marker = dir.path().join(CHUNKS_DIR_NAME).join(LAYOUT_FILE_NAME);
        let other = StoreLayout {
            scheme: "prefix-hex".to_string(),
            ..StoreLayout::default()
        };
        std::fs::write(&marker, serde_json::to_vec(&other).expect("encode")).expect("write");
        let err = ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: 0,
        })
        .await
        .expect_err("must refuse an unknown scheme");
        assert!(format!("{err}").contains("shard scheme"), "{err}");
    }

    #[tokio::test]
    async fn writes_are_refused_when_the_disk_reserve_cannot_be_met() {
        let dir = TempDir::new().expect("temp dir");
        let store = ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: u64::MAX / 2,
        })
        .await
        .expect("open store");

        let (addr, content) = addressed("full");
        let err = store.put(&addr, &content).await.expect_err("must refuse");
        assert!(
            format!("{err}").contains("Insufficient disk space"),
            "{err}"
        );
        assert!(store.check_capacity().is_err());
    }

    #[tokio::test]
    async fn capacity_is_size_aware() {
        // Wide enough that a test running alongside this one cannot move the answer.
        const MARGIN: u64 = 512 * 1024 * 1024;

        let dir = TempDir::new().expect("temp dir");
        let available = fs2::available_space(dir.path()).expect("free space");
        // A reserve that leaves room for a small write but not a huge one. This is the
        // whole reason the predicate takes a size: free bytes alone stopped being a
        // sufficient answer once chunks became files.
        let store = ChunkStore::new(ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: true,
            disk_reserve: available.saturating_sub(MARGIN),
        })
        .await
        .expect("open store");

        assert!(store.check_capacity_for(1024).is_ok());
        assert!(store.check_capacity_for(4 * MARGIN).is_err());
    }

    #[test]
    fn suffix_shards_stay_uniform_for_a_close_group_of_keys() {
        // The real distribution: a node holds keys it is closest to, so they share a
        // long leading prefix with its own ID. Sharding on that prefix collapses to one
        // directory. The trailing byte is untouched by close-group membership.
        let mut prefix_dirs = HashSet::new();
        let mut suffix_dirs = HashSet::new();
        for i in 0u32..4096 {
            let mut key = [0u8; XORNAME_LEN];
            // 20 shared leading bits, as a ~1M-node network would impose.
            let tail = crate::client::compute_address(&i.to_le_bytes());
            key.copy_from_slice(&tail);
            if let Some(b) = key.first_mut() {
                *b = 0xab;
            }
            if let Some(b) = key.get_mut(1) {
                *b = 0xcd;
            }
            if let Some(b) = key.get_mut(2) {
                *b &= 0x0f;
            }
            prefix_dirs.insert(key.first().copied().unwrap_or(0));
            suffix_dirs.insert(shard_index(&key));
        }
        assert_eq!(
            prefix_dirs.len(),
            1,
            "prefix sharding collapses for a node's own holdings"
        );
        assert!(
            suffix_dirs.len() > 250,
            "suffix sharding must stay uniform, got {} of 256 directories",
            suffix_dirs.len()
        );
    }

    #[test]
    fn no_chunk_filename_can_spell_a_reserved_windows_device_name() {
        // Hex has no `n`, `u`, `x`, `p`, `r`, `l`, `t`, `o` or `s`, so `CON`, `NUL`,
        // `AUX`, `PRN`, `COM1` and `LPT1` are all unspellable at any length. This is why
        // the encoding is hex and not base32 or base64url.
        for reserved in ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"] {
            assert!(
                !is_lower_hex(reserved),
                "{reserved} must not be a valid chunk or shard name"
            );
        }
    }

    #[test]
    fn only_full_length_lowercase_hex_decodes_to_an_address() {
        // 0xab so the hex form actually contains letters, which is where case matters.
        assert!(decode_chunk_name(&hex::encode([0xabu8; XORNAME_LEN])).is_some());
        assert!(decode_chunk_name(&hex::encode_upper([0xabu8; XORNAME_LEN])).is_none());
        assert!(decode_chunk_name("deadbeef").is_none());
        assert!(decode_chunk_name("").is_none());
        assert!(decode_chunk_name(&"g".repeat(CHUNK_NAME_LEN)).is_none());
    }

    #[tokio::test]
    async fn repair_replaces_bad_bytes_without_the_file_ever_being_absent() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("repairable");
        store.put(&addr, &content).await.expect("put");
        let path = store.chunk_path(&addr);

        std::fs::write(&path, b"rotted").expect("corrupt");
        store.repair(&addr, &content).await.expect("repair");

        assert_eq!(
            store.get(&addr).await.expect("get").expect("present"),
            content
        );
        assert!(store.exists(&addr).expect("exists"));
    }

    #[tokio::test]
    async fn a_repair_with_the_wrong_bytes_is_refused_and_changes_nothing() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("guarded");
        store.put(&addr, &content).await.expect("put");
        let path = store.chunk_path(&addr);

        // The whole point of repairing in place is that a failure must leave the old file
        // where it was. Deleting first and writing after would open a window whose only
        // surviving copy is the one the caller is about to destroy.
        let err = store
            .repair(&addr, b"not this chunk")
            .await
            .expect_err("must refuse");
        assert!(format!("{err}").contains("Refusing to repair"), "{err}");
        assert!(
            path.exists(),
            "the existing file must survive a refused repair"
        );
        assert_eq!(
            store.get(&addr).await.expect("get").expect("present"),
            content
        );
    }

    #[tokio::test]
    async fn a_chunk_can_be_deleted_and_stored_again() {
        let (store, _dir) = test_store().await;
        let (addr, content) = addressed("cycle");

        assert!(store.put(&addr, &content).await.expect("put"));
        assert!(store.delete(&addr).await.expect("delete"));
        assert!(
            store.put(&addr, &content).await.expect("re-put"),
            "a re-stored chunk is new again"
        );
        assert_eq!(
            store.get(&addr).await.expect("get").expect("present"),
            content
        );
    }

    /// Write a chunk file straight into its shard, the way an existing store already
    /// contains thousands of them. Bypasses the write path deliberately: this exercises
    /// the startup scan, not `put`.
    fn plant(chunks_dir: &Path, key: &XorName) {
        let dir = chunks_dir.join(shard_name(key));
        std::fs::create_dir_all(&dir).expect("mkdir");
        std::fs::write(dir.join(hex::encode(key)), key).expect("plant");
    }

    #[tokio::test]
    async fn a_populated_and_churned_store_scans_correctly_at_scale() {
        // Every shard populated, then aged the way a long-lived node ages: some keys
        // deleted, others added in their place, so the directories carry holes rather
        // than being freshly written. APFS enumeration is known to degrade with churn
        // rather than with size, so a fresh corpus is not a realistic one.
        const PLANTED: u32 = 20_000;
        const CHURN: u32 = 1_000;

        let dir = TempDir::new().expect("temp dir");
        let chunks_dir = dir.path().join(CHUNKS_DIR_NAME);
        std::fs::create_dir_all(&chunks_dir).expect("mkdir");

        let mut expected: Vec<XorName> = Vec::new();
        for i in 0..PLANTED {
            let key = crate::client::compute_address(&i.to_le_bytes());
            plant(&chunks_dir, &key);
            expected.push(key);
        }
        for i in 0..CHURN {
            let key = crate::client::compute_address(&i.to_le_bytes());
            std::fs::remove_file(chunks_dir.join(shard_name(&key)).join(hex::encode(key)))
                .expect("churn out");
            let replacement = crate::client::compute_address(&(PLANTED + i).to_le_bytes());
            plant(&chunks_dir, &replacement);
        }
        expected.retain(|k| chunks_dir.join(shard_name(k)).join(hex::encode(k)).exists());
        for i in 0..CHURN {
            expected.push(crate::client::compute_address(&(PLANTED + i).to_le_bytes()));
        }
        expected.sort_unstable();
        expected.dedup();

        let started = std::time::Instant::now();
        let store = reopen(&dir).await;
        let scan = started.elapsed();

        assert_eq!(
            store.current_chunks().expect("count"),
            expected.len() as u64
        );
        assert_eq!(store.all_keys().await.expect("all_keys"), expected);

        // Every shard should be in use at this size: 20,000 keys over 256 directories is
        // about 78 each, and the last byte of a BLAKE3 output is uniform.
        let occupied = std::fs::read_dir(&chunks_dir)
            .expect("read store root")
            .filter_map(std::result::Result::ok)
            .filter(|e| e.file_name().to_str().is_some_and(|n| n.len() == 2))
            .count();
        assert_eq!(occupied, SHARD_COUNT, "the suffix must reach every shard");

        println!(
            "scan of {} keys across {SHARD_COUNT} shards took {scan:?}",
            expected.len()
        );
    }

    #[tokio::test]
    async fn wait_idle_returns_once_writes_have_drained() {
        let (store, _dir) = test_store().await;
        let store = Arc::new(store);
        for i in 0..32 {
            let store = Arc::clone(&store);
            let (addr, content) = addressed(&format!("drain-{i}"));
            tokio::spawn(async move { store.put(&addr, &content).await });
        }
        // Not a synchronisation point for tasks that have not been spawned yet, but it
        // must not hang and it must leave the store usable.
        store.wait_idle().await;
        let (addr, content) = addressed("after-drain");
        assert!(store.put(&addr, &content).await.expect("put after drain"));
    }

    /// A full-size chunk reads into an exactly-sized buffer, verified or raw.
    #[tokio::test]
    async fn reads_allocate_exactly_the_chunk() {
        let (store, _dir) = test_store().await;
        let content: Vec<u8> = (0..=u8::MAX).cycle().take(MAX_CHUNK_SIZE).collect();
        let addr = crate::client::compute_address(&content);
        store.put(&addr, &content).await.expect("put");

        let verified = store.get(&addr).await.expect("get").expect("bytes");
        assert_eq!(verified, content);
        assert_eq!(verified.capacity(), MAX_CHUNK_SIZE);
        let raw = store.get_raw(&addr).await.expect("get_raw").expect("bytes");
        assert_eq!(raw.capacity(), MAX_CHUNK_SIZE);
    }

    #[tokio::test]
    async fn recheck_corrupt_takes_a_rotted_file_out_of_service_and_spares_a_good_one() {
        let (store, dir) = test_store().await;
        let (good, good_bytes) = addressed("intact");
        let (bad, bad_bytes) = addressed("rotted");
        store.put(&good, &good_bytes).await.expect("put good");
        store.put(&bad, &bad_bytes).await.expect("put bad");

        let path = dir
            .path()
            .join(CHUNKS_DIR_NAME)
            .join(format!("{:02x}", bad.last().copied().unwrap_or(0)))
            .join(hex::encode(bad));
        std::fs::write(&path, b"rotted").expect("corrupt the file");
        // The raw read that answers audits still hands the rotted bytes out.
        assert_eq!(
            store.get_raw(&bad).await.expect("raw").as_deref(),
            Some(b"rotted".as_slice())
        );

        // A false alarm must never cost a good chunk: the recheck reads it back first.
        store.recheck_corrupt(&good).await;
        store.recheck_corrupt(&bad).await;

        let keys = store.all_keys().await.expect("keys");
        assert!(keys.contains(&good), "an intact chunk stays in service");
        assert!(
            !keys.contains(&bad),
            "a rotted chunk must leave the view the next commitment is built from"
        );
        assert!(!path.exists(), "the rotted file is removed");
        assert!(!store.exists(&bad).expect("exists"));
        assert_eq!(
            store.get(&good).await.expect("get").expect("present"),
            good_bytes
        );

        // Replication's repair is an ordinary store of the right bytes.
        store.put(&bad, &bad_bytes).await.expect("repair");
        assert_eq!(
            store.get(&bad).await.expect("get").expect("present"),
            bad_bytes
        );
    }

    /// Poll `done` until it holds, failing with `what` if it has not within 30 seconds.
    async fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
        let deadline = Instant::now() + Duration::from_secs(30);
        while !done() {
            assert!(Instant::now() < deadline, "{what}");
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    }

    /// Hold the write lane `address` is quarantined under until the returned sender is used
    /// or dropped, stalling that shard the way a hung disk would. Held from a thread of its
    /// own, so nothing holds a blocking guard across an await.
    fn stall_write_lane(store: &ChunkStore, address: &XorName) -> (Sender<()>, JoinHandle<()>) {
        let (lanes, lane) = store.test_write_lane(address);
        let (held_tx, held_rx) = mpsc::channel::<()>();
        let (release_tx, release_rx) = mpsc::channel::<()>();
        let holder = std::thread::spawn(move || {
            let _stalled = lanes.get(lane).map(parking_lot::Mutex::lock);
            held_tx.send(()).ok();
            release_rx.recv().ok();
        });
        held_rx.recv().expect("the lane is held");
        (release_tx, holder)
    }

    /// A quarantine stalled on its shard's write lane holds one blocking thread, however
    /// many audits report rot meanwhile, and what they reported is worked through once the
    /// lane frees.
    ///
    /// This is the hazard as it arises: a retained commitment keeps the rotted key in
    /// every subtree an auditor selects over it, the raw read that answers audits keeps
    /// reading the file, and identities are cheap, so reports keep coming while the
    /// quarantine waits. A recheck run by each report would park a blocking thread per
    /// report, outside every responder limit.
    #[tokio::test]
    async fn a_stalled_quarantine_holds_one_blocking_thread_however_many_reports_arrive() {
        let (store, dir) = test_store().await;
        let store = Arc::new(store);
        let chunk_path = |key: &XorName| {
            dir.path()
                .join(CHUNKS_DIR_NAME)
                .join(format!("{:02x}", key.last().copied().unwrap_or(0)))
                .join(hex::encode(key))
        };
        let (bad, bad_bytes) = addressed("stalled");
        let (other, other_bytes) = addressed("queued-behind-the-stall");
        let (later, later_bytes) = addressed("rotted-after-the-stall");
        for (key, bytes) in [
            (&bad, &bad_bytes),
            (&other, &other_bytes),
            (&later, &later_bytes),
        ] {
            store.put(key, bytes).await.expect("put");
        }
        for key in [&bad, &other] {
            std::fs::write(chunk_path(key), b"rotted").expect("rot the file");
        }

        let (release, holder) = stall_write_lane(&store, &bad);

        let stop = CancellationToken::new();
        let worker = {
            let store = Arc::clone(&store);
            let stop = stop.clone();
            tokio::spawn(async move { store.run_corrupt_rechecks(&stop).await })
        };

        // The first report: the worker reads the file, proves it wrong, stops claiming it
        // and parks in the quarantine behind the held lane. Waited for rather than slept
        // at, so the reports below really do arrive while the quarantine is stalled.
        store.report_corrupt(&[bad]);
        wait_until("the recheck never reached the stalled quarantine", || {
            !store.exists(&bad).expect("exists") && store.tasks_in_flight() > 0
        })
        .await;

        // Audits keep reporting it, and another rotted chunk, while the quarantine waits.
        let reporters: Vec<_> = (0..32)
            .map(|_| {
                let store = Arc::clone(&store);
                tokio::spawn(async move { store.report_corrupt(&[bad, other]) })
            })
            .collect();
        let mut most_in_flight = 0;
        let watch_until = Instant::now() + Duration::from_millis(500);
        while Instant::now() < watch_until {
            most_in_flight = most_in_flight.max(store.tasks_in_flight());
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
        assert!(
            most_in_flight <= 1,
            "{most_in_flight} rechecks held blocking threads behind one stalled write lane; \
             reports must queue for the single worker, not each start one"
        );
        let waiting = reporters.iter().filter(|r| !r.is_finished()).count();
        assert_eq!(
            waiting, 0,
            "{waiting} reports waited on the stalled recheck"
        );
        for reporter in reporters {
            reporter.await.expect("report");
        }
        {
            let reports = store.corrupt.lock();
            assert_eq!(
                reports.waiting,
                VecDeque::from([other]),
                "the key being rechecked must not be queued again, and the other waits its turn"
            );
            assert_eq!(reports.queued.len(), 2, "one being rechecked, one waiting");
        }

        // The lane frees: both rotted chunks leave service in turn.
        release.send(()).ok();
        holder.join().expect("lane holder");
        wait_until(
            "the queue was not worked through after the lane freed",
            || {
                !chunk_path(&bad).exists()
                    && !chunk_path(&other).exists()
                    && store.corrupt.lock().queued.is_empty()
            },
        )
        .await;
        let keys = store.all_keys().await.expect("keys");
        assert!(
            !keys.contains(&bad) && !keys.contains(&other),
            "both rotted chunks must leave the view the next commitment is built from"
        );
        assert!(keys.contains(&later), "an intact chunk stays in service");

        // The worker is still there for the next report.
        std::fs::write(chunk_path(&later), b"rotted").expect("rot the file");
        store.report_corrupt(&[later]);
        wait_until("a report after the stall was never rechecked", || {
            !chunk_path(&later).exists()
        })
        .await;

        stop.cancel();
        tokio::time::timeout(Duration::from_secs(10), worker)
            .await
            .expect("an idle worker stops when told to")
            .expect("worker");
    }

    /// Every key one maximal round-1 proof can report fits an empty queue, so none of a
    /// subtree that rotted whole is dropped for want of room.
    #[tokio::test]
    async fn the_corrupt_queue_holds_everything_one_proof_can_report() {
        let most = usize::try_from(max_subtree_leaves(MAX_COMMITMENT_KEY_COUNT))
            .expect("a leaf count fits in usize");
        let (store, _dir) = test_store().await;
        let keys: Vec<XorName> = (0..most)
            .map(|i| addressed(&format!("leaf-{i}")).0)
            .collect();
        store.report_corrupt(&keys);
        assert_eq!(
            store.corrupt.lock().waiting.len(),
            most,
            "a maximal proof's report must fit an empty queue"
        );
    }

    /// Reports are deduplicated against both the queue and the key being rechecked, and
    /// what does not fit is dropped rather than waited for.
    #[tokio::test]
    async fn corrupt_reports_are_deduplicated_and_capped() {
        let (store, _dir) = test_store().await;
        let keys: Vec<XorName> = (0..MAX_CORRUPT_REPORTS + 8)
            .map(|i| addressed(&format!("reported-{i}")).0)
            .collect();

        store.report_corrupt(&keys);
        {
            let reports = store.corrupt.lock();
            assert_eq!(reports.waiting.len(), MAX_CORRUPT_REPORTS);
            assert_eq!(reports.queued.len(), MAX_CORRUPT_REPORTS);
            assert_eq!(reports.waiting.front(), keys.first(), "oldest first");
        }

        // Reported again, nothing is queued twice.
        store.report_corrupt(&keys);
        assert_eq!(store.corrupt.lock().waiting.len(), MAX_CORRUPT_REPORTS);

        // Nor is a key the worker has taken and not yet finished, and it still counts
        // toward the cap. Taken here exactly as the worker takes one.
        let taken = store
            .corrupt
            .lock()
            .waiting
            .pop_front()
            .expect("a waiting key");
        store.report_corrupt(&[taken]);
        {
            let reports = store.corrupt.lock();
            assert!(
                !reports.waiting.contains(&taken),
                "a key being rechecked was queued again"
            );
            assert_eq!(reports.queued.len(), MAX_CORRUPT_REPORTS);
        }

        // A worker stopped part-way through that recheck leaves the key marked. The next
        // one to start clears the mark, so the key can be reported again.
        let stopped = CancellationToken::new();
        stopped.cancel();
        store.run_corrupt_rechecks(&stopped).await;
        store.report_corrupt(&[taken]);
        assert_eq!(store.corrupt.lock().waiting.back(), Some(&taken));
    }
}