ant-node 0.23.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
//! Durable storage for pointer records, with merge-on-put.
//!
//! The chunk store answers "already have it" and stops, which is right for an
//! immutable record and wrong for a mutable one — it would silently drop every
//! update. It also requires `BLAKE3(content) == address`, which no pointer can
//! satisfy. So pointers get their own store rather than an exemption carved
//! into that one.
//!
//! # The shape of a write
//!
//! A put is three steps, because the caller's gates sit between them:
//!
//! 1. `inspect` parses and compares against what is held: the arrival is
//!    either unchanged, stale, or a candidate that would win.
//! 2. `verify` checks the candidate's signature — after the caller's
//!    admission gates, and before it verifies payment.
//! 3. `commit` writes it, and settles the disk charge taken for it.
//!
//! Those three are internal to the crate; [`PointerStore::put_bytes`] is the
//! same sequence in one call, for callers with nothing to do in between.
//!
//! Nothing cheap happens after something expensive: a resubmission of what is
//! held is refused before any signature check, so repeatedly submitting one
//! paid state buys no ML-DSA verifications. Step 2 runs **outside** any store
//! lock, so a flood of unpaid candidates cannot block every other address
//! behind one verification, and step 3 re-checks under the lock, because the
//! world may have moved while payment was being verified.
//!
//! # Atomicity
//!
//! The commit — compare, write, re-index — runs inside a single blocking task
//! holding a synchronous lock. Splitting it across an `await` would let a
//! cancelled caller release the lock while its write was still in flight,
//! leaving the index describing a record the disk no longer holds. Because the
//! whole transaction lives in one task, dropping the caller's future cannot
//! tear it.
//!
//! On disk each record is one file named by its hex address, under
//! `{root}/pointers/<shard>/`, where the shard is the address's last byte in
//! hex: 256 directories, as the chunk store keeps, so no directory grows with
//! the whole store. The last byte rather than the first because a node holds
//! addresses near its own identity, and their leading bytes cluster. Writes go
//! to a uniquely named temporary file in the shard and are renamed into place,
//! so a crash leaves either the old record or the new one, never a torn one. A
//! lock file under `{root}/pointers/` keeps two processes from keeping two
//! indexes over one set of files.

use std::collections::{HashMap, VecDeque};

use bytes::Bytes;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use fs2::FileExt;
use parking_lot::Mutex;
use tokio::task::spawn_blocking;

use crate::ant_protocol::XorName;
use crate::error::{Error, Result};
use crate::logging::{debug, warn};
use ant_protocol::pointer::{ParsedPointer, Pointer, PointerState, POINTER_WIRE_LEN};

use crate::storage::{rename_with_retry, Reservation};

/// Directory under the store root that holds pointer records.
const POINTERS_DIR_NAME: &str = "pointers";

/// Prefix for the temporary file a write lands in before being renamed.
const TEMP_PREFIX: &str = ".tmp-";

/// Name of the file whose lock grants exclusive use of the directory.
const LOCK_FILE_NAME: &str = ".pointer-store-lock";

/// How many shard directories records are spread across: one per value of an
/// address's last byte.
const SHARD_COUNT: u16 = 256;

/// How long a replaced record is kept after an update, in memory.
///
/// A storage audit binds the record a node holds in its first round and asks
/// for it in the second (ADR-0016). An owner updating the pointer between the
/// two would otherwise fail the honest node that took the update, so every
/// record an update replaces stays servable, however many updates follow it
/// (ADR-0019), for longer than the slowest audit takes with the default
/// configuration: a round 1 over the largest subtree an auditor will wait
/// for, then the session its round 2 must arrive within. Round 1 can read a
/// pointer at its very start and take that long to finish, so the time counts
/// from the read, not from the session.
pub const SUPERSEDED_RETENTION: Duration = Duration::from_mins(10);

/// Most replaced records kept at once, across every address, about 11 MB at
/// the cap. Past it the oldest goes first; reaching it inside
/// [`SUPERSEDED_RETENTION`] takes that many paid updates to pointers this
/// node holds.
const MAX_SUPERSEDED: usize = 2048;

/// Every record a recent update replaced, by address, oldest first, each with
/// when it was replaced (see [`SUPERSEDED_RETENTION`]). Held as [`Bytes`] so
/// handing them out copies nothing.
type Superseded = HashMap<XorName, VecDeque<(Instant, Bytes)>>;

/// Drop every kept record older than [`SUPERSEDED_RETENTION`] at `now`, and
/// every address left with none.
fn drop_expired(superseded: &mut Superseded, now: Instant) {
    superseded.retain(|_, kept| {
        kept.retain(|(at, _)| now.saturating_duration_since(*at) < SUPERSEDED_RETENTION);
        !kept.is_empty()
    });
}

/// The name of the shard directory `address` lives in: its last byte in hex.
fn shard_name(address: &XorName) -> String {
    let last = address.last().copied().unwrap_or_default();
    format!("{last:02x}")
}

/// The shard directory `address` lives in.
fn shard_dir(dir: &Path, address: &XorName) -> PathBuf {
    dir.join(shard_name(address))
}

/// The file that holds the record at `address`.
fn record_path(dir: &Path, address: &XorName) -> PathBuf {
    shard_dir(dir, address).join(hex::encode(address))
}

/// What a put did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PutOutcome {
    /// The record was written: either nothing was held, or it won the merge.
    ///
    /// One outcome rather than two, because nothing downstream treats "stored"
    /// differently from "replaced": both mean the node now holds this state.
    Changed,
    /// The held record is the same authenticated state. Nothing was written.
    ///
    /// This is the case that keeps one payment from funding many writes: an
    /// owner can produce unboundedly many valid signatures over one state, and
    /// every one of them lands here.
    Unchanged,
    /// The incoming record lost under the merge rule. Nothing was written.
    Stale,
}

/// What the store has done since it was opened, for telemetry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PointerStoreStats {
    /// Records written, whether new or replacing an older state.
    pub written: u64,
    /// Arrivals that carried the state already held. Nothing was written.
    pub unchanged: u64,
    /// Arrivals that lost to the state already held. Nothing was written.
    pub stale: u64,
    /// Records served to a reader.
    pub served: u64,
    /// Records removed because this node stopped being responsible for them.
    pub deleted: u64,
}

/// The live counters behind [`PointerStoreStats`].
#[derive(Debug, Default)]
struct Counters {
    written: AtomicU64,
    unchanged: AtomicU64,
    stale: AtomicU64,
    served: AtomicU64,
    deleted: AtomicU64,
}

impl Counters {
    fn count(&self, outcome: PutOutcome) {
        let counter = match outcome {
            PutOutcome::Changed => &self.written,
            PutOutcome::Unchanged => &self.unchanged,
            PutOutcome::Stale => &self.stale,
        };
        counter.fetch_add(1, Ordering::Relaxed);
    }

    fn snapshot(&self) -> PointerStoreStats {
        PointerStoreStats {
            written: self.written.load(Ordering::Relaxed),
            unchanged: self.unchanged.load(Ordering::Relaxed),
            stale: self.stale.load(Ordering::Relaxed),
            served: self.served.load(Ordering::Relaxed),
            deleted: self.deleted.load(Ordering::Relaxed),
        }
    }
}

/// The result of [`PointerStore::inspect`]: what an arrival claims, before any
/// signature has been checked.
#[derive(Debug)]
pub(crate) enum Inspected {
    /// The node already holds exactly this state. No signature check is owed:
    /// a resubmission of what was paid for and a forgery of it are the same
    /// no-op.
    Unchanged(PointerState),
    /// The arrival loses to what is held, so it changes nothing either.
    Stale(PointerState),
    /// The arrival would win as it stands. Its signature has **not** been
    /// checked yet — pass it to [`PointerStore::verify`] once admission gates
    /// have had their say.
    Candidate(ParsedPointer),
}

/// What the store knows about a held record without reading it back.
#[derive(Debug, Clone, Copy)]
struct IndexEntry {
    /// The held record's authenticated state.
    ///
    /// The state itself rather than fields copied out of it, so the merge order
    /// the store applies is the protocol's own rule applied to the held state,
    /// and cannot drift from it.
    state: PointerState,
    /// Whether the file behind `state` is still there and still that record.
    ///
    /// A read that finds it gone or different clears this rather than dropping
    /// the entry. The node stops serving the record, because it does not have
    /// it — but it still knows what it had, and that is what lets the state be
    /// restored. Dropping the entry would leave the address looking untouched,
    /// where any record is admissible, so a replay of an older state could roll
    /// the node back.
    on_disk: bool,
    /// Which insertion this entry is.
    ///
    /// Monotonic for the life of this store, so an entry can be told apart
    /// from a later one carrying the same `state_id`. Without it a repair that
    /// restores exactly the state a reader found corrupt would be
    /// indistinguishable from the corrupt entry that reader set out to disown,
    /// and a second reader would erase the repair. Reuse would take 2^64
    /// commits without a restart, and an observation never outlives the store
    /// that produced it, so a restart resetting the counter is harmless.
    generation: u64,
}

impl IndexEntry {
    /// Describe a validated record.
    fn of(record: &Pointer, generation: u64) -> Self {
        Self::held(record.state(), generation)
    }

    /// Describe a record held on disk in `state`.
    const fn held(state: PointerState, generation: u64) -> Self {
        Self {
            state,
            on_disk: true,
            generation,
        }
    }
}

/// A store of pointer records.
#[derive(Debug, Clone)]
pub struct PointerStore {
    inner: Arc<Inner>,
}

/// Shared state behind [`PointerStore`].
#[derive(Debug)]
struct Inner {
    /// Directory holding one file per record.
    dir: PathBuf,
    /// What is held, by address.
    ///
    /// Guarded by a synchronous lock held across the disk write, so the index
    /// and the directory can never disagree about which version is current.
    /// The critical section is one ~5 KB write, and it is only ever taken
    /// inside a blocking task.
    index: Mutex<HashMap<XorName, IndexEntry>>,
    /// Distinguishes concurrent temporary files so two writers to one address
    /// cannot land in the same partial file.
    write_seq: AtomicU64,
    /// Source of index generations, monotonic for this store's lifetime.
    generation: AtomicU64,
    /// What the store has done, for telemetry.
    counters: Counters,
    /// Every record a recent update replaced (see [`Superseded`]).
    superseded: Mutex<Superseded>,
    /// Held for the store's lifetime; releasing it releases the directory.
    _lock_file: File,
}

impl PointerStore {
    /// Open a store under `root_dir`, rebuilding its index from disk.
    ///
    /// Takes an exclusive lock on the directory. Two stores over one directory
    /// would each keep their own index, and the one with the staler view would
    /// happily overwrite the other's newer record.
    ///
    /// A file that does not parse as a valid pointer, or that is not at the
    /// address its owner derives, is skipped and logged rather than deleted: a
    /// store that prunes what it cannot read destroys the evidence of its own
    /// bug.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the directory cannot be created, locked or
    /// read.
    pub async fn new(root_dir: &Path) -> Result<Self> {
        let dir = root_dir.join(POINTERS_DIR_NAME);
        let scan_dir = dir.clone();
        let (lock_file, index) = spawn_blocking(move || {
            std::fs::create_dir_all(&scan_dir).map_err(|e| {
                Error::Storage(format!("cannot create {}: {e}", scan_dir.display()))
            })?;
            let lock_file = acquire_lock(&scan_dir)?;
            create_shards(&scan_dir)?;
            let index = scan(&scan_dir)?;
            Ok::<_, Error>((lock_file, index))
        })
        .await
        .map_err(|e| Error::Storage(format!("pointer store scan panicked: {e}")))??;

        let next_generation = index
            .values()
            .map(|entry| entry.generation)
            .max()
            .map_or(0, |highest| highest.saturating_add(1));
        debug!(
            "Pointer store opened at {} with {} records",
            dir.display(),
            index.len()
        );
        Ok(Self {
            inner: Arc::new(Inner {
                dir,
                index: Mutex::new(index),
                write_seq: AtomicU64::new(0),
                generation: AtomicU64::new(next_generation),
                counters: Counters::default(),
                superseded: Mutex::new(HashMap::new()),
                _lock_file: lock_file,
            }),
        })
    }

    /// Parse an arrival and decide whether it could change anything, without
    /// verifying its signature.
    ///
    /// Cheap checks first: an arrival that cannot change anything is refused
    /// before its signature is looked at, because it is a no-op whether or not
    /// it is correctly signed. That ordering is what stops repeated submission
    /// of one paid state from buying ML-DSA verifications. Callers that gate on
    /// admission — capacity, responsibility for the address — run this first,
    /// apply their
    /// gates, and only then pay for [`Self::verify`]. Otherwise a forged record
    /// for an address the node is not responsible for still buys an ML-DSA
    /// verification before anything rejects it.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Protocol`] if the bytes are not a well-formed record.
    pub(crate) async fn inspect(&self, bytes: &[u8]) -> Result<Inspected> {
        // Off the executor: deciding this reads the held record back off the
        // disk, and a flood of arrivals must not put a blocking read on a
        // runtime worker for each one.
        let store = self.clone();
        let bytes = bytes.to_vec();
        spawn_blocking(move || store.inspect_blocking(&bytes))
            .await
            .map_err(|e| Error::Storage(format!("pointer inspection panicked: {e}")))?
    }

    /// The body of [`Self::inspect`], on a blocking thread.
    fn inspect_blocking(&self, bytes: &[u8]) -> Result<Inspected> {
        // Parsing decodes the owner key once; `verify` reuses that parse rather
        // than decoding again. The bytes travel with it, so the two cannot be
        // mismatched.
        let parsed = ParsedPointer::parse(bytes.to_vec())?;
        let state = *parsed.state();

        // Both early answers below assert that this node holds something at
        // least as good as what arrived, so neither may be given on the index's
        // word alone.
        if let Some(held) = self.held_state(&state.address) {
            if held.state_id == state.state_id {
                self.inner.counters.count(PutOutcome::Unchanged);
                return Ok(Inspected::Unchanged(state));
            }
            if !state.replaces(&held) {
                self.inner.counters.count(PutOutcome::Stale);
                return Ok(Inspected::Stale(state));
            }
        }
        Ok(Inspected::Candidate(parsed))
    }

    /// Verify a candidate's signature.
    ///
    /// Runs with no lock held and off the async executor: an ML-DSA
    /// verification is milliseconds of CPU, and an attacker can ask for one per
    /// forged record, so it must not run on a thread other work needs.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Crypto`] if the signature does not verify.
    pub(crate) async fn verify(&self, parsed: ParsedPointer) -> Result<Pointer> {
        spawn_blocking(move || Pointer::verify_parsed(parsed))
            .await
            .map_err(|e| Error::Storage(format!("pointer verification panicked: {e}")))?
            .map_err(Into::into)
    }

    /// Commit a prepared record.
    ///
    /// Re-checks against what is held before writing: `prepare` may have run
    /// before a payment check that took long enough for a newer state to
    /// arrive, and the re-check is what keeps that newer state from being
    /// overwritten.
    ///
    /// `reservation` is the disk charge for this write, taken before the call.
    /// It moves into the blocking transaction rather than staying with the
    /// caller, because the caller's future can be dropped while that
    /// transaction runs on: a charge released here would leave the file that
    /// landed a moment later uncounted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the write fails.
    pub(crate) async fn commit(
        &self,
        record: Pointer,
        reservation: Option<Reservation>,
    ) -> Result<PutOutcome> {
        let inner = Arc::clone(&self.inner);
        // The whole transaction runs in one task, so dropping this future
        // cannot leave the write done and the index un-updated.
        let outcome = spawn_blocking(move || inner.commit_blocking(&record, reservation))
            .await
            .map_err(|e| Error::Storage(format!("pointer commit panicked: {e}")))??;
        self.inner.counters.count(outcome);
        Ok(outcome)
    }

    /// Validate and store in one step, with no payment gate.
    ///
    /// For callers that have already settled payment, and for tests. The
    /// request path runs the same three steps with its admission and payment
    /// gates between them.
    ///
    /// # Errors
    ///
    /// As the three steps it runs: a malformed record, a signature that does
    /// not verify, or a write that fails.
    pub async fn put_bytes(&self, bytes: &[u8]) -> Result<PutOutcome> {
        match self.inspect(bytes).await? {
            Inspected::Unchanged(_) => Ok(PutOutcome::Unchanged),
            Inspected::Stale(_) => Ok(PutOutcome::Stale),
            Inspected::Candidate(parsed) => {
                let record = self.verify(parsed).await?;
                self.commit(record, None).await
            }
        }
    }

    /// Read the record held at `address`, if any.
    ///
    /// Re-validates on the way out: the signature is checked and the record
    /// must belong at the address asked for, so a file corrupted under the node
    /// is reported as missing rather than served as authentic, and the entry is
    /// disowned so the node will take a fresh copy instead of answering
    /// "unchanged" to its own repair.
    ///
    /// The file is what is served, not the index. A file replaced under the
    /// node by a *different* record that is genuinely signed for this address
    /// is served as held — it is a real record, the reader verifies it, and the
    /// read quorum is what decides between replicas that disagree. What the
    /// index is not allowed to do is claim a state the file does not have —
    /// that check guards `inspect`'s two early answers, the ones that
    /// assert this node already holds something.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the file cannot be read for a reason other
    /// than its absence.
    pub async fn get(&self, address: &XorName) -> Result<Option<Pointer>> {
        // What the index claimed before the read. A commit can land while the
        // read is in flight, and its entry must not then be mistaken for the
        // stale one this read is about to disown.
        let claimed = self.snapshot(address).map(|entry| entry.generation);

        let path = self.path_for(address);
        // Reading and verifying happen in one blocking task: an ML-DSA check is
        // milliseconds of CPU and must not run on an async worker thread.
        let read = spawn_blocking(move || {
            read_record_file(&path).map(|bytes| bytes.map(|bytes| Pointer::from_bytes(&bytes)))
        })
        .await
        .map_err(|e| Error::Storage(format!("pointer read panicked: {e}")))?;

        let validated = match read {
            Ok(Some(validated)) => validated,
            Ok(None) => {
                self.disown_if_unchanged(address, claimed);
                return Ok(None);
            }
            Err(e) => return Err(e),
        };

        match validated {
            Ok(record) if record.address() == *address => {
                self.inner.counters.served.fetch_add(1, Ordering::Relaxed);
                Ok(Some(record))
            }
            Ok(_) => {
                warn!(
                    "Pointer file at {} holds a record for another address; dropping it \
                     from the index",
                    hex::encode(address)
                );
                self.disown_if_unchanged(address, claimed);
                Ok(None)
            }
            Err(e) => {
                warn!(
                    "Pointer file at {} does not validate ({e}); dropping it from the index",
                    hex::encode(address)
                );
                self.disown_if_unchanged(address, claimed);
                Ok(None)
            }
        }
    }

    /// The authenticated-state identifier held at `address`, if any.
    ///
    /// This is what a sync hint carries and what a fetch decision compares. It
    /// names the state, not the encoding, so two replicas holding one state
    /// under different signatures agree and do not refetch each other forever.
    #[must_use]
    pub fn state_id(&self, address: &XorName) -> Option<XorName> {
        self.snapshot(address)
            .filter(|entry| entry.on_disk)
            .map(|entry| entry.state.state_id)
    }

    /// The record the last update at `address` replaced, within the last
    /// [`SUPERSEDED_RETENTION`], if any. See [`Self::superseded_all`] for
    /// every one kept.
    #[must_use]
    pub fn superseded(&self, address: &XorName) -> Option<Vec<u8>> {
        self.superseded_all(address)
            .into_iter()
            .next()
            .map(|bytes| bytes.to_vec())
    }

    /// Every record updates at `address` replaced within the last
    /// [`SUPERSEDED_RETENTION`], newest first: what a storage audit that bound
    /// one of them before the updates is still owed (ADR-0019).
    #[must_use]
    pub fn superseded_all(&self, address: &XorName) -> Vec<Bytes> {
        self.inner
            .superseded
            .lock()
            .get(address)
            .map(|kept| {
                kept.iter()
                    .rev()
                    .filter(|(at, _)| at.elapsed() < SUPERSEDED_RETENTION)
                    .map(|(_, bytes)| bytes.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Forget every replaced record older than [`SUPERSEDED_RETENTION`].
    ///
    /// Updates do this as they keep a record; this is for when none come, so
    /// memory goes back within a pass of the retention running out rather
    /// than at the next update, which may never come.
    pub fn drop_expired_superseded(&self) {
        drop_expired(&mut self.inner.superseded.lock(), Instant::now());
    }

    /// The bytes of the record held at `address`, read from disk without
    /// verifying them.
    ///
    /// For a caller that only binds the bytes and has them verified later, by
    /// whoever they are served to: verifying here would cost a signature check
    /// per record for nothing.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the file exists but cannot be read.
    pub async fn record_bytes(&self, address: &XorName) -> Result<Option<Vec<u8>>> {
        let path = self.path_for(address);
        spawn_blocking(move || read_record_file(&path))
            .await
            .map_err(|e| Error::Storage(format!("pointer read panicked: {e}")))?
    }

    /// The state held at `address`, as the index records it, if this node can
    /// serve one.
    ///
    /// What a peer asking "which state do you hold?" is told. Taken from the
    /// index rather than the file, so answering costs no disk read; a file lost
    /// since is caught by the first read, which stops the index claiming it.
    #[must_use]
    pub fn state(&self, address: &XorName) -> Option<PointerState> {
        self.snapshot(address)
            .filter(|entry| entry.on_disk)
            .map(|entry| entry.state)
    }

    /// The state this node holds at `address`, or held until it lost the
    /// file.
    ///
    /// Unlike [`Self::state`], a lost record still answers: it is the one
    /// state, besides a newer one, that [`Self::admits`] lets restore it.
    #[must_use]
    pub fn remembered(&self, address: &XorName) -> Option<PointerState> {
        self.snapshot(address).map(|entry| entry.state)
    }

    /// Whether a paid PUT of `state` may be taken.
    ///
    /// Any state the merge rule prefers to what is held, whatever its counter.
    /// The counter orders states; it does not meter them, since each state is
    /// paid for on its own. That is also what lets a node catch up: a write
    /// ends once its quorum has answered, so a node can miss an update, and one
    /// that joins the group later holds nothing at all. Either takes the next
    /// update, however far ahead of it that is.
    ///
    /// A record this node knew and lost admits the lost state itself as well,
    /// so the arrival that restores it is not mistaken for a resubmission. It
    /// admits nothing older, so a node that lost its copy cannot be rolled
    /// back by a replay.
    #[must_use]
    pub fn admits(&self, state: &PointerState) -> bool {
        self.snapshot(&state.address).is_none_or(|entry| {
            state.replaces(&entry.state)
                || (!entry.on_disk && state.state_id == entry.state.state_id)
        })
    }

    /// Whether a record is held at `address`.
    #[must_use]
    pub fn contains(&self, address: &XorName) -> bool {
        self.snapshot(address).is_some_and(|entry| entry.on_disk)
    }

    /// How many records the store holds.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner
            .index
            .lock()
            .values()
            .filter(|entry| entry.on_disk)
            .count()
    }

    /// Whether the store holds nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Directory holding the records.
    #[must_use]
    pub fn dir(&self) -> &Path {
        &self.inner.dir
    }

    /// The file the record at `address` is kept in.
    #[must_use]
    pub fn file_for(&self, address: &XorName) -> PathBuf {
        self.path_for(address)
    }

    /// Every state this node can serve, sorted by address.
    ///
    /// Taken from the index, which every other answer the store gives is also
    /// based on. A record whose file has gone is left out: it is not something
    /// this node can offer to anyone.
    #[must_use]
    pub fn held_states(&self) -> Vec<PointerState> {
        let mut states: Vec<PointerState> = self
            .inner
            .index
            .lock()
            .values()
            .filter(|entry| entry.on_disk)
            .map(|entry| entry.state)
            .collect();
        states.sort_unstable_by_key(|state| state.address);
        states
    }

    /// What the store has done since it was opened.
    #[must_use]
    pub fn stats(&self) -> PointerStoreStats {
        self.inner.counters.snapshot()
    }

    /// Remove the record at `address` and forget it entirely.
    ///
    /// For a node that is no longer responsible for the address. Unlike a
    /// record lost to the disk, nothing about it is remembered, because the
    /// node is not meant to take it back. Returns whether a file was removed,
    /// so the caller can give its space back to the disk budget.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Storage`] if the file exists and cannot be removed; the
    /// record is then still held and still indexed.
    pub async fn delete(&self, address: &XorName) -> Result<bool> {
        let inner = Arc::clone(&self.inner);
        let address = *address;
        let removed = spawn_blocking(move || inner.delete_blocking(&address))
            .await
            .map_err(|e| Error::Storage(format!("pointer delete panicked: {e}")))??;
        if removed {
            self.inner.counters.deleted.fetch_add(1, Ordering::Relaxed);
        }
        Ok(removed)
    }

    /// The state this node can actually serve at `address`, having read it
    /// back.
    ///
    /// The index is a claim about a file; this is that claim checked. The file
    /// must still be there and must still be the record the index names —
    /// comparing the state, not merely the address, because the disk and the
    /// index are updated under one lock and an answer taken between the two
    /// would otherwise describe a record that is no longer the one held.
    ///
    /// Only the structure is parsed: these bytes verified when they were
    /// committed, and the question here is what is held, not whether it is
    /// authentic. Corruption inside the signature therefore passes here — the
    /// state is read from the body — and is caught by [`Self::get`], which
    /// verifies and disowns. Checking it here instead would put an ML-DSA
    /// verification in front of the payment gate, which is the one place it
    /// must not be. A failed check disowns the entry, so the arrival that found
    /// it becomes a repair.
    fn held_state(&self, address: &XorName) -> Option<PointerState> {
        let entry = self.snapshot(address).filter(|entry| entry.on_disk)?;
        let serves = matches!(
            read_record_file(&self.path_for(address)),
            Ok(Some(ref bytes)) if matches!(
                PointerState::parse(bytes),
                Ok(ref state) if *state == entry.state
            )
        );
        if !serves {
            self.disown_if_unchanged(address, Some(entry.generation));
            return None;
        }
        Some(entry.state)
    }

    /// Copy out what is held for `address`, releasing the index lock at once.
    fn snapshot(&self, address: &XorName) -> Option<IndexEntry> {
        self.inner.index.lock().get(address).copied()
    }

    /// Stop serving `address`, but only if the entry is still the exact one
    /// the caller found unreadable.
    ///
    /// The entry stays, marked as no longer on disk: what was lost is what says
    /// which states can restore it.
    ///
    /// A read is not atomic with a write. Removing unconditionally would let a
    /// slow read of a corrupt file erase the entry for a record committed while
    /// it was reading, leaving the node holding a record it no longer
    /// announces, commits to, or can be audited for. Matching on the generation
    /// rather than the state identifier also covers the case where the record
    /// written meanwhile is a *repair of the same state*, which a state
    /// comparison could not tell apart from the entry being disowned.
    fn disown_if_unchanged(&self, address: &XorName, claimed: Option<u64>) {
        let Some(claimed) = claimed else {
            // Nothing was claimed when the read began, so there is nothing this
            // read is entitled to disown.
            return;
        };
        let mut index = self.inner.index.lock();
        if let Some(entry) = index.get_mut(address) {
            if entry.generation == claimed {
                entry.on_disk = false;
            }
        }
    }

    /// Path of the file backing `address`.
    fn path_for(&self, address: &XorName) -> PathBuf {
        record_path(&self.inner.dir, address)
    }
}

impl Inner {
    /// Keep `bytes` beside whatever else was recently replaced at `address`,
    /// dropping what has aged out.
    ///
    /// Nothing is evicted to make room here: the update that replaced it may
    /// yet fail, and a record evicted for an update that never happened would
    /// be lost for nothing. [`Self::trim_superseded`] does that once it has.
    fn keep_superseded(&self, address: XorName, bytes: Vec<u8>) {
        let now = Instant::now();
        let mut superseded = self.superseded.lock();
        drop_expired(&mut superseded, now);
        superseded
            .entry(address)
            .or_default()
            .push_back((now, Bytes::from(bytes)));
    }

    /// Past the cap, drop the oldest kept records, wherever they are.
    fn trim_superseded(&self) {
        let mut superseded = self.superseded.lock();
        let mut held: usize = superseded.values().map(VecDeque::len).sum();
        while held > MAX_SUPERSEDED {
            // Each address keeps its records oldest first, so the oldest
            // anywhere is the first of one of them.
            let Some(oldest) = superseded
                .iter()
                .filter_map(|(address, kept)| kept.front().map(|(at, _)| (*at, *address)))
                .min()
                .map(|(_, address)| address)
            else {
                break;
            };
            if let Some(kept) = superseded.get_mut(&oldest) {
                kept.pop_front();
                if kept.is_empty() {
                    superseded.remove(&oldest);
                }
            }
            held = held.saturating_sub(1);
        }
        drop(superseded);
    }

    /// Take back the record [`Self::keep_superseded`] just kept for `address`,
    /// when the update that replaced it did not happen after all. Called under
    /// the index lock that kept it, so nothing was kept for `address` since.
    fn unkeep_superseded(&self, address: &XorName) {
        let mut superseded = self.superseded.lock();
        if let Some(kept) = superseded.get_mut(address) {
            kept.pop_back();
            if kept.is_empty() {
                superseded.remove(address);
            }
        }
    }

    /// Remove the file and the index entry for `address` under one lock, so a
    /// commit can never land between the two and be forgotten on disk.
    fn delete_blocking(&self, address: &XorName) -> Result<bool> {
        let shard = shard_dir(&self.dir, address);
        let path = record_path(&self.dir, address);
        let removed = {
            let mut index = self.index.lock();
            let removed = match std::fs::remove_file(&path) {
                Ok(()) => true,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
                Err(e) => {
                    return Err(Error::Storage(format!(
                        "cannot delete {}: {e}",
                        path.display()
                    )))
                }
            };
            index.remove(address);
            removed
        };
        if removed {
            if let Err(e) = sync_directory(&shard) {
                warn!(
                    "{} is deleted, but {} could not be synced: {e}",
                    path.display(),
                    shard.display()
                );
            }
        }
        Ok(removed)
    }

    /// Compare, write and re-index under one lock.
    ///
    /// Runs entirely inside a blocking task: the lock is synchronous and is
    /// never released between the decision and the index update, so neither
    /// caller cancellation nor a concurrent writer can separate them.
    // Holding the guard across the write is the point of this function, so the
    // lint's advice to drop it earlier would reintroduce exactly the window
    // this closes: a second writer deciding against an index that no longer
    // describes the disk.
    #[allow(
        clippy::significant_drop_tightening,
        reason = "the write must happen under the same guard as the decision"
    )]
    fn commit_blocking(
        &self,
        record: &Pointer,
        reservation: Option<Reservation>,
    ) -> Result<PutOutcome> {
        let address = record.address();
        let shard = shard_dir(&self.dir, &address);
        let path = record_path(&self.dir, &address);

        // A cheap look before doing any work. The authoritative check is the
        // one under the lock below; this only avoids staging a file for an
        // arrival that is already obviously a no-op.
        if let Some(entry) = self.index.lock().get(&address).filter(|e| e.on_disk) {
            if entry.state.state_id == record.state_id() {
                return Ok(PutOutcome::Unchanged);
            }
            if !record.state().replaces(&entry.state) {
                return Ok(PutOutcome::Stale);
            }
        }

        // Stage and fsync the new bytes *before* taking the lock. This is the
        // slow part — a 5 KB write plus an fsync — and holding the index lock
        // across it would block every other address, including the cheap
        // lookups async callers make.
        let seq = self.write_seq.fetch_add(1, Ordering::Relaxed);
        let temp = shard.join(format!("{TEMP_PREFIX}{}-{seq}", hex::encode(address)));
        if let Err(failed) = stage(&temp, &record.to_bytes()) {
            // Bytes that could not be cleaned up are still on the disk, so the
            // charge for them stands rather than going back.
            if failed.bytes_remain {
                settle(reservation);
            }
            return Err(failed.error);
        }

        let outcome = {
            let mut index = self.index.lock();

            // Re-check: staging is not instantaneous and a newer state may
            // have committed while it ran.
            let replacing = index.get(&address).is_some_and(|entry| entry.on_disk);
            let outcome = match index.get(&address) {
                // Nothing held: any state lands.
                None => PutOutcome::Changed,
                // A record this node lost: the lost state itself lands, to
                // restore it, and so does anything that replaces it, but
                // nothing older, so an arrival verified before the loss cannot
                // roll the node back past it (the rule `admits` states).
                Some(entry @ IndexEntry { on_disk: false, .. }) => {
                    if entry.state.state_id == record.state_id()
                        || record.state().replaces(&entry.state)
                    {
                        PutOutcome::Changed
                    } else {
                        PutOutcome::Stale
                    }
                }
                Some(entry) if entry.state.state_id == record.state_id() => PutOutcome::Unchanged,
                Some(entry) if record.state().replaces(&entry.state) => PutOutcome::Changed,
                Some(_) => PutOutcome::Stale,
            };
            if outcome != PutOutcome::Changed {
                // Nothing lands, so the charge goes back — unless the staged
                // bytes could not be removed, in which case they are still on
                // the disk and the charge has to stand for them.
                if std::fs::remove_file(&temp).is_err() {
                    settle(reservation);
                }
                return Ok(outcome);
            }

            // What this replaces, read under the lock so it is the record the
            // index names. Kept for an audit that bound it, and kept before
            // the rename makes the new record visible, so a round 2 reading
            // the new record always finds the old one kept beside it. A record
            // that cannot be read is not kept, and an audit owed it fails as
            // it would have on the lost file.
            let mut kept = false;
            if replacing {
                if let Some(previous) = read_record_file(&path).ok().flatten() {
                    self.keep_superseded(address, previous);
                    kept = true;
                }
            }

            // The rename is the commit point: nothing fallible happens between
            // it and the index update, and both are under this one lock.
            if let Err(e) = rename_with_retry(&temp, &path) {
                // Nothing was replaced, so nothing replaced is kept.
                if kept {
                    self.unkeep_superseded(&address);
                }
                if std::fs::remove_file(&temp).is_err() {
                    settle(reservation);
                }
                return Err(Error::Storage(format!(
                    "cannot rename {} onto {}: {e}",
                    temp.display(),
                    path.display()
                )));
            }
            if kept {
                self.trim_superseded();
            }
            let generation = self.generation.fetch_add(1, Ordering::Relaxed);
            index.insert(address, IndexEntry::of(record, generation));
            // A file is on the disk now. Charge it whether or not this replaced
            // one: telling those apart would mean trusting an observation taken
            // before the rename, and that observation can be wrong in the one
            // direction that matters — a file the index claims can be gone, so
            // what looks like a replacement grows the disk after all.
            // Over-counting corrects itself at the next measurement.
            settle(reservation);
            outcome
        };

        // Durability of the directory entry, after the commit and outside the
        // lock. The record is already stored and indexed, so a failure here
        // cannot be reported as "nothing happened"; it is logged instead, which
        // is how an operator learns the filesystem is not giving the store what
        // it asks for.
        if let Err(e) = sync_directory(&shard) {
            warn!(
                "{} is stored and indexed, but {} could not be synced: {e}. It is \
                 visible now; its survival across a power loss depends on the \
                 filesystem",
                path.display(),
                shard.display()
            );
        }
        Ok(outcome)
    }
}

/// Take the exclusive lock that grants use of `dir`.
fn acquire_lock(dir: &Path) -> Result<File> {
    let path = dir.join(LOCK_FILE_NAME);
    let file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .map_err(|e| {
            Error::Storage(format!(
                "cannot create the pointer store lock {}: {e}",
                path.display()
            ))
        })?;
    file.try_lock_exclusive().map_err(|e| {
        Error::Storage(format!(
            "another pointer store already has {} open ({e}). Two stores over one \
             directory each keep their own index, and the staler one would overwrite \
             the other's newer record",
            dir.display()
        ))
    })?;
    Ok(file)
}

/// Read one record file, refusing anything that is not exactly a record long.
///
/// The length is taken from the directory entry before any bytes are read, so a
/// corrupt oversized file cannot be pulled into memory.
fn read_record_file(path: &Path) -> Result<Option<Vec<u8>>> {
    let file = match File::open(path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(Error::Storage(format!("pointer read failed: {e}"))),
    };
    let len = file
        .metadata()
        .map_err(|e| Error::Storage(format!("pointer stat failed: {e}")))?
        .len();
    if len != POINTER_WIRE_LEN as u64 {
        warn!(
            "Pointer file {} is {len} bytes, not {POINTER_WIRE_LEN}",
            path.display()
        );
        return Ok(None);
    }

    let mut bytes = Vec::with_capacity(POINTER_WIRE_LEN);
    // One byte past the record: a file that grew between the stat and the read
    // is refused rather than silently truncated into something that parses.
    file.take(POINTER_WIRE_LEN as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| Error::Storage(format!("pointer read failed: {e}")))?;
    if bytes.len() != POINTER_WIRE_LEN {
        warn!(
            "Pointer file {} changed size while being read",
            path.display()
        );
        return Ok(None);
    }
    Ok(Some(bytes))
}

/// Create the shard directories, so a write never has to.
fn create_shards(dir: &Path) -> Result<()> {
    for shard in 0..SHARD_COUNT {
        let path = dir.join(format!("{shard:02x}"));
        std::fs::create_dir_all(&path)
            .map_err(|e| Error::Storage(format!("cannot create {}: {e}", path.display())))?;
    }
    sync_directory(dir)
}

/// Rebuild the index from the records in `dir`'s shards.
///
/// Each record's structure is parsed, but its signature is not checked. Every
/// record was verified when it was committed, and every read verifies it again
/// before serving it, so a file damaged in place is caught — and disowned — the
/// first time anyone asks for it. Checking an ML-DSA signature per record here
/// instead would make opening a large store take minutes, and the chunk store
/// likewise opens on names alone.
///
/// A record left at the top level by the flat layout earlier builds used is
/// moved into its shard.
fn scan(dir: &Path) -> Result<HashMap<XorName, IndexEntry>> {
    let entries = std::fs::read_dir(dir)
        .map_err(|e| Error::Storage(format!("cannot read {}: {e}", dir.display())))?;

    let mut index = HashMap::new();
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                warn!("Skipping unreadable pointer directory entry: {e}");
                continue;
            }
        };
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if name == LOCK_FILE_NAME {
            continue;
        }
        if path.is_dir() {
            if name.len() == 2 && name.bytes().all(|b| b.is_ascii_hexdigit()) {
                scan_shard(&path, &mut index);
            }
            continue;
        }
        adopt_flat_record(dir, &path, name, &mut index);
    }
    Ok(index)
}

/// Index the records in one shard directory.
fn scan_shard(shard: &Path, index: &mut HashMap<XorName, IndexEntry>) {
    let entries = match std::fs::read_dir(shard) {
        Ok(entries) => entries,
        Err(e) => {
            warn!("Skipping unreadable pointer shard {}: {e}", shard.display());
            return;
        }
    };
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                warn!("Skipping unreadable pointer directory entry: {e}");
                continue;
            }
        };
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if name.starts_with(TEMP_PREFIX) {
            // A temporary file means a crash mid-write: the rename never
            // happened, so the old record (if any) is intact and the partial
            // file has no claim. Sweep it, or the next write to that address
            // collides with it — `create_new` would refuse, and the write
            // sequence restarts at zero on every opening.
            if let Err(e) = std::fs::remove_file(&path) {
                warn!(
                    "Could not sweep the partial pointer write {}: {e}",
                    path.display()
                );
            }
            continue;
        }
        let Some(state) = parse_record_file(&path) else {
            continue;
        };
        let in_its_shard = shard
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n == shard_name(&state.address));
        if hex::encode(state.address) != name || !in_its_shard {
            warn!(
                "Skipping pointer file {} that is not at its own address",
                path.display()
            );
            continue;
        }
        let generation = u64::try_from(index.len()).unwrap_or(u64::MAX);
        index.insert(state.address, IndexEntry::held(state, generation));
    }
}

/// Move a record from the flat layout into its shard and index it.
fn adopt_flat_record(
    dir: &Path,
    path: &Path,
    name: &str,
    index: &mut HashMap<XorName, IndexEntry>,
) {
    if name.starts_with(TEMP_PREFIX) {
        if let Err(e) = std::fs::remove_file(path) {
            warn!(
                "Could not sweep the partial pointer write {}: {e}",
                path.display()
            );
        }
        return;
    }
    let Some(state) = parse_record_file(path) else {
        return;
    };
    if hex::encode(state.address) != name {
        warn!(
            "Skipping pointer file {} that is not at its own address",
            path.display()
        );
        return;
    }
    let target = record_path(dir, &state.address);
    if let Err(e) = rename_with_retry(path, &target) {
        warn!(
            "Could not move pointer file {} into its shard: {e}",
            path.display()
        );
        return;
    }
    let generation = u64::try_from(index.len()).unwrap_or(u64::MAX);
    index.insert(state.address, IndexEntry::held(state, generation));
}

/// Read a record file and parse its structure, logging anything unusable.
fn parse_record_file(path: &Path) -> Option<PointerState> {
    let bytes = match read_record_file(path) {
        Ok(Some(bytes)) => bytes,
        Ok(None) => return None,
        Err(e) => {
            warn!("Skipping unreadable pointer file {}: {e}", path.display());
            return None;
        }
    };
    match PointerState::parse(&bytes) {
        Ok(state) => Some(state),
        Err(e) => {
            warn!("Skipping invalid pointer file {}: {e}", path.display());
            None
        }
    }
}

/// Write `bytes` to `temp` and fsync it, ready to be renamed into place.
///
/// Leaves nothing half written: the bytes are durable in the temporary file
/// before any rename can make them visible. The caller performs the rename,
/// which is the commit point.
///
/// A failure tries to remove what it wrote, and says whether that worked:
/// `Err(StagingFailed { bytes_remain })` reports a partial file still on the
/// disk, so the caller knows the charge for it cannot be given back.
fn stage(temp: &Path, bytes: &[u8]) -> std::result::Result<(), StagingFailed> {
    // `create_new` so a leftover temporary file from a crashed write is never
    // silently appended to or shared with a concurrent writer.
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(temp)
        .map_err(|e| StagingFailed {
            // Nothing was created, so nothing is left behind.
            error: Error::Storage(format!("cannot create {}: {e}", temp.display())),
            bytes_remain: false,
        })?;
    let written = file
        .write_all(bytes)
        .and_then(|()| file.sync_all())
        .map_err(|e| Error::Storage(format!("cannot write {}: {e}", temp.display())));
    drop(file);
    if let Err(error) = written {
        // A partial file exists. If it cannot be removed it is still occupying
        // the disk, and its charge has to stand for it.
        return Err(StagingFailed {
            error,
            bytes_remain: std::fs::remove_file(temp).is_err(),
        });
    }
    Ok(())
}

/// A staged write that did not complete, and whether it left bytes behind.
struct StagingFailed {
    /// What went wrong, for the caller to return.
    error: Error,
    /// Whether a partial file is still on the disk.
    bytes_remain: bool,
}

/// Turn a charge into bytes that are now on the disk.
///
/// A charge that is simply dropped is released instead, which is what every
/// path that writes nothing wants.
fn settle(reservation: Option<Reservation>) {
    if let Some(reservation) = reservation {
        reservation.commit();
    }
}

/// Flush the directory entry a rename created.
///
/// Without it a crash can leave the entry unflushed and the record invisible on
/// restart.
#[cfg(unix)]
fn sync_directory(dir: &Path) -> Result<()> {
    match File::open(dir) {
        Ok(handle) => handle
            .sync_all()
            .map_err(|e| Error::Storage(format!("cannot sync {}: {e}", dir.display()))),
        Err(e) => Err(Error::Storage(format!(
            "cannot open {} to flush it: {e}",
            dir.display()
        ))),
    }
}

/// As above, where there is no such thing to ask for.
///
/// A directory cannot be opened as a file on Windows without backup semantics,
/// so the Unix form fails on every write there — which is not a durability
/// warning, it is the wrong question. NTFS orders the rename's own metadata.
#[cfg(not(unix))]
#[allow(clippy::unnecessary_wraps, reason = "one signature for both platforms")]
fn sync_directory(_dir: &Path) -> Result<()> {
    Ok(())
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "test assertions"
)]
mod tests {
    use super::*;
    use ant_protocol::pointer::{PointerTarget, PointerTargetKind, POINTER_BODY_LEN};
    use saorsa_pqc::api::sig::{ml_dsa_65, MlDsaPublicKey, MlDsaSecretKey};
    use std::future::Future;

    fn keypair(seed: u8) -> (MlDsaPublicKey, MlDsaSecretKey) {
        ml_dsa_65().generate_keypair_from_seed(&[seed; 32])
    }

    fn signed(seed: u8, counter: u64, target_byte: u8) -> Pointer {
        let (pk, sk) = keypair(seed);
        let target = PointerTarget::new(PointerTargetKind::Chunk, [target_byte; 32]);
        Pointer::sign(&sk, &pk, counter, target).expect("sign")
    }

    /// A record with its signature destroyed: the body still parses, the
    /// record does not verify.
    fn forged(record: &Pointer) -> Vec<u8> {
        let mut bytes = record.to_bytes();
        if let Some(byte) = bytes.get_mut(POINTER_BODY_LEN + 3) {
            *byte ^= 0xff;
        }
        assert!(
            Pointer::from_bytes(&bytes).is_err(),
            "the forged record must not verify"
        );
        bytes
    }

    async fn store() -> (PointerStore, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("tempdir");
        let store = PointerStore::new(dir.path()).await.expect("open store");
        (store, dir)
    }

    /// The record an update replaces stays servable for a while, byte for
    /// byte, so an audit that bound it before the update is not failed by it.
    #[tokio::test]
    async fn an_update_keeps_the_record_it_replaced_for_a_while() {
        let (store, _dir) = store().await;
        let first = signed(1, 1, 1);
        store.put_bytes(&first.to_bytes()).await.expect("put");
        assert!(
            store.superseded_all(&first.address()).is_empty(),
            "a creation replaces nothing"
        );

        let second = signed(1, 2, 2);
        assert_eq!(
            store.put_bytes(&second.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );
        assert_eq!(
            store.superseded_all(&first.address()),
            vec![Bytes::from(first.to_bytes())],
            "the replaced record, exactly as it was held"
        );
        assert_eq!(
            store.record_bytes(&first.address()).await.expect("read"),
            Some(second.to_bytes()),
            "and the new one is what is held"
        );

        // A stale arrival replaces nothing, so it keeps nothing.
        store.put_bytes(&first.to_bytes()).await.expect("put");
        assert_eq!(
            store.superseded_all(&first.address()),
            vec![Bytes::from(first.to_bytes())]
        );

        // A later update keeps the one before it too, newest first: an audit
        // may have bound either.
        let third = signed(1, 3, 3);
        store.put_bytes(&third.to_bytes()).await.expect("put");
        assert_eq!(
            store.superseded_all(&first.address()),
            vec![
                Bytes::from(second.to_bytes()),
                Bytes::from(first.to_bytes())
            ]
        );
        assert_eq!(
            store.superseded(&first.address()),
            Some(second.to_bytes()),
            "the earlier accessor still answers with the record last replaced"
        );
    }

    /// Past the cap the oldest record kept goes first, whichever address it
    /// is for, and an address whose last record goes is forgotten.
    /// Keeping a record evicts nothing: an update that then fails takes back
    /// what it kept and leaves every other kept record where it was.
    #[tokio::test]
    async fn a_record_kept_for_an_update_that_fails_costs_no_other_record() {
        let (store, _dir) = store().await;
        let (owed, failing) = ([1u8; 32], [2u8; 32]);
        store.inner.keep_superseded(owed, vec![1]);
        for i in 0..MAX_SUPERSEDED - 1 {
            store
                .inner
                .keep_superseded(failing, (i as u64).to_le_bytes().to_vec());
        }
        // The cap is full. The next update keeps its record first ...
        store.inner.keep_superseded(failing, vec![0xFF]);
        // ... and its rename fails, so it takes that record back.
        store.inner.unkeep_superseded(&failing);
        assert_eq!(
            store.superseded_all(&owed),
            vec![Bytes::from(vec![1])],
            "the record an audit may be owed is still kept"
        );
        assert_eq!(store.superseded_all(&failing).len(), MAX_SUPERSEDED - 1);
    }

    /// A replaced record past its retention is forgotten even if no update
    /// comes to do it.
    #[tokio::test]
    async fn expired_replaced_records_are_dropped_without_another_update() {
        let (store, _dir) = store().await;
        let old = Instant::now()
            .checked_sub(SUPERSEDED_RETENTION + Duration::from_secs(1))
            .expect("the clock is past one retention");
        store
            .inner
            .superseded
            .lock()
            .insert([3u8; 32], VecDeque::from([(old, Bytes::from(vec![3]))]));
        store.inner.keep_superseded([4u8; 32], vec![4]);
        store.drop_expired_superseded();
        assert!(
            store.superseded_all(&[3u8; 32]).is_empty()
                && !store.inner.superseded.lock().contains_key(&[3u8; 32]),
            "the expired record is gone"
        );
        assert!(
            store.inner.superseded.lock().contains_key(&[4u8; 32]),
            "a fresh one stays"
        );
    }

    #[tokio::test]
    async fn past_the_cap_the_oldest_replaced_record_anywhere_goes_first() {
        let (store, _dir) = store().await;
        let (first, second) = ([1u8; 32], [2u8; 32]);
        let keep = |address: XorName, bytes: Vec<u8>| {
            store.inner.keep_superseded(address, bytes);
            store.inner.trim_superseded();
        };
        keep(first, vec![1]);
        for i in 0..MAX_SUPERSEDED - 1 {
            keep(second, (i as u64).to_le_bytes().to_vec());
        }
        assert_eq!(store.superseded_all(&first), vec![Bytes::from(vec![1])]);
        assert_eq!(store.superseded_all(&second).len(), MAX_SUPERSEDED - 1);

        // One more: the first address held the oldest record, so it goes.
        keep(second, vec![0xFF]);
        let evicted = store.superseded_all(&first);
        assert!(
            evicted.is_empty(),
            "expected the oldest address evicted, got {evicted:?}"
        );
        assert!(!store.inner.superseded.lock().contains_key(&first));
        assert_eq!(store.superseded_all(&second).len(), MAX_SUPERSEDED);

        // And the next goes from the front of the second address's history.
        keep(first, vec![2]);
        let kept = store.superseded_all(&second);
        assert_eq!(kept.len(), MAX_SUPERSEDED - 1);
        assert_eq!(kept.first(), Some(&Bytes::from(vec![0xFF])), "newest first");
        assert_eq!(
            kept.last(),
            Some(&Bytes::from(1u64.to_le_bytes().to_vec())),
            "the oldest of them went"
        );
    }

    #[tokio::test]
    async fn stores_then_reads_back_the_same_bytes() {
        let (store, _dir) = store().await;
        let record = signed(1, 1, 1);
        assert_eq!(
            store.put_bytes(&record.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );

        let read = store
            .get(&record.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(read.to_bytes(), record.to_bytes());
        assert_eq!(store.state_id(&record.address()), Some(record.state_id()));
        assert!(store.contains(&record.address()));
        assert_eq!(store.len(), 1);
    }

    #[tokio::test]
    async fn a_higher_counter_replaces_and_a_lower_one_does_not() {
        let (store, _dir) = store().await;
        let first = signed(1, 1, 1);
        let second = signed(1, 2, 1);
        assert_eq!(
            store.put_bytes(&first.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );
        assert_eq!(
            store.put_bytes(&second.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );
        assert_eq!(
            store.put_bytes(&first.to_bytes()).await.expect("put"),
            PutOutcome::Stale
        );

        let held = store
            .get(&first.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(held.counter(), 2);
        assert_eq!(store.len(), 1, "an update replaces in place");
    }

    #[tokio::test]
    async fn re_signing_one_state_never_reaches_the_disk() {
        // One payment must not fund many writes. Every re-signature of a stored
        // state is a no-op, so storage, replication and commitment work is paid
        // for once.
        let (store, _dir) = store().await;
        let first = signed(1, 5, 5);
        store.put_bytes(&first.to_bytes()).await.expect("put");

        let path = store.file_for(&first.address());
        let held_bytes = std::fs::read(&path).expect("read");

        for _ in 0..16 {
            let variant = signed(1, 5, 5);
            assert_ne!(
                variant.to_bytes(),
                first.to_bytes(),
                "signing is randomized"
            );
            assert_eq!(variant.state_id(), first.state_id());
            assert_eq!(
                store.put_bytes(&variant.to_bytes()).await.expect("put"),
                PutOutcome::Unchanged
            );
        }

        assert_eq!(
            std::fs::read(&path).expect("read"),
            held_bytes,
            "not one of the 16 re-signatures reached the disk"
        );
    }

    #[tokio::test]
    async fn a_resubmission_is_refused_before_its_signature_is_checked() {
        // An arrival that cannot change anything is a no-op whether or not it
        // is correctly signed, so it must not buy an ML-DSA verification. A
        // record whose signature is destroyed proves the check was skipped:
        // had it run, this would have been an error rather than Unchanged.
        let (store, _dir) = store().await;
        let held = signed(1, 4, 4);
        store.put_bytes(&held.to_bytes()).await.expect("put");

        assert_eq!(
            store.put_bytes(&forged(&held)).await.expect("put"),
            PutOutcome::Unchanged
        );

        let after = store
            .get(&held.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(after.to_bytes(), held.to_bytes(), "nothing was written");
    }

    #[tokio::test]
    async fn a_stale_arrival_is_refused_before_its_signature_is_checked() {
        let (store, _dir) = store().await;
        store
            .put_bytes(&signed(1, 9, 1).to_bytes())
            .await
            .expect("put");

        // Unsigned *and* stale: refused as Stale, which can only happen if the
        // signature was never checked.
        let older = signed(1, 2, 1);
        assert_eq!(
            store.put_bytes(&forged(&older)).await.expect("put"),
            PutOutcome::Stale
        );
    }

    #[tokio::test]
    async fn a_would_be_winner_is_always_verified() {
        // Losing records skip verification; a record that would win never does.
        let (store, _dir) = store().await;
        store
            .put_bytes(&signed(1, 1, 1).to_bytes())
            .await
            .expect("put");

        let winner = signed(1, 5, 1);
        assert!(store.put_bytes(&forged(&winner)).await.is_err());

        let held = store
            .get(&winner.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(held.counter(), 1, "the forged winner did not land");
    }

    #[tokio::test]
    async fn an_arrival_that_changes_nothing_is_not_a_candidate() {
        let (store, _dir) = store().await;
        let held = signed(1, 6, 6);
        store.put_bytes(&held.to_bytes()).await.expect("put");

        match store.inspect(&held.to_bytes()).await.expect("inspect") {
            Inspected::Unchanged(_) => (),
            other => panic!("an identical state is not a candidate, got {other:?}"),
        }
        match store
            .inspect(&signed(1, 1, 6).to_bytes())
            .await
            .expect("inspect")
        {
            Inspected::Stale(_) => (),
            other => panic!("a stale record is not a candidate, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_verified_record_exposes_what_a_payment_check_needs() {
        let (store, _dir) = store().await;
        let record = signed(1, 2, 2);
        let verified = verified(&store, &record).await;
        // A verified record is a `Pointer`, so the payment check reads the
        // address and state straight off it — there is no wrapper type in
        // between restating what it already knows.
        assert_eq!(verified.address(), record.address());
        assert_eq!(verified.state_id(), record.state_id());
        assert_eq!(verified.to_bytes(), record.to_bytes());
        assert_eq!(
            store.commit(verified, None).await.expect("commit"),
            PutOutcome::Changed
        );
        assert_eq!(store.len(), 1);
    }

    #[tokio::test]
    async fn a_commit_that_writes_nothing_gives_its_charge_back() {
        // The reservation settles inside the commit transaction, so this is
        // where a no-op has to release it. Losing a race is the reachable way
        // to get there: the arrival is a candidate when it is inspected, and by
        // the time it commits a better state is held.
        //
        // Asserted on the guard's own counters, because "the next reservation
        // still succeeds" would pass just as well with the charge stranded.
        let (store, dir) = store().await;
        let chunks = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: false,
            disk_reserve: 0,
        })
        .await
        .expect("chunk store");

        // Verified while nothing is held, so it is a candidate...
        let slow = verified(&store, &signed(1, 2, 1)).await;
        // ...and a better state lands before it commits.
        store
            .put_bytes(&signed(1, 7, 1).to_bytes())
            .await
            .expect("put");

        let before = chunks.capacity_counters();
        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");
        assert!(
            chunks.capacity_counters().1 > before.1,
            "taking a charge must raise in-flight"
        );

        assert_eq!(
            store.commit(slow, Some(charge)).await.expect("commit"),
            PutOutcome::Stale,
            "the newer state must stand"
        );
        assert_eq!(
            chunks.capacity_counters(),
            before,
            "a write that did not happen must leave both counters where it found them"
        );
    }

    #[tokio::test]
    async fn a_commit_that_writes_charges_the_disk_for_it() {
        // The other half: bytes that land move from in-flight to written, so
        // the guard counts them against the reserve from then on.
        let (store, dir) = store().await;
        let chunks = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
            root_dir: dir.path().to_path_buf(),
            verify_on_read: false,
            disk_reserve: 0,
        })
        .await
        .expect("chunk store");

        let record = verified(&store, &signed(1, 0, 1)).await;
        // Exactly one allocation charge, not merely "more than before": a
        // record is rounded up to the allocation unit, so an inequality would
        // accept one charge standing in for two writes.
        let one = crate::storage::ChunkStore::capacity_charge_for(POINTER_WIRE_LEN as u64);
        let (written_before, in_flight_before) = chunks.capacity_counters();
        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");

        assert_eq!(
            store.commit(record, Some(charge)).await.expect("commit"),
            PutOutcome::Changed
        );
        assert_eq!(
            chunks.capacity_counters(),
            (written_before + one, in_flight_before),
            "the bytes that landed move from in flight to written, exactly once"
        );

        // A replacement charges too: telling it apart would mean trusting an
        // observation taken before the rename.
        let update = verified(&store, &signed(1, 1, 1)).await;
        let charge = chunks.reserve(POINTER_WIRE_LEN as u64).expect("reserve");
        assert_eq!(
            store.commit(update, Some(charge)).await.expect("commit"),
            PutOutcome::Changed
        );
        assert_eq!(
            chunks.capacity_counters(),
            (written_before + 2 * one, in_flight_before)
        );
    }

    #[tokio::test]
    async fn a_commit_rechecks_what_verification_saw() {
        // Verification runs before the payment check; a newer state can land
        // while that check is in flight, and must not then be overwritten.
        let (store, _dir) = store().await;
        let slow = verified(&store, &signed(1, 2, 1)).await;

        // Someone else's newer state arrives while the payment is being checked.
        store
            .put_bytes(&signed(1, 7, 1).to_bytes())
            .await
            .expect("put");

        assert_eq!(
            store.commit(slow, None).await.expect("commit"),
            PutOutcome::Stale,
            "the newer state must survive a late commit"
        );
        let held = store
            .get(&signed(1, 2, 1).address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(held.counter(), 7);
    }

    #[tokio::test]
    async fn put_bytes_rejects_junk() {
        let (store, _dir) = store().await;
        assert!(store.put_bytes(b"not a pointer").await.is_err());
        assert!(store.put_bytes(&[]).await.is_err());
        assert!(store.is_empty());
    }

    #[tokio::test]
    async fn every_rotation_of_a_delivery_reaches_one_answer() {
        let records = [
            signed(1, 1, 9),
            signed(1, 3, 4),
            signed(1, 3, 1),
            signed(1, 2, 8),
            signed(1, 3, 7),
        ];
        let address = records.first().expect("non-empty").address();

        let mut winners = Vec::new();
        for rotation in 0..records.len() {
            let (store, _dir) = store().await;
            for offset in 0..records.len() {
                let index = (rotation + offset) % records.len();
                let record = records.get(index).expect("in range");
                store.put_bytes(&record.to_bytes()).await.expect("put");
            }
            let held = store.get(&address).await.expect("get").expect("present");
            winners.push(held.state_id());
        }

        let distinct: std::collections::BTreeSet<&XorName> = winners.iter().collect();
        assert_eq!(
            distinct.len(),
            1,
            "every rotation converges: {winners:?}. Exhaustive permutations are \
             covered by the convergence property test"
        );
    }

    #[tokio::test]
    async fn a_node_started_empty_reaches_the_same_answer() {
        let dir = tempfile::tempdir().expect("tempdir");
        let address;
        let before;
        {
            let store = PointerStore::new(dir.path()).await.expect("open");
            for record in [signed(1, 1, 1), signed(1, 4, 2), signed(1, 2, 3)] {
                store.put_bytes(&record.to_bytes()).await.expect("put");
            }
            address = signed(1, 1, 1).address();
            before = store.get(&address).await.expect("get").expect("present");
        }

        // A fresh store over the same directory, as after a restart. The first
        // must be dropped: the directory lock allows only one at a time.
        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
        assert_eq!(reopened.len(), 1);
        let after = reopened.get(&address).await.expect("get").expect("present");
        assert_eq!(after.to_bytes(), before.to_bytes());
        assert_eq!(reopened.state_id(&address), Some(before.state_id()));
    }

    #[tokio::test]
    async fn a_second_store_over_one_directory_is_refused() {
        // Two indexes over one set of files means the staler one overwrites the
        // fresher one's record.
        let dir = tempfile::tempdir().expect("tempdir");
        let _first = PointerStore::new(dir.path()).await.expect("open");
        let err = PointerStore::new(dir.path())
            .await
            .expect_err("a second store must not open the same directory");
        let message = format!("{err}");
        assert!(
            message.contains("another pointer store already has"),
            "it must be refused by the directory lock, not by something else: {message}"
        );
    }

    #[tokio::test]
    async fn two_owners_occupy_two_addresses() {
        let (store, _dir) = store().await;
        let first = signed(1, 1, 1);
        let second = signed(2, 1, 1);
        assert_ne!(first.address(), second.address());
        store.put_bytes(&first.to_bytes()).await.expect("put");
        store.put_bytes(&second.to_bytes()).await.expect("put");
        assert_eq!(store.len(), 2);
    }

    #[tokio::test]
    async fn a_corrupt_file_is_forgotten_so_the_record_can_be_repaired() {
        let (store, _dir) = store().await;
        let record = signed(1, 1, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");

        let path = store.file_for(&record.address());
        let mut bytes = std::fs::read(&path).expect("read back");
        if let Some(byte) = bytes.get_mut(10) {
            *byte ^= 0xff;
        }
        std::fs::write(&path, &bytes).expect("corrupt it");

        assert!(store.get(&record.address()).await.expect("get").is_none());
        assert!(
            !store.contains(&record.address()),
            "the index must not keep claiming a record the disk lost"
        );
        assert_eq!(store.state_id(&record.address()), None);

        // The repair a peer would send is accepted rather than dismissed as
        // "unchanged", which is the whole point of forgetting it.
        assert_eq!(
            store.put_bytes(&record.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );
        assert!(store.get(&record.address()).await.expect("get").is_some());
    }

    /// Run the production sequence as far as the payment gate: inspect, then
    /// verify the candidate it yields.
    async fn verified(store: &PointerStore, record: &Pointer) -> Pointer {
        match store.inspect(&record.to_bytes()).await.expect("inspect") {
            Inspected::Candidate(parsed) => store.verify(parsed).await.expect("verify"),
            other => panic!("expected a candidate, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_resubmission_repairs_a_record_the_disk_lost() {
        // "Unchanged" is an acknowledgement: the sender stops on it. If the
        // index still claims a record whose file has gone, answering Unchanged
        // would end the write while this node holds nothing.
        let (store, _dir) = store().await;
        let record = signed(1, 0, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");

        // The file disappears under the node; the index has not noticed.
        std::fs::remove_file(store.file_for(&record.address())).expect("remove");
        assert!(
            store.contains(&record.address()),
            "the index still claims it"
        );

        // The same state arriving again is a repair, not a no-op.
        assert_eq!(
            store.put_bytes(&record.to_bytes()).await.expect("put"),
            PutOutcome::Changed,
            "a resubmission must repair a record the disk lost"
        );
        assert!(store.get(&record.address()).await.expect("get").is_some());
    }

    /// The commit itself holds the line `admits` states for a lost record, so
    /// an older state that reaches it without that gate, or was admitted
    /// before the loss, cannot roll the node back.
    #[tokio::test]
    async fn a_commit_after_a_loss_takes_nothing_older_than_what_was_lost() {
        let (store, _dir) = store().await;
        let held = signed(1, 3, 1);
        store.put_bytes(&held.to_bytes()).await.expect("put");
        std::fs::remove_file(store.file_for(&held.address())).expect("remove");
        assert!(store.get(&held.address()).await.expect("get").is_none());

        assert_eq!(
            store
                .put_bytes(&signed(1, 2, 2).to_bytes())
                .await
                .expect("put"),
            PutOutcome::Stale,
            "an older state must not replace the one that was lost"
        );
        assert!(!store.contains(&held.address()), "nothing was written");
        assert_eq!(
            store.put_bytes(&held.to_bytes()).await.expect("put"),
            PutOutcome::Changed,
            "the lost state itself is restored"
        );
    }

    #[tokio::test]
    async fn a_lost_record_is_restored_and_cannot_be_rolled_back() {
        // The node remembers what it lost. Without that the address would look
        // untouched, where any record is admissible, and a replay of an older
        // state would roll the node back.
        let (store, _dir) = store().await;
        for counter in 0..=3u64 {
            store
                .put_bytes(&signed(1, counter, 1).to_bytes())
                .await
                .expect("put");
        }
        let held = signed(1, 3, 1);

        std::fs::remove_file(store.file_for(&held.address())).expect("remove");
        // A read notices the loss and stops the node answering for it.
        assert!(store.get(&held.address()).await.expect("get").is_none());
        assert!(!store.contains(&held.address()), "it is not served");
        assert_eq!(store.state_id(&held.address()), None);

        // What it lost is what it will take back, and so is anything newer.
        assert!(
            store.admits(&held.state()),
            "the state this node lost must be admissible again"
        );
        assert!(
            store.admits(&signed(1, 9, 1).state()),
            "so must a newer state the rest of the group has moved on to"
        );
        assert!(
            !store.admits(&signed(1, 2, 1).state()),
            "but not one that loses to what was lost"
        );

        assert_eq!(
            store.put_bytes(&held.to_bytes()).await.expect("put"),
            PutOutcome::Changed,
            "the repair must write, not be answered as unchanged"
        );
        let back = store
            .get(&held.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(back.counter(), 3);
        assert_eq!(back.state_id(), held.state_id());

        // Held again: any later counter is admitted, the held state is not.
        assert!(store.admits(&signed(1, 4, 1).state()));
        assert!(store.admits(&signed(1, 6, 1).state()), "a skip is admitted");
        assert!(
            !store.admits(&held.state()),
            "held again, so a resubmission"
        );
    }

    #[tokio::test]
    async fn a_file_swapped_for_another_valid_record_is_not_answered_for() {
        // The index names one state; the disk holds a different, perfectly
        // valid one. Answering from the index would acknowledge a state this
        // node cannot serve.
        let (store, _dir) = store().await;
        let indexed = signed(1, 4, 1);
        store.put_bytes(&indexed.to_bytes()).await.expect("put");

        let other = signed(1, 9, 1);
        std::fs::write(store.file_for(&indexed.address()), other.to_bytes())
            .expect("swap the file");

        match store.inspect(&indexed.to_bytes()).await.expect("inspect") {
            Inspected::Candidate(_) => (),
            other => panic!("a state the node cannot serve must not be answered for: {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_deleted_file_is_forgotten_too() {
        let (store, _dir) = store().await;
        let record = signed(1, 1, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");

        std::fs::remove_file(store.file_for(&record.address())).expect("remove");
        assert!(store.get(&record.address()).await.expect("get").is_none());
        assert!(!store.contains(&record.address()));
    }

    #[tokio::test]
    async fn a_scan_skips_what_it_cannot_validate() {
        let dir = tempfile::tempdir().expect("tempdir");
        let record = signed(1, 1, 1);
        {
            let store = PointerStore::new(dir.path()).await.expect("open");
            store.put_bytes(&record.to_bytes()).await.expect("put");

            // Junk under a plausible name, an oversized file, and a partial write.
            std::fs::write(store.file_for(&[9u8; 32]), b"not a pointer").expect("write junk");
            std::fs::write(store.file_for(&[8u8; 32]), vec![0u8; POINTER_WIRE_LEN * 4])
                .expect("write oversized");
            std::fs::write(
                store.file_for(&[7u8; 32]).with_file_name(".tmp-abc-0"),
                vec![0u8; POINTER_WIRE_LEN],
            )
            .expect("write temp");
        }

        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
        assert_eq!(reopened.len(), 1, "only the valid record is indexed");
        assert!(reopened.contains(&record.address()));
    }

    #[tokio::test]
    async fn concurrent_writers_leave_the_index_agreeing_with_the_disk() {
        let (store, _dir) = store().await;
        let address = signed(1, 0, 0).address();

        let mut tasks = Vec::new();
        for counter in 1..=12u64 {
            let store = store.clone();
            let bytes = signed(1, counter, 1).to_bytes();
            tasks.push(tokio::spawn(async move { store.put_bytes(&bytes).await }));
        }
        for task in tasks {
            task.await.expect("join").expect("put");
        }

        let held = store.get(&address).await.expect("get").expect("present");
        assert_eq!(held.counter(), 12, "the highest counter must win");
        assert_eq!(store.state_id(&address), Some(held.state_id()));
        assert_eq!(store.len(), 1);

        // No temporary file survived the race.
        assert!(
            temporary_files(&store).is_empty(),
            "temporary files were left behind"
        );
    }

    /// Every temporary file anywhere under the store.
    fn temporary_files(store: &PointerStore) -> Vec<PathBuf> {
        let mut found = Vec::new();
        for shard in std::fs::read_dir(store.dir()).expect("read dir").flatten() {
            if !shard.path().is_dir() {
                continue;
            }
            for entry in std::fs::read_dir(shard.path())
                .expect("read shard")
                .flatten()
            {
                if entry.file_name().to_string_lossy().starts_with(TEMP_PREFIX) {
                    found.push(entry.path());
                }
            }
        }
        found
    }

    #[tokio::test]
    async fn a_record_is_kept_in_the_shard_named_by_its_last_byte() {
        let (store, _dir) = store().await;
        let record = signed(3, 0, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");

        let path = store.file_for(&record.address());
        let last = record.address().last().copied().expect("32 bytes");
        assert_eq!(
            path.parent().expect("a shard"),
            store.dir().join(format!("{last:02x}"))
        );
        assert_eq!(
            std::fs::read(&path).expect("read"),
            record.to_bytes(),
            "the record is on disk where the store says it is"
        );
        let shards = std::fs::read_dir(store.dir())
            .expect("read dir")
            .flatten()
            .filter(|e| e.path().is_dir())
            .count();
        assert_eq!(shards, 256, "every shard exists before any write needs it");
    }

    #[tokio::test]
    async fn held_states_lists_what_is_served_in_address_order() {
        let (store, _dir) = store().await;
        let records: Vec<Pointer> = (1..=5u8).map(|seed| signed(seed, 2, seed)).collect();
        for record in &records {
            store.put_bytes(&record.to_bytes()).await.expect("put");
        }
        let lost = records.first().expect("five records");
        std::fs::remove_file(store.file_for(&lost.address())).expect("remove");
        assert!(store.get(&lost.address()).await.expect("get").is_none());

        let held = store.held_states();
        let mut expected: Vec<XorName> = records.iter().skip(1).map(Pointer::address).collect();
        expected.sort_unstable();
        assert_eq!(
            held.iter().map(|state| state.address).collect::<Vec<_>>(),
            expected,
            "sorted, and without the record whose file is gone"
        );
        for state in &held {
            assert_eq!(store.state_id(&state.address), Some(state.state_id));
        }
    }

    #[tokio::test]
    async fn delete_removes_the_record_and_forgets_it() {
        let (store, _dir) = store().await;
        let record = signed(4, 3, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");
        let path = store.file_for(&record.address());

        assert!(store.delete(&record.address()).await.expect("delete"));
        assert!(!path.exists(), "the file is gone");
        assert!(!store.contains(&record.address()));
        assert!(store.get(&record.address()).await.expect("get").is_none());
        // Forgotten, not remembered as lost: an older state is admissible again,
        // which a lost record would refuse.
        assert!(store.admits(&signed(4, 1, 1).state()));
        assert!(
            !store.delete(&record.address()).await.expect("delete"),
            "nothing left to delete"
        );
        assert_eq!(store.stats().deleted, 1);

        // Still usable afterwards, and gone across a reopen too.
        store
            .put_bytes(&record.to_bytes())
            .await
            .expect("put again");
        assert!(store.contains(&record.address()));
        store.delete(&record.address()).await.expect("delete");
        let dir = store.dir().parent().expect("root").to_path_buf();
        drop(store);
        let reopened = PointerStore::new(&dir).await.expect("reopen");
        assert!(!reopened.contains(&record.address()));
    }

    #[tokio::test]
    async fn stats_count_what_each_arrival_did() {
        let (store, _dir) = store().await;
        let first = signed(5, 1, 1);
        let newer = signed(5, 2, 1);
        store.put_bytes(&first.to_bytes()).await.expect("put");
        store.put_bytes(&newer.to_bytes()).await.expect("put");
        store
            .put_bytes(&signed(5, 2, 1).to_bytes())
            .await
            .expect("put");
        store.put_bytes(&first.to_bytes()).await.expect("put");
        store.get(&first.address()).await.expect("get");

        assert_eq!(
            store.stats(),
            PointerStoreStats {
                written: 2,
                unchanged: 1,
                stale: 1,
                served: 1,
                deleted: 0,
            }
        );
    }

    #[tokio::test]
    async fn opening_indexes_records_without_verifying_them_and_a_read_still_does() {
        // The scan parses structure only. A signature damaged in place is
        // indexed, and caught by the first read, which disowns it.
        let dir = tempfile::tempdir().expect("tempdir");
        let record = signed(6, 1, 1);
        let path = {
            let store = PointerStore::new(dir.path()).await.expect("open");
            store.put_bytes(&record.to_bytes()).await.expect("put");
            store.file_for(&record.address())
        };
        let mut bytes = std::fs::read(&path).expect("read");
        if let Some(byte) = bytes.get_mut(POINTER_BODY_LEN + 7) {
            *byte ^= 0xff;
        }
        std::fs::write(&path, &bytes).expect("damage");

        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
        assert!(
            reopened.contains(&record.address()),
            "indexed on its structure"
        );
        assert!(
            reopened
                .get(&record.address())
                .await
                .expect("get")
                .is_none(),
            "never served"
        );
        assert!(
            !reopened.contains(&record.address()),
            "and disowned once read"
        );
    }

    #[tokio::test]
    async fn a_record_in_the_flat_layout_is_moved_into_its_shard() {
        let dir = tempfile::tempdir().expect("tempdir");
        let record = signed(7, 4, 2);
        let flat = dir
            .path()
            .join(POINTERS_DIR_NAME)
            .join(hex::encode(record.address()));
        std::fs::create_dir_all(flat.parent().expect("parent")).expect("mkdir");
        std::fs::write(&flat, record.to_bytes()).expect("write");

        let store = PointerStore::new(dir.path()).await.expect("open");
        assert!(!flat.exists(), "moved out of the top level");
        assert!(store.file_for(&record.address()).exists(), "into its shard");
        let held = store
            .get(&record.address())
            .await
            .expect("get")
            .expect("present");
        assert_eq!(held.state_id(), record.state_id());
    }

    #[tokio::test]
    async fn a_cancelled_commit_leaves_the_index_agreeing_with_the_disk() {
        // Dropping the caller's future must not split the transaction: either
        // the write and the index update both happened, or neither did.
        let (store, _dir) = store().await;
        let record = signed(1, 3, 3);
        let prepared = verified(&store, &record).await;

        {
            let committing = store.commit(prepared, None);
            tokio::pin!(committing);
            // Poll exactly once, then drop. That first poll hands the write to
            // a blocking thread and returns `Pending`, so the caller is always
            // abandoned mid-commit. A timeout would not be: on a fast machine
            // the commit finishes inside any timeout and the test then proves
            // nothing, which is how this failed on CI and passed locally.
            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
            assert!(
                committing.as_mut().poll(&mut cx).is_pending(),
                "the first poll must hand the write to a blocking task, not finish it"
            );
        }

        // Wait for the detached task to settle rather than guessing at a
        // duration: poll until the disk and the index agree and stop changing.
        let mut settled = false;
        for _ in 0..200 {
            let on_disk = store.get(&record.address()).await.expect("get").is_some();
            if on_disk == store.contains(&record.address()) && on_disk {
                settled = true;
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }

        let on_disk = store.get(&record.address()).await.expect("get").is_some();
        let indexed = store.contains(&record.address());
        assert_eq!(
            on_disk, indexed,
            "the index and the disk must agree however the commit was interrupted"
        );
        assert!(
            settled,
            "the detached commit must run to completion rather than stopping half done"
        );
    }

    #[tokio::test]
    async fn an_empty_store_holds_nothing() {
        let (store, _dir) = store().await;
        assert!(store.is_empty());
        assert_eq!(store.state_id(&[0u8; 32]), None);
        assert!(store.get(&[0u8; 32]).await.expect("get").is_none());
    }

    #[tokio::test]
    async fn a_failed_read_does_not_erase_a_record_written_since() {
        // A read that finds the file unreadable may only disown the entry it
        // set out to read. A commit that lands meanwhile must survive, or the
        // node ends up holding a record it never announces or commits to.
        let (store, _dir) = store().await;
        let old = signed(1, 1, 1);
        store.put_bytes(&old.to_bytes()).await.expect("put");

        // Simulate the interleaving: the read observed the old entry, then a
        // newer state was committed, and only then does the read disown what
        // it saw.
        let observed = store.snapshot(&old.address()).map(|entry| entry.generation);
        let new = signed(1, 2, 1);
        store.put_bytes(&new.to_bytes()).await.expect("put");

        store.disown_if_unchanged(&old.address(), observed);
        assert_eq!(
            store.state_id(&new.address()),
            Some(new.state_id()),
            "the record committed during the read must still be indexed"
        );

        // And the ordinary case still works: disowning what is actually there.
        let current = store.snapshot(&new.address()).map(|entry| entry.generation);
        store.disown_if_unchanged(&new.address(), current);
        assert!(!store.contains(&new.address()));
    }

    #[tokio::test]
    async fn a_repair_of_the_same_state_is_not_erased_by_a_second_reader() {
        // Two readers observe one corrupt entry. The first disowns it, a repair
        // restores exactly the same logical state, and the second reader must
        // not then erase the repair — the state identifier alone cannot tell
        // the repaired entry from the corrupt one it replaced.
        let (store, _dir) = store().await;
        let record = signed(1, 1, 1);
        store.put_bytes(&record.to_bytes()).await.expect("put");

        let first_reader = store
            .snapshot(&record.address())
            .map(|entry| entry.generation);
        let second_reader = first_reader;

        // Reader one finds the file unreadable and disowns what it saw.
        store.disown_if_unchanged(&record.address(), first_reader);
        assert!(!store.contains(&record.address()));

        // A peer repairs it with the very same state.
        assert_eq!(
            store.put_bytes(&record.to_bytes()).await.expect("put"),
            PutOutcome::Changed
        );

        // Reader two, still holding its stale observation, must not erase it.
        store.disown_if_unchanged(&record.address(), second_reader);
        assert!(
            store.contains(&record.address()),
            "the repair must survive a second reader disowning the old entry"
        );
        assert_eq!(store.state_id(&record.address()), Some(record.state_id()));
    }

    #[tokio::test]
    async fn a_leftover_partial_write_is_swept_and_does_not_block_the_next_write() {
        // The write sequence restarts at zero on every opening, so a temporary
        // file left by a crash would collide with the next write to that
        // address and `create_new` would refuse it.
        let dir = tempfile::tempdir().expect("tempdir");
        let record = signed(1, 1, 1);
        {
            let store = PointerStore::new(dir.path()).await.expect("open");
            let leftover = store
                .dir()
                .join(format!("{TEMP_PREFIX}{}-0", hex::encode(record.address())));
            std::fs::write(&leftover, vec![0u8; POINTER_WIRE_LEN]).expect("write leftover");
        }

        let reopened = PointerStore::new(dir.path()).await.expect("reopen");
        assert_eq!(
            reopened.put_bytes(&record.to_bytes()).await.expect("put"),
            PutOutcome::Changed,
            "a swept leftover must not block the first write to its address"
        );
    }

    #[tokio::test]
    async fn holding_the_key_is_not_holding_the_state() {
        // The fetch decision a mutable record needs: a replica on version N
        // must not count as satisfied for version N+1.
        let (store, _dir) = store().await;
        let old = signed(1, 1, 1);
        let new = signed(1, 2, 1);
        store.put_bytes(&old.to_bytes()).await.expect("put");

        assert!(store.contains(&new.address()));
    }
}