redb 4.6.0

Rust Embedded DataBase
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
use crate::BackendError;
use crate::transaction_tracker::{SavepointId, TransactionId, TransactionTracker};
use crate::transactions::AllocatorStateLatch;
use crate::tree_store::ReadOnlyBackend;
use crate::tree_store::{
    AllocationPolicy, BtreeHeader, HeaderGuard, InternalTableDefinition, PAGE_SIZE, PageHint,
    PageNumber, PageResolver, SerializedSavepoint, ShrinkPolicy, TableTree, TableType,
    TransactionalMemory, WriterLock,
};
use crate::types::{Key, Value};
use crate::{
    CompactionError, DatabaseError, ReadOnlyTable, ReadableTable, StorageError, TableError,
};
use crate::{ReadTransaction, Result, WriteTransaction};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt::{Debug, Display, Formatter};

use alloc::sync::Arc;
use core::marker::PhantomData;
use core::ops::{Bound, Range};
#[cfg(all(not(redb_no_std), not(feature = "experimental-api-5")))]
use std::fs::File;
#[cfg(not(redb_no_std))]
use std::fs::OpenOptions;
#[cfg(not(redb_no_std))]
use std::path::Path;

use crate::error::TransactionError;
use crate::sealed::{Sealed, SealedInApi5};
use crate::transactions::{
    ALLOCATOR_STATE_TABLE_NAME, AllocatorStateKey, AllocatorStateTree, DATA_ALLOCATED_TABLE,
    DATA_FREED_TABLE, PageList, SAVEPOINT_TABLE, SYSTEM_FREED_TABLE, SystemTableDefinition,
    TransactionIdWithPagination,
};
#[cfg(not(redb_no_std))]
use crate::tree_store::file_backend::FileBackend;
#[cfg(feature = "logging")]
use log::{debug, warn};

// The error type of the I/O methods of StorageBackend
#[cfg(feature = "experimental-api-5")]
pub(crate) type BackendIoError = BackendError;
#[cfg(not(feature = "experimental-api-5"))]
pub(crate) type BackendIoError = std::io::Error;

#[allow(clippy::len_without_is_empty)]
/// Implements persistent storage for a database.
///
/// Failures are reported as [`BackendError`]. Without `experimental-api-5`, the I/O methods report
/// [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html) instead.
///
/// Locking is optional. Backends that implement it must override the lock methods. Locks belong to
/// a backend instance and must conflict with locks held by independently opened instances,
/// including those in the same process. All locks must be released by [`Self::close`].
/// redb never acquires overlapping locks on the same backend. Failed or refused acquisitions
/// must not acquire any locks or change existing locks.
///
/// Lock bounds refer to byte offsets and may extend beyond the current length of the storage.
/// An unbounded start means offset zero; an unbounded end includes all future growth. Bounds
/// must describe a nonempty range. Implementations may reject offsets or lengths that their
/// underlying locking API cannot represent, with an error other than [`BackendError::Unsupported`].
///
/// redb never queries backend-reserved ranges and only locks them during whole-storage fallback.
/// See the [design document](https://github.com/cberner/redb/blob/master/docs/design.md#lock-bytes).
///
/// Backends that support locking must support one of the following levels:
/// 1) All representable ranges requested by redb are supported. All concurrency modes will work.
/// 2) Only whole-storage locks (`Unbounded, Unbounded` or `Included(0), Unbounded`) are
///    supported. Other ranges return [`BackendError::Unsupported`]. Only the `ExclusiveWriter`
///    concurrency mode will work.
/// 3) All inputs return [`BackendError::Unsupported`]. Only the `ExclusiveWriter` concurrency
///    mode will work, and redb will log a warning on open if logging is enabled.
///
/// A lock method's I/O error of kind `Unsupported` counts as [`BackendError::Unsupported`],
/// whether it is returned as `BackendError::Io` or wrapped in `BackendError::Other`.
pub trait StorageBackend: 'static + Debug + Send + Sync {
    /// Gets the current length of the storage.
    fn len(&self) -> core::result::Result<u64, BackendIoError>;

    /// Reads the specified array of bytes from the storage.
    ///
    /// If `out.len()` + `offset` exceeds the length of the storage an appropriate `Error` must be returned.
    fn read(&self, offset: u64, out: &mut [u8]) -> core::result::Result<(), BackendIoError>;

    /// Sets the length of the storage.
    ///
    /// New positions in the storage must be initialized to zero.
    fn set_len(&self, len: u64) -> core::result::Result<(), BackendIoError>;

    /// Syncs all buffered data with the persistent storage.
    fn sync_data(&self) -> core::result::Result<(), BackendIoError>;

    /// Writes the specified array to the storage.
    fn write(&self, offset: u64, data: &[u8]) -> core::result::Result<(), BackendIoError>;

    /// Release any resources held by the backend
    ///
    /// Must release all locks acquired by one of the lock methods.
    ///
    /// Note: redb will not access the backend after calling this method and will call it exactly
    /// once: when the [`Database`] is dropped, or, if a [`WriteTransaction`] was live at that
    /// point, when that transaction completes, or if opening the database fails. For a read-only
    /// database, it is called by `ReadOnlyDatabase::close()`, or once the database and all of its
    /// read transactions have been dropped
    fn close(&self) -> core::result::Result<(), BackendIoError> {
        Ok(())
    }

    /// Attempts to acquire an exclusive byte-range lock.
    ///
    /// Returns `Ok(true)` on acquisition, `Ok(false)` on a conflicting lock, or an error.
    /// Defaults to [`BackendError::Unsupported`].
    fn try_lock_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<bool, BackendError> {
        Err(BackendError::Unsupported)
    }

    /// Attempts to acquire a shared byte-range lock.
    ///
    /// Returns `Ok(true)` on acquisition, `Ok(false)` on a conflicting lock, or an error.
    /// Defaults to [`BackendError::Unsupported`].
    fn try_lock_shared_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<bool, BackendError> {
        Err(BackendError::Unsupported)
    }

    /// Acquires an exclusive byte-range lock, waiting for conflicting locks to be released.
    ///
    /// Defaults to [`BackendError::Unsupported`].
    fn lock_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<(), BackendError> {
        Err(BackendError::Unsupported)
    }

    /// Acquires a shared byte-range lock, waiting for conflicting locks to be released.
    ///
    /// Defaults to [`BackendError::Unsupported`].
    fn lock_shared_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<(), BackendError> {
        Err(BackendError::Unsupported)
    }

    /// Releases the lock acquired over exactly this range.
    ///
    /// The range passed will exactly match a range successfully locked by one of the lock methods.
    ///
    /// If it fails, the lock is taken to be still held: every later operation on the database
    /// returns [`StorageError::PreviousIo`], until the database is closed and [`Self::close`]
    /// releases the lock.
    ///
    /// Defaults to [`BackendError::Unsupported`].
    fn unlock_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<(), BackendError> {
        Err(BackendError::Unsupported)
    }

    /// Reports whether an exclusive lock over the range would conflict with a lock held elsewhere.
    ///
    /// The queried range will not overlap any lock currently held by this backend.
    /// Defaults to [`BackendError::Unsupported`].
    fn query_lock_range(
        &self,
        _start: Bound<u64>,
        _end: Bound<u64>,
    ) -> core::result::Result<bool, BackendError> {
        Err(BackendError::Unsupported)
    }
}

#[cfg_attr(redb_no_std, allow(dead_code))]
pub(crate) const FULL_RANGE: (Bound<u64>, Bound<u64>) = (Bound::Unbounded, Bound::Unbounded);

#[cfg_attr(not(any(windows, unix, target_os = "wasi")), allow(dead_code))]
const LOCK_BASE: u64 = 1 << 62;
/// Reserved for backend locking. Core only covers these bytes with a whole-storage fallback lock.
pub(crate) const BACKEND_LOCK_RANGE: Range<u64> = LOCK_BASE + 896..LOCK_BASE + 1024;

/// Held exclusively by the writing process in single-writer mode.
pub(crate) const WRITER_BYTE: u64 = LOCK_BASE;
/// Whether the database is open for a single writer (held exclusively by it) or for many (held
/// shared by each writing process while the database is open).
#[cfg_attr(not(any(windows, unix, target_os = "wasi")), allow(dead_code))]
pub(crate) const SHARED_WRITER_BYTE: u64 = LOCK_BASE + 1;
/// Held shared by every read-only multi-process handle while the database is open, so that a
/// exclusive-writer open conflicts with a live reader no matter what the reader is doing.
pub(crate) const SHARED_READER_BYTE: u64 = LOCK_BASE + 2;
/// The first range an exclusive writer takes of its whole-file lock: from the shared writer byte
/// up to the backend's bytes. It starts with the shared writer byte and the shared reader byte.
/// Every shared-mode handle holds one of the two, so it refuses the writer whichever of them has
/// the database open.
#[cfg(feature = "experimental-api-5")]
pub(crate) const MODE_RANGE: (Bound<u64>, Bound<u64>) = (
    Bound::Included(SHARED_WRITER_BYTE),
    Bound::Excluded(BACKEND_LOCK_RANGE.start),
);
/// Held shared by a read-only exclusive-writer handle as part of its whole-file lock. Such a
/// handle leaves `SHARED_WRITER_BYTE` free, so a multi-writer open, which takes only that byte,
/// must probe this one to find it.
pub(crate) const WHOLE_FILE_READER_BYTE: u64 = LOCK_BASE + 3;
/// Held shared by a writing process from the moment its open is complete -- past recovery and
/// the allocator load -- until it closes: the file is consistent, and the recovery flag, set from
/// here on, means only that a writer is live. `SHARED_WRITER_BYTE` is taken before recovery, so
/// it cannot say that; this byte can. Only a writer holds it: a read-only exclusive-writer handle
/// leaves it out of its whole-file lock.
pub(crate) const CONSISTENT_BYTE: u64 = LOCK_BASE + 4;
/// One byte per generation of the locking protocol. A handle holds a shared lock on the byte of
/// the generation it implements while the database is open, and an open fails while a byte of
/// another generation is locked. Processes that disagree on what the other lock bytes mean
/// therefore never share a file. Each change to the protocol that a released version cannot
/// follow takes the next byte.
pub(crate) const PROTOCOL_GENERATION_BYTES: Range<u64> = LOCK_BASE + 5..LOCK_BASE + 69;
/// The byte of the generation this version implements.
pub(crate) const PROTOCOL_GENERATION_BYTE: u64 = PROTOCOL_GENERATION_BYTES.start;
const _: () = assert!(
    PROTOCOL_GENERATION_BYTE >= PROTOCOL_GENERATION_BYTES.start
        && PROTOCOL_GENERATION_BYTE < PROTOCOL_GENERATION_BYTES.end
);
/// Never locked, except within an exclusive writer's whole range. A reader of 4.3 or 4.4 holds it
/// along with every generation byte, so a reader that finds it locked skips the generation check,
/// except under `experimental-api-5`.
pub(crate) const LEGACY_READER_BYTE: u64 = PROTOCOL_GENERATION_BYTES.end;
const _: () = assert!(LEGACY_READER_BYTE < BACKEND_LOCK_RANGE.start);
/// Base of the "active transaction range": a handle reading transaction `t` holds `TXN_BASE + t`
/// shared for as long as it is reading it
pub(crate) const TXN_BASE: u64 = LOCK_BASE + 1024;

pub(crate) fn byte_range(offset: u64) -> (Bound<u64>, Bound<u64>) {
    (Bound::Included(offset), Bound::Included(offset))
}

pub trait TableHandle: Sealed {
    // Returns the name of the table
    fn name(&self) -> &str;
}

#[derive(Clone)]
pub struct UntypedTableHandle {
    name: String,
}

impl UntypedTableHandle {
    pub(crate) fn new(name: String) -> Self {
        Self { name }
    }
}

impl TableHandle for UntypedTableHandle {
    fn name(&self) -> &str {
        &self.name
    }
}

impl Sealed for UntypedTableHandle {}

pub trait MultimapTableHandle: Sealed {
    // Returns the name of the multimap table
    fn name(&self) -> &str;
}

#[derive(Clone)]
pub struct UntypedMultimapTableHandle {
    name: String,
}

impl UntypedMultimapTableHandle {
    pub(crate) fn new(name: String) -> Self {
        Self { name }
    }
}

impl MultimapTableHandle for UntypedMultimapTableHandle {
    fn name(&self) -> &str {
        &self.name
    }
}

impl Sealed for UntypedMultimapTableHandle {}

/// Defines the name and types of a table
///
/// A [`TableDefinition`] should be opened for use by calling [`ReadTransaction::open_table`] or [`WriteTransaction::open_table`]
///
/// Note that the lifetime of the `K` and `V` type parameters does not impact the lifetimes of the data
/// that is stored or retreived from the table
pub struct TableDefinition<'a, K: Key + 'static, V: Value + 'static> {
    name: &'a str,
    _key_type: PhantomData<K>,
    _value_type: PhantomData<V>,
}

impl<'a, K: Key + 'static, V: Value + 'static> TableDefinition<'a, K, V> {
    /// Construct a new table with given `name`
    ///
    /// # Panics
    ///
    /// Panics if `name` is empty. When `name` is a non-empty string literal
    /// this is checked at compile time, but callers that build the name at
    /// runtime are responsible for ensuring it is non-empty.
    pub const fn new(name: &'a str) -> Self {
        assert!(!name.is_empty());
        Self {
            name,
            _key_type: PhantomData,
            _value_type: PhantomData,
        }
    }
}

impl<K: Key + 'static, V: Value + 'static> TableHandle for TableDefinition<'_, K, V> {
    fn name(&self) -> &str {
        self.name
    }
}

impl<K: Key, V: Value> Sealed for TableDefinition<'_, K, V> {}

impl<K: Key + 'static, V: Value + 'static> Clone for TableDefinition<'_, K, V> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<K: Key + 'static, V: Value + 'static> Copy for TableDefinition<'_, K, V> {}

impl<K: Key + 'static, V: Value + 'static> Display for TableDefinition<'_, K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{}<{}, {}>",
            self.name,
            K::type_name().name(),
            V::type_name().name()
        )
    }
}

/// Defines the name and types of a multimap table
///
/// A [`MultimapTableDefinition`] should be opened for use by calling [`ReadTransaction::open_multimap_table`] or [`WriteTransaction::open_multimap_table`]
///
/// [Multimap tables](https://en.wikipedia.org/wiki/Multimap) may have multiple values associated with each key
///
/// Note that the lifetime of the `K` and `V` type parameters does not impact the lifetimes of the data
/// that is stored or retreived from the table
pub struct MultimapTableDefinition<'a, K: Key + 'static, V: Key + 'static> {
    name: &'a str,
    _key_type: PhantomData<K>,
    _value_type: PhantomData<V>,
}

impl<'a, K: Key + 'static, V: Key + 'static> MultimapTableDefinition<'a, K, V> {
    /// Construct a new multimap table with given `name`
    ///
    /// # Panics
    ///
    /// Panics if `name` is empty. When `name` is a non-empty string literal
    /// this is checked at compile time, but callers that build the name at
    /// runtime are responsible for ensuring it is non-empty.
    pub const fn new(name: &'a str) -> Self {
        assert!(!name.is_empty());
        Self {
            name,
            _key_type: PhantomData,
            _value_type: PhantomData,
        }
    }
}

impl<K: Key + 'static, V: Key + 'static> MultimapTableHandle for MultimapTableDefinition<'_, K, V> {
    fn name(&self) -> &str {
        self.name
    }
}

impl<K: Key, V: Key> Sealed for MultimapTableDefinition<'_, K, V> {}

impl<K: Key + 'static, V: Key + 'static> Clone for MultimapTableDefinition<'_, K, V> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<K: Key + 'static, V: Key + 'static> Copy for MultimapTableDefinition<'_, K, V> {}

impl<K: Key + 'static, V: Key + 'static> Display for MultimapTableDefinition<'_, K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{}<{}, {}>",
            self.name,
            K::type_name().name(),
            V::type_name().name()
        )
    }
}

/// Information regarding the usage of the in-memory cache
///
/// Note: these metrics are only collected when the "`cache_metrics`" feature is enabled
#[derive(Debug)]
pub struct CacheStats {
    pub(crate) evictions: u64,
    pub(crate) read_hits: u64,
    pub(crate) read_misses: u64,
    pub(crate) write_hits: u64,
    pub(crate) write_misses: u64,
    pub(crate) used_bytes: usize,
}

impl CacheStats {
    /// Number of times that data has been evicted, due to the cache being full
    ///
    /// To increase the cache size use [`Builder::set_cache_size`]
    pub fn evictions(&self) -> u64 {
        self.evictions
    }

    /// Number of times that unmodified data has been read from the cache
    pub fn read_hits(&self) -> u64 {
        self.read_hits
    }

    /// Number of times that unmodified data was not in the cache and was read from storage
    pub fn read_misses(&self) -> u64 {
        self.read_misses
    }

    /// Number of times that data modified in a transaction has been read from the cache
    pub fn write_hits(&self) -> u64 {
        self.write_hits
    }

    /// Number of times that data modified in a transaction was not in the cache and was read from storage
    pub fn write_misses(&self) -> u64 {
        self.write_misses
    }

    /// Number of bytes in the cache
    pub fn used_bytes(&self) -> usize {
        self.used_bytes
    }
}

// The write slot, taken ahead of the writer byte and held until the transaction ends. Releases
// it on drop, and performs the close a `Database::drop()` deferred to that end
pub(crate) struct WriteSlot {
    tracker: Arc<TransactionTracker>,
}

impl WriteSlot {
    fn take(tracker: Arc<TransactionTracker>) -> Self {
        tracker.take_write_slot();
        Self { tracker }
    }

    // None while another write transaction holds the slot
    fn try_take(tracker: Arc<TransactionTracker>) -> Option<Self> {
        tracker.try_take_write_slot().then(|| Self { tracker })
    }
}

impl Drop for WriteSlot {
    fn drop(&mut self) {
        if let Some(mem) = self.tracker.end_write_transaction() {
            // close_database() has logged any error, and the Database is gone, so it has no caller
            // to return to
            let _ = close_database(&self.tracker, &mem);
        }
    }
}

pub(crate) enum TransactionGuard {
    Read {
        tracker: Arc<TransactionTracker>,
        transaction_id: TransactionId,
        // `Some` while this guard owns the transaction's reference, carrying what the tracker
        // needs to release it. `None` when a savepoint becomes persistent: the database
        // owns the reference from then on and releases it when the savepoint is deleted
        reference: Option<Arc<TransactionalMemory>>,
    },
    Write {
        transaction_id: TransactionId,
        // Dropped ahead of the slot, in this order: a thread waiting on the slot would take the
        // same byte on this file description, and this release would free theirs
        _writer_lock: Arc<WriterLock>,
        slot: WriteSlot,
    },
    // Used for internal accesses that happen outside of any tracked transaction,
    // such as opening the database, repairing it, and running integrity checks.
    Untracked,
}

impl TransactionGuard {
    pub(crate) fn new_read(
        transaction_id: TransactionId,
        tracker: Arc<TransactionTracker>,
        mem: &Arc<TransactionalMemory>,
    ) -> Self {
        Self::Read {
            tracker,
            transaction_id,
            reference: Some(mem.clone()),
        }
    }

    // A guard for a transaction whose reference the database already owns
    pub(crate) fn new_read_unowned(
        transaction_id: TransactionId,
        tracker: Arc<TransactionTracker>,
    ) -> Self {
        Self::Read {
            tracker,
            transaction_id,
            reference: None,
        }
    }

    // Leak the reference to the transaction. The caller becomes responsible for decrementing the
    // reference count.
    // Dropping this guard then releases nothing.
    pub(crate) fn release_to_database(&mut self) {
        let Self::Read { reference, .. } = self else {
            unreachable!("only a read transaction's reference may be leaked")
        };
        drop(reference.take());
    }

    pub(crate) fn owns_reference(&self) -> bool {
        matches!(self, Self::Read { reference, .. } if reference.is_some())
    }

    pub(crate) fn tracker(&self) -> &Arc<TransactionTracker> {
        match self {
            Self::Read { tracker, .. } => tracker,
            Self::Write { slot, .. } => &slot.tracker,
            Self::Untracked => unreachable!("an untracked guard has no tracker"),
        }
    }

    // Returns a read guard and the data root its registration protects.
    pub(crate) fn allocate_read(
        tracker: Arc<TransactionTracker>,
        mem: &Arc<TransactionalMemory>,
    ) -> Result<(Self, Option<BtreeHeader>)> {
        let (id, root) = tracker.register_read_transaction(mem)?;

        Ok((Self::new_read(id, tracker, mem), root))
    }

    pub(crate) fn new_write(
        transaction_id: TransactionId,
        slot: WriteSlot,
        writer_lock: Arc<WriterLock>,
    ) -> Self {
        Self::Write {
            transaction_id,
            _writer_lock: writer_lock,
            slot,
        }
    }

    pub(crate) fn untracked() -> Self {
        Self::Untracked
    }

    pub(crate) fn id(&self) -> TransactionId {
        match self {
            Self::Read { transaction_id, .. } | Self::Write { transaction_id, .. } => {
                *transaction_id
            }
            Self::Untracked => {
                panic!("TransactionGuard::id() called on an untracked guard")
            }
        }
    }
}

impl Drop for TransactionGuard {
    fn drop(&mut self) {
        match self {
            Self::Read {
                tracker,
                transaction_id,
                reference,
            } => {
                if let Some(mem) = reference {
                    tracker.deallocate_read_transaction(mem, *transaction_id);
                }
            }
            Self::Write { slot, .. } => {
                // Leave `Live` before the fields drop the writer lock and then the slot.
                slot.tracker.begin_finalizing();
            }
            Self::Untracked => {}
        }
    }
}

pub trait ReadableDatabase: SealedInApi5 {
    /// Begins a read transaction
    ///
    /// Captures a snapshot of the database, so that only data committed before calling this method
    /// is visible in the transaction
    ///
    /// Returns a [`ReadTransaction`] which may be used to read from the database. Read transactions
    /// may exist concurrently with writes
    fn begin_read(&self) -> Result<ReadTransaction, TransactionError>;

    /// Information regarding the usage of the in-memory cache
    ///
    /// Note: these metrics are only collected when the "`cache_metrics`" feature is enabled
    fn cache_stats(&self) -> CacheStats;
}

/// A redb database opened in read-only mode
///
/// Use [`Self::begin_read`] to get a [`ReadTransaction`] object that can be used to read from the database
///
/// Multiple processes may open a [`ReadOnlyDatabase`], but it may not be opened concurrently
/// with a [`Database`].
///
/// That holds in `ExclusiveWriter`, the default concurrency mode, alone: in the others, a reader
/// opened in the writer's mode shares the file with it and follows its commits. See
/// [`Builder::set_concurrency_mode`](crate::Builder::set_concurrency_mode).
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// use redb::*;
/// # use tempfile::NamedTempFile;
/// const TABLE: TableDefinition<u64, u64> = TableDefinition::new("my_data");
///
/// # fn main() -> Result<(), Error> {
/// # #[cfg(not(target_os = "wasi"))]
/// # let tmpfile = NamedTempFile::new().unwrap();
/// # #[cfg(target_os = "wasi")]
/// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
/// # let filename = tmpfile.path();
/// let db = Database::create(filename)?;
/// let txn = db.begin_write()?;
/// {
///     let mut table = txn.open_table(TABLE)?;
///     table.insert(&0, &0)?;
/// }
/// txn.commit()?;
/// drop(db);
///
/// let db = ReadOnlyDatabase::open(filename)?;
/// let txn = db.begin_read()?;
/// {
///     let mut table = txn.open_table(TABLE)?;
///     println!("{}", table.get(&0)?.unwrap().value());
/// }
/// # Ok(())
/// # }
/// ```
pub struct ReadOnlyDatabase {
    mem: Arc<TransactionalMemory>,
    transaction_tracker: Arc<TransactionTracker>,
}

impl Sealed for ReadOnlyDatabase {}

impl ReadableDatabase for ReadOnlyDatabase {
    fn begin_read(&self) -> Result<ReadTransaction, TransactionError> {
        let (guard, root) =
            TransactionGuard::allocate_read(self.transaction_tracker.clone(), &self.mem)?;
        #[cfg(feature = "logging")]
        debug!("Beginning read transaction id={:?}", guard.id());

        ReadTransaction::new(self.mem.clone(), guard, root)
    }

    fn cache_stats(&self) -> CacheStats {
        self.mem.cache_stats()
    }
}

impl ReadOnlyDatabase {
    /// Opens an existing redb database.
    #[cfg(not(redb_no_std))]
    pub fn open(path: impl AsRef<Path>) -> Result<ReadOnlyDatabase, DatabaseError> {
        Builder::new().open_read_only(path)
    }

    /// Closes the database
    ///
    /// The file and its locks are released immediately, rather than when the last read transaction
    /// is dropped. Read transactions that are still alive can no longer access the file, so their
    /// reads return [`StorageError::DatabaseClosed`]. Data they have already loaded into memory,
    /// such as the root page of an open table, may still be returned.
    pub fn close(self) -> Result<(), DatabaseError> {
        Ok(self.mem.close(None)?)
    }

    fn new(
        file: Box<dyn StorageBackend>,
        page_size: usize,
        region_size: Option<u64>,
        cache_size: usize,
        concurrency_mode: ConcurrencyMode,
    ) -> Result<Self, DatabaseError> {
        #[cfg(feature = "logging")]
        let file_path = format!("{:?}", &file);
        #[cfg(feature = "logging")]
        debug!("Opening database in read-only {:?}", &file_path);
        let (mem, _writer_lock) = TransactionalMemory::new(
            Box::new(ReadOnlyBackend::new(file)),
            false,
            page_size,
            region_size,
            cache_size,
            true,
            concurrency_mode,
        )?;
        let mem = Arc::new(mem);
        // A reader beside a multi-process writer never allocates, so it loads no allocator state
        if !concurrency_mode.is_multi_process_writable() {
            // If the last transaction used 2-phase commit and updated the allocator state table, then
            // we can just load the allocator state from there. Otherwise, we need a full repair
            if let Some(tree) = Database::get_allocator_state_table(&mem)? {
                mem.load_allocator_state(&tree)?;
            } else {
                #[cfg(feature = "logging")]
                warn!(
                    "Database {:?} not shutdown cleanly. Repair required",
                    &file_path
                );
                return Err(DatabaseError::RepairAborted);
            }
        }

        let next_transaction_id = mem.get_last_committed_transaction_id()?.next();
        let db = Self {
            mem,
            transaction_tracker: Arc::new(TransactionTracker::new(next_transaction_id)),
        };

        Ok(db)
    }
}

/// Opened redb database file
///
/// Use [`Self::begin_read`] to get a [`ReadTransaction`] object that can be used to read from the database
/// Use [`Self::begin_write`] to get a [`WriteTransaction`] object that can be used to read or write to the database
///
/// Multiple reads may be performed concurrently, with each other, and with writes. Only a single write
/// may be in progress at a time.
///
/// # Close semantics
///
/// Dropping the [`Database`] closes the database: buffered data is flushed, the file lock is
/// released, and outstanding [`ReadTransaction`]s are invalidated (their operations will return
/// [`StorageError::DatabaseClosed`]). Dropping it ignores any error from closing, which
/// [`Self::close()`] returns instead.
///
/// A live [`WriteTransaction`] keeps the database open, however: if one exists when the
/// [`Database`] is dropped or closed, the transaction remains fully usable and the close
/// described above is deferred until the transaction commits, aborts, or is dropped. Until then
/// the database file remains locked, so re-opening it fails with
/// [`DatabaseError::DatabaseAlreadyOpen`].
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// use redb::*;
/// # use tempfile::NamedTempFile;
/// const TABLE: TableDefinition<u64, u64> = TableDefinition::new("my_data");
///
/// # fn main() -> Result<(), Error> {
/// # #[cfg(not(target_os = "wasi"))]
/// # let tmpfile = NamedTempFile::new().unwrap();
/// # #[cfg(target_os = "wasi")]
/// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
/// # let filename = tmpfile.path();
/// let db = Database::create(filename)?;
/// let write_txn = db.begin_write()?;
/// {
///     let mut table = write_txn.open_table(TABLE)?;
///     table.insert(&0, &0)?;
/// }
/// write_txn.commit()?;
/// # Ok(())
/// # }
/// ```
pub struct Database {
    mem: Arc<TransactionalMemory>,
    transaction_tracker: Arc<TransactionTracker>,
    // Set once close() has closed the database, or deferred the close, leaving drop nothing to do
    closed: bool,
}

impl Sealed for Database {}

impl ReadableDatabase for Database {
    fn begin_read(&self) -> Result<ReadTransaction, TransactionError> {
        let (guard, root) =
            TransactionGuard::allocate_read(self.transaction_tracker.clone(), &self.mem)?;
        #[cfg(feature = "logging")]
        debug!("Beginning read transaction id={:?}", guard.id());
        ReadTransaction::new(self.get_memory(), guard, root)
    }

    fn cache_stats(&self) -> CacheStats {
        self.mem.cache_stats()
    }
}

impl Database {
    /// Opens the specified file as a redb database.
    /// * if the file does not exist, or is an empty file, a new database will be initialized in it
    /// * if the file is a valid redb database, it will be opened
    /// * otherwise this function will return an error
    #[cfg(not(redb_no_std))]
    pub fn create(path: impl AsRef<Path>) -> Result<Database, DatabaseError> {
        Self::builder().create(path)
    }

    /// Opens an existing redb database.
    ///
    /// The open trusts a file that was shut down cleanly and may panic if it was corrupted outside
    /// redb. [`Builder::set_check_integrity_on_open`] reports corruption as
    /// [`StorageError::Corrupted`] instead.
    #[cfg(not(redb_no_std))]
    pub fn open(path: impl AsRef<Path>) -> Result<Database, DatabaseError> {
        Self::builder().open(path)
    }

    /// Closes the database
    ///
    /// This does what dropping the database does, but returns any error rather than ignoring it.
    /// Read transactions that are still alive can no longer access the file, so their reads return
    /// [`StorageError::DatabaseClosed`]. Data they have already loaded into memory, such as the
    /// root page of an open table, may still be returned.
    ///
    /// If a [`WriteTransaction`] is still alive, this returns
    /// [`DatabaseError::TransactionInProgress`], and the database stays open until the transaction
    /// ends. It then closes as a dropped database does, ignoring any error.
    pub fn close(mut self) -> Result<(), DatabaseError> {
        self.close_or_defer()
    }

    // Closes the database, or defers the close to the end of the live write transaction, which is
    // reported as TransactionInProgress. Runs once, from close() or from drop
    fn close_or_defer(&mut self) -> Result<(), DatabaseError> {
        self.closed = true;
        if self
            .transaction_tracker
            .defer_close_if_write_transaction_live(&self.mem)
        {
            // The write transaction holds the memory and tracker alive, so it remains fully
            // usable; WriteSlot::drop performs the deferred close when it ends
            #[cfg(feature = "logging")]
            warn!(
                "Database closed while a write transaction is in progress. The database will remain open until the write transaction completes."
            );
            return Err(DatabaseError::TransactionInProgress);
        }

        Ok(close_database(&self.transaction_tracker, &self.mem)?)
    }

    pub(crate) fn get_memory(&self) -> Arc<TransactionalMemory> {
        self.mem.clone()
    }

    pub(crate) fn verify_primary_checksums(mem: Arc<TransactionalMemory>) -> Result<bool> {
        let data_root = mem.get_data_root();
        let system_root = mem.get_system_root();
        Self::verify_checksums(mem, data_root, system_root)
    }

    // Verifies the checksums reachable from the given data and system roots, and from the user
    // roots of the persistent savepoints recorded in the system tree, reading pages through `mem`
    // (i.e. from disk if its cache was invalidated first).
    fn verify_checksums(
        mem: Arc<TransactionalMemory>,
        data_root: Option<BtreeHeader>,
        system_root: Option<BtreeHeader>,
    ) -> Result<bool> {
        let resolver = PageResolver::new(mem.clone());
        let table_tree = TableTree::new(
            data_root,
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver.clone(),
        )?;
        if !table_tree.verify_checksums()? {
            return Ok(false);
        }
        let system_table_tree = TableTree::new(
            system_root,
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver.clone(),
        )?;
        if !system_table_tree.verify_checksums()? {
            return Ok(false);
        }
        // A persistent savepoint keeps the pages of the user tree it saved, and restoring it makes
        // them the current tree again, so they are part of the committed state. The system tree
        // verified above, so the savepoint records are intact.
        for user_root in Self::persistent_savepoint_roots(&system_table_tree, resolver.clone())? {
            let saved_tree = TableTree::new(
                user_root,
                PageHint::None,
                Arc::new(TransactionGuard::untracked()),
                resolver.clone(),
            )?;
            if !saved_tree.verify_checksums()? {
                return Ok(false);
            }
        }

        Ok(true)
    }

    // The user roots of the persistent savepoints recorded in the given system tree
    fn persistent_savepoint_roots(
        system_tree: &TableTree,
        resolver: PageResolver,
    ) -> Result<Vec<Option<BtreeHeader>>> {
        let table_name = SAVEPOINT_TABLE.name();
        let definition = match system_tree
            .get_table::<SavepointId, SerializedSavepoint<'static>>(table_name, TableType::Normal)
        {
            Ok(Some(definition)) => definition,
            Ok(None) | Err(TableError::TableDoesNotExist(_)) => return Ok(vec![]),
            Err(TableError::Storage(err)) => return Err(err),
            Err(_) => {
                return Err(StorageError::Corrupted(format!(
                    "Unable to open {table_name}"
                )));
            }
        };
        let table_root = match definition {
            InternalTableDefinition::Normal { table_root, .. } => table_root,
            InternalTableDefinition::Multimap { .. } => {
                return Err(StorageError::Corrupted(format!(
                    "{table_name} is not a normal table"
                )));
            }
        };
        let table: ReadOnlyTable<SavepointId, SerializedSavepoint<'static>> = ReadOnlyTable::new(
            table_name.to_string(),
            table_root,
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver,
        )?;
        let mut roots = vec![];
        for entry in ReadableTable::iter(&table)? {
            let (_, savepoint) = entry?;
            roots.push(savepoint.value().get_user_root()?);
        }
        Ok(roots)
    }

    /// Force a check of the integrity of the database file, and repair it if possible.
    ///
    /// Reports a file corrupted outside redb as [`StorageError::Corrupted`] rather than panicking,
    /// as does an open with [`Builder::set_check_integrity_on_open`]. A plain open makes no such
    /// promise.
    ///
    /// Note: Calling this function is unnecessary during normal operation. redb will automatically
    /// detect and recover from crashes, power loss, and other unclean shutdowns. This function is
    /// quite slow and should only be used when you suspect the database file may have been modified
    /// externally to redb, or that a redb bug may have left the database in a corrupted state.
    ///
    /// Returns `Ok(true)` if the database passed integrity checks; `Ok(false)` if it failed but was repaired,
    /// and `Err(Corrupted)` if the check failed and the file could not be repaired.
    ///
    /// Returns [`DatabaseError::TransactionInProgress`] if any read or write transaction, or an
    /// ephemeral [`Savepoint`](crate::Savepoint), is still alive on this handle when this method
    /// is called.
    ///
    /// Transactions committed with [`Durability::None`](crate::Durability::None) that have not yet
    /// been made durable are made durable if the check passes, or rolled back if the database must
    /// be repaired.
    ///
    /// In the concurrency modes that share the file between processes, the check holds the writer
    /// lock: it waits for a write transaction in another process to end, and no other process
    /// writes to the file until it returns. A read transaction in another process neither blocks
    /// the check nor is disturbed by it. See
    /// [`Builder::set_concurrency_mode`](crate::Builder::set_concurrency_mode).
    pub fn check_integrity(&mut self) -> Result<bool, DatabaseError> {
        if Arc::get_mut(&mut self.mem).is_none() {
            return Err(DatabaseError::TransactionInProgress);
        }
        // An ephemeral savepoint may pin a non-durable transaction whose pages the reload below
        // discards; restoring it afterwards could corrupt the database. Persistent savepoints are
        // durable, so they are unaffected.
        if self.transaction_tracker.any_ephemeral_savepoint_exists() {
            return Err(DatabaseError::TransactionInProgress);
        }

        // Report a latched I/O failure as such, not as the discarded allocator state it also causes
        self.mem.check_io_errors()?;
        // Once the allocator state has been discarded (by a failed commit or integrity check),
        // the database must be reopened to rebuild it; this check requires one to compare against
        if self.mem.allocator_state_invalidated() {
            return Err(StorageError::Corrupted(
                "Allocator state was discarded by a failed integrity check or commit; reopen the database to repair it".to_string(),
            )
            .into());
        }

        // Held until the check returns, so the file it reloads is the file it repairs
        let writer_lock = self.mem.lock_writer()?;
        // Repairing rebuilds the allocator state, so a failure part way through leaves one that
        // describes neither the file nor anything else. Holding an allocator state must continue
        // to mean it describes the file.
        let result = self.check_integrity_inner(&writer_lock);
        if result.is_err() {
            self.mem.invalidate_allocator_state();
        }
        result
    }

    fn check_integrity_inner(
        &mut self,
        writer_lock: &Arc<WriterLock>,
    ) -> Result<bool, DatabaseError> {
        // A pending Durability::None commit is acknowledged, live data that the reload below would
        // discard. If the live state verifies, promote it to durable rather than losing it -- even
        // if the durable state it replaces turns out to be corrupt, in which case we recover from
        // the live state and report not-clean.
        let mut rolling_back_non_durable = false;
        if self.mem.pending_non_durable_commit() {
            // Verify from disk, not the page cache, so external modification is detected.
            self.mem.clear_read_cache();
            // Don't promote over a truncated or extended file -- the committed layout would be
            // inconsistent with it. Fall through to reload + repair instead.
            if self.mem.file_len_matches_layout()?
                && let Some(live_allocator_clean) = self.repair_live_state()?
            {
                // The live tree is intact (its allocator state was rebuilt above if it was stale),
                // so promote the acknowledged commit rather than rolling it back. The result is
                // clean only if neither the allocator nor the durable state below needed repair.
                let durable_clean = self.durable_state_clean()?;
                let mut txn = self
                    .begin_write_with(Some(writer_lock), None)
                    .map_err(|e| DatabaseError::Storage(e.into_storage_error()))?;
                txn.disable_post_commit_free();
                txn.commit()
                    .map_err(|e| DatabaseError::Storage(e.into_storage_error()))?;
                // The rebuild above reclaimed any leaked pages, so the close may record a
                // clean shutdown again
                self.mem.clear_needs_repair();
                return Ok(live_allocator_clean && durable_clean);
            }
            // The live tree is corrupt (or the file size changed), so the reload rolls the commit
            // back -- not clean, even if the durable state it falls back to is intact.
            rolling_back_non_durable = true;
        }

        // No pending commit, or fall-through: verify and repair the durable state. Capture the
        // allocator hash to compare against the rebuild below; with the pending case handled above,
        // the live and durable states are identical here, so this is a valid check. When the reload
        // finds another process's commit, the snapshot it recorded is compared instead: that is
        // what the next open trusts.
        let own_allocator_hash = self.mem.allocator_hash();
        let mem = Arc::get_mut(&mut self.mem).unwrap();
        let (mut was_clean, peer_committed) = mem.clear_cache_and_reload()?;
        let allocator_hash = if peer_committed {
            // The peer's snapshot is in pages this handle has not verified; verify before decoding
            // it, so that a corrupted file is reported rather than panicking
            if Self::primary_verifies(&self.mem)? {
                match Self::get_allocator_state_table(&self.mem)? {
                    Some(tree) => {
                        self.mem.load_allocator_state(&tree)?;
                        Some(self.mem.allocator_hash())
                    }
                    None => None,
                }
            } else {
                None
            }
        } else {
            Some(own_allocator_hash)
        };
        // An interrupted compaction or repair may leave no allocator snapshot. Record one so
        // the next writer can load it without rebuilding again.
        if peer_committed
            && allocator_hash.is_none()
            && self.mem.concurrency_mode().is_multi_writer()
        {
            was_clean = false;
        }

        let old_roots = [self.mem.get_data_root(), self.mem.get_system_root()];

        let new_roots = Self::do_repair(&mut self.mem, &|_| {}).map_err(|err| match err {
            DatabaseError::Storage(storage_err) => storage_err,
            _ => unreachable!(),
        })?;

        if old_roots != new_roots
            || allocator_hash.is_some_and(|hash| hash != self.mem.allocator_hash())
            || rolling_back_non_durable
        {
            was_clean = false;
        }

        if !was_clean {
            let next_transaction_id = self.mem.get_last_committed_transaction_id()?.next();
            let [data_root, system_root] = new_roots;
            self.mem.commit(
                data_root,
                system_root,
                next_transaction_id,
                true,
                ShrinkPolicy::Never,
                None,
            )?;
            // Reserve the id, or the next write transaction would commit with the same one,
            // which crash recovery could then resolve to the wrong slot
            self.transaction_tracker
                .reserve_repair_transaction_id(next_transaction_id);
        }

        // The rebuild reclaimed any leaked pages, so the close may record a clean shutdown
        // again
        self.mem.clear_needs_repair();
        self.mem.begin_writable()?;

        // The tracker holds the persistent savepoints the reloaded tables hold, as the open's does
        if peer_committed {
            Self::sync_persistent_savepoints(
                &self.transaction_tracker,
                &self.mem,
                Some(writer_lock),
            )?;
        }
        // In multi-writer mode a repair ends with a commit recording the allocator state, as the
        // open's does; after the savepoints are held, since a commit frees what nothing pins
        if !was_clean && self.mem.concurrency_mode().is_multi_writer() {
            ensure_allocator_state_table_and_trim(
                &self.transaction_tracker,
                &self.mem,
                Some(writer_lock),
                None,
            )?;
        }

        Ok(was_clean)
    }

    // Synchronizes the tracker state for the file's persistent savepoints. The transaction this
    // begins is lent `writer_lock`, when the caller holds one
    fn sync_persistent_savepoints(
        transaction_tracker: &Arc<TransactionTracker>,
        mem: &Arc<TransactionalMemory>,
        writer_lock: Option<&Arc<WriterLock>>,
    ) -> Result<(), DatabaseError> {
        let txn = begin_write_with_allocation_policy(
            transaction_tracker,
            mem,
            writer_lock,
            None,
            AllocationPolicy::Default,
        )
        .map_err(|e| e.into_storage_error())?;
        sync_persistent_savepoints(transaction_tracker, mem, &txn)?;
        txn.abort()?;

        Ok(())
    }

    // Verifies, and repairs in memory, the live (possibly non-durable) state. Returns:
    // - `None` if the live tree is corrupt and the commit must be rolled back;
    // - `Some(true)` if the live state is fully clean;
    // - `Some(false)` if the tree is intact but its allocator state was stale and has been rebuilt,
    //   so promoting it repairs the allocator while the check reports not-clean.
    // The allocator is rebuilt from the live roots -- a rebuild from the durable roots would
    // falsely differ when the live state is ahead of durable (e.g. a durable commit's free-page
    // epilogue).
    fn repair_live_state(&mut self) -> Result<Option<bool>, DatabaseError> {
        match Self::verify_primary_checksums(self.mem.clone()) {
            Ok(true) => {
                let live_allocator_hash = self.mem.allocator_hash();
                let live_roots = [self.mem.get_data_root(), self.mem.get_system_root()];
                match Self::rebuild_allocator_state(&self.mem, &|_| {}) {
                    // Only a durable root can be rewritten from here, so a live root whose table
                    // count was recomputed must be rolled back and repaired by the reload below
                    Ok(roots) if roots != live_roots => Ok(None),
                    Ok(_) => Ok(Some(live_allocator_hash == self.mem.allocator_hash())),
                    Err(DatabaseError::Storage(StorageError::Corrupted(_))) => Ok(None),
                    Err(err) => Err(err),
                }
            }
            Ok(false) | Err(StorageError::Corrupted(_)) => Ok(None),
            Err(err) => Err(err.into()),
        }
    }

    // Whether the durable (primary slot) state is intact. Any corruption -- a bad primary slot
    // checksum, a checksum mismatch, or an error raised while walking a malformed tree -- counts as
    // not-clean: the caller promotes the verified live commit to recover from it, so corruption
    // here must not abort the check. Only non-corruption errors (e.g. I/O) propagate.
    fn durable_state_clean(&self) -> Result<bool, DatabaseError> {
        match self.verify_durable_state() {
            Ok(clean) => Ok(clean),
            Err(DatabaseError::Storage(StorageError::Corrupted(_))) => Ok(false),
            Err(err) => Err(err),
        }
    }

    fn verify_durable_state(&self) -> Result<bool, DatabaseError> {
        if self.mem.durable_primary_slot_corrupt()? {
            return Ok(false);
        }
        let data_root = self.mem.get_durable_data_root();
        let system_root = self.mem.get_durable_system_root();
        Ok(Self::verify_checksums(
            self.mem.clone(),
            data_root,
            system_root,
        )?)
    }

    /// Compacts the database file
    ///
    /// Returns `true` if compaction was performed, and `false` if no futher compaction was possible
    pub fn compact(&mut self) -> Result<bool, CompactionError> {
        // These checks must run before begin_write(): the caller may legally hold an open
        // WriteTransaction (it is not lifetime-bound to the Database), on which begin_write()
        // below would wait forever. Savepoints must be diagnosed before read references,
        // because every live savepoint also holds a read reference, and the write transaction
        // after both, so that what it holds is reported first. The tracker covers persistent
        // savepoints created by previous Database instances, because they are re-registered
        // when the database is opened.
        // In multi-writer mode the tracker's savepoints go stale: a peer may have deleted one
        // since this handle last synced, and only a write transaction of this handle's own syncs
        // them again. Refresh before reporting one as a blocker, unless this process already has
        // a write transaction live, since beginning another would block on it.
        if self.mem.concurrency_mode().is_multi_writer()
            && self.transaction_tracker.any_persistent_savepoint_exists()
            && !self.transaction_tracker.write_transaction_live()
        {
            self.begin_write()
                .map_err(|e| e.into_storage_error())?
                .abort()?;
        }
        if self.transaction_tracker.any_persistent_savepoint_exists() {
            return Err(CompactionError::PersistentSavepointExists);
        }
        if self.transaction_tracker.any_savepoint_exists() {
            return Err(CompactionError::EphemeralSavepointExists);
        }
        if self.transaction_tracker.any_user_read_reference_exists() {
            return Err(CompactionError::TransactionInProgress);
        }
        if self.transaction_tracker.write_transaction_live() {
            return Err(CompactionError::TransactionInProgress);
        }
        // Where the file is shared, held until the compaction is over and lent to the
        // transactions it runs: no other process begins a transaction under them, and one that
        // already has is a transaction in progress. Taken once a write transaction begun before
        // this call has ended: its commit would wait on the holds, and in multi-writer mode its
        // end would release the writer byte from under a hold taken meanwhile
        let (writer_lock, header_lock) = if self.mem.concurrency_mode().is_multi_process_writable()
        {
            self.begin_write()
                .map_err(|e| e.into_storage_error())?
                .abort()?;
            (
                Some(self.mem.lock_writer()?),
                Some(self.mem.lock_header_exclusive()?),
            )
        } else {
            (None, None)
        };
        // Use 2-phase commit to avoid any possible security issues. Plus this compaction is going to be so slow that it doesn't matter.
        // Once https://github.com/cberner/redb/issues/829 is fixed, we should upgrade this to use quick-repair -- that way the user
        // can cancel the compaction without requiring a full repair afterwards
        let txn = self
            .begin_write_with(writer_lock.as_ref(), header_lock.as_ref())
            .map_err(|e| e.into_storage_error())?;
        // Re-check inside the write transaction: a concurrent writer may have created a
        // savepoint between the checks above and the start of this transaction.
        if txn.list_persistent_savepoints()?.next().is_some() {
            return Err(CompactionError::PersistentSavepointExists);
        }
        if self.transaction_tracker.any_savepoint_exists() {
            return Err(CompactionError::EphemeralSavepointExists);
        }
        if self.transaction_tracker.any_user_read_reference_exists() {
            return Err(CompactionError::TransactionInProgress);
        }
        // No local read is left to bound the scan, so a pin it finds is a peer's
        if let Some(header_lock) = &header_lock
            && self
                .mem
                .oldest_active_transaction(None, header_lock)?
                .is_some()
        {
            return Err(CompactionError::TransactionInProgress);
        }
        txn.abort()?;
        // Commit to free up any pending free pages
        self.drain_pending_free_pages(
            ShrinkPolicy::Maximum,
            writer_lock.as_ref(),
            header_lock.as_ref(),
        )?;

        let mut compacted = false;
        // Iteratively compact until no progress is made
        loop {
            let mut progress = false;

            let mut txn = self
                .begin_write_with(writer_lock.as_ref(), header_lock.as_ref())
                .map_err(|e| e.into_storage_error())?;
            txn.skip_allocator_state_record();
            if txn.compact_pages()? {
                progress = true;
                txn.commit_with(header_lock.as_ref())
                    .map_err(|e| e.into_storage_error())?;
            } else {
                txn.abort()?;
            }

            // Drain pages freed by compact_pages(), including system pages queued by any
            // post-commit cleanup root updates.
            self.drain_pending_free_pages(
                ShrinkPolicy::Maximum,
                writer_lock.as_ref(),
                header_lock.as_ref(),
            )?;

            if !progress {
                break;
            }

            compacted = true;
        }

        // In multi-writer mode the file's latest commit records the allocator state, for the
        // next writer, in any process, to load rather than rebuild: the commit the close makes.
        // Not in the other modes, where the close records and a second record would leave the
        // file one record larger, the pages of the one it replaces being freed only by the next
        // commit
        if self.mem.concurrency_mode().is_multi_writer() {
            ensure_allocator_state_table_and_trim(
                &self.transaction_tracker,
                &self.mem,
                writer_lock.as_ref(),
                header_lock.as_ref(),
            )?;
        }

        Ok(compacted)
    }

    fn drain_pending_free_pages(
        &self,
        shrink_policy: ShrinkPolicy,
        writer_lock: Option<&Arc<WriterLock>>,
        header_lock: Option<&HeaderGuard<'_>>,
    ) -> Result {
        // Preserve compact()'s empty durable commit, which also publishes pending
        // non-durable roots before checking for pending frees.
        let mut force_commit = true;
        loop {
            let mut txn = self
                .begin_write_with(writer_lock, header_lock)
                .map_err(|e| e.into_storage_error())?;
            if !force_commit && !txn.pending_free_pages()? {
                txn.abort()?;
                return Ok(());
            }
            force_commit = false;
            txn.skip_allocator_state_record();
            txn.set_two_phase_commit(true);
            txn.set_shrink_policy(shrink_policy);
            txn.commit_with(header_lock)
                .map_err(|e| e.into_storage_error())?;
        }
    }

    #[cfg_attr(not(debug_assertions), expect(dead_code))]
    fn check_repaired_allocated_pages_table(
        system_root: Option<BtreeHeader>,
        mem: Arc<TransactionalMemory>,
    ) -> Result {
        let resolver = PageResolver::new(mem.clone());
        let table_tree = TableTree::new(
            system_root,
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver.clone(),
        )?;
        if let Some(table_def) = table_tree
            .get_table::<TransactionIdWithPagination, PageList>(
                DATA_ALLOCATED_TABLE.name(),
                TableType::Normal,
            )
            .map_err(|e| e.into_storage_error_or_corrupted("Allocated pages table corrupted"))?
        {
            let InternalTableDefinition::Normal { table_root, .. } = table_def else {
                unreachable!()
            };
            let table: ReadOnlyTable<TransactionIdWithPagination, PageList> = ReadOnlyTable::new(
                DATA_ALLOCATED_TABLE.name().to_string(),
                table_root,
                PageHint::None,
                Arc::new(TransactionGuard::untracked()),
                resolver,
            )?;
            for result in ReadableTable::iter(&table)? {
                let (_, pages) = result?;
                for page in pages.value().pages()? {
                    assert!(mem.is_allocated(page));
                }
            }
        }

        Ok(())
    }

    fn visit_freed_tree<K: Key, V: Value, F>(
        system_root: Option<BtreeHeader>,
        table_def: SystemTableDefinition<K, V>,
        mem: Arc<TransactionalMemory>,
        mut visitor: F,
    ) -> Result
    where
        F: FnMut(PageNumber) -> Result,
    {
        let untracked_guard = Arc::new(TransactionGuard::untracked());
        let resolver = PageResolver::new(mem.clone());
        let system_tree = TableTree::new(
            system_root,
            PageHint::None,
            untracked_guard,
            resolver.clone(),
        )?;
        let table_name = table_def.name();
        let result = match system_tree.get_table::<K, V>(table_name, TableType::Normal) {
            Ok(result) => result,
            Err(TableError::Storage(err)) => {
                return Err(err);
            }
            Err(TableError::TableDoesNotExist(_)) => {
                return Ok(());
            }
            Err(_) => {
                return Err(StorageError::Corrupted(format!(
                    "Unable to open {table_name}"
                )));
            }
        };

        if let Some(definition) = result {
            let table_root = match definition {
                InternalTableDefinition::Normal { table_root, .. } => table_root,
                InternalTableDefinition::Multimap { .. } => unreachable!(),
            };
            let table: ReadOnlyTable<TransactionIdWithPagination, PageList<'static>> =
                ReadOnlyTable::new(
                    table_name.to_string(),
                    table_root,
                    PageHint::None,
                    Arc::new(TransactionGuard::untracked()),
                    resolver,
                )?;
            for result in ReadableTable::iter(&table)? {
                let (_, page_list) = result?;
                for page in page_list.value().pages()? {
                    visitor(page)?;
                }
            }
        }

        Ok(())
    }

    #[cfg(debug_assertions)]
    fn mark_allocated_page_for_debug(mem: &Arc<TransactionalMemory>) -> Result {
        let data_root = mem.get_data_root();
        {
            let untracked = Arc::new(TransactionGuard::untracked());
            let tables = TableTree::new(
                data_root,
                PageHint::None,
                untracked,
                PageResolver::new(mem.clone()),
            )?;
            tables.visit_all_pages(|path| {
                mem.mark_debug_allocated_page(path.page_number());
                Ok(())
            })?;
        }

        let system_root = mem.get_system_root();
        {
            let untracked = Arc::new(TransactionGuard::untracked());
            let system_tables = TableTree::new(
                system_root,
                PageHint::None,
                untracked,
                PageResolver::new(mem.clone()),
            )?;
            system_tables.visit_all_pages(|path| {
                mem.mark_debug_allocated_page(path.page_number());
                Ok(())
            })?;
        }

        Self::visit_freed_tree(system_root, DATA_FREED_TABLE, mem.clone(), |page| {
            mem.mark_debug_allocated_page(page);
            Ok(())
        })?;
        Self::visit_freed_tree(system_root, SYSTEM_FREED_TABLE, mem.clone(), |page| {
            mem.mark_debug_allocated_page(page);
            Ok(())
        })?;

        Ok(())
    }

    // Whether the primary slot's trees verify. A Corrupted error counts as "they do not", so that
    // a torn slot carrying an invalid page number falls back to the secondary like any other bad
    // primary, rather than aborting the repair. Other errors (e.g. I/O) still propagate.
    fn primary_verifies(mem: &Arc<TransactionalMemory>) -> Result<bool> {
        match Self::verify_primary_checksums(mem.clone()) {
            Ok(verified) => Ok(verified),
            Err(StorageError::Corrupted(_)) => Ok(false),
            Err(err) => Err(err),
        }
    }

    fn do_repair(
        mem: &mut Arc<TransactionalMemory>, // Only &mut to ensure exclusivity
        repair_callback: &(dyn Fn(&mut RepairSession) + 'static),
    ) -> Result<[Option<BtreeHeader>; 2], DatabaseError> {
        if !Self::primary_verifies(mem)? {
            if mem.used_two_phase_commit() {
                return Err(DatabaseError::Storage(StorageError::Corrupted(
                    "Primary is corrupted despite 2-phase commit".to_string(),
                )));
            }

            // 0.3 because the repair takes 3 full scans and the first is done now
            let mut handle = RepairSession::new(0.3);
            repair_callback(&mut handle);
            if handle.aborted() {
                return Err(DatabaseError::RepairAborted);
            }

            let fell_back = mem.repair_primary_corrupted();
            // We need to invalidate the userspace cache, because walking the tree in verify_primary_checksums() may
            // have poisoned it with pages that just got rolled back by repair_primary_corrupted(), since
            // that rolls back a partially committed transaction.
            mem.clear_read_cache();
            if !fell_back || !Self::primary_verifies(mem)? {
                return Err(DatabaseError::Storage(StorageError::Corrupted(
                    "Failed to repair database. All roots are corrupted".to_string(),
                )));
            }
        }
        // 0.6 because the repair takes 3 full scans and the second is done now
        let mut handle = RepairSession::new(0.6);
        repair_callback(&mut handle);
        if handle.aborted() {
            return Err(DatabaseError::RepairAborted);
        }

        let [data_root, system_root] = Self::rebuild_allocator_state(mem, repair_callback)?;

        mem.clear_recovery_required()?;

        // We need to invalidate the userspace cache, because we're about to implicitly free the freed table
        // by storing an empty root during the below commit()
        mem.clear_read_cache();

        Ok([data_root, system_root])
    }

    // Rebuilds the in-memory allocator state by marking every page reachable from the current
    // roots (including the pages referenced by the freed-page tables) as allocated. Operates
    // purely on in-memory state and does not modify the file.
    //
    // The returned roots carry table counts recounted from the trees that were walked. These
    // counts are stored in the commit slot rather than in a page, so no page checksum covers
    // them; recounting here is what lets the rest of the codebase trust them.
    //
    // Callers must ensure nothing else uses the allocator meanwhile: either no transaction is
    // live, or the caller holds the write slot (read transactions never allocate or free).
    fn rebuild_allocator_state(
        mem: &Arc<TransactionalMemory>,
        repair_callback: &(dyn Fn(&mut RepairSession) + 'static),
    ) -> Result<[Option<BtreeHeader>; 2], DatabaseError> {
        mem.reset_allocator_state()?;

        let data_root = {
            let root = mem.get_data_root();
            let untracked = Arc::new(TransactionGuard::untracked());
            let tables = TableTree::new(
                root,
                PageHint::None,
                untracked,
                PageResolver::new(mem.clone()),
            )?;
            tables.visit_all_pages(|path| mem.mark_page_allocated(path.page_number()))?;
            Self::with_recounted_length(root, tables.count_tables()?)
        };

        // 0.9 because the repair takes 3 full scans and the third is done now. There is just some system tables left
        let mut handle = RepairSession::new(0.9);
        repair_callback(&mut handle);
        if handle.aborted() {
            return Err(DatabaseError::RepairAborted);
        }

        let system_root = {
            let root = mem.get_system_root();
            let untracked = Arc::new(TransactionGuard::untracked());
            let system_tables = TableTree::new(
                root,
                PageHint::None,
                untracked,
                PageResolver::new(mem.clone()),
            )?;
            system_tables.visit_all_pages(|path| mem.mark_page_allocated(path.page_number()))?;
            Self::with_recounted_length(root, system_tables.count_tables()?)
        };

        Self::visit_freed_tree(system_root, DATA_FREED_TABLE, mem.clone(), |page| {
            mem.mark_page_allocated(page)
        })?;
        Self::visit_freed_tree(system_root, SYSTEM_FREED_TABLE, mem.clone(), |page| {
            mem.mark_page_allocated(page)
        })?;
        // Non-durable commits hold their data-freed records in memory rather than in
        // DATA_FREED_TABLE, so the walk above does not reach those pages. They are still allocated
        // until a commit processes the records, so mark them like any other freed-table page.
        for page in mem.unpersisted_data_freed_pages() {
            mem.mark_page_allocated(page)?;
        }
        #[cfg(debug_assertions)]
        {
            Self::check_repaired_allocated_pages_table(system_root, mem.clone())?;
        }

        Ok([data_root, system_root])
    }

    fn with_recounted_length(root: Option<BtreeHeader>, length: u64) -> Option<BtreeHeader> {
        root.map(|header| BtreeHeader::new(header.root, header.checksum, length))
    }

    /// Loads the latest allocator snapshot, or rebuilds it if compaction or repair stopped before
    /// recording one. The caller holds the write slot and writer byte throughout.
    fn load_synced_allocator_state(
        mem: &Arc<TransactionalMemory>,
        _writer_lock: &WriterLock,
    ) -> Result {
        if let Some(tree) = Self::get_allocator_state_table(mem)? {
            mem.load_allocator_state(&tree)?;
            #[cfg(debug_assertions)]
            Self::mark_allocated_page_for_debug(mem)?;
        } else {
            if !Self::verify_primary_checksums(mem.clone())? {
                return Err(StorageError::Corrupted(
                    "Cannot rebuild allocator state: committed trees are corrupted".to_string(),
                ));
            }
            // Freed-page tables retain the pages that readers and persistent savepoints still
            // reference. Rebuilding must keep those allocated as well as the current trees.
            let roots = Self::rebuild_allocator_state(mem, &|_| {})
                .map_err(DatabaseError::into_storage_error_or_corrupted)?;
            if roots != [mem.get_data_root(), mem.get_system_root()] {
                return Err(StorageError::Corrupted(
                    "Committed table counts do not match the database trees".to_string(),
                ));
            }
        }
        // Loaded or rebuilt, this state holds none of the pages leaked by a transaction that
        // was dropped while a panic unwound. The next commit can record it again.
        mem.clear_needs_repair();

        Ok(())
    }

    fn new(
        file: Box<dyn StorageBackend>,
        allow_initialize: bool,
        page_size: usize,
        region_size: Option<u64>,
        cache_size: usize,
        concurrency_mode: ConcurrencyMode,
        repair: RepairConfig<'_>,
    ) -> Result<Self, DatabaseError> {
        let RepairConfig {
            check_integrity: check_integrity_on_open,
            callback: repair_callback,
        } = repair;
        #[cfg(feature = "logging")]
        let file_path = format!("{:?}", &file);
        #[cfg(feature = "logging")]
        debug!("Opening database {:?}", &file_path);
        // The open runs under this lock, which the multi-writer open took for the header read
        // below and the repair after it, and which the transactions it runs are lent
        let (mem, writer_lock) = TransactionalMemory::new(
            file,
            allow_initialize,
            page_size,
            region_size,
            cache_size,
            false,
            concurrency_mode,
        )?;
        let mut mem = Arc::new(mem);
        // If the last transaction used 2-phase commit and updated the allocator state table, then
        // we can just load the allocator state from there. Otherwise, unless nothing has been
        // committed, we need a full repair. An integrity check on open skips the recorded state,
        // and the unverified read of the system tree that finding it takes, and verifies the file
        let allocator_state = if check_integrity_on_open {
            None
        } else {
            Self::get_allocator_state_table(&mem)?
        };
        let repaired = if let Some(tree) = allocator_state {
            #[cfg(feature = "logging")]
            debug!("Found valid allocator state, full repair not needed");
            mem.load_allocator_state(&tree)?;
            #[cfg(debug_assertions)]
            Self::mark_allocated_page_for_debug(&mem)?;
            false
        } else if mem.never_committed() {
            // Just initialized, or created and never written: with no commit there is nothing to
            // recover, and a repair would only report a new file as not shut down cleanly, and
            // fail every create for a repair callback that aborts
            mem.load_empty_allocator_state()?;
            false
        } else {
            #[cfg(feature = "logging")]
            if check_integrity_on_open {
                debug!(
                    "Integrity check of database {:?} requested. Repairing",
                    &file_path
                );
            } else {
                warn!("Database {:?} not shutdown cleanly. Repairing", &file_path);
            }
            let mut handle = RepairSession::new(0.0);
            repair_callback(&mut handle);
            if handle.aborted() {
                return Err(DatabaseError::RepairAborted);
            }
            let [data_root, system_root] = Self::do_repair(&mut mem, repair_callback)?;
            let next_transaction_id = mem.get_last_committed_transaction_id()?.next();
            mem.commit(
                data_root,
                system_root,
                next_transaction_id,
                true,
                ShrinkPolicy::Never,
                None,
            )?;
            true
        };

        // Past recovery, so the file is consistent, which the byte asserts from here on. Taken
        // before the flag is published: a reader finding the flag without the byte refuses the
        // file as one a crash left
        mem.mark_consistent()?;
        mem.begin_writable()?;
        let next_transaction_id = mem.get_last_committed_transaction_id()?.next();

        let transaction_tracker = Arc::new(TransactionTracker::new(next_transaction_id));

        // Restore the tracker state for any persistent savepoints
        Self::sync_persistent_savepoints(&transaction_tracker, &mem, writer_lock.as_ref())?;
        // In multi-writer mode a repair ends with a commit recording the allocator state, as
        // compaction and the integrity check do, so that the next open, in any process, loads it
        if repaired && concurrency_mode.is_multi_writer() {
            ensure_allocator_state_table_and_trim(
                &transaction_tracker,
                &mem,
                writer_lock.as_ref(),
                None,
            )?;
        }
        // Construct only after initialization succeeds: Database::drop takes the writer lock,
        // which the open still holds, and assumes the savepoint tracker is complete.
        Ok(Database {
            mem,
            transaction_tracker,
            closed: false,
        })
    }

    fn get_allocator_state_table(
        mem: &Arc<TransactionalMemory>,
    ) -> Result<Option<AllocatorStateTree>> {
        // The allocator state table is only valid if the primary was written using 2-phase commit
        if !mem.used_two_phase_commit() {
            return Ok(None);
        }

        // See if it's present in the system table tree
        let resolver = PageResolver::new(mem.clone());
        let system_table_tree = TableTree::new(
            mem.get_system_root(),
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver.clone(),
        )?;
        let Some(allocator_state_table) = system_table_tree
            .get_table::<AllocatorStateKey, &[u8]>(ALLOCATOR_STATE_TABLE_NAME, TableType::Normal)
            .map_err(|e| e.into_storage_error_or_corrupted("Unexpected TableError"))?
        else {
            return Ok(None);
        };

        // Load the allocator state table
        let InternalTableDefinition::Normal { table_root, .. } = allocator_state_table else {
            unreachable!();
        };
        let tree = AllocatorStateTree::new(
            table_root,
            PageHint::None,
            Arc::new(TransactionGuard::untracked()),
            resolver,
        )?;

        // Make sure this isn't stale allocator state left over from a previous transaction
        if !mem.is_valid_allocator_state(&tree)? {
            return Ok(None);
        }

        Ok(Some(tree))
    }

    /// Convenience method for [`Builder::new`]
    pub fn builder() -> Builder {
        Builder::new()
    }

    /// Begins a write transaction
    ///
    /// Returns a [`WriteTransaction`] which may be used to read/write to the database. Only a single
    /// write may be in progress at a time. If a write is in progress, this function will block
    /// until it completes.
    ///
    /// The returned transaction is not lifetime-bound to this [`Database`] and keeps the
    /// database open: if the [`Database`] is dropped while the transaction is live, the
    /// transaction remains usable and the database closes when the transaction completes.
    pub fn begin_write(&self) -> Result<WriteTransaction, TransactionError> {
        self.begin_write_with(None, None)
    }

    /// Begins a write transaction, without waiting for another one to finish
    ///
    /// Returns [`TransactionError::WouldBlock`] where [`Self::begin_write`] would wait: while
    /// another write transaction of this database is alive, or, in
    /// [`ConcurrencyMode::MultiWriter`], while another process is in a write transaction.
    pub fn try_begin_write(&self) -> Result<WriteTransaction, TransactionError> {
        self.mem.check_io_errors()?;
        // In the order begin_write() takes them, and released if the second is not free
        let slot = WriteSlot::try_take(self.transaction_tracker.clone())
            .ok_or(TransactionError::WouldBlock)?;
        let writer_lock = self
            .mem
            .try_lock_writer()?
            .ok_or(TransactionError::WouldBlock)?;
        begin_write_holding(
            &self.transaction_tracker,
            &self.mem,
            slot,
            writer_lock,
            None,
            AllocationPolicy::Default,
        )
    }

    fn begin_write_with(
        &self,
        writer_lock: Option<&Arc<WriterLock>>,
        header_lock: Option<&HeaderGuard<'_>>,
    ) -> Result<WriteTransaction, TransactionError> {
        begin_write_with_allocation_policy(
            &self.transaction_tracker,
            &self.mem,
            writer_lock,
            header_lock,
            AllocationPolicy::Default,
        )
    }
}

// Syncs the file's persistent savepoints, which another process may have created or
// deleted since the tracker last saw the file, and continues savepoint ids past the file's.
fn sync_persistent_savepoints(
    transaction_tracker: &TransactionTracker,
    mem: &TransactionalMemory,
    txn: &WriteTransaction,
) -> Result {
    if let Some(next_id) = txn.next_persistent_savepoint_id()? {
        transaction_tracker.restore_savepoint_counter_state(next_id);
    }
    let current = txn.persistent_savepoint_transactions()?;
    for &transaction_id in current.values() {
        // The file names its persistent savepoints, so the transaction each points at is
        // untrusted: one outside the lock range would be tracked as a read this process holds
        mem.check_active_transaction_id(transaction_id)?;
    }
    transaction_tracker.sync_persistent_savepoints(&current)
}

/// Brings this handle up to the file's latest commit, in multi-writer mode, when it is not
/// already on it. That is the case when another process has committed since this handle last
/// read the file, and when a panic latched a repair, which leaves this handle's allocator state
/// holding pages that the file's latest commit does not.
///
/// `writer_lock` proves that the caller holds the writer byte, so that no other process commits
/// while the header is read and the allocator state loaded from it; `header_lock` is the header
/// lock the caller already holds, if any.
///
/// Returns `None` when the handle was already on the file's latest commit. Otherwise returns a
/// latch that discards the allocator state unless the caller finishes the sync.
fn sync_to_latest_commit(
    mem: &Arc<TransactionalMemory>,
    writer_lock: &WriterLock,
    header_lock: Option<&HeaderGuard<'_>>,
) -> Result<Option<AllocatorStateLatch>> {
    if !mem.concurrency_mode().is_multi_writer() {
        return Ok(None);
    }
    let synced = {
        let hold = mem.header_hold(header_lock)?;
        mem.reload_for_write(writer_lock, &hold)?
    };
    if !synced {
        return Ok(None);
    }
    // Armed before the load, because a load that stops part way leaves an allocator state that
    // describes neither the commit it came from nor the one it was going to
    let latch = AllocatorStateLatch::arm(mem.clone());
    Database::load_synced_allocator_state(mem, writer_lock)?;
    // Loading the allocator state cleared the recovery flag that a live writer keeps set, and a
    // peer's close may have cleared it in the file as well. Set it again, so that the next
    // commit writes it back and a crash of this handle is still recovered from.
    mem.mark_recovery_required();

    Ok(Some(latch))
}

// Takes the write slot and the writer byte, syncs to the file's latest commit, and builds the
// transaction on them.
//
// A caller that already holds the writer byte lends its lock as `writer_lock`. Taking the writer
// byte again from this file description would return that same lock, and the end of this
// transaction would then release the caller's. A caller that holds the header lock lends it as
// `header_lock`, because the in-process half of that lock cannot be taken twice.
//
// The allocation policy is fixed for the lifetime of the transaction; every page allocation the
// transaction makes goes through it.
fn begin_write_with_allocation_policy(
    transaction_tracker: &Arc<TransactionTracker>,
    mem: &Arc<TransactionalMemory>,
    writer_lock: Option<&Arc<WriterLock>>,
    header_lock: Option<&HeaderGuard<'_>>,
    allocation_policy: AllocationPolicy,
) -> Result<WriteTransaction, TransactionError> {
    // Fail early if there has been an I/O error -- nothing can be committed in that case
    mem.check_io_errors()?;
    // The slot ahead of the byte: locks on the byte from one file description are one lock, so
    // the slot is what orders this process's writers. An error return drops both
    let slot = WriteSlot::take(transaction_tracker.clone());
    let writer_lock = writer_lock.map_or_else(|| mem.lock_writer(), |lent| Ok(lent.clone()))?;
    begin_write_holding(
        transaction_tracker,
        mem,
        slot,
        writer_lock,
        header_lock,
        allocation_policy,
    )
}

// The rest of beginning a write transaction, once the caller holds the write slot and the
// writer byte
fn begin_write_holding(
    transaction_tracker: &Arc<TransactionTracker>,
    mem: &Arc<TransactionalMemory>,
    slot: WriteSlot,
    writer_lock: Arc<WriterLock>,
    header_lock: Option<&HeaderGuard<'_>>,
    allocation_policy: AllocationPolicy,
) -> Result<WriteTransaction, TransactionError> {
    let latch = sync_to_latest_commit(mem, &writer_lock, header_lock)?;
    // Re-checked after acquiring the write slot: the writer this call blocked on can fail its
    // commit, latching an I/O error and discarding the allocator state. The I/O check comes
    // first so a backend failure is not misreported as corruption
    mem.check_io_errors()?;
    if mem.allocator_state_invalidated() {
        return Err(StorageError::Corrupted(
            "Allocator state was discarded by a failed integrity check or commit; reopen the database to repair it".to_string(),
        )
        .into());
    }
    // Issued once the sync is done, so that the id follows the file's latest commit
    let transaction_id = transaction_tracker
        .issue_write_transaction_id(mem.get_last_committed_transaction_id()?, &writer_lock);
    let guard = TransactionGuard::new_write(transaction_id, slot, writer_lock);
    let transaction = WriteTransaction::new(
        guard,
        transaction_tracker.clone(),
        mem.clone(),
        allocation_policy,
    )?;
    // The file's persistent savepoints are synced here, before this transaction frees anything,
    // so that the transactions they point at stay pinned. If the sync fails, the transaction is
    // aborted and the latch then discards the allocator state.
    if latch.is_some() {
        sync_persistent_savepoints(transaction_tracker, mem, &transaction)?;
    }
    if let Some(latch) = latch {
        latch.disarm();
    }

    Ok(transaction)
}

// Records the allocator state in a commit that also trims the file: the close's last commit,
// compaction's, and the one ending a repair in the open or the integrity check. Not for a state
// that needs repair: a transaction dropped while a panic unwound leaked its pages, and recording
// that state would make the leak permanent, where the next open's rebuild reclaims it.
// `writer_lock` and `header_lock` are the ones the caller lends, when it holds them; nothing is
// waiting on the write slot in any of these cases
fn ensure_allocator_state_table_and_trim(
    transaction_tracker: &Arc<TransactionTracker>,
    mem: &Arc<TransactionalMemory>,
    writer_lock: Option<&Arc<WriterLock>>,
    header_lock: Option<&HeaderGuard<'_>>,
) -> Result {
    assert!(
        !mem.needs_repair(),
        "recording an allocator state that needs repair"
    );
    #[cfg(feature = "logging")]
    debug!("Writing allocator state table");
    commit_and_trim(transaction_tracker, mem, writer_lock, header_lock, true)
}

// A commit that trims the file, and records the allocator state when asked to
fn commit_and_trim(
    transaction_tracker: &Arc<TransactionTracker>,
    mem: &Arc<TransactionalMemory>,
    writer_lock: Option<&Arc<WriterLock>>,
    header_lock: Option<&HeaderGuard<'_>>,
    record_allocator_state: bool,
) -> Result {
    // If compact() left no free pages, the default allocator lands this
    // commit's writes at high page indices (see AllocationPolicy::Lowest)
    // and try_shrink can't reclaim the growth. See
    // https://github.com/cberner/redb/issues/1165
    let mut tx = begin_write_with_allocation_policy(
        transaction_tracker,
        mem,
        writer_lock,
        header_lock,
        AllocationPolicy::Lowest,
    )
    .map_err(|e| e.into_storage_error())?;
    tx.set_quick_repair(record_allocator_state);
    tx.disable_post_commit_free();
    tx.set_shrink_policy(ShrinkPolicy::Maximum);
    tx.commit_with(header_lock)
        .map_err(|e| e.into_storage_error())?;

    Ok(())
}

// Closes the database: makes any pending non-durable commit durable, persists the allocator
// state table, so that the next open does not require a repair, and closes the storage backend.
// Runs exactly once, when the database closes: from Database::close() or Database::drop, or from
// the end of the write transaction that was live at that point. In all cases the Database is
// being, or has been, consumed, so no new write transaction can be started concurrently and the
// commit in here cannot block on the write-transaction slot. Errors are logged as well as
// returned, since only Database::close() has a caller to return them to.
fn close_database(
    transaction_tracker: &Arc<TransactionTracker>,
    mem: &Arc<TransactionalMemory>,
) -> Result {
    // A transaction dropped while a panic unwound leaked its pages: the allocator state is not
    // recorded, and the next open rebuilds it. A pending non-durable commit is still made
    // durable, by a plain commit, so that the rebuild does not roll it back
    let promote_only = mem.needs_repair();
    // A latched I/O failure leaves the file for the next open to recover, and is the close's error
    let mut result = mem.check_io_errors();
    // Not after a latched I/O failure, nor with nothing to write, decided ahead of the lock
    let writing = !crate::panicking()
        && result.is_ok()
        && (!promote_only || mem.pending_non_durable_commit());
    // One hold across the allocator state's commit and the shutdown header: a commit another
    // process made between them would be overwritten by the header. Without the hold, neither
    // is written: the commit would take one of its own and release it, and the header would
    // then overwrite a commit made between them
    let writer_lock = if writing {
        // Multi-writer commits are durable and record allocator state, so close can skip
        // maintenance rather than deadlock waiting for a peer's write transaction.
        mem.try_lock_writer().unwrap_or_else(|err| {
            result = Err(err);
            None
        })
    } else {
        None
    };
    let recorded = match &writer_lock {
        None => false,
        Some(writer_lock) if promote_only => {
            result = commit_and_trim(transaction_tracker, mem, Some(writer_lock), None, false);
            #[cfg(feature = "logging")]
            if result.is_err() {
                warn!("Failed to make the pending non-durable commits durable. They are lost.");
            }
            false
        }
        Some(writer_lock) => {
            result = ensure_allocator_state_table_and_trim(
                transaction_tracker,
                mem,
                Some(writer_lock),
                None,
            );
            #[cfg(feature = "logging")]
            if result.is_err() {
                warn!("Failed to write allocator state table. Repair may be required at restart.");
            }
            result.is_ok()
        }
    };
    // The shutdown header describes this handle, which matches the file only once the commit
    // above has synced to the file's latest commit and recorded the allocator state. Without a
    // record, write no header, and leave the file for the next open to recover.
    let writer_lock = writer_lock.filter(|_| recorded);

    let close_result = mem.close(writer_lock.as_ref());
    #[cfg(feature = "logging")]
    if close_result.is_err() {
        warn!("Failed to flush database file. Repair may be required at restart.");
    }
    result.and(close_result)
}

impl Drop for Database {
    fn drop(&mut self) {
        if !self.closed {
            // close_database() has logged any error
            let _ = self.close_or_defer();
        }
    }
}

pub struct RepairSession {
    progress: f64,
    aborted: bool,
}

impl RepairSession {
    pub(crate) fn new(progress: f64) -> Self {
        Self {
            progress,
            aborted: false,
        }
    }

    pub(crate) fn aborted(&self) -> bool {
        self.aborted
    }

    /// Abort the repair process. The open that is repairing the database returns
    /// [`DatabaseError::RepairAborted`].
    pub fn abort(&mut self) {
        self.aborted = true;
    }

    /// Returns an estimate of the repair progress in the range [0.0, 1.0). At 1.0 the repair is complete.
    pub fn progress(&self) -> f64 {
        self.progress
    }
}

/// How processes share a database: the regime a writer operates under. Whether a given handle
/// writes is chosen by `open()` or `open_read_only()`, not by the mode.
///
/// Every process opening one database concurrently must use a compatible mode: one
/// `SingleWriter` writer or any number of `MultiWriter` writers, plus any number of read-only
/// handles opened in the same mode. Those two modes need byte-range file locks, so they are
/// supported on Linux, the Apple platforms and Windows; elsewhere, opening a database in one of
/// them fails. `ExclusiveWriter` locks the whole file and works everywhere.
///
/// Every process must also implement the same generation of the multi-process locking protocol.
/// A handle announces its generation with a lock byte, and an open fails with
/// [`DatabaseError::LockProtocolMismatch`](crate::DatabaseError::LockProtocolMismatch) if a
/// process implementing another generation already has the database open. A writer in
/// `ExclusiveWriter` mode locks the whole file instead of announcing a generation. It excludes
/// every other process, and every other process excludes it, with
/// [`DatabaseError::DatabaseAlreadyOpen`](crate::DatabaseError::DatabaseAlreadyOpen) whatever
/// generation each implements.
///
/// A `SingleWriter` or `MultiWriter` handle also excludes a writer running redb before 4.3, which
/// locks the whole file, and is excluded by one. A read-only handle of redb 4.0 to 4.2 holds that
/// lock shared, and on Linux, where it is a separate lock from the byte-range locks, is not
/// excluded by a writer in either mode: it must not be opened on a database such a writer has
/// open, since it reads a snapshot the writer may reuse. Under the `experimental-api-5` feature
/// the whole-file lock is not held, and on Linux only an `ExclusiveWriter` writer detects a version
/// before 4.3.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Default)]
#[non_exhaustive]
pub enum ConcurrencyMode {
    /// A writer excludes every other process; read-only handles share the file with each other
    /// and exclude any writer. Enforced by locking the whole file. The default.
    #[default]
    ExclusiveWriter,
    /// One process writes; any number of processes may, concurrently, open the database read-only
    /// and follow its commits.
    SingleWriter,
    /// Any number of processes may, concurrently, open the database for reading and writing.
    /// Only one write transaction may be open at a time.
    MultiWriter,
}

impl ConcurrencyMode {
    /// Whether another process may have the database open, concurrently, and one process
    /// (possibly this one) is a writer
    pub(crate) fn is_multi_process_writable(self) -> bool {
        !matches!(self, ConcurrencyMode::ExclusiveWriter)
    }

    /// Whether any number of processes may write
    pub(crate) fn is_multi_writer(self) -> bool {
        matches!(self, ConcurrencyMode::MultiWriter)
    }
}

// How an open treats a file that needs a repair, or is asked for one
struct RepairConfig<'a> {
    check_integrity: bool,
    callback: &'a (dyn Fn(&mut RepairSession) + 'static),
}

/// Configuration builder of a redb [Database].
pub struct Builder {
    page_size: usize,
    region_size: Option<u64>,
    cache_size: usize,
    concurrency_mode: ConcurrencyMode,
    check_integrity_on_open: bool,
    repair_callback: Box<dyn Fn(&mut RepairSession)>,
}

impl Builder {
    /// Construct a new [Builder] with sensible defaults.
    ///
    /// ## Defaults
    ///
    /// - `cache_size_bytes`: 1GiB
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            // Default to 4k pages. Benchmarking showed that this was a good default on all platforms,
            // including MacOS with 16k pages. Therefore, users are not allowed to configure it at the moment.
            // It is part of the file format, so can be enabled in the future.
            page_size: PAGE_SIZE,
            region_size: None,
            concurrency_mode: ConcurrencyMode::ExclusiveWriter,
            cache_size: 1024 * 1024 * 1024,
            check_integrity_on_open: false,
            repair_callback: Box::new(|_| {}),
        }
    }

    /// Set a callback which will be invoked periodically in the event that the database file needs
    /// to be repaired.
    ///
    /// The [`RepairSession`] argument can be used to control the repair process.
    ///
    /// If the database file needs repair, the callback will be invoked at least once.
    /// There is no upper limit on the number of times it may be called.
    pub fn set_repair_callback(
        &mut self,
        callback: impl Fn(&mut RepairSession) + 'static,
    ) -> &mut Self {
        self.repair_callback = Box::new(callback);
        self
    }

    /// Set the internal page size of the database
    ///
    /// Valid values are powers of two, greater than or equal to 512
    ///
    /// ## Defaults
    ///
    /// Default to 4 Kib pages.
    #[cfg(any(fuzzing, test))]
    pub fn set_page_size(&mut self, size: usize) -> &mut Self {
        assert!(size.is_power_of_two());
        self.page_size = core::cmp::max(size, 512);
        self
    }

    /// Set the amount of memory (in bytes) used for caching data
    pub fn set_cache_size(&mut self, bytes: usize) -> &mut Self {
        self.cache_size = bytes;
        self
    }

    /// Set how processes may share this database. Defaults to [`ConcurrencyMode::ExclusiveWriter`].
    pub fn set_concurrency_mode(&mut self, mode: ConcurrencyMode) -> &mut Self {
        self.concurrency_mode = mode;
        self
    }

    /// Check the integrity of the database every time it is opened, not only after a crash.
    ///
    /// With this set, the open runs the check and repair of [`Database::check_integrity`]: the
    /// checksum of every page of the committed trees is verified and the allocator state is
    /// rebuilt. A file altered since redb last wrote it fails to open with
    /// [`StorageError::Corrupted`] instead of being trusted, where a plain open may panic.
    ///
    /// The check reads the whole file and commits, so it does not apply to read-only opens.
    ///
    /// Defaults to `false`.
    pub fn set_check_integrity_on_open(&mut self, enabled: bool) -> &mut Self {
        self.check_integrity_on_open = enabled;
        self
    }

    #[cfg(any(test, fuzzing))]
    pub fn set_region_size(&mut self, size: u64) -> &mut Self {
        assert!(size.is_power_of_two());
        self.region_size = Some(size);
        self
    }

    /// Opens the specified file as a redb database.
    /// * if the file does not exist, or is an empty file, a new database will be initialized in it
    /// * if the file is a valid redb database, it will be opened
    /// * otherwise this function will return an error
    #[cfg(not(redb_no_std))]
    pub fn create(&self, path: impl AsRef<Path>) -> Result<Database, DatabaseError> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)?;

        Database::new(
            Box::new(FileBackend::from_file(file)),
            true,
            self.page_size,
            self.region_size,
            self.cache_size,
            self.concurrency_mode,
            RepairConfig {
                check_integrity: self.check_integrity_on_open,
                callback: &self.repair_callback,
            },
        )
    }

    /// Opens an existing redb database.
    #[cfg(not(redb_no_std))]
    pub fn open(&self, path: impl AsRef<Path>) -> Result<Database, DatabaseError> {
        let file = OpenOptions::new().read(true).write(true).open(path)?;

        Database::new(
            Box::new(FileBackend::from_file(file)),
            false,
            self.page_size,
            None,
            self.cache_size,
            self.concurrency_mode,
            RepairConfig {
                check_integrity: self.check_integrity_on_open,
                callback: &self.repair_callback,
            },
        )
    }

    /// Opens an existing redb database.
    ///
    /// If the file has been opened for writing (i.e. as a [`Database`]) [`DatabaseError::DatabaseAlreadyOpen`]
    /// will be returned on platforms which support file locks (macOS, Windows, Linux). On other platforms,
    /// the caller MUST avoid calling this method when the database is open for writing.
    ///
    /// Only an `ExclusiveWriter` writer is refused: in the other modes, a reader opened in the
    /// writer's mode shares the file with it and picks up its commits. See
    /// [`Self::set_concurrency_mode`].
    #[cfg(not(redb_no_std))]
    pub fn open_read_only(
        &self,
        path: impl AsRef<Path>,
    ) -> Result<ReadOnlyDatabase, DatabaseError> {
        let file = OpenOptions::new().read(true).open(path)?;
        self.open_read_only_with_backend(FileBackend::from_file(file))
    }

    /// Opens an existing redb database with the given backend, without modifying it.
    ///
    /// A database requiring recovery is rejected rather than repaired. The locking and concurrency
    /// rules of `open_read_only()` also apply to this method.
    pub fn open_read_only_with_backend(
        &self,
        backend: impl StorageBackend,
    ) -> Result<ReadOnlyDatabase, DatabaseError> {
        ReadOnlyDatabase::new(
            Box::new(backend),
            self.page_size,
            None,
            self.cache_size,
            self.concurrency_mode,
        )
    }

    /// Open an existing or create a new database in the given `file`.
    ///
    /// The file must be empty or contain a valid database.
    #[cfg(all(not(redb_no_std), not(feature = "experimental-api-5")))]
    #[deprecated(
        since = "4.5.0",
        note = "use `create_with_backend(FileBackend::new(file)?)` instead"
    )]
    pub fn create_file(&self, file: File) -> Result<Database, DatabaseError> {
        Database::new(
            Box::new(FileBackend::from_file(file)),
            true,
            self.page_size,
            self.region_size,
            self.cache_size,
            self.concurrency_mode,
            RepairConfig {
                check_integrity: self.check_integrity_on_open,
                callback: &self.repair_callback,
            },
        )
    }

    /// Open an existing or create a new database with the given backend.
    pub fn create_with_backend(
        &self,
        backend: impl StorageBackend,
    ) -> Result<Database, DatabaseError> {
        Database::new(
            Box::new(backend),
            true,
            self.page_size,
            self.region_size,
            self.cache_size,
            self.concurrency_mode,
            RepairConfig {
                check_integrity: self.check_integrity_on_open,
                callback: &self.repair_callback,
            },
        )
    }
}

impl core::fmt::Debug for Database {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Database").finish()
    }
}

#[cfg(test)]
mod test {
    use crate::backends::FileBackend;
    use crate::db::BackendIoError;
    use crate::{
        CommitError, Database, DatabaseError, Durability, ReadableTable, StorageBackend,
        StorageError, TableDefinition, TransactionError,
    };
    use alloc::sync::Arc;
    use core::sync::atomic::{AtomicU64, Ordering};
    use std::fs::File;
    use std::io::{ErrorKind, Read, Seek, SeekFrom};

    #[derive(Debug)]
    struct FailingBackend {
        inner: FileBackend,
        countdown: Arc<AtomicU64>,
    }

    impl FailingBackend {
        fn new(backend: FileBackend, countdown: u64) -> Self {
            Self {
                inner: backend,
                countdown: Arc::new(AtomicU64::new(countdown)),
            }
        }

        fn check_countdown(&self) -> Result<(), std::io::Error> {
            if self.countdown.load(Ordering::SeqCst) == 0 {
                return Err(std::io::Error::from(ErrorKind::Other));
            }

            Ok(())
        }

        fn decrement_countdown(&self) -> Result<(), std::io::Error> {
            if self
                .countdown
                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
                    if x > 0 { Some(x - 1) } else { None }
                })
                .is_err()
            {
                return Err(std::io::Error::from(ErrorKind::Other));
            }

            Ok(())
        }
    }

    impl StorageBackend for FailingBackend {
        fn len(&self) -> Result<u64, BackendIoError> {
            self.inner.len()
        }

        fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), BackendIoError> {
            self.check_countdown()?;
            self.inner.read(offset, out)
        }

        fn set_len(&self, len: u64) -> Result<(), BackendIoError> {
            self.inner.set_len(len)
        }

        fn sync_data(&self) -> Result<(), BackendIoError> {
            self.check_countdown()?;
            self.inner.sync_data()
        }

        fn write(&self, offset: u64, data: &[u8]) -> Result<(), BackendIoError> {
            self.decrement_countdown()?;
            self.inner.write(offset, data)
        }
    }

    #[test]
    fn read_snapshot_survives_commits_before_construction() {
        use super::{ReadTransaction, TransactionGuard};

        const TABLE: TableDefinition<u64, u64> = TableDefinition::new("snapshot");
        for durability in [Durability::Immediate, Durability::None] {
            let tmpfile = crate::create_tempfile();
            let db = Database::create(tmpfile.path()).unwrap();
            let mut write = db.begin_write().unwrap();
            write.set_durability(durability).unwrap();
            write.open_table(TABLE).unwrap().insert(0, 0).unwrap();
            write.commit().unwrap();

            let (guard, root) =
                TransactionGuard::allocate_read(db.transaction_tracker.clone(), &db.mem).unwrap();
            assert_eq!(
                guard.id(),
                db.mem.get_last_committed_transaction_id().unwrap()
            );

            // Commits between registration and construction must not change this read's root.
            for value in 1..4 {
                let mut write = db.begin_write().unwrap();
                write.set_durability(durability).unwrap();
                write.open_table(TABLE).unwrap().insert(0, value).unwrap();
                write.commit().unwrap();
            }

            let read = ReadTransaction::new(db.mem.clone(), guard, root).unwrap();
            assert_eq!(
                read.open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                0
            );
        }
    }

    #[test]
    fn crash_regression4() {
        let tmpfile = crate::create_tempfile();
        let (file, path) = tmpfile.into_parts();

        // Fails the fourth write of the second commit below; the create makes three
        let backend = FailingBackend::new(FileBackend::from_file(file), 17);
        let db = Database::builder()
            .set_cache_size(12686)
            .set_page_size(8 * 1024)
            .set_region_size(32 * 4096)
            .create_with_backend(backend)
            .unwrap();

        let table_def: TableDefinition<u64, &[u8]> = TableDefinition::new("x");

        let tx = db.begin_write().unwrap();
        let _savepoint = tx.ephemeral_savepoint().unwrap();
        let _persistent_savepoint = tx.persistent_savepoint().unwrap();
        tx.commit().unwrap();
        let tx = db.begin_write().unwrap();
        {
            let mut table = tx.open_table(table_def).unwrap();
            let _ = table.insert_reserve(118821, 360).unwrap();
        }
        let result = tx.commit();
        assert!(result.is_err());

        drop(db);
        Database::builder()
            .set_cache_size(1024 * 1024)
            .set_page_size(8 * 1024)
            .set_region_size(32 * 4096)
            .create(&path)
            .unwrap();
    }

    #[test]
    fn transient_io_error() {
        let tmpfile = crate::create_tempfile();
        let (file, path) = tmpfile.into_parts();

        let backend = FailingBackend::new(FileBackend::from_file(file), u64::MAX);
        let countdown = backend.countdown.clone();
        let db = Database::builder()
            .set_cache_size(0)
            .create_with_backend(backend)
            .unwrap();

        let table_def: TableDefinition<u64, u64> = TableDefinition::new("x");

        // Create some garbage
        let tx = db.begin_write().unwrap();
        {
            let mut table = tx.open_table(table_def).unwrap();
            table.insert(0, 0).unwrap();
        }
        tx.commit().unwrap();
        let tx = db.begin_write().unwrap();
        {
            let mut table = tx.open_table(table_def).unwrap();
            table.insert(0, 1).unwrap();
        }
        tx.commit().unwrap();

        let tx = db.begin_write().unwrap();
        // Cause an error in the commit
        countdown.store(0, Ordering::SeqCst);
        let result = tx.commit().err().unwrap();
        assert!(matches!(result, CommitError::Storage(StorageError::Io(_))));
        let result = db.begin_write().err().unwrap();
        assert!(matches!(
            result,
            TransactionError::Storage(StorageError::PreviousIo)
        ));
        // Simulate a transient error
        countdown.store(u64::MAX, Ordering::SeqCst);
        drop(db);

        // Check that recovery flag is set, even though the error has "cleared"
        let mut file = File::open(&path).unwrap();
        file.seek(SeekFrom::Start(9)).unwrap();
        let mut god_byte = vec![0u8];
        assert_eq!(file.read(&mut god_byte).unwrap(), 1);
        assert_ne!(god_byte[0] & 2, 0);
    }

    #[test]
    fn small_pages() {
        let tmpfile = crate::create_tempfile();

        let db = Database::builder()
            .set_page_size(512)
            .create(tmpfile.path())
            .unwrap();

        let table_definition: TableDefinition<u64, &[u8]> = TableDefinition::new("x");
        let txn = db.begin_write().unwrap();
        {
            txn.open_table(table_definition).unwrap();
        }
        txn.commit().unwrap();
    }

    #[test]
    fn small_pages2() {
        let tmpfile = crate::create_tempfile();

        let db = Database::builder()
            .set_page_size(512)
            .create(tmpfile.path())
            .unwrap();

        let table_def: TableDefinition<u64, &[u8]> = TableDefinition::new("x");

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let savepoint0 = tx.ephemeral_savepoint().unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let savepoint1 = tx.ephemeral_savepoint().unwrap();
        tx.restore_savepoint(&savepoint0).unwrap();
        tx.set_durability(Durability::None).unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            t.insert_reserve(&660503, 489).unwrap().as_mut().fill(0xFF);
            assert!(t.remove(&291295).unwrap().is_none());
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        tx.restore_savepoint(&savepoint0).unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let savepoint2 = tx.ephemeral_savepoint().unwrap();
        drop(savepoint0);
        tx.restore_savepoint(&savepoint2).unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            assert!(t.get(&2059).unwrap().is_none());
            assert!(t.remove(&145227).unwrap().is_none());
            assert!(t.remove(&145227).unwrap().is_none());
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let savepoint3 = tx.ephemeral_savepoint().unwrap();
        drop(savepoint1);
        tx.restore_savepoint(&savepoint3).unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let savepoint4 = tx.ephemeral_savepoint().unwrap();
        drop(savepoint2);
        tx.restore_savepoint(&savepoint3).unwrap();
        tx.set_durability(Durability::None).unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            assert!(t.remove(&207936).unwrap().is_none());
        }
        tx.abort().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        let _savepoint5 = tx.ephemeral_savepoint().unwrap();
        drop(savepoint3);
        // savepoint4 was invalidated by the restore_savepoint(savepoint3) call
        // above, but that transaction was aborted, so the invalidation is
        // reversed and savepoint4 is valid again. Restoring it here invalidates
        // savepoint5 (which is newer), so the next transaction restores
        // savepoint4 again rather than savepoint5.
        tx.restore_savepoint(&savepoint4).unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();

        let mut tx = db.begin_write().unwrap();
        tx.set_two_phase_commit(true);
        tx.restore_savepoint(&savepoint4).unwrap();
        tx.set_durability(Durability::None).unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();
    }

    #[test]
    fn small_pages3() {
        let tmpfile = crate::create_tempfile();

        let db = Database::builder()
            .set_page_size(1024)
            .create(tmpfile.path())
            .unwrap();

        let table_def: TableDefinition<u64, &[u8]> = TableDefinition::new("x");

        let mut tx = db.begin_write().unwrap();
        let _savepoint0 = tx.ephemeral_savepoint().unwrap();
        tx.set_durability(Durability::None).unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            let value = vec![0; 306];
            t.insert(&539717, value.as_slice()).unwrap();
        }
        tx.abort().unwrap();

        let mut tx = db.begin_write().unwrap();
        let savepoint1 = tx.ephemeral_savepoint().unwrap();
        tx.restore_savepoint(&savepoint1).unwrap();
        tx.set_durability(Durability::None).unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            let value = vec![0; 2008];
            t.insert(&784384, value.as_slice()).unwrap();
        }
        tx.abort().unwrap();
    }

    #[test]
    fn small_pages4() {
        let tmpfile = crate::create_tempfile();

        let db = Database::builder()
            .set_cache_size(1024 * 1024)
            .set_page_size(1024)
            .create(tmpfile.path())
            .unwrap();

        let table_def: TableDefinition<u64, &[u8]> = TableDefinition::new("x");

        let tx = db.begin_write().unwrap();
        {
            tx.open_table(table_def).unwrap();
        }
        tx.commit().unwrap();

        let tx = db.begin_write().unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            assert!(t.get(&131072).unwrap().is_none());
            let value = vec![0xFF; 1130];
            t.insert(&42394, value.as_slice()).unwrap();
            t.insert_reserve(&744037, 3645).unwrap().as_mut().fill(0xFF);
            assert!(t.get(&0).unwrap().is_none());
        }
        tx.abort().unwrap();

        let tx = db.begin_write().unwrap();
        {
            let mut t = tx.open_table(table_def).unwrap();
            t.insert_reserve(&118749, 734).unwrap().as_mut().fill(0xFF);
        }
        tx.abort().unwrap();
    }

    #[test]
    fn abort_shrinks_multiple_regions() {
        use crate::ReadableDatabase;

        const TABLE: TableDefinition<u64, &[u8]> = TableDefinition::new("x");
        let value = vec![0xAB; 2000];
        for quick_repair in [false, true] {
            let tmpfile = crate::create_tempfile();
            let mut db = Database::builder()
                .set_region_size(256 * 1024)
                .create(tmpfile.path())
                .unwrap();
            let mut txn = db.begin_write().unwrap();
            txn.set_quick_repair(quick_repair);
            txn.open_table(TABLE)
                .unwrap()
                .insert(0, b"committed".as_slice())
                .unwrap();
            txn.commit().unwrap();

            let original_len = tmpfile.as_file().metadata().unwrap().len();
            for _ in 0..2 {
                let txn = db.begin_write().unwrap();
                {
                    let mut table = txn.open_table(TABLE).unwrap();
                    for key in 0..1800 {
                        table.insert(key, value.as_slice()).unwrap();
                    }
                }
                assert!(tmpfile.as_file().metadata().unwrap().len() > original_len + 1024 * 1024);
                txn.abort().unwrap();
                assert_eq!(tmpfile.as_file().metadata().unwrap().len(), original_len);
            }
            assert!(db.check_integrity().unwrap());
            drop(db);
            let mut db = Database::open(tmpfile.path()).unwrap();
            assert!(db.check_integrity().unwrap());
            let txn = db.begin_read().unwrap();
            let table = txn.open_table(TABLE).unwrap();
            assert_eq!(table.get(0).unwrap().unwrap().value(), b"committed");
            assert!(table.get(1).unwrap().is_none());
        }
    }

    #[test]
    fn dynamic_shrink() {
        let tmpfile = crate::create_tempfile();
        let table_definition: TableDefinition<u64, &[u8]> = TableDefinition::new("x");
        let big_value = vec![0u8; 1024];

        let db = Database::builder()
            .set_region_size(1024 * 1024)
            .create(tmpfile.path())
            .unwrap();

        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            for i in 0..2048 {
                table.insert(&i, big_value.as_slice()).unwrap();
            }
        }
        txn.commit().unwrap();

        let file_size = tmpfile.as_file().metadata().unwrap().len();

        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            for i in 0..2048 {
                table.remove(&i).unwrap();
            }
        }
        txn.commit().unwrap();

        // Perform a couple more commits to be sure the database has a chance to compact
        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            table.insert(0, [].as_slice()).unwrap();
        }
        txn.commit().unwrap();
        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            table.remove(0).unwrap();
        }
        txn.commit().unwrap();
        let txn = db.begin_write().unwrap();
        txn.commit().unwrap();

        let final_file_size = tmpfile.as_file().metadata().unwrap().len();
        assert!(final_file_size < file_size);
    }

    /// Compaction packs what is left into the first region, and drops every region after it
    #[test]
    fn compact_drops_every_free_trailing_region() {
        let tmpfile = crate::create_tempfile();
        let table_definition: TableDefinition<u64, &[u8]> = TableDefinition::new("x");
        let region_size = 256 * 1024;
        let mut db = Database::builder()
            .set_region_size(region_size)
            .create(tmpfile.path())
            .unwrap();

        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            for i in 0..4096 {
                table.insert(i, [0u8; 1024].as_slice()).unwrap();
            }
        }
        txn.commit().unwrap();
        let txn = db.begin_write().unwrap();
        {
            let mut table = txn.open_table(table_definition).unwrap();
            for i in 0..4095 {
                table.remove(i).unwrap();
            }
        }
        txn.commit().unwrap();

        assert!(db.compact().unwrap());
        let file_size = tmpfile.as_file().metadata().unwrap().len();
        assert!(file_size < 2 * region_size, "{file_size}");
    }

    #[test]
    fn create_new_db_in_empty_file() {
        let tmpfile = crate::create_tempfile();

        let _db = Database::builder()
            .create_with_backend(FileBackend::from_file(tmpfile.into_file()))
            .unwrap();
    }

    #[test]
    fn open_missing_file() {
        let tmpfile = crate::create_tempfile();

        let err = Database::builder()
            .open(tmpfile.path().with_extension("missing"))
            .unwrap_err();

        match err {
            DatabaseError::Storage(StorageError::Io(err)) if err.kind() == ErrorKind::NotFound => {}
            err => panic!("Unexpected error for empty file: {err}"),
        }
    }

    #[test]
    fn open_empty_file() {
        let tmpfile = crate::create_tempfile();

        let err = Database::builder().open(tmpfile.path()).unwrap_err();

        match err {
            DatabaseError::Storage(StorageError::Io(err))
                if err.kind() == ErrorKind::InvalidData => {}
            err => panic!("Unexpected error for empty file: {err}"),
        }
    }
}

/// Probed directly, since the public API reports every lock conflict the same way and so
/// cannot say which byte caused one.
#[cfg(all(test, any(target_os = "linux", target_vendor = "apple", windows)))]
mod writer_byte_test {
    use super::{ConcurrencyMode, Database, WRITER_BYTE, byte_range};
    use crate::TableDefinition;
    use crate::tree_store::file_backend::range_lock::RangeLock;
    use crate::tree_store::page_store::page_manager::HEADER_LOCK;
    use std::fs::{File, OpenOptions};
    use std::path::Path;

    const TABLE: TableDefinition<u64, u64> = TableDefinition::new("x");

    fn create(path: &Path, mode: ConcurrencyMode) -> Database {
        let mut builder = Database::builder();
        builder.set_concurrency_mode(mode);
        builder.create(path).unwrap()
    }

    /// A separate description, so its locks conflict with the database's exactly as another
    /// process's would
    fn probe(path: &Path) -> File {
        OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap()
    }

    fn commit_one(db: &Database) {
        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(0, 0).unwrap();
        }
        write.commit().unwrap();
    }

    /// Whether the file is unclean, as a shared reader sees it: it is refused an unclean file
    /// no live writer holds
    fn left_unclean(path: &Path) -> bool {
        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        match builder.open_read_only(path) {
            Err(super::DatabaseError::RepairAborted) => true,
            Err(err) => panic!("{err}"),
            Ok(_) => false,
        }
    }

    /// The shutdown header is written under the writer byte, or not at all: written without it,
    /// it would overwrite a commit another process makes meanwhile
    #[test]
    fn the_shutdown_header_is_written_under_the_writer_byte_or_not_at_all() {
        // The memory's close alone, without the database's, which would write the header itself
        fn close(path: &Path, under_the_byte: bool) {
            let db = create(path, ConcurrencyMode::MultiWriter);
            commit_one(&db);
            let mem = db.mem.clone();
            std::mem::forget(db);
            if under_the_byte {
                let writer_lock = mem.lock_writer().unwrap();
                mem.close(Some(&writer_lock)).unwrap();
            } else {
                mem.close(None).unwrap();
            }
        }

        let tmpfile = crate::create_tempfile();
        close(tmpfile.path(), false);
        assert!(
            left_unclean(tmpfile.path()),
            "a header was written without the byte"
        );

        let tmpfile = crate::create_tempfile();
        close(tmpfile.path(), true);
        assert!(
            !left_unclean(tmpfile.path()),
            "no header was written under the byte"
        );
    }

    /// The close takes the byte once, for its commit and for the header after it
    #[test]
    fn a_close_leaves_a_clean_file() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        commit_one(&db);
        drop(db);
        assert!(
            !left_unclean(tmpfile.path()),
            "the close left the file unclean"
        );
    }

    /// A multi-writer repair ends with a commit recording the allocator state it rebuilt, for
    /// the next open to load
    #[test]
    fn a_multi_writer_repair_records_the_allocator_state() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        // A commit that records no allocator state, closed without the shutdown header that
        // would record one, leaves the next open a repair
        let mut write = db.begin_write().unwrap();
        write.skip_allocator_state_record();
        write.open_table(TABLE).unwrap().insert(0, 0).unwrap();
        write.commit().unwrap();
        let mem = db.mem.clone();
        std::mem::forget(db);
        assert!(Database::get_allocator_state_table(&mem).unwrap().is_none());
        mem.close(None).unwrap();

        let repaired = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        assert!(
            Database::get_allocator_state_table(&repaired.mem)
                .unwrap()
                .is_some()
        );
    }

    /// A database nothing has been committed to needs no repair in any process: each open loads
    /// the empty allocator state
    #[test]
    fn a_peer_opens_a_never_written_database_without_repair() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let mut builder = Database::builder();
        builder
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .set_repair_callback(|session| session.abort());
        let peer = builder.open(tmpfile.path()).unwrap();
        commit_one(&peer);
        commit_one(&db);
    }

    /// Rebuilding keeps live readers and the peer's persistent savepoints usable, even if the
    /// first transaction using that allocator aborts.
    #[test]
    fn a_sync_rebuilds_a_missing_allocator_state() {
        use crate::{ReadableDatabase, ReadableTable};

        let tmpfile = crate::create_tempfile();
        let mut builder = Database::builder();
        builder
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .set_cache_size(0);
        let db = builder.create(tmpfile.path()).unwrap();
        commit_one(&db);
        let old_read = db.begin_read().unwrap();
        let peer = builder.open(tmpfile.path()).unwrap();
        let mut write = peer.begin_write().unwrap();
        let savepoint_id = write.persistent_savepoint().unwrap();
        write.skip_allocator_state_record();
        write.open_table(TABLE).unwrap().insert(0, 1).unwrap();
        write.commit().unwrap();

        let mut write = db.begin_write().unwrap();
        {
            let table = write.open_table(TABLE).unwrap();
            assert_eq!(table.get(0).unwrap().unwrap().value(), 1);
        }
        let savepoint = write.get_persistent_savepoint(savepoint_id).unwrap();
        write.restore_savepoint(&savepoint).unwrap();
        write.abort().unwrap();

        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            assert_eq!(table.get(0).unwrap().unwrap().value(), 1);
            table.insert(0, 2).unwrap();
        }
        write.commit().unwrap();
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
        let old_table = old_read.open_table(TABLE).unwrap();
        assert_eq!(old_table.get(0).unwrap().unwrap().value(), 0);

        let mut write = peer.begin_write().unwrap();
        let savepoint = write.get_persistent_savepoint(savepoint_id).unwrap();
        write.restore_savepoint(&savepoint).unwrap();
        write.commit().unwrap();
        let read = peer.begin_read().unwrap();
        let table = read.open_table(TABLE).unwrap();
        assert_eq!(table.get(0).unwrap().unwrap().value(), 0);
    }

    /// Exit after compaction's initial drain, before its final allocator snapshot. The surviving
    /// writer must resume without reopening, including while a peer reads the published commit.
    #[test]
    fn a_writer_recovers_after_interrupted_compaction() {
        use crate::tree_store::ShrinkPolicy;
        use crate::{ReadableDatabase, ReadableTable};
        use std::process::Command;

        const CHILD_PATH: &str = "REDB_TEST_INTERRUPTED_COMPACTION_PATH";
        let mut builder = Database::builder();
        builder
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .set_cache_size(0);
        if let Some(path) = std::env::var_os(CHILD_PATH) {
            let db = builder.open(path).unwrap();
            let write = db.begin_write().unwrap();
            write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
            write.commit().unwrap();
            let writer = db.mem.lock_writer().unwrap();
            let header = db.mem.lock_header_exclusive().unwrap();
            db.drain_pending_free_pages(ShrinkPolicy::Maximum, Some(&writer), Some(&header))
                .unwrap();
            assert!(
                Database::get_allocator_state_table(&db.mem)
                    .unwrap()
                    .is_none()
            );
            std::process::exit(42);
        }

        let tmpfile = crate::create_tempfile();
        let db = builder.create(tmpfile.path()).unwrap();
        commit_one(&db);
        let child = Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "db::writer_byte_test::a_writer_recovers_after_interrupted_compaction",
                "--nocapture",
            ])
            .env(CHILD_PATH, tmpfile.path())
            .output()
            .unwrap();
        assert_eq!(child.status.code(), Some(42), "{child:?}");

        let reader = builder.open_read_only(tmpfile.path()).unwrap();
        let old_read = reader.begin_read().unwrap();
        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            assert_eq!(table.get(1).unwrap().unwrap().value(), 1);
            table.insert(2, 2).unwrap();
        }
        write.commit().unwrap();
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
        let old_table = old_read.open_table(TABLE).unwrap();
        assert_eq!(old_table.get(1).unwrap().unwrap().value(), 1);
        assert!(old_table.get(2).unwrap().is_none());

        builder
            .set_repair_callback(|_| panic!("the recovered writer did not record its allocator"));
        let peer = builder.open(tmpfile.path()).unwrap();
        let read = peer.begin_read().unwrap();
        let table = read.open_table(TABLE).unwrap();
        for key in 0..3u64 {
            assert_eq!(table.get(key).unwrap().unwrap().value(), key);
        }
    }

    /// A missing snapshot permits rebuilding the allocator, but never trusting damaged roots.
    #[test]
    fn a_sync_refuses_corruption_without_an_allocator_snapshot() {
        use crate::tree_store::ShrinkPolicy;
        use crate::{StorageError, TransactionError};

        for corrupt_checksum in [true, false] {
            let tmpfile = crate::create_tempfile();
            let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
            let peer = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
            commit_one(&peer);
            let writer = peer.mem.lock_writer().unwrap();
            let mut root = peer.mem.get_data_root().unwrap();
            if corrupt_checksum {
                root.checksum ^= 1;
            } else {
                root.length += 1;
            }
            peer.mem
                .commit(
                    Some(root),
                    peer.mem.get_system_root(),
                    peer.mem.get_last_committed_transaction_id().unwrap().next(),
                    true,
                    ShrinkPolicy::Never,
                    None,
                )
                .unwrap();
            peer.mem.invalidate_allocator_state();
            drop(writer);

            assert!(matches!(
                db.begin_write(),
                Err(TransactionError::Storage(StorageError::Corrupted(_)))
            ));
            assert!(!db.mem.allocator_state_loaded());
            assert!(matches!(
                db.begin_write(),
                Err(TransactionError::Storage(StorageError::Corrupted(_)))
            ));
        }
    }

    /// A transaction dropped while a panic unwinds leaks its pages, which latches a repair.
    /// Syncing to a peer's commit replaces the allocator state with the file's, which does not
    /// hold those pages, so the next commit records the state again.
    #[test]
    fn syncing_to_a_peers_commit_releases_the_repair_a_panic_latched() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        let peer = builder.open(tmpfile.path()).unwrap();
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let write = db.begin_write().unwrap();
            write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
            panic!("unwinding through the transaction");
        }));
        assert!(unwound.is_err());
        assert!(db.mem.needs_repair());

        commit_one(&peer);
        commit_one(&db);
        assert!(!db.mem.needs_repair());
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
    }

    /// The first transaction after a panic releases the repair latch, so its commit records the
    /// allocator state without making a peer rebuild it.
    #[test]
    fn a_transaction_releases_the_repair_a_panic_latched_without_a_peers_commit() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        let peer = builder.open(tmpfile.path()).unwrap();
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let write = db.begin_write().unwrap();
            write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
            panic!("unwinding through the transaction");
        }));
        assert!(unwound.is_err());
        assert!(db.mem.needs_repair());

        commit_one(&db);
        assert!(!db.mem.needs_repair());
        peer.begin_write()
            .expect("the peer syncs to a commit that recorded the allocator state")
            .abort()
            .unwrap();
    }

    /// An open reads the file's length under the header lock, so a create holding that lock is
    /// waited for and its result read, rather than the file being sampled part way through it.
    /// Before, the length was sampled outside any lock: an empty file was called empty and a
    /// resized one not a redb database, however far the create had got by the time it was read
    #[test]
    fn an_open_waits_behind_a_creator_instead_of_calling_the_file_empty() {
        use std::io::{Read, Seek, SeekFrom, Write};
        use std::sync::mpsc;
        use std::thread;
        use std::time::Duration;

        // What the create will have produced by the time it releases the lock
        let initialized = crate::create_tempfile();
        drop(create(initialized.path(), ConcurrencyMode::MultiWriter));
        let mut bytes = Vec::new();
        File::open(initialized.path())
            .unwrap()
            .read_to_end(&mut bytes)
            .unwrap();

        let tmpfile = crate::create_tempfile();
        let probe = probe(tmpfile.path());
        // Stands in for a create holding the header lock across its initialization
        assert!(probe.try_lock_range(HEADER_LOCK).unwrap());

        let path = tmpfile.path().to_path_buf();
        let (opened, opens) = mpsc::channel();
        let opening = thread::spawn(move || {
            let mut builder = Database::builder();
            builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
            let result = builder.open(&path);
            opened.send(()).unwrap();
            result
        });

        assert!(
            opens.recv_timeout(Duration::from_millis(500)).is_err(),
            "the open read the file while the creator held the header lock"
        );
        // The create finishes: from here the file is a database, as it would be at the release.
        // Written through the handle that holds the lock, as a create writes under its own: on
        // Windows a byte-range lock is mandatory, and excludes writes from every other handle
        (&probe).seek(SeekFrom::Start(0)).unwrap();
        (&probe).write_all(&bytes).unwrap();
        probe.sync_all().unwrap();
        probe.unlock_range(HEADER_LOCK).unwrap();

        opens
            .recv_timeout(Duration::from_secs(10))
            .expect("the open never took the header lock");
        // A length sampled before the lock would still be the zero it read at the start
        opening
            .join()
            .unwrap()
            .expect("the open used a length it read before the creator finished");
    }

    /// A multi-writer open runs under the writer byte, so that two processes do not repair the
    /// same file at once and commit over each other
    #[test]
    fn a_multi_writer_open_waits_for_the_writer_byte() {
        use std::sync::mpsc;
        use std::thread;
        use std::time::Duration;

        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        // A commit recording nothing leaves the file for the next open to repair. The handle
        // stays open, since its close would record
        let mut write = db.begin_write().unwrap();
        write.skip_allocator_state_record();
        write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        write.commit().unwrap();

        let probe = probe(tmpfile.path());
        assert!(probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap());
        let path = tmpfile.path().to_path_buf();
        let (repairing, repairs) = mpsc::channel();
        let opening = thread::spawn(move || {
            let mut builder = Database::builder();
            builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
            builder.set_repair_callback(move |_| {
                let _ = repairing.send(());
            });
            builder.open(&path).unwrap()
        });

        assert!(
            repairs.recv_timeout(Duration::from_millis(500)).is_err(),
            "the open repaired while the writer byte was held"
        );
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
        repairs
            .recv_timeout(Duration::from_secs(10))
            .expect("the repair runs once the byte is free");
        opening.join().unwrap();
    }

    /// A peer can commit while an open waits for the writer byte. The open reads the file only
    /// once it holds the byte, so it sees that commit and repairs nothing it recorded.
    #[test]
    fn a_multi_writer_open_reads_the_file_a_peer_committed_while_it_waited() {
        use std::sync::mpsc;
        use std::thread;
        use std::time::Duration;

        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let mut write = db.begin_write().unwrap();
        write.skip_allocator_state_record();
        write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        write.commit().unwrap();
        // Holds the byte across the open, and records the allocator state when it commits
        let held = db.begin_write().unwrap();
        held.open_table(TABLE).unwrap().insert(2, 2).unwrap();

        let path = tmpfile.path().to_path_buf();
        let (repairing, repairs) = mpsc::channel();
        let (opened, opens) = mpsc::channel();
        let opening = thread::spawn(move || {
            let mut builder = Database::builder();
            builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
            builder.set_repair_callback(move |_| {
                let _ = repairing.send(());
            });
            let db = builder.open(&path).unwrap();
            opened.send(()).unwrap();
            db
        });

        assert!(
            opens.recv_timeout(Duration::from_millis(500)).is_err(),
            "the open did not wait for the byte"
        );
        held.commit().unwrap();
        opens
            .recv_timeout(Duration::from_secs(10))
            .expect("the open takes the byte the commit released");
        let peer = opening.join().unwrap();

        assert!(
            repairs.try_recv().is_err(),
            "the open repaired a file the commit had recorded"
        );
        // A repair from the header read before that commit would have committed over it
        let read = super::ReadableDatabase::begin_read(&peer).unwrap();
        let table = read.open_table(TABLE).unwrap();
        assert_eq!(
            crate::ReadableTable::get(&table, 2)
                .unwrap()
                .unwrap()
                .value(),
            2
        );
    }
    /// A multi-writer compaction ends with a commit recording the allocator state, for the next
    /// writer, in any process, to load rather than rebuild
    #[test]
    fn a_multi_writer_compaction_records_the_allocator_state() {
        let tmpfile = crate::create_tempfile();
        let mut db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        commit_one(&db);

        db.compact().unwrap();
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
    }

    /// Held for the transaction and no longer, which is what lets the next writer in
    #[test]
    fn a_multi_writer_transaction_holds_the_byte_and_gives_it_back() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        let write = db.begin_write().unwrap();
        assert!(
            !probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "the byte was free while a write transaction was open"
        );
        write.commit().unwrap();

        assert!(
            probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "the byte was still held after the transaction ended"
        );
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
    }

    /// This mode settles who writes at open instead, so the byte is held from then until the
    /// database closes. A transaction taking it again would convert that hold and drop what
    /// remained on release, so it holds the open's instead.
    #[test]
    fn a_single_writer_open_holds_the_byte_for_its_lifetime() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::SingleWriter);
        let probe = probe(tmpfile.path());

        assert!(
            !probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "the open did not take the writer byte"
        );
        commit_one(&db);
        assert!(
            !probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "a write transaction punctured the open's hold on the writer byte"
        );

        drop(db);
        assert!(
            probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "the byte was still held after the database closed"
        );
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
    }

    /// A transaction that outlives the database keeps the lock, and the deferred close writes
    /// the allocator state under it
    #[test]
    fn a_transaction_outliving_the_database_keeps_the_writer_lock() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::SingleWriter);
        let probe = probe(tmpfile.path());

        let write = db.begin_write().unwrap();
        drop(db);
        assert!(
            !probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "dropping the database released the byte from under a live transaction"
        );

        write.commit().unwrap();
        assert!(
            probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap(),
            "the byte was still held after the deferred close"
        );
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
    }
}

/// The consistent byte, probed directly: a byte-range lock is invisible through the public API.
#[cfg(all(test, any(target_os = "linux", target_vendor = "apple", windows)))]
mod consistent_byte_test {
    use super::{CONSISTENT_BYTE, ConcurrencyMode, Database, byte_range};
    use crate::backends::FileBackend;
    use crate::db::BackendIoError;
    use crate::tree_store::file_backend::range_lock::RangeLock;
    use crate::{BackendError, StorageBackend, TableDefinition};
    use std::fs::{File, OpenOptions};
    use std::ops::Bound;
    use std::path::{Path, PathBuf};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};

    const TABLE: TableDefinition<u64, u64> = TableDefinition::new("x");

    fn builder(mode: ConcurrencyMode) -> crate::Builder {
        let mut builder = Database::builder();
        builder.set_concurrency_mode(mode);
        builder
    }

    /// A separate description, so its locks conflict with the database's exactly as another
    /// process's would
    fn probe(path: &Path) -> File {
        OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap()
    }

    /// True when some writer asserts the database is consistent
    fn held(probe: &File) -> bool {
        let taken = probe.try_lock_range(byte_range(CONSISTENT_BYTE)).unwrap();
        if taken {
            probe.unlock_range(byte_range(CONSISTENT_BYTE)).unwrap();
        }
        !taken
    }

    /// Power loss: once armed, every write silently does nothing, so the close writes neither
    /// the allocator record nor the clean-shutdown header
    #[derive(Debug)]
    struct CrashBackend {
        inner: FileBackend,
        dead: Arc<AtomicBool>,
    }

    impl StorageBackend for CrashBackend {
        fn len(&self) -> Result<u64, BackendIoError> {
            self.inner.len()
        }
        fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), BackendIoError> {
            self.inner.read(offset, out)
        }
        fn set_len(&self, len: u64) -> Result<(), BackendIoError> {
            if self.dead.load(Ordering::SeqCst) {
                return Ok(());
            }
            self.inner.set_len(len)
        }
        fn sync_data(&self) -> Result<(), BackendIoError> {
            if self.dead.load(Ordering::SeqCst) {
                return Ok(());
            }
            self.inner.sync_data()
        }
        fn write(&self, offset: u64, data: &[u8]) -> Result<(), BackendIoError> {
            if self.dead.load(Ordering::SeqCst) {
                return Ok(());
            }
            self.inner.write(offset, data)
        }
    }

    /// Leaves the file as a crashed writer would: a committed transaction, no allocator record
    /// and the recovery flag still set, so the next open has to repair it. Built through a
    /// caller-supplied backend, which takes no locks, so nothing of this handle outlives it.
    fn dirty(path: &Path) {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap();
        let dead = Arc::new(AtomicBool::new(false));
        let db = Database::builder()
            .create_with_backend(CrashBackend {
                inner: FileBackend::from_file(file),
                dead: Arc::clone(&dead),
            })
            .unwrap();
        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(0, 0).unwrap();
        }
        write.commit().unwrap();
        // Nothing this handle does from here on reaches the file, its close included
        dead.store(true, Ordering::SeqCst);
        drop(db);
    }

    #[test]
    fn a_shared_writable_open_asserts_consistency_until_it_closes() {
        for mode in [ConcurrencyMode::SingleWriter, ConcurrencyMode::MultiWriter] {
            let tmpfile = crate::create_tempfile();
            let db = builder(mode).create(tmpfile.path()).unwrap();
            let probe = probe(tmpfile.path());
            assert!(held(&probe), "{mode:?} open did not take the byte");

            drop(db);
            assert!(!held(&probe), "{mode:?} close did not release the byte");
        }
    }

    /// The byte's whole purpose. `SHARED_WRITER_BYTE` is taken before recovery runs, so during a
    /// repair it says a writer is here while the file is still the one the last writer left. This
    /// byte is taken after, so it says nothing until the file is consistent.
    #[test]
    fn a_repairing_open_asserts_consistency_only_once_the_repair_is_done() {
        let tmpfile = crate::create_tempfile();
        dirty(tmpfile.path());

        let probe = Arc::new(Mutex::new(probe(tmpfile.path())));
        let during: Arc<Mutex<Option<bool>>> = Arc::new(Mutex::new(None));

        let db = {
            let probe = probe.clone();
            let during = during.clone();
            let mut builder = builder(ConcurrencyMode::MultiWriter);
            builder.set_repair_callback(move |_| {
                let mut during = during.lock().unwrap();
                if during.is_none() {
                    *during = Some(held(&probe.lock().unwrap()));
                }
            });
            builder.open(tmpfile.path()).unwrap()
        };

        assert_eq!(
            during.lock().unwrap().take(),
            Some(false),
            "the byte was held while the open was still repairing"
        );
        assert!(held(&probe.lock().unwrap()), "the open never took the byte");
        drop(db);
    }

    /// The file, with a shared reader opened as the consistent byte is about to be taken, which
    /// records what the reader was told
    #[derive(Debug)]
    struct ReaderAtConsistentByte {
        inner: FileBackend,
        path: PathBuf,
        reader_saw: Arc<Mutex<Option<String>>>,
    }

    impl StorageBackend for ReaderAtConsistentByte {
        fn len(&self) -> Result<u64, BackendIoError> {
            self.inner.len()
        }
        fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), BackendIoError> {
            self.inner.read(offset, out)
        }
        fn set_len(&self, len: u64) -> Result<(), BackendIoError> {
            self.inner.set_len(len)
        }
        fn sync_data(&self) -> Result<(), BackendIoError> {
            self.inner.sync_data()
        }
        fn write(&self, offset: u64, data: &[u8]) -> Result<(), BackendIoError> {
            self.inner.write(offset, data)
        }
        fn close(&self) -> Result<(), BackendIoError> {
            self.inner.close()
        }
        fn try_lock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<bool, BackendError> {
            self.inner.try_lock_range(start, end)
        }
        fn try_lock_shared_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<bool, BackendError> {
            self.inner.try_lock_shared_range(start, end)
        }
        fn lock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<(), BackendError> {
            self.inner.lock_range(start, end)
        }
        fn lock_shared_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<(), BackendError> {
            if (start, end) == byte_range(CONSISTENT_BYTE) {
                let saw = match builder(ConcurrencyMode::MultiWriter).open_read_only(&self.path) {
                    Ok(_) => "opened".to_string(),
                    Err(err) => format!("{err:?}"),
                };
                *self.reader_saw.lock().unwrap() = Some(saw);
            }
            self.inner.lock_shared_range(start, end)
        }
        fn unlock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<(), BackendError> {
            self.inner.unlock_range(start, end)
        }
        fn query_lock_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<bool, BackendError> {
            self.inner.query_lock_range(start, end)
        }
    }

    /// A reader reads the flag and queries the byte under one hold, so the open must take the
    /// byte before it publishes the flag: taken after, a reader between the two found the flag
    /// without the byte, and refused a consistent file as one left by a crash
    #[test]
    fn an_open_takes_the_byte_before_it_publishes_the_flag() {
        let tmpfile = crate::create_tempfile();
        drop(
            builder(ConcurrencyMode::MultiWriter)
                .create(tmpfile.path())
                .unwrap(),
        );

        let reader_saw = Arc::new(Mutex::new(None));
        let db = builder(ConcurrencyMode::MultiWriter)
            .create_with_backend(ReaderAtConsistentByte {
                inner: FileBackend::from_file(probe(tmpfile.path())),
                path: tmpfile.path().to_path_buf(),
                reader_saw: reader_saw.clone(),
            })
            .unwrap();
        assert_eq!(reader_saw.lock().unwrap().as_deref(), Some("opened"));
        drop(db);
    }
}

/// The mark a commit's header write carries until the writer has flushed it, probed through a
/// backend that acts at the flush, as another process would
#[cfg(all(test, any(target_os = "linux", target_vendor = "apple", windows)))]
mod unflushed_primary_test {
    use super::{ConcurrencyMode, Database, ReadOnlyDatabase, ReadableDatabase};
    #[cfg(feature = "experimental-api-5")]
    use crate::ReadableTable;
    use crate::backends::FileBackend;
    use crate::db::BackendIoError;
    use crate::tree_store::page_store::header::is_primary_unflushed;
    use crate::{BackendError, StorageBackend, TableDefinition, TableError};
    use std::fmt::{self, Debug, Formatter};
    use std::fs::OpenOptions;
    use std::io;
    use std::ops::Bound;
    use std::path::Path;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};

    const TABLE: TableDefinition<u64, u64> = TableDefinition::new("x");
    const SHARED_MODES: [ConcurrencyMode; 2] =
        [ConcurrencyMode::SingleWriter, ConcurrencyMode::MultiWriter];

    fn builder(mode: ConcurrencyMode) -> crate::Builder {
        let mut builder = Database::builder();
        builder.set_concurrency_mode(mode);
        builder
    }

    /// A separate description, so its locks conflict with the database's exactly as another
    /// process's would
    fn file(path: &Path) -> FileBackend {
        FileBackend::from_file(
            OpenOptions::new()
                .read(true)
                .write(true)
                .open(path)
                .unwrap(),
        )
    }

    /// Whether the file marks its primary unflushed
    fn marked(file: &FileBackend) -> bool {
        let mut head = [0; 16];
        file.read(0, &mut head).unwrap();
        is_primary_unflushed(&head)
    }

    fn commit(db: &Database, value: u64) {
        let write = db.begin_write().unwrap();
        write.open_table(TABLE).unwrap().insert(0, value).unwrap();
        write.commit().unwrap();
    }

    /// The value of the one key, or `None` before the commit that created the table
    fn read(db: &impl ReadableDatabase) -> Option<u64> {
        let read = db.begin_read().unwrap();
        match read.open_table(TABLE) {
            Ok(table) => Some(table.get(0).unwrap().unwrap().value()),
            Err(TableError::TableDoesNotExist(_)) => None,
            Err(err) => panic!("{err}"),
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Event {
        /// A write of the header, and whether it marks the primary unflushed
        Header(bool),
        Flush,
    }

    type AtFlush = Box<dyn Fn(&FileBackend) -> io::Result<()> + Send + Sync>;

    /// The file, logging every write of the header and every flush, and running `at_flush`
    /// ahead of each flush
    struct Observed {
        inner: FileBackend,
        events: Arc<Mutex<Vec<Event>>>,
        at_flush: AtFlush,
    }

    impl Observed {
        fn new(
            path: &Path,
            events: Arc<Mutex<Vec<Event>>>,
            at_flush: impl Fn(&FileBackend) -> io::Result<()> + Send + Sync + 'static,
        ) -> Self {
            Self {
                inner: file(path),
                events,
                at_flush: Box::new(at_flush),
            }
        }
    }

    impl Debug for Observed {
        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
            self.inner.fmt(f)
        }
    }

    impl StorageBackend for Observed {
        fn len(&self) -> Result<u64, BackendIoError> {
            self.inner.len()
        }
        fn read(&self, offset: u64, out: &mut [u8]) -> Result<(), BackendIoError> {
            self.inner.read(offset, out)
        }
        fn set_len(&self, len: u64) -> Result<(), BackendIoError> {
            self.inner.set_len(len)
        }
        fn sync_data(&self) -> Result<(), BackendIoError> {
            (self.at_flush)(&self.inner)?;
            self.events.lock().unwrap().push(Event::Flush);
            self.inner.sync_data()
        }
        fn write(&self, offset: u64, data: &[u8]) -> Result<(), BackendIoError> {
            if offset == 0 {
                self.events
                    .lock()
                    .unwrap()
                    .push(Event::Header(is_primary_unflushed(data)));
            }
            self.inner.write(offset, data)
        }
        fn close(&self) -> Result<(), BackendIoError> {
            self.inner.close()
        }
        fn try_lock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<bool, BackendError> {
            self.inner.try_lock_range(start, end)
        }
        fn try_lock_shared_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<bool, BackendError> {
            self.inner.try_lock_shared_range(start, end)
        }
        fn lock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<(), BackendError> {
            self.inner.lock_range(start, end)
        }
        fn lock_shared_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<(), BackendError> {
            self.inner.lock_shared_range(start, end)
        }
        fn unlock_range(&self, start: Bound<u64>, end: Bound<u64>) -> Result<(), BackendError> {
            self.inner.unlock_range(start, end)
        }
        fn query_lock_range(
            &self,
            start: Bound<u64>,
            end: Bound<u64>,
        ) -> Result<bool, BackendError> {
            self.inner.query_lock_range(start, end)
        }
    }

    fn observed(path: &Path, events: Arc<Mutex<Vec<Event>>>) -> Observed {
        Observed::new(path, events, |_| Ok(()))
    }

    /// Whether the handle flushed the file before its first header write, so that a dead
    /// writer's header write was durable before the cleared header could be read
    fn flushed_before_writing(events: &Mutex<Vec<Event>>) -> bool {
        let events = events.lock().unwrap();
        let flush = events.iter().position(|event| *event == Event::Flush);
        let write = events
            .iter()
            .position(|event| matches!(event, Event::Header(_)));
        matches!((flush, write), (Some(flush), Some(write)) if flush < write)
    }

    /// What a commit writes, as the file sees it. In the multi-process modes the write that makes
    /// the commit the primary marks it unflushed, and a write after the flush clears the mark. A
    /// single-process commit writes the header once, unmarked: nothing else reads it.
    #[test]
    fn the_flip_marks_the_primary_unflushed_and_a_write_after_the_flush_clears_it() {
        let shared = vec![
            Event::Header(false),
            Event::Flush,
            Event::Header(true),
            Event::Flush,
            Event::Header(false),
        ];
        for (mode, expected) in [
            (
                ConcurrencyMode::ExclusiveWriter,
                vec![Event::Header(false), Event::Flush],
            ),
            (ConcurrencyMode::SingleWriter, shared.clone()),
            (ConcurrencyMode::MultiWriter, shared),
        ] {
            let tmpfile = crate::create_tempfile();
            let events = Arc::new(Mutex::new(Vec::new()));
            let db = builder(mode)
                .create_with_backend(observed(tmpfile.path(), events.clone()))
                .unwrap();
            commit(&db, 1);
            events.lock().unwrap().clear();
            commit(&db, 2);
            assert_eq!(*events.lock().unwrap(), expected, "{mode:?}");
            drop(db);
        }
    }

    /// Another process serves the previous commit while the flush runs, and the new one once the
    /// write after the flush has cleared the mark
    #[test]
    fn the_previous_commit_is_served_until_the_flush_completes() {
        for mode in SHARED_MODES {
            let tmpfile = crate::create_tempfile();
            let path = tmpfile.path().to_path_buf();
            let reader: Arc<Mutex<Option<ReadOnlyDatabase>>> = Arc::new(Mutex::new(None));
            let served = Arc::new(Mutex::new(Vec::new()));
            let db = builder(mode)
                .create_with_backend(Observed::new(&path, Arc::new(Mutex::new(Vec::new())), {
                    let (reader, served, path) = (reader.clone(), served.clone(), path.clone());
                    move |file| {
                        if marked(file) {
                            let mut reader = reader.lock().unwrap();
                            let reader = reader.get_or_insert_with(|| {
                                builder(mode).open_read_only(&path).unwrap()
                            });
                            served.lock().unwrap().push(read(reader));
                        }
                        Ok(())
                    }
                }))
                .unwrap();
            commit(&db, 1);
            commit(&db, 2);
            assert_eq!(*served.lock().unwrap(), [None, Some(1)], "{mode:?}");
            assert_eq!(
                read(reader.lock().unwrap().as_ref().unwrap()),
                Some(2),
                "{mode:?}"
            );
            drop(db);
        }
    }

    /// A writer that dies before its flush completes leaves the mark in the file, so the other
    /// processes keep serving the previous commit. A writer's recovery flushes the file and
    /// clears the mark, which publishes the commit.
    #[test]
    fn a_commit_whose_writer_died_in_the_flush_is_published_by_recovery() {
        for mode in SHARED_MODES {
            let tmpfile = crate::create_tempfile();
            let dying = Arc::new(AtomicBool::new(false));
            let db = builder(mode)
                .create_with_backend(Observed::new(
                    tmpfile.path(),
                    Arc::new(Mutex::new(Vec::new())),
                    {
                        let dying = dying.clone();
                        move |file| {
                            if dying.load(Ordering::SeqCst) && marked(file) {
                                return Err(io::Error::other("power loss"));
                            }
                            Ok(())
                        }
                    },
                ))
                .unwrap();
            commit(&db, 1);
            let reader = builder(mode).open_read_only(tmpfile.path()).unwrap();
            assert_eq!(read(&reader), Some(1), "{mode:?}");

            dying.store(true, Ordering::SeqCst);
            let write = db.begin_write().unwrap();
            write.open_table(TABLE).unwrap().insert(0, 2).unwrap();
            assert!(write.commit().is_err(), "{mode:?}");
            // The crash: nothing more reaches the file, and the locks go with the process
            drop(db);
            assert!(marked(&file(tmpfile.path())), "{mode:?}");
            assert_eq!(read(&reader), Some(1), "{mode:?}");

            let events = Arc::new(Mutex::new(Vec::new()));
            let recovered = builder(mode)
                .create_with_backend(observed(tmpfile.path(), events.clone()))
                .unwrap();
            assert!(!marked(&file(tmpfile.path())), "{mode:?}");
            assert!(flushed_before_writing(&events), "{mode:?}");
            assert_eq!(read(&recovered), Some(2), "{mode:?}");
            assert_eq!(read(&reader), Some(2), "{mode:?}");
            drop(recovered);
        }
    }

    /// A multi-writer peer that is still open takes over a dead writer's commit when it next
    /// reloads the header: it flushes the file and then clears the mark, so the other processes
    /// see the commit before the peer commits anything itself
    #[test]
    fn a_peer_publishes_a_dead_writers_commit_when_it_reloads() {
        let mode = ConcurrencyMode::MultiWriter;
        let tmpfile = crate::create_tempfile();
        let dying = Arc::new(AtomicBool::new(false));
        let db = builder(mode)
            .create_with_backend(Observed::new(
                tmpfile.path(),
                Arc::new(Mutex::new(Vec::new())),
                {
                    let dying = dying.clone();
                    move |file| {
                        if dying.load(Ordering::SeqCst) && marked(file) {
                            return Err(io::Error::other("power loss"));
                        }
                        Ok(())
                    }
                },
            ))
            .unwrap();
        commit(&db, 1);
        let events = Arc::new(Mutex::new(Vec::new()));
        let peer = builder(mode)
            .create_with_backend(observed(tmpfile.path(), events.clone()))
            .unwrap();
        let reader = builder(mode).open_read_only(tmpfile.path()).unwrap();
        assert_eq!(read(&peer), Some(1));
        assert_eq!(read(&reader), Some(1));

        dying.store(true, Ordering::SeqCst);
        let write = db.begin_write().unwrap();
        write.open_table(TABLE).unwrap().insert(0, 2).unwrap();
        assert!(write.commit().is_err());
        drop(db);
        assert!(marked(&file(tmpfile.path())));
        assert_eq!(read(&peer), Some(1));
        assert_eq!(read(&reader), Some(1));

        events.lock().unwrap().clear();
        let write = peer.begin_write().unwrap();
        assert!(!marked(&file(tmpfile.path())));
        assert!(flushed_before_writing(&events));
        assert_eq!(read(&reader), Some(2));
        write.open_table(TABLE).unwrap().insert(0, 3).unwrap();
        write.commit().unwrap();
        assert_eq!(read(&reader), Some(3));
        drop(peer);
    }

    /// The cache tag follows the published commit. A read beginning on the committing handle
    /// while its flush runs is served the previous commit and finds the tag still naming it; the
    /// read after the commit finds the tag advanced. Neither drops the cache
    #[cfg(feature = "cache_metrics")]
    #[test]
    fn a_commit_drops_no_cache_during_or_after_its_flush() {
        use std::sync::Weak;

        let mode = ConcurrencyMode::MultiWriter;
        let tmpfile = crate::create_tempfile();
        let handle: Arc<Mutex<Weak<Database>>> = Arc::new(Mutex::new(Weak::new()));
        // Each read begun during a flush: the value served, and the cache before and after
        // the read began
        let during: Arc<Mutex<Vec<(u64, usize, usize)>>> = Arc::new(Mutex::new(Vec::new()));
        let db = Arc::new(
            builder(mode)
                .create_with_backend(Observed::new(
                    tmpfile.path(),
                    Arc::new(Mutex::new(Vec::new())),
                    {
                        let (handle, during) = (handle.clone(), during.clone());
                        move |file| {
                            if marked(file)
                                && let Some(db) = handle.lock().unwrap().upgrade()
                            {
                                let before = db.cache_stats().used_bytes();
                                let read = db.begin_read().unwrap();
                                let after = db.cache_stats().used_bytes();
                                let table = read.open_table(TABLE).unwrap();
                                let value = table.get(0).unwrap().unwrap().value();
                                during.lock().unwrap().push((value, before, after));
                            }
                            Ok(())
                        }
                    },
                ))
                .unwrap(),
        );
        commit(&db, 1);
        // Armed once the table exists, so the read during the flush has something to read
        *handle.lock().unwrap() = Arc::downgrade(&db);
        commit(&db, 2);

        let during = during.lock().unwrap().clone();
        assert_eq!(during.len(), 1);
        let (value, before, after) = during[0];
        assert_eq!(value, 1);
        assert!(before > 0);
        assert_eq!(after, before, "a read during the flush dropped the cache");

        let cached = db.cache_stats().used_bytes();
        assert!(cached > 0);
        let _read = db.begin_read().unwrap();
        assert_eq!(
            db.cache_stats().used_bytes(),
            cached,
            "the read after the commit dropped the cache"
        );
        assert_eq!(read(db.as_ref()), Some(2));
        drop(db);
    }
}

/// The "active transaction range" locks a read transaction publishes, probed directly: a
/// byte-range lock is invisible through the public API
#[cfg(all(test, any(target_os = "linux", target_vendor = "apple", windows)))]
mod active_transaction_test {
    use super::{ConcurrencyMode, Database, ReadableDatabase, TXN_BASE, WRITER_BYTE, byte_range};
    use crate::tree_store::file_backend::range_lock::RangeLock;
    use crate::tree_store::page_store::page_manager::HEADER_LOCK;
    use crate::{Durability, SavepointError, SetDurabilityError, TableDefinition};
    use std::fs::{File, OpenOptions};
    use std::path::Path;

    const TABLE: TableDefinition<u64, u64> = TableDefinition::new("x");
    // The ids a freshly created database can have committed, with room for a few more commits
    const SEARCHED: std::ops::Range<u64> = 0..16;

    fn create(path: &Path, mode: ConcurrencyMode) -> Database {
        let mut builder = Database::builder();
        builder.set_concurrency_mode(mode);
        let db = builder.create(path).unwrap();
        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(0, 0).unwrap();
        }
        write.commit().unwrap();
        db
    }

    /// A separate description, so its locks conflict with the database's exactly as another
    /// process's would
    fn probe(path: &Path) -> File {
        OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .unwrap()
    }

    /// Probed exclusively, since the byte is held shared and another process may hold the same
    /// one. Reports the whole-file lock a exclusive-writer open holds as well, which is what
    /// `an_exclusive_writer_read_does_not_puncture_the_whole_file_lock` relies on
    fn is_held(probe: &File, id: u64) -> bool {
        let free = probe.try_lock_range(byte_range(TXN_BASE + id)).unwrap();
        if free {
            probe.unlock_range(byte_range(TXN_BASE + id)).unwrap();
        }
        !free
    }

    fn held_ids(probe: &File) -> Vec<u64> {
        SEARCHED.filter(|id| is_held(probe, *id)).collect()
    }

    #[test]
    fn a_read_transaction_locks_the_id_it_reads_until_it_ends() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());
        assert!(held_ids(&probe).is_empty());

        let read = db.begin_read().unwrap();
        assert_eq!(
            held_ids(&probe).len(),
            1,
            "a read transaction locked {:?}",
            held_ids(&probe)
        );

        drop(read);
        assert!(
            held_ids(&probe).is_empty(),
            "a lock outlived the read transaction that took it"
        );
    }

    /// Two readers of one snapshot take the byte once, since it does not nest through a single
    /// file description: it is released only as the last of them ends
    #[test]
    fn concurrent_readers_of_one_snapshot_share_the_lock() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        let first = db.begin_read().unwrap();
        let second = db.begin_read().unwrap();
        let held = held_ids(&probe);
        assert_eq!(held.len(), 1, "expected one active id: {held:?}");

        drop(first);
        assert!(is_held(&probe, held[0]), "released early");
        drop(second);
        assert!(!is_held(&probe, held[0]), "never released");
    }

    /// A read-only handle is a participant like any other: its snapshot is exactly what a
    /// writer in another process must not reclaim
    #[test]
    fn a_read_only_handle_locks_what_it_reads() {
        let tmpfile = crate::create_tempfile();
        // Dropped, so the read-only open is the only handle: it takes SHARED_READER_BYTE, and
        // the writer that created the file would otherwise hold the whole storage
        drop(create(tmpfile.path(), ConcurrencyMode::MultiWriter));
        let probe = probe(tmpfile.path());

        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        let db = builder.open_read_only(tmpfile.path()).unwrap();
        let read = db.begin_read().unwrap();
        assert_eq!(
            held_ids(&probe).len(),
            1,
            "a read-only handle locked {:?}",
            held_ids(&probe)
        );

        drop(read);
        assert!(held_ids(&probe).is_empty(), "the lock outlived the reader");
    }

    #[test]
    fn read_only_snapshot_survives_new_read_before_construction() {
        use super::{ReadTransaction, TransactionGuard};
        #[cfg(feature = "experimental-api-5")]
        use crate::ReadableTable;

        for mode in [ConcurrencyMode::SingleWriter, ConcurrencyMode::MultiWriter] {
            let tmpfile = crate::create_tempfile();
            let writer = create(tmpfile.path(), mode);
            let db = Database::builder()
                .set_concurrency_mode(mode)
                .set_cache_size(0)
                .open_read_only(tmpfile.path())
                .unwrap();
            let (guard, root) =
                TransactionGuard::allocate_read(db.transaction_tracker.clone(), &db.mem).unwrap();

            for value in 1..4 {
                let write = writer.begin_write().unwrap();
                write.open_table(TABLE).unwrap().insert(0, value).unwrap();
                write.commit().unwrap();
            }
            // Another read observes the peer's commit before the first read is constructed.
            let latest = db.begin_read().unwrap();
            assert_eq!(
                latest
                    .open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                3
            );

            let read = ReadTransaction::new(db.mem.clone(), guard, root).unwrap();
            assert_eq!(
                read.open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                0
            );
        }
    }

    #[cfg(feature = "cache_metrics")]
    #[test]
    fn read_only_file_snapshots_preserve_memory_state_and_reuse_cache() {
        use super::TransactionGuard;
        use crate::ReadableTable;

        for mode in [ConcurrencyMode::SingleWriter, ConcurrencyMode::MultiWriter] {
            let tmpfile = crate::create_tempfile();
            let writer = create(tmpfile.path(), mode);
            let db = Database::builder()
                .set_concurrency_mode(mode)
                .open_read_only(tmpfile.path())
                .unwrap();
            let original_id = db.mem.get_last_committed_transaction_id().unwrap();
            let original_root = db.mem.get_data_root();
            let read = db.begin_read().unwrap();
            assert_eq!(
                read.open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                0
            );
            let cached_bytes = db.cache_stats().used_bytes();
            assert!(cached_bytes > 0);

            let (same, _) =
                TransactionGuard::allocate_read(db.transaction_tracker.clone(), &db.mem).unwrap();
            assert_eq!(same.id(), original_id);
            assert_eq!(db.cache_stats().used_bytes(), cached_bytes);

            let write = writer.begin_write().unwrap();
            write.open_table(TABLE).unwrap().insert(0, 1).unwrap();
            write.commit().unwrap();

            let (latest, _) =
                TransactionGuard::allocate_read(db.transaction_tracker.clone(), &db.mem).unwrap();
            assert!(latest.id() > original_id);
            assert_eq!(db.cache_stats().used_bytes(), 0);
            assert_eq!(
                db.mem.get_last_committed_transaction_id().unwrap(),
                original_id
            );
            assert_eq!(db.mem.get_data_root(), original_root);

            let current = db.begin_read().unwrap();
            assert_eq!(
                current
                    .open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                1
            );
            let cached_bytes = db.cache_stats().used_bytes();
            assert!(cached_bytes > 0);
            let (repeated, _) =
                TransactionGuard::allocate_read(db.transaction_tracker.clone(), &db.mem).unwrap();
            assert_eq!(repeated.id(), latest.id());
            assert_eq!(db.cache_stats().used_bytes(), cached_bytes);
            assert_eq!(
                read.open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                0
            );
        }
    }

    #[cfg(feature = "cache_metrics")]
    #[test]
    fn a_multi_writer_commit_keeps_its_read_cache() {
        use crate::ReadableTable;

        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        {
            let read = db.begin_read().unwrap();
            assert_eq!(
                read.open_table(TABLE)
                    .unwrap()
                    .get(0)
                    .unwrap()
                    .unwrap()
                    .value(),
                0
            );
        }

        let write = db.begin_write().unwrap();
        write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        write.commit().unwrap();
        let cached_bytes = db.cache_stats().used_bytes();
        assert!(cached_bytes > 0);

        let _read = db.begin_read().unwrap();
        assert_eq!(db.cache_stats().used_bytes(), cached_bytes);
    }

    /// Syncing to a peer's commit empties the cache and tags it with that commit, so a read that
    /// then observes the commit keeps what the write transaction has cached since
    #[cfg(feature = "cache_metrics")]
    #[test]
    fn a_read_after_a_sync_keeps_the_transactions_cache() {
        use crate::ReadableTable;

        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let peer = Database::builder()
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .open(tmpfile.path())
            .unwrap();
        let write = peer.begin_write().unwrap();
        write.open_table(TABLE).unwrap().insert(0, 1).unwrap();
        write.commit().unwrap();

        // Syncs to the peer's commit, then caches the pages it reads
        let write = db.begin_write().unwrap();
        assert_eq!(
            write
                .open_table(TABLE)
                .unwrap()
                .get(0)
                .unwrap()
                .unwrap()
                .value(),
            1
        );
        let cached_bytes = db.cache_stats().used_bytes();
        assert!(cached_bytes > 0);

        let _read = db.begin_read().unwrap();
        assert_eq!(db.cache_stats().used_bytes(), cached_bytes);
        write.abort().unwrap();
    }

    /// A savepoint holds a read transaction live, so its snapshot stays active for as long as
    /// the savepoint does. In the shared mode that supports an ephemeral one
    #[test]
    fn an_ephemeral_savepoint_locks_the_snapshot_it_references() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::SingleWriter);
        let probe = probe(tmpfile.path());
        assert!(held_ids(&probe).is_empty());

        let write = db.begin_write().unwrap();
        let savepoint = write.ephemeral_savepoint().unwrap();
        write.commit().unwrap();
        assert_eq!(
            held_ids(&probe).len(),
            1,
            "a savepoint locked {:?}",
            held_ids(&probe)
        );

        drop(savepoint);
        assert!(
            held_ids(&probe).is_empty(),
            "the lock outlived the savepoint"
        );
    }

    /// A persistent savepoint bounds this process's reclamation, but takes no byte: the file
    /// names it, so every process protects it by syncing, and a byte would go on pinning the
    /// transaction after another process deleted the savepoint, until this one next synced
    #[test]
    fn a_persistent_savepoint_takes_no_active_transaction_byte() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        // Nothing else references the savepoint's transaction, so the byte is the savepoint's to
        // take or leave
        let pinned = db.mem.get_last_committed_transaction_id().unwrap();
        let write = db.begin_write().unwrap();
        let savepoint = write.persistent_savepoint().unwrap();
        write.commit().unwrap();
        assert!(
            held_ids(&probe).is_empty(),
            "the savepoint locked {:?}",
            held_ids(&probe)
        );
        assert_eq!(
            db.transaction_tracker.oldest_local_referenced_transaction(),
            Some(pinned),
            "the savepoint stopped bounding this process's reclamation"
        );
        // The probe does see a byte where there is one to see
        let read = db.begin_read().unwrap();
        assert_eq!(held_ids(&probe).len(), 1);
        drop(read);
        assert!(held_ids(&probe).is_empty());

        let write = db.begin_write().unwrap();
        assert!(write.delete_persistent_savepoint(savepoint).unwrap());
        write.commit().unwrap();
        assert_eq!(
            db.transaction_tracker.oldest_local_referenced_transaction(),
            None,
            "the deleted savepoint kept its reference"
        );
        assert!(held_ids(&probe).is_empty());
    }

    /// The same for a savepoint this handle adopted rather than created: the open syncs the
    /// file's persistent savepoints, and references them without locking them either
    #[test]
    fn a_synced_persistent_savepoint_takes_no_active_transaction_byte() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let write = db.begin_write().unwrap();
        write.persistent_savepoint().unwrap();
        write.commit().unwrap();
        drop(db);

        let probe = probe(tmpfile.path());
        assert!(
            held_ids(&probe).is_empty(),
            "the closed database left a lock"
        );

        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        assert!(
            held_ids(&probe).is_empty(),
            "the open locked {:?} for the file's savepoint",
            held_ids(&probe)
        );
        assert!(
            db.transaction_tracker
                .oldest_local_referenced_transaction()
                .is_some(),
            "the open did not adopt the file's savepoint"
        );
        // The probe does see a byte where there is one to see
        let read = db.begin_read().unwrap();
        assert_eq!(held_ids(&probe).len(), 1);
        drop(read);
    }

    /// A non-durable commit exists only in this process's memory, so a shared mode refuses it
    #[test]
    fn a_shared_mode_refuses_durability_none() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::SingleWriter);

        let mut write = db.begin_write().unwrap();
        assert!(matches!(
            write.set_durability(Durability::None),
            Err(SetDurabilityError::NonDurableCommitUnsupported)
        ));
    }

    /// Every multi-writer commit records the allocator state, for the next writer, in any
    /// process, to load rather than rebuild: turning quick-repair off has no effect there
    #[test]
    fn a_multi_writer_commit_records_the_allocator_state_regardless() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);

        let mut write = db.begin_write().unwrap();
        write.set_quick_repair(false);
        write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        write.commit().unwrap();
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
    }

    /// An ephemeral savepoint would be known to this process alone, and a persistent savepoint
    /// a peer creates could take its id, so multi-writer mode refuses it
    #[test]
    fn a_multi_writer_mode_refuses_an_ephemeral_savepoint() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);

        let write = db.begin_write().unwrap();
        assert!(matches!(
            write.ephemeral_savepoint(),
            Err(SavepointError::EphemeralSavepointUnsupported)
        ));
        write.persistent_savepoint().unwrap();
        write.commit().unwrap();
    }

    /// An interrupted repair may leave no allocator snapshot. The check records it so the next
    /// writer can load it without rebuilding again.
    #[test]
    fn an_integrity_check_records_a_peers_unrecorded_commit() {
        let tmpfile = crate::create_tempfile();
        let mut db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let peer = Database::builder()
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .open(tmpfile.path())
            .unwrap();
        // A commit recording no allocator state, as a repair's does. The peer stays open, since
        // its close would record
        let mut write = peer.begin_write().unwrap();
        write.skip_allocator_state_record();
        write.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        write.commit().unwrap();

        assert!(!db.check_integrity().unwrap());
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
        drop(peer);
    }

    #[test]
    fn a_write_transaction_releases_the_writer_byte_and_slot() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        let txn = db.begin_write().unwrap();
        assert!(db.transaction_tracker.holds_writer_byte());
        assert!(db.transaction_tracker.write_transaction_live());
        assert!(!probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap());

        txn.abort().unwrap();
        assert!(!db.transaction_tracker.holds_writer_byte());
        assert!(!db.transaction_tracker.write_transaction_live());
        assert!(probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap());
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
    }

    /// A leak another process left in the file is repaired, and the repair records the allocator
    /// state for the next writer to load
    #[test]
    fn an_integrity_check_repairs_a_leak_a_peer_recorded() {
        use crate::tree_store::{AllocationPolicy, PageAllocator, PageTracker};

        let tmpfile = crate::create_tempfile();
        let mut db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let peer = Database::builder()
            .set_concurrency_mode(ConcurrencyMode::MultiWriter)
            .open(tmpfile.path())
            .unwrap();
        // A page the peer allocates and neither frees nor references: a leak its close's snapshot
        // records as allocated
        let allocator = PageAllocator::new(peer.mem.clone(), AllocationPolicy::Default);
        drop(allocator.allocate(64, &PageTracker::ignore()).unwrap());
        drop(allocator);
        drop(peer);

        assert!(!db.check_integrity().unwrap());
        // The repair recorded the allocator state, for a peer to load
        assert!(
            Database::get_allocator_state_table(&db.mem)
                .unwrap()
                .is_some()
        );
        assert!(db.check_integrity().unwrap());
    }

    /// A read-only participant sees what another process committed, not the header it read at open
    #[test]
    fn a_read_only_participant_picks_up_a_peers_commit() {
        let tmpfile = crate::create_tempfile();
        let writer = create(tmpfile.path(), ConcurrencyMode::MultiWriter);

        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        let reader = builder.open_read_only(tmpfile.path()).unwrap();
        let probe = probe(tmpfile.path());

        let read = reader.begin_read().unwrap();
        let before = held_ids(&probe);
        assert_eq!(before.len(), 1, "expected one active id: {before:?}");
        let before = before[0];
        drop(read);

        let write = writer.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(1, 1).unwrap();
        }
        write.commit().unwrap();
        drop(writer);
        assert!(
            held_ids(&probe).is_empty(),
            "the closed writer left {:?} locked",
            held_ids(&probe)
        );

        let read = reader.begin_read().unwrap();
        let after = held_ids(&probe);
        assert_eq!(after.len(), 1, "expected one active id: {after:?}");
        assert!(
            after[0] > before,
            "the reader stayed at {before} after the writer committed"
        );
        drop(read);
    }

    /// A read-only participant takes the primary as recorded: choosing between the slots is a
    /// repairing writer's job, and a newer secondary it can see is a commit whose pages are not in
    /// the file yet, or one a repair has just rolled back
    #[test]
    fn a_read_only_participant_takes_the_primary_as_recorded() {
        use std::io::{Read, Write};

        let tmpfile = crate::create_tempfile();
        drop(create(tmpfile.path(), ConcurrencyMode::ExclusiveWriter));

        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        let reader = builder.open_read_only(tmpfile.path()).unwrap();

        // A newer commit whose pages this file never received: made in a copy, then its slot
        // spliced into this file's secondary slot
        let copy = crate::create_tempfile();
        std::fs::copy(tmpfile.path(), copy.path()).unwrap();
        let db = Database::open(copy.path()).unwrap();
        let write = db.begin_write().unwrap();
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(0, 1).unwrap();
        }
        write.commit().unwrap();
        drop(db);

        let header = |path: &Path| -> Vec<u8> {
            let mut header = vec![0u8; 320];
            File::open(path).unwrap().read_exact(&mut header).unwrap();
            header
        };
        let slot = |index: usize| 64 + index * 128..64 + (index + 1) * 128;
        let id = |header: &[u8], index: usize| {
            u64::from_le_bytes(header[slot(index)][104..112].try_into().unwrap())
        };
        let newer = header(copy.path());
        let mut spliced = header(tmpfile.path());
        let primary = usize::from(spliced[9] & 1);
        spliced[slot(1 - primary)].copy_from_slice(&newer[slot(usize::from(newer[9] & 1))]);
        // The god byte a repair leaves on a 1-phase history: recovery clear, 2-phase clear
        spliced[9] &= !6;
        OpenOptions::new()
            .write(true)
            .open(tmpfile.path())
            .unwrap()
            .write_all(&spliced)
            .unwrap();
        assert!(id(&spliced, 1 - primary) > id(&spliced, primary));
        let probe = probe(tmpfile.path());

        // Reloading into that state, and opening in it
        let read = reader.begin_read().unwrap();
        assert_eq!(
            held_ids(&probe),
            vec![id(&spliced, primary)],
            "the reader adopted a slot whose pages the file never received"
        );
        drop(read);
        let opened = builder.open_read_only(tmpfile.path()).unwrap();
        let read = opened.begin_read().unwrap();
        assert_eq!(held_ids(&probe), vec![id(&spliced, primary)]);
        drop(read);
    }

    /// Sharing the file forces 2-phase, whatever the transaction asked for
    #[test]
    fn a_shared_commit_is_two_phase() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);

        let mut write = db.begin_write().unwrap();
        write.set_two_phase_commit(false);
        {
            let mut table = write.open_table(TABLE).unwrap();
            table.insert(1, 1).unwrap();
        }
        write.commit().unwrap();

        assert!(
            db.mem.used_two_phase_commit(),
            "a shared commit published without the flush between the header writes"
        );
    }

    /// With no writer holding the file, an unclean one is refused: nothing is coming to repair it
    #[test]
    fn a_shared_read_refuses_an_unclean_file_with_no_writer() {
        use std::io::{Read, Seek, SeekFrom, Write};

        let tmpfile = crate::create_tempfile();
        drop(create(tmpfile.path(), ConcurrencyMode::MultiWriter));

        // The god byte's recovery-required bit, which a clean shutdown clears
        {
            let mut file = OpenOptions::new()
                .read(true)
                .write(true)
                .open(tmpfile.path())
                .unwrap();
            let mut byte = [0u8; 1];
            file.seek(SeekFrom::Start(9)).unwrap();
            file.read_exact(&mut byte).unwrap();
            byte[0] |= 2;
            file.seek(SeekFrom::Start(9)).unwrap();
            file.write_all(&byte).unwrap();
        }

        let mut builder = Database::builder();
        builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
        assert!(matches!(
            builder.open_read_only(tmpfile.path()),
            Err(crate::DatabaseError::RepairAborted)
        ));
    }

    /// A exclusive-writer open holds the whole file, which covers these bytes. Locking one and
    /// releasing it would punch a hole in that lock, so this mode locks nothing
    #[test]
    fn an_exclusive_writer_read_does_not_puncture_the_whole_file_lock() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::ExclusiveWriter);
        let probe = probe(tmpfile.path());

        drop(db.begin_read().unwrap());

        assert_eq!(
            held_ids(&probe),
            SEARCHED.collect::<Vec<_>>(),
            "a read transaction punctured the whole-file lock"
        );
    }

    /// The floor is the older of this process's oldest read and a peer's pin, and a peer's pin
    /// only matters below the former, which is where the scan looks
    #[test]
    fn the_oldest_active_transaction_is_the_lower_of_ours_and_a_peers() {
        for mode in [ConcurrencyMode::SingleWriter, ConcurrencyMode::MultiWriter] {
            let tmpfile = crate::create_tempfile();
            let db = create(tmpfile.path(), mode);
            let scan = |local| {
                let header_lock = db.mem.lock_header_exclusive().unwrap();
                db.mem
                    .oldest_active_transaction(local, &header_lock)
                    .unwrap()
            };
            let first = db.mem.get_last_committed_transaction_id().unwrap();
            assert_eq!(scan(None), None);

            // A peer pins the last committed transaction, as its read of the header would
            let probe = probe(tmpfile.path());
            probe
                .lock_shared_range(byte_range(TXN_BASE + first.raw_id()))
                .unwrap();
            assert_eq!(scan(None), Some(first), "{mode:?}");

            let write = db.begin_write().unwrap();
            {
                let mut table = write.open_table(TABLE).unwrap();
                table.insert(1, 1).unwrap();
            }
            write.commit().unwrap();
            let second = db.mem.get_last_committed_transaction_id().unwrap();
            assert!(first < second);
            assert_eq!(scan(Some(second)), Some(first), "{mode:?}");
            probe
                .unlock_range(byte_range(TXN_BASE + first.raw_id()))
                .unwrap();
            assert_eq!(scan(Some(second)), Some(second), "{mode:?}");
        }
    }

    /// A transaction that is lent the exclusive header lock syncs to a peer's commit under that
    /// lock, savepoints included, rather than trying to take the lock a second time.
    #[test]
    fn a_lent_header_lock_covers_syncing_to_a_peers_commit() {
        use std::sync::mpsc;
        use std::thread;
        use std::time::Duration;

        fn open(path: &Path) -> Database {
            let mut builder = Database::builder();
            builder.set_concurrency_mode(ConcurrencyMode::MultiWriter);
            builder.open(path).unwrap()
        }

        let tmpfile = crate::create_tempfile();
        create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let peer = open(tmpfile.path());
        // The handle syncs to the commit under holds it took itself, as compaction does, in a
        // thread, so that taking the header lock again fails rather than hangs
        let path = tmpfile.path().to_path_buf();
        let (opened, wait_for_open) = mpsc::channel();
        let (committed, wait_for_commit) = mpsc::channel();
        let (synced, wait_for_sync) = mpsc::channel();
        let syncing = thread::spawn(move || {
            let db = open(&path);
            opened.send(()).unwrap();
            wait_for_commit.recv().unwrap();
            let writer_lock = db.mem.lock_writer().unwrap();
            let header_lock = db.mem.lock_header_exclusive().unwrap();
            let txn = db
                .begin_write_with(Some(&writer_lock), Some(&header_lock))
                .unwrap();
            let savepoints: Vec<u64> = txn.list_persistent_savepoints().unwrap().collect();
            txn.abort().unwrap();
            drop(header_lock);
            drop(writer_lock);
            synced.send(savepoints).unwrap();
        });
        wait_for_open.recv().unwrap();
        let txn = peer.begin_write().unwrap();
        let peers_savepoint = txn.persistent_savepoint().unwrap();
        txn.commit().unwrap();
        // Closed first: otherwise its close would wait on the writer byte that a hung
        // transaction still holds
        drop(peer);
        committed.send(()).unwrap();

        let savepoints = wait_for_sync
            .recv_timeout(Duration::from_secs(10))
            .expect("the transaction took the header lock its caller holds");
        assert_eq!(savepoints, vec![peers_savepoint]);
        syncing.join().unwrap();
    }

    /// A transaction that is lent the exclusive header lock begins and commits under it, and
    /// leaves the lock held afterwards.
    #[test]
    fn a_lent_header_hold_outlives_the_commit() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        let header_lock = db.mem.lock_header_exclusive().unwrap();
        let txn = db.begin_write_with(None, Some(&header_lock)).unwrap();
        txn.open_table(TABLE).unwrap().insert(1, 1).unwrap();
        txn.commit_with(Some(&header_lock)).unwrap();
        assert!(!probe.try_lock_shared_range(HEADER_LOCK).unwrap());

        drop(header_lock);
        assert!(probe.try_lock_shared_range(HEADER_LOCK).unwrap());
        probe.unlock_range(HEADER_LOCK).unwrap();
    }

    /// A transaction lent the writer byte leaves it held when it ends
    #[test]
    fn a_lent_writer_byte_outlives_the_transaction() {
        let tmpfile = crate::create_tempfile();
        let db = create(tmpfile.path(), ConcurrencyMode::MultiWriter);
        let probe = probe(tmpfile.path());

        let writer_lock = db.mem.lock_writer().unwrap();
        let txn = db.begin_write_with(Some(&writer_lock), None).unwrap();
        txn.abort().unwrap();
        assert!(!probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap());

        drop(writer_lock);
        assert!(probe.try_lock_range(byte_range(WRITER_BYTE)).unwrap());
        probe.unlock_range(byte_range(WRITER_BYTE)).unwrap();
    }
}