turso_core 0.6.1

The Turso database library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use crate::io::FileSyncType;
use crate::sync::Mutex;
use crate::sync::OnceLock;
use crate::{turso_assert, turso_assert_greater_than, turso_debug_assert};
use branches::mark_unlikely;
use rustc_hash::{FxHashMap, FxHashSet};
use std::array;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use strum::EnumString;
use tracing::{instrument, Level};

use crate::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use crate::sync::RwLock;
use bitflags::bitflags;
use std::fmt::{Debug, Formatter};
use std::{fmt, sync::Arc};

use super::buffer_pool::BufferPool;
use super::pager::{PageRef, Pager};
use super::sqlite3_ondisk::{
    self, checksum_wal, DatabaseHeader, WalHeader, WAL_MAGIC_BE, WAL_MAGIC_LE,
};
use crate::fast_lock::SpinLock;
use crate::io::clock::MonotonicInstant;
use crate::io::CompletionGroup;
use crate::io::{File, IO};
use crate::storage::database::{DatabaseStorage, EncryptionOrChecksum};
#[cfg(host_shared_wal)]
use crate::storage::shared_wal_coordination::SharedWalCoordinationOpenMode;
#[cfg(host_shared_wal)]
use crate::storage::shared_wal_coordination::{
    MappedSharedWalCoordination, SharedOwnerRecord, SharedReaderSlot, SharedWalCoordinationHeader,
};
use crate::storage::sqlite3_ondisk::{
    begin_read_wal_frame, begin_read_wal_frame_raw, finish_read_page, prepare_wal_frame,
    write_pages_vectored, PageSize, WAL_FRAME_HEADER_SIZE, WAL_HEADER_SIZE,
};
use crate::types::{IOCompletions, IOResult};
use crate::{
    bail_corrupt_error, io_yield_one, Buffer, Completion, CompletionError, IOContext, LimboError,
    Result,
};

/// this contains the frame to rollback to and its associated checksum.
#[derive(Debug, Clone)]
pub struct RollbackTo {
    pub frame: u64,
    pub checksum: (u32, u32),
}

#[derive(Debug, Clone, Default)]
pub struct CheckpointResult {
    /// max frame in the WAL after checkpoint
    /// note, that as we TRUNCATE wal outside of the main checkpoint routine - this field will be set to non-zero number even for TRUNCATE mode
    pub wal_max_frame: u64,
    /// total amount of frames backfilled to the DB file after checkpoint
    pub wal_total_backfilled: u64,
    /// amount of new frames backfilled to the DB file during this checkpoint procedure
    pub wal_checkpoint_backfilled: u64,
    /// In the case of everything backfilled, we need to hold the locks until the db
    /// file is truncated.
    maybe_guard: Option<CheckpointLocks>,
    pub db_truncate_sent: bool,
    pub db_sync_sent: bool,
    /// Whether WAL truncation I/O has been submitted (for TRUNCATE checkpoint mode)
    pub wal_truncate_sent: bool,
    /// Whether WAL sync I/O has been submitted after truncation
    pub wal_sync_sent: bool,
}

impl Drop for CheckpointResult {
    fn drop(&mut self) {
        let _ = self.maybe_guard.take();
    }
}

impl CheckpointResult {
    pub fn new(
        wal_max_frame: u64,
        wal_total_backfilled: u64,
        wal_checkpoint_backfilled: u64,
    ) -> Self {
        Self {
            wal_max_frame,
            wal_total_backfilled,
            wal_checkpoint_backfilled,
            maybe_guard: None,
            db_sync_sent: false,
            db_truncate_sent: false,
            wal_truncate_sent: false,
            wal_sync_sent: false,
        }
    }

    pub const fn everything_backfilled(&self) -> bool {
        self.wal_max_frame == self.wal_total_backfilled
    }
    pub fn should_truncate(&self) -> bool {
        // TRUNCATE should also clear any stale WAL bytes when the log was restarted
        // (wal_max_frame=0) but the file still contains old frames.
        self.everything_backfilled()
    }
    pub fn release_guard(&mut self) {
        let _ = self.maybe_guard.take();
    }
}

#[cfg(host_shared_wal)]
pub(crate) fn coordination_path_for_wal_path(wal_path: &str) -> String {
    if let Some(db_path) = wal_path.strip_suffix("-wal") {
        format!("{db_path}-tshm")
    } else {
        format!("{wal_path}-tshm")
    }
}

bitflags! {
    /// Automatic WAL maintenance actions a caller permits the engine to take
    /// during routine operations (begin write tx, commit, shutdown).
    ///
    /// Callers that manage WAL state out-of-band — e.g. the sync engine,
    /// which keeps its own watermarks across the WAL header — pass an
    /// explicit subset so unrelated bookkeeping remains untouched. The
    /// previous single `wal_auto_checkpoint_disabled` boolean conflated both
    /// auto-checkpoint and WAL header restart; spelling them out separately
    /// avoids breaking sync-engine assumptions whenever one of the two is
    /// disabled.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct WalAutoActions: u8 {
        /// Run an auto-checkpoint after commit when `should_checkpoint()`
        /// is true, and the truncate-checkpoint on connection shutdown.
        const Checkpoint = 0b01;
        /// Restart the WAL header in `try_restart_log_before_write` when
        /// every frame has been backfilled, before starting a write tx.
        const Restart    = 0b10;
    }
}

impl WalAutoActions {
    /// Default policy for ordinary connections: every auto action allowed.
    pub const fn all_enabled() -> Self {
        Self::from_bits_truncate(Self::Checkpoint.bits() | Self::Restart.bits())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, EnumString)]
#[strum(ascii_case_insensitive)]
pub enum CheckpointMode {
    /// Checkpoint as many frames as possible without waiting for any database readers or writers to finish, then sync the database file if all frames in the log were checkpointed.
    /// Passive never blocks readers or writers, only ensures (like all modes do) that there are no other checkpointers.
    ///
    /// Optional upper_bound_inclusive parameter can be set in order to checkpoint frames with number no larger than the parameter
    Passive { upper_bound_inclusive: Option<u64> },
    /// This mode blocks until there is no database writer and all readers are reading from the most recent database snapshot. It then checkpoints all frames in the log file and syncs the database file. This mode blocks new database writers while it is pending, but new database readers are allowed to continue unimpeded.
    Full,
    /// This mode works the same way as `Full` with the addition that after checkpointing the log file it blocks (calls the busy-handler callback) until all readers are reading from the database file only. This ensures that the next writer will restart the log file from the beginning. Like `Full`, this mode blocks new database writer attempts while it is pending, but does not impede readers.
    Restart,
    /// This mode works the same way as `Restart` with the addition that it also truncates the log file to zero bytes just prior to a successful return.
    ///
    /// Extra parameter can be set in order to perform conditional TRUNCATE: database will be checkpointed and truncated only if max_frames equals to the parameter value
    /// this behaviour used by sync-engine which consolidate WAL before checkpoint and needs to be sure that no frames will be missed
    Truncate { upper_bound_inclusive: Option<u64> },
}

impl CheckpointMode {
    fn should_restart_log(&self) -> bool {
        matches!(
            self,
            CheckpointMode::Truncate { .. } | CheckpointMode::Restart
        )
    }
    /// All modes other than Passive require a complete backfilling of all available frames
    /// from `shared.metadata.nbackfills + 1 -> shared.metadata.max_frame`
    fn require_all_backfilled(&self) -> bool {
        !matches!(self, CheckpointMode::Passive { .. })
    }
}

/// Immutable view of the WAL metadata a connection snapshots from shared state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct WalSnapshot {
    max_frame: u64,
    nbackfills: u64,
    last_checksum: (u32, u32),
    checkpoint_seq: u32,
    transaction_count: u64,
}

impl WalSnapshot {
    /// First frame that is still visible in the WAL after checkpoint backfill.
    const fn min_frame(self) -> u64 {
        self.nbackfills + 1
    }
}

/// Which read-mark, if any, currently protects this connection's snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReadGuardKind {
    None,
    DbFile,
    ReadMark(NonZeroUsize),
}

impl ReadGuardKind {
    /// Convert the lock index stored on `WalFile` into a semantic guard kind.
    const fn from_lock_index(lock_index: usize) -> Self {
        match lock_index {
            NO_LOCK_HELD => Self::None,
            0 => Self::DbFile,
            idx => Self::ReadMark(NonZeroUsize::new(idx).expect("idx checked to be non-zero")),
        }
    }

    /// Convert the semantic guard kind back into the legacy lock index representation.
    fn lock_index(self) -> usize {
        match self {
            Self::None => NO_LOCK_HELD,
            Self::DbFile => 0,
            Self::ReadMark(idx) => idx.into(),
        }
    }
}

/// Connection-local WAL state derived from a shared snapshot plus a held read guard.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct WalConnectionState {
    snapshot: WalSnapshot,
    read_guard: ReadGuardKind,
}

impl WalConnectionState {
    /// Build a new connection-local WAL state bundle.
    const fn new(snapshot: WalSnapshot, read_guard: ReadGuardKind) -> Self {
        Self {
            snapshot,
            read_guard,
        }
    }

    /// Replace just the shared snapshot while preserving the current read guard.
    const fn with_snapshot(self, snapshot: WalSnapshot) -> Self {
        Self {
            snapshot,
            read_guard: self.read_guard,
        }
    }
}

#[repr(transparent)]
#[derive(Debug, Default)]
/// A 64-bit read-write lock with embedded 32-bit value storage.
/// Using a single Atomic allows the reader count and lock state are updated
/// atomically together while sitting in a single cpu cache line.
///
/// # Memory Layout:
/// ```ignore
/// [63:32] Value bits    - 32 bits for stored value
/// [31:1]  Reader count  - 31 bits for reader count
/// [0]     Writer bit    - 1 bit indicating exclusive write lock
/// ```
///
/// # Synchronization Guarantees:
/// - Acquire semantics on lock acquisition ensure visibility of all writes
///   made by the previous lock holder
/// - Release semantics on unlock ensure all writes made while holding the
///   lock are visible to the next acquirer
/// - The embedded value can be atomically read without holding any lock
pub struct TursoRwLock(AtomicU64);

pub const READMARK_NOT_USED: u32 = 0xffffffff;
const NO_LOCK_HELD: usize = usize::MAX;

impl TursoRwLock {
    /// Bit 0: Writer flag
    const WRITER: u64 = 0b1;

    /// Reader increment value (bit 1)
    const READER_INC: u64 = 0b10;

    /// Reader count starts at bit 1
    const READER_SHIFT: u32 = 1;

    /// Mask for 31 reader bits [31:1]
    const READER_COUNT_MASK: u64 = 0x7fff_ffffu64 << Self::READER_SHIFT;

    /// Value starts at bit 32
    const VALUE_SHIFT: u32 = 32;

    /// Mask for 32 value bits [63:32]
    const VALUE_MASK: u64 = 0xffff_ffffu64 << Self::VALUE_SHIFT;

    #[inline]
    pub const fn new() -> Self {
        Self(AtomicU64::new(0))
    }

    const fn has_writer(val: u64) -> bool {
        val & Self::WRITER != 0
    }

    const fn has_readers(val: u64) -> bool {
        val & Self::READER_COUNT_MASK != 0
    }

    #[inline]
    /// Try to acquire a shared read lock.
    pub fn read(&self) -> bool {
        let mut count = 0;
        // Bounded loop to avoid infinite loops
        // Retry on Reader contention (should hopefully be spurious)
        while count < 1_000_000 {
            let cur = self.0.load(Ordering::Acquire);
            // If a writer is present we cannot proceed.
            if Self::has_writer(cur) {
                return false;
            }
            // 2 billion readers is a high enough number where we will skip the branch
            // and assume that we are not overflowing :)
            let desired = cur.wrapping_add(Self::READER_INC);
            // for success, Acquire establishes happens-before relationship with the previous Release from unlock
            // for failure we only care about reading it for the next iteration so we can use Relaxed.
            let res = self
                .0
                .compare_exchange(cur, desired, Ordering::Acquire, Ordering::Relaxed);
            if res.is_err() {
                count += 1;
                crate::thread::spin_loop();
                continue;
            }
            return true;
        }
        // Too much reader contention return Busy
        false
    }

    /// Try to take an exclusive lock. Succeeds if no readers and no writer.
    #[inline]
    pub fn write(&self) -> bool {
        let cur = self.0.load(Ordering::Acquire);
        // exclusive lock, so require no readers and no writer
        if Self::has_writer(cur) || Self::has_readers(cur) {
            return false;
        }
        let desired = cur | Self::WRITER;
        self.0 // Safety: Failure here can be Relaxed as we will read again on next iteration.
            .compare_exchange(cur, desired, Ordering::Acquire, Ordering::Relaxed)
            .is_ok()
    }

    /// upgrade read lock to the write lock
    /// only possible if there is exactly single reader at the moment
    /// return true if lock was upgraded succesfully - and false otherwise
    #[inline]
    pub fn upgrade(&self) -> bool {
        let cur = self.0.load(Ordering::Acquire);
        // Check for single reader: exactly one reader, any value
        if (cur & !Self::VALUE_MASK) != Self::READER_INC {
            return false;
        }
        // Preserve value bits, replace reader with writer
        let desired = (cur & Self::VALUE_MASK) | Self::WRITER;
        self.0
            .compare_exchange(cur, desired, Ordering::Acquire, Ordering::Relaxed)
            .is_ok()
    }

    /// downgrade write lock to the read lock
    /// MUST be called for a lock acquired by the writer
    #[inline]
    pub fn downgrade(&self) {
        let cur = self.0.load(Ordering::Acquire);
        turso_debug_assert!(Self::has_writer(cur));
        // Preserve value bits, replace writer with one reader
        let desired = (cur & Self::VALUE_MASK) | Self::READER_INC;
        #[cfg(debug_assertions)]
        {
            let prev = self
                .0
                .compare_exchange(cur, desired, Ordering::AcqRel, Ordering::Relaxed);
            turso_debug_assert!(
                prev.is_ok(),
                "downgrade CAS failed — lock was mutated concurrently"
            );
        }
        #[cfg(not(debug_assertions))]
        {
            self.0.store(desired, Ordering::Release);
        }
    }

    #[inline]
    /// Unlock whatever lock is currently held.
    /// For write lock: clear writer bit
    /// For read lock: decrement reader count
    pub fn unlock(&self) {
        let cur = self.0.load(Ordering::Acquire);
        if (cur & Self::WRITER) != 0 {
            // Clear writer bit, preserve everything else (including value)
            // Release ordering ensures all our writes are visible to next acquirer
            let cur = self.0.fetch_and(!Self::WRITER, Ordering::Release);
            turso_assert!(!Self::has_readers(cur), "write lock was held with readers");
        } else {
            turso_assert!(
                Self::has_readers(cur),
                "unlock called with no readers or writers"
            );
            self.0.fetch_sub(Self::READER_INC, Ordering::Release);
        }
    }

    #[inline]
    /// Read the embedded 32-bit value atomically regardless of slot occupancy.
    pub fn get_value(&self) -> u32 {
        (self.0.load(Ordering::Acquire) >> Self::VALUE_SHIFT) as u32
    }

    #[inline]
    /// Set the embedded value while holding the write lock.
    pub fn set_value_exclusive(&self, v: u32) {
        // Must be called only while WRITER bit is set
        let cur = self.0.load(Ordering::Acquire);
        turso_assert!(Self::has_writer(cur), "must hold exclusive lock");
        let desired = (cur & !Self::VALUE_MASK) | ((v as u64) << Self::VALUE_SHIFT);
        self.0.store(desired, Ordering::Release);
    }
}

/// Represents a batch of WAL frames which will be appended to the log
/// with a `pwritev` call and then sync'd to disk.
pub struct PreparedFrames {
    /// File offset for the first frame
    pub offset: u64,
    /// Serialized frame buffers
    pub bufs: Vec<Arc<Buffer>>,
    /// Per-frame metadata: (page_ref, frame_id, cumulative_checksum)
    pub metadata: Vec<(PageRef, u64, (u32, u32))>,
    /// Checksum after all frames in this batch
    pub final_checksum: (u32, u32),
    /// Max frame ID after this batch
    pub final_max_frame: u64,
    /// Epoch at preparation time
    pub epoch: u32,
}

/// Metadata published by the coordination backend once a WAL commit becomes visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct WalCommitState {
    max_frame: u64,
    last_checksum: (u32, u32),
    transaction_count: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CoordinationCheckpointGuardKind {
    Read0,
    Writer,
}

/// Coordination operations that back the WAL's authoritative state.
trait WalCoordination: Debug + Send + Sync {
    /// Load the current authoritative WAL snapshot.
    fn load_snapshot(&self) -> WalSnapshot;

    /// Ensure any process-local fallback cache is complete for `snapshot`.
    fn ensure_local_frame_cache_covers(
        &self,
        _io: &Arc<dyn IO>,
        _snapshot: WalSnapshot,
    ) -> Result<()> {
        Ok(())
    }

    /// Publish a newly committed WAL state snapshot.
    fn publish_commit(&self, commit: WalCommitState);

    /// Publish the highest frame durably backfilled during checkpoint.
    fn publish_backfill(&self, max_frame: u64);

    /// Install any backend-specific durable proof before publishing backfill.
    /// Returns an optional completion that must finish before `publish_backfill`.
    fn install_durable_backfill_proof(
        &self,
        max_frame: u64,
        db_size_pages: u32,
        db_header_crc32c: u32,
        sync_type: FileSyncType,
    ) -> Result<Option<Completion>>;

    /// Find the newest frame for `page_id` within the caller's visible range.
    fn find_frame(
        &self,
        page_id: u64,
        min_frame: u64,
        max_frame: u64,
        frame_watermark: Option<u64>,
    ) -> Option<u64>;

    /// Enumerate the latest visible frame per page in the requested frame range.
    fn iter_latest_frames(&self, min_frame: u64, max_frame: u64) -> Vec<(u64, u64)>;

    /// Read the current checkpoint epoch used to tag cached WAL pages.
    fn checkpoint_epoch(&self) -> u32;

    /// Advance the checkpoint epoch after checkpoint or restart invalidates cached pages.
    fn bump_checkpoint_epoch(&self) -> u32;

    /// Try to acquire the reader protection needed for `snapshot`.
    fn try_begin_read_tx(&self, snapshot: WalSnapshot) -> Option<ReadGuardKind>;

    /// Release a read guard previously returned by `try_begin_read_tx`.
    fn end_read_tx(&self, guard: ReadGuardKind);

    /// Try to acquire the WAL writer guard.
    fn try_begin_write_tx(&self) -> bool;

    /// Release a previously acquired WAL writer guard.
    fn end_write_tx(&self);

    /// Acquire the checkpoint-related locks needed for `mode`.
    fn acquire_checkpoint_guard(
        &self,
        mode: CheckpointMode,
    ) -> Result<CoordinationCheckpointGuardKind>;

    /// Acquire the remaining checkpoint-related locks for VACUUM when the
    /// caller already owns the raw process-local checkpoint lock.
    ///
    /// On error, implementations must release that held checkpoint lock before
    /// returning.
    ///
    fn acquire_vacuum_checkpoint_guard_from_held_lock(
        &self,
    ) -> Result<CoordinationCheckpointGuardKind>;

    /// Release the checkpoint-related locks previously acquired for `guard`.
    fn release_checkpoint_guard(&self, guard: CoordinationCheckpointGuardKind);

    /// Compute the highest frame a checkpoint may safely backfill and refresh read marks.
    fn determine_max_safe_checkpoint_frame(&self, max_frame: u64) -> u64;

    /// Begin a restart while the caller holds the required external checkpoint/write guards.
    fn begin_restart(&self, io: &dyn IO) -> Result<WalSnapshot>;

    /// Release any restart-only coordination state held by `begin_restart`.
    fn end_restart(&self);

    /// Attempt the restart path used by a writer holding read-mark 0.
    fn try_restart_log_for_write(&self, io: &dyn IO) -> Result<Option<WalSnapshot>>;

    /// Mark the WAL uninitialized before truncation and return the WAL file handle.
    fn prepare_truncate(&self) -> Result<Arc<dyn File>>;

    /// Return the current WAL header snapshot.
    fn wal_header(&self) -> WalHeader;

    /// Return the WAL file used for durable reads and writes.
    fn wal_file(&self) -> Result<Arc<dyn File>>;

    /// Clone the shared WAL state backing this coordination backend.
    fn shared_wal_state(&self) -> Arc<RwLock<WalFileShared>>;

    /// Report whether the WAL header has already been written and synced.
    fn wal_is_initialized(&self) -> bool;

    /// Initialize or refresh the WAL header before the first append after restart/truncate.
    fn prepare_wal_header(&self, io: &dyn IO, page_size: PageSize) -> Option<WalHeader>;

    /// Mark the WAL header durable after the header sync completes.
    fn mark_initialized(&self);

    /// Record a newly appended frame in the backend's page-to-frame lookup state.
    fn cache_frame(&self, page_id: u64, frame_id: u64);

    /// Drop any cached frame mappings newer than `max_frame`.
    fn rollback_cache(&self, max_frame: u64);

    /// Whether a process-local "last connection" close may run shutdown checkpointing.
    fn should_checkpoint_on_close(&self) -> bool;

    #[cfg(test)]
    fn backend_name(&self) -> &'static str;

    #[cfg(test)]
    fn shared_ptr(&self) -> usize;

    #[cfg(test)]
    fn open_mode_name(&self) -> Option<&'static str> {
        None
    }
}

/// Write-ahead log (WAL).
pub trait Wal: Debug + Send + Sync {
    /// Begin a read transaction.
    /// Returns whether the database state has changed since the last read transaction.
    fn begin_read_tx(&self) -> Result<bool>;
    /// MVCC helper: check if WAL state changed without starting a read tx.
    fn mvcc_refresh_if_db_changed(&self) -> bool;

    /// Begin a write transaction.
    ///
    /// `allowed_auto_actions` controls which automatic WAL maintenance
    /// actions are permitted within this call — currently only
    /// `WalAutoActions::Restart` is consulted (it gates
    /// `try_restart_log_before_write`). Callers that own WAL state
    /// externally (e.g. the sync engine) pass an empty set to opt out.
    fn begin_write_tx(&self, allowed_auto_actions: WalAutoActions) -> Result<()>;

    /// End a read transaction.
    fn end_read_tx(&self);

    /// End a write transaction.
    fn end_write_tx(&self);

    /// Returns true if this WAL instance currently holds a read lock.
    fn holds_read_lock(&self) -> bool;

    /// Returns true if this WAL instance currently holds the write lock.
    fn holds_write_lock(&self) -> bool;

    /// Whether shutdown checkpointing is valid when this process closes its last connection.
    fn should_checkpoint_on_close(&self) -> bool;

    /// Find the latest frame containing a page.
    ///
    /// optional frame_watermark parameter can be passed to force WAL to find frame not larger than watermark value
    /// caller must guarantee, that frame_watermark must be greater than last checkpointed frame, otherwise method will panic
    fn find_frame(&self, page_id: u64, frame_watermark: Option<u64>) -> Result<Option<u64>>;

    /// Read a frame from the WAL.
    fn read_frame(
        &self,
        frame_id: u64,
        page: PageRef,
        buffer_pool: Arc<BufferPool>,
    ) -> Result<Completion>;

    /// Read a contiguous run of WAL frames with a single `pread`.
    /// For each `i`, `pages[i]` receives the decoded page body of frame
    /// `start_frame + i`. This method is a batched version of `read_frame`.
    ///
    /// If `scratch_buf` is `Some`, it is used as the pread destination (must
    /// have length exactly `(page_size + WAL_FRAME_HEADER_SIZE) * pages.len()`).
    /// Otherwise a fresh temporary buffer is allocated. VACUUM passes a
    /// pre-allocated buffer to amortize the ~batch-size allocation across
    /// batches.
    fn read_frames_batch(
        &self,
        start_frame: u64,
        pages: &[PageRef],
        buffer_pool: Arc<BufferPool>,
        scratch_buf: Option<Arc<Buffer>>,
    ) -> Result<Completion>;

    /// Read a raw frame (header included) from the WAL.
    fn read_frame_raw(&self, frame_id: u64, frame: &mut [u8]) -> Result<Completion>;

    /// Write a raw frame (header included) from the WAL.
    /// Note, that turso-db will use page_no and size_after fields from the header, but will overwrite checksum with proper value
    fn write_frame_raw(
        &self,
        buffer_pool: Arc<BufferPool>,
        frame_id: u64,
        page_id: u64,
        db_size: u64,
        page: &[u8],
        sync_type: FileSyncType,
    ) -> Result<()>;

    /// Prepare WAL header for the future append
    /// Most of the time this method will return Ok(None)
    fn prepare_wal_start(&self, page_sz: PageSize) -> Result<Option<Completion>>;

    fn prepare_wal_finish(&self, sync_type: FileSyncType) -> Result<Completion>;

    /// Prepare a batch of WAL frames for durable commit/append to the log.
    fn prepare_frames(
        &self,
        pages: &[PageRef],
        page_sz: PageSize,
        db_size_on_commit: Option<u32>,
        prev: Option<&PreparedFrames>,
    ) -> Result<PreparedFrames>;

    /// For each prepared frame, update in-memory WAL index and rolling checksum
    /// and advance max_frame to make committed frames visible to readers.
    fn commit_prepared_frames(&self, prepared: &[PreparedFrames]);

    /// Mark in-memory pages clean and set WAL tags after durable commit.
    fn finalize_committed_pages(&self, prepared: &[PreparedFrames]);

    /// Return a handle to the underlying File.
    fn wal_file(&self) -> Result<Arc<dyn File>>;

    /// Write a bunch of frames to the WAL.
    /// db_size is the database size in pages after the transaction finishes.
    /// db_size is set  -> last frame written in transaction
    /// db_size is none -> non-last frame written in transaction
    fn append_frames_vectored(&self, pages: Vec<PageRef>, page_sz: PageSize) -> Result<Completion>;

    /// Complete append of frames by updating shared wal state. Before this
    /// all changes were stored locally.
    fn finish_append_frames_commit(&self) -> Result<()>;

    fn should_checkpoint(&self) -> bool;
    fn checkpoint(&self, pager: &Pager, mode: CheckpointMode)
        -> Result<IOResult<CheckpointResult>>;
    fn install_durable_backfill_proof(
        &self,
        max_frame: u64,
        db_size_pages: u32,
        db_header_crc32c: u32,
        sync_type: FileSyncType,
    ) -> Result<Option<Completion>>;
    fn publish_backfill(&self, max_frame: u64);
    fn sync(&self, sync_type: FileSyncType) -> Result<Completion>;
    fn is_syncing(&self) -> bool;
    fn get_max_frame_in_wal(&self) -> u64;
    fn get_checkpoint_seq(&self) -> u32;
    fn get_max_frame(&self) -> u64;
    fn get_min_frame(&self) -> u64;
    fn rollback(&self, rollback_to: Option<RollbackTo>);
    fn abort_checkpoint(&self);
    fn get_last_checksum(&self) -> (u32, u32);

    /// Return unique set of pages changed **after** frame_watermark position and until current WAL session max_frame_no
    fn changed_pages_after(&self, frame_watermark: u64) -> Result<Vec<u32>>;

    fn set_io_context(&self, ctx: IOContext);

    /// Update the max frame to the current shared max frame.
    /// Currently this is only used for MVCC as it takes care of write conflicts on its own.
    /// This should't be used with regular WAL mode.
    fn update_max_frame(&self);

    /// Truncate WAL file to zero and sync it. This is called AFTER the DB file has been
    /// synced during TRUNCATE checkpoint mode, ensuring data durability.
    /// The result parameter is used to track I/O progress (wal_truncate_sent, wal_sync_sent).
    fn truncate_wal(
        &self,
        result: &mut CheckpointResult,
        sync_type: FileSyncType,
    ) -> Result<IOResult<()>>;

    /// Try to acquire the checkpoint serialization lock. Returns `Busy` if
    /// another checkpointer or VACUUM already holds it. Used by plain VACUUM
    /// to fail fast if a concurrent checkpoint would block later.
    fn try_begin_vacuum_checkpoint_lock(&self) -> Result<()>;

    /// Release the checkpoint serialization lock acquired by
    /// `try_begin_vacuum_checkpoint_lock`.
    fn release_vacuum_checkpoint_lock(&self);

    /// Acquire exclusive WAL access. This will block all new readers and writers. Also,
    /// this routine succeeds only if no other transactions are active. This is used by
    /// VACUUM routine.
    ///
    ///
    /// VACUUM: take `vacuum_lock` exclusively, take the WAL write lock, and install
    /// the source snapshot that VACUUM will copy from.
    ///
    /// This does not acquire a physical read-mark lock. The exclusive snapshot
    /// is protected by `vacuum_lock`: normal readers hold that lock shared for
    /// their read transaction, so once the exclusive lock is acquired no new
    /// normal reader or writer can enter.
    fn begin_vacuum_blocking_tx(&self) -> Result<()>;

    /// Checkpoint using a checkpoint lock already held by the caller. The
    /// method consumes that raw checkpoint-lock ownership: on success the guard
    /// is held by the checkpoint state machine, and on early failure it is
    /// released before returning.
    fn vacuum_checkpoint_with_held_lock(&self, pager: &Pager)
        -> Result<IOResult<CheckpointResult>>;

    /// Release the exclusive VACUUM lock acquired by `begin_vacuum_blocking_tx`.
    /// VACUUM calls this once done, after which new
    /// readers and writers may proceed again.
    fn release_vacuum_lock(&self);

    #[cfg(any(test, debug_assertions))]
    fn as_any(&self) -> &dyn std::any::Any;
}

#[derive(Debug)]
struct InProcessWalCoordination {
    shared: Arc<RwLock<WalFileShared>>,
}

impl InProcessWalCoordination {
    /// Build the in-process coordination backend over the existing shared WAL state.
    fn new(shared: Arc<RwLock<WalFileShared>>) -> Self {
        Self { shared }
    }

    fn try_read_mark_shared(&self, slot: usize) -> bool {
        self.shared.read().runtime.read_locks[slot].read()
    }

    fn try_read_mark_exclusive(&self, slot: usize) -> bool {
        self.shared.read().runtime.read_locks[slot].write()
    }

    fn unlock_read_mark(&self, slot: usize) {
        self.shared.read().runtime.read_locks[slot].unlock();
    }

    fn read_mark_value(&self, slot: usize) -> u32 {
        self.shared.read().runtime.read_locks[slot].get_value()
    }

    fn set_read_mark_value_exclusive(&self, slot: usize, value: u32) {
        self.shared.read().runtime.read_locks[slot].set_value_exclusive(value);
    }

    fn try_upgrade_read_mark(&self, slot: usize) -> bool {
        self.shared.read().runtime.read_locks[slot].upgrade()
    }

    fn downgrade_read_mark(&self, slot: usize) {
        self.shared.read().runtime.read_locks[slot].downgrade();
    }

    fn try_write_lock(&self) -> bool {
        self.shared.read().runtime.write_lock.write()
    }

    fn unlock_write_lock(&self) {
        self.shared.read().runtime.write_lock.unlock();
    }

    fn try_checkpoint_lock(&self) -> bool {
        self.shared.read().runtime.checkpoint_lock.write()
    }

    fn unlock_checkpoint_lock(&self) {
        self.shared.read().runtime.checkpoint_lock.unlock();
    }
}

impl WalCoordination for InProcessWalCoordination {
    fn load_snapshot(&self) -> WalSnapshot {
        let shared = self.shared.read();
        let checkpoint_seq = shared.metadata.wal_header.lock().checkpoint_seq;
        WalSnapshot {
            max_frame: shared.metadata.max_frame.load(Ordering::Acquire),
            nbackfills: shared.metadata.nbackfills.load(Ordering::Acquire),
            last_checksum: shared.metadata.last_checksum,
            checkpoint_seq,
            transaction_count: shared.metadata.transaction_count.load(Ordering::Acquire),
        }
    }

    fn publish_commit(&self, commit: WalCommitState) {
        let mut shared = self.shared.write();
        shared
            .metadata
            .max_frame
            .store(commit.max_frame, Ordering::Release);
        shared.metadata.last_checksum = commit.last_checksum;
        shared
            .metadata
            .transaction_count
            .store(commit.transaction_count, Ordering::Release);
    }

    fn publish_backfill(&self, max_frame: u64) {
        self.shared
            .write()
            .metadata
            .nbackfills
            .store(max_frame, Ordering::Release);
    }

    fn install_durable_backfill_proof(
        &self,
        _max_frame: u64,
        _db_size_pages: u32,
        _db_header_crc32c: u32,
        _sync_type: FileSyncType,
    ) -> Result<Option<Completion>> {
        Ok(None)
    }

    fn find_frame(
        &self,
        page_id: u64,
        min_frame: u64,
        max_frame: u64,
        frame_watermark: Option<u64>,
    ) -> Option<u64> {
        let shared = self.shared.read();
        let frame_cache = shared.runtime.frame_cache.lock();
        let range = frame_watermark
            .map(|x| 0..=x)
            .unwrap_or(min_frame..=max_frame);
        frame_cache.get(&page_id).and_then(|frames| {
            frames
                .iter()
                .rfind(|&&frame| range.contains(&frame))
                .copied()
        })
    }

    fn iter_latest_frames(&self, min_frame: u64, max_frame: u64) -> Vec<(u64, u64)> {
        let shared = self.shared.read();
        let frame_cache = shared.runtime.frame_cache.lock();
        let mut list = Vec::with_capacity(frame_cache.len());
        for (&page_id, frames) in frame_cache.iter() {
            if let Some(&frame_id) = frames
                .iter()
                .rfind(|&&frame| (min_frame..=max_frame).contains(&frame))
            {
                list.push((page_id, frame_id));
            }
        }
        list.sort_unstable_by_key(|&(page_id, _)| page_id);
        list
    }

    fn checkpoint_epoch(&self) -> u32 {
        self.shared.read().runtime.epoch.load(Ordering::Acquire)
    }

    fn bump_checkpoint_epoch(&self) -> u32 {
        self.shared
            .read()
            .runtime
            .epoch
            .fetch_add(1, Ordering::Release)
    }

    fn try_begin_read_tx(&self, snapshot: WalSnapshot) -> Option<ReadGuardKind> {
        turso_assert!(
            snapshot.max_frame <= u32::MAX as u64,
            "max_frame exceeds u32 read mark range"
        );
        if snapshot.max_frame == snapshot.nbackfills {
            if !self.try_read_mark_shared(0) {
                return None;
            }
            if self.load_snapshot() != snapshot {
                self.unlock_read_mark(0);
                return None;
            }
            return Some(ReadGuardKind::DbFile);
        }

        let mut best_idx: i64 = -1;
        let mut best_mark: u32 = 0;
        for idx in 1..5 {
            let mark = self.read_mark_value(idx);
            if mark != READMARK_NOT_USED && mark <= snapshot.max_frame as u32 && mark > best_mark {
                best_mark = mark;
                best_idx = idx as i64;
            }
        }

        if best_idx == -1 || (best_mark as u64) < snapshot.max_frame {
            for idx in 1..5 {
                if !self.try_read_mark_exclusive(idx) {
                    continue;
                }
                self.set_read_mark_value_exclusive(idx, snapshot.max_frame as u32);
                best_idx = idx as i64;
                best_mark = snapshot.max_frame as u32;
                self.unlock_read_mark(idx);
                break;
            }
        }

        if best_idx == -1 || !self.try_read_mark_shared(best_idx as usize) {
            return None;
        }

        let snapshot_after_lock = self.load_snapshot();
        let current_slot_mark = self.read_mark_value(best_idx as usize);
        if current_slot_mark != best_mark || snapshot_after_lock != snapshot {
            self.unlock_read_mark(best_idx as usize);
            return None;
        }

        Some(ReadGuardKind::ReadMark(
            NonZeroUsize::new(best_idx as usize)
                .expect("best_idx checked to be non-negative and non-zero"),
        ))
    }

    fn end_read_tx(&self, guard: ReadGuardKind) {
        match guard {
            ReadGuardKind::None => {}
            ReadGuardKind::DbFile => self.unlock_read_mark(0),
            ReadGuardKind::ReadMark(slot) => self.unlock_read_mark(slot.into()),
        }
    }

    fn try_begin_write_tx(&self) -> bool {
        self.try_write_lock()
    }

    fn end_write_tx(&self) {
        self.unlock_write_lock();
    }

    fn acquire_checkpoint_guard(
        &self,
        mode: CheckpointMode,
    ) -> Result<CoordinationCheckpointGuardKind> {
        if !self.try_checkpoint_lock() {
            tracing::trace!("CheckpointGuard::new: checkpoint lock failed, returning Busy");
            return Err(LimboError::Busy);
        }
        match mode {
            CheckpointMode::Passive { .. } => {
                if !self.try_read_mark_exclusive(0) {
                    self.unlock_checkpoint_lock();
                    tracing::trace!("CheckpointGuard: read0 lock failed, returning Busy");
                    return Err(LimboError::Busy);
                }
                Ok(CoordinationCheckpointGuardKind::Read0)
            }
            CheckpointMode::Full => {
                if !self.try_read_mark_exclusive(0) {
                    self.unlock_checkpoint_lock();
                    tracing::trace!("CheckpointGuard: read0 lock failed (Full), Busy");
                    return Err(LimboError::Busy);
                }
                if !self.try_write_lock() {
                    self.unlock_read_mark(0);
                    self.unlock_checkpoint_lock();
                    tracing::trace!("CheckpointGuard: write lock failed (Full), Busy");
                    return Err(LimboError::Busy);
                }
                Ok(CoordinationCheckpointGuardKind::Writer)
            }
            CheckpointMode::Restart | CheckpointMode::Truncate { .. } => {
                if !self.try_read_mark_exclusive(0) {
                    self.unlock_checkpoint_lock();
                    tracing::trace!("CheckpointGuard: read0 lock failed, returning Busy");
                    return Err(LimboError::Busy);
                }
                if !self.try_write_lock() {
                    self.unlock_checkpoint_lock();
                    self.unlock_read_mark(0);
                    tracing::trace!("CheckpointGuard: write lock failed, returning Busy");
                    return Err(LimboError::Busy);
                }
                Ok(CoordinationCheckpointGuardKind::Writer)
            }
        }
    }

    fn acquire_vacuum_checkpoint_guard_from_held_lock(
        &self,
    ) -> Result<CoordinationCheckpointGuardKind> {
        if !self.try_read_mark_exclusive(0) {
            self.unlock_checkpoint_lock();
            tracing::trace!("CheckpointGuard: held VACUUM read0 lock failed, returning Busy");
            return Err(LimboError::Busy);
        }
        if !self.try_write_lock() {
            self.unlock_read_mark(0);
            self.unlock_checkpoint_lock();
            tracing::trace!("CheckpointGuard: held VACUUM write lock failed, returning Busy");
            return Err(LimboError::Busy);
        }
        Ok(CoordinationCheckpointGuardKind::Writer)
    }

    fn release_checkpoint_guard(&self, guard: CoordinationCheckpointGuardKind) {
        match guard {
            CoordinationCheckpointGuardKind::Writer => {
                self.unlock_write_lock();
                self.unlock_read_mark(0);
                self.unlock_checkpoint_lock();
            }
            CoordinationCheckpointGuardKind::Read0 => {
                self.unlock_read_mark(0);
                self.unlock_checkpoint_lock();
            }
        }
    }

    fn determine_max_safe_checkpoint_frame(&self, max_frame: u64) -> u64 {
        turso_assert!(
            max_frame <= u32::MAX as u64,
            "max_frame exceeds u32 read mark range"
        );
        let mut max_safe_frame = max_frame;
        for read_lock_idx in 1..5 {
            let this_mark = self.read_mark_value(read_lock_idx);
            if this_mark < max_safe_frame as u32 {
                let busy = !self.try_read_mark_exclusive(read_lock_idx);
                if !busy {
                    let val = if read_lock_idx == 1 {
                        max_safe_frame as u32
                    } else {
                        READMARK_NOT_USED
                    };
                    self.set_read_mark_value_exclusive(read_lock_idx, val);
                    self.unlock_read_mark(read_lock_idx);
                } else {
                    max_safe_frame = this_mark as u64;
                }
            }
        }
        max_safe_frame
    }

    fn begin_restart(&self, io: &dyn IO) -> Result<WalSnapshot> {
        for idx in 1..5 {
            if !self.try_read_mark_exclusive(idx) {
                for j in 1..idx {
                    self.unlock_read_mark(j);
                }
                return Err(LimboError::Busy);
            }
            self.set_read_mark_value_exclusive(idx, READMARK_NOT_USED);
        }
        let mut shared = self.shared.write();
        shared.restart_wal_header(io);
        let checkpoint_seq = shared.metadata.wal_header.lock().checkpoint_seq;
        Ok(WalSnapshot {
            max_frame: shared.metadata.max_frame.load(Ordering::Acquire),
            nbackfills: shared.metadata.nbackfills.load(Ordering::Acquire),
            last_checksum: shared.metadata.last_checksum,
            checkpoint_seq,
            transaction_count: shared.metadata.transaction_count.load(Ordering::Acquire),
        })
    }

    fn end_restart(&self) {
        for idx in 1..5 {
            self.unlock_read_mark(idx);
        }
    }

    fn try_restart_log_for_write(&self, io: &dyn IO) -> Result<Option<WalSnapshot>> {
        if !self.try_upgrade_read_mark(0) {
            return Ok(None);
        }
        let result = self.begin_restart(io);
        self.downgrade_read_mark(0);
        match result {
            Ok(snapshot) => {
                self.end_restart();
                Ok(Some(snapshot))
            }
            Err(err) => Err(err),
        }
    }

    fn prepare_truncate(&self) -> Result<Arc<dyn File>> {
        let shared = self.shared.read();
        turso_assert!(
            shared.metadata.enabled.load(Ordering::Relaxed),
            "WAL must be enabled"
        );
        shared.metadata.initialized.store(false, Ordering::Release);
        shared.runtime.file.as_ref().cloned().ok_or_else(|| {
            mark_unlikely();
            LimboError::InternalError("WAL file not open".into())
        })
    }

    fn wal_header(&self) -> WalHeader {
        *self.shared.read().metadata.wal_header.lock()
    }

    fn wal_file(&self) -> Result<Arc<dyn File>> {
        let shared = self.shared.read();
        turso_assert!(
            shared.metadata.enabled.load(Ordering::Relaxed),
            "WAL must be enabled"
        );
        shared.runtime.file.as_ref().cloned().ok_or_else(|| {
            mark_unlikely();
            LimboError::InternalError("WAL file not open".into())
        })
    }

    fn wal_is_initialized(&self) -> bool {
        self.shared
            .read()
            .metadata
            .initialized
            .load(Ordering::Acquire)
    }

    fn prepare_wal_header(&self, io: &dyn IO, page_size: PageSize) -> Option<WalHeader> {
        let mut shared: crate::sync::RwLockWriteGuard<'_, WalFileShared> = self.shared.write();
        if shared.metadata.initialized.load(Ordering::Acquire) {
            return None;
        }

        let (header, checksum) = {
            let mut hdr = shared.metadata.wal_header.lock();
            hdr.magic = if cfg!(target_endian = "big") {
                WAL_MAGIC_BE
            } else {
                WAL_MAGIC_LE
            };
            if hdr.page_size == 0 {
                hdr.page_size = page_size.get();
            }
            if hdr.salt_1 == 0 && hdr.salt_2 == 0 {
                hdr.salt_1 = io.generate_random_number() as u32;
                hdr.salt_2 = io.generate_random_number() as u32;
            }

            let prefix = &hdr.as_bytes()[..WAL_HEADER_SIZE - 8];
            let use_native = (hdr.magic & 1) != 0;
            let (c1, c2) = checksum_wal(prefix, &hdr, (0, 0), use_native);
            hdr.checksum_1 = c1;
            hdr.checksum_2 = c2;
            (*hdr, (c1, c2))
        };
        shared.metadata.last_checksum = checksum;
        Some(header)
    }

    fn mark_initialized(&self) {
        self.shared
            .read()
            .metadata
            .initialized
            .store(true, Ordering::Release);
    }

    fn cache_frame(&self, page_id: u64, frame_id: u64) {
        let shared = self.shared.read();
        let mut frame_cache = shared.runtime.frame_cache.lock();
        match frame_cache.get_mut(&page_id) {
            Some(frames) => {
                frames.push(frame_id);
            }
            None => {
                frame_cache.insert(page_id, vec![frame_id]);
            }
        }
    }

    fn rollback_cache(&self, max_frame: u64) {
        let shared = self.shared.read();
        let mut frame_cache = shared.runtime.frame_cache.lock();
        frame_cache.retain(|_page_id, frames| {
            while frames.last().is_some_and(|&frame| frame > max_frame) {
                frames.pop();
            }
            !frames.is_empty()
        });
    }

    fn should_checkpoint_on_close(&self) -> bool {
        true
    }

    #[cfg(test)]
    fn backend_name(&self) -> &'static str {
        "in_process"
    }

    #[cfg(test)]
    fn shared_ptr(&self) -> usize {
        Arc::as_ptr(&self.shared) as usize
    }

    fn shared_wal_state(&self) -> Arc<RwLock<WalFileShared>> {
        self.shared.clone()
    }
}

/// Per-connection WAL coordination that delegates to the mmap'd tshm authority.
///
/// One instance exists per `WalFile` (i.e. per `Connection`). All instances
/// within a process share the same `Arc<MappedSharedWalCoordination>` and the
/// same `SharedOwnerRecord` (derived from the authority at construction time).
///
/// `fallback` provides the process-local read-mark / write-lock layer (the
/// same locks used in single-process mode). `authority` provides the
/// cross-process shared state (reader slots, frame index, snapshot metadata).
/// Both are consulted: the fallback serializes same-process connections, the
/// authority serializes across processes.
#[cfg(host_shared_wal)]
#[derive(Debug)]
struct ShmWalCoordination {
    shared: Arc<RwLock<WalFileShared>>,
    fallback: InProcessWalCoordination,
    authority: Arc<MappedSharedWalCoordination>,
    /// This connection's currently held reader slot, if any.
    active_reader: Mutex<Option<SharedReaderSlot>>,
    /// Copied from `authority.owner_record()` at construction — all connections
    /// in the same process share the same owner identity.
    owner: SharedOwnerRecord,
}

#[cfg(host_shared_wal)]
impl ShmWalCoordination {
    fn overflow_fallback_covers(
        &self,
        snapshot: SharedWalCoordinationHeader,
        max_frame: u64,
    ) -> bool {
        self.shared
            .read()
            .runtime
            .overflow_fallback_coverage
            .lock()
            .covers(snapshot, max_frame)
    }

    fn clear_overflow_fallback_coverage(&self) {
        self.shared
            .read()
            .runtime
            .overflow_fallback_coverage
            .lock()
            .clear();
    }

    fn local_authority_snapshot_from_shared(
        shared: &WalFileShared,
        authority_snapshot: SharedWalCoordinationHeader,
    ) -> SharedWalCoordinationHeader {
        let header = shared.metadata.wal_header.lock();
        SharedWalCoordinationHeader {
            max_frame: shared.metadata.max_frame.load(Ordering::Acquire),
            nbackfills: shared.metadata.nbackfills.load(Ordering::Acquire),
            transaction_count: shared.metadata.transaction_count.load(Ordering::Acquire),
            visibility_generation: authority_snapshot.visibility_generation,
            checkpoint_seq: header.checkpoint_seq,
            checkpoint_epoch: shared.runtime.epoch.load(Ordering::Acquire),
            page_size: header.page_size,
            salt_1: header.salt_1,
            salt_2: header.salt_2,
            checksum_1: shared.metadata.last_checksum.0,
            checksum_2: shared.metadata.last_checksum.1,
            reader_slot_count: authority_snapshot.reader_slot_count,
        }
    }

    fn new(
        shared: Arc<RwLock<WalFileShared>>,
        authority: Arc<MappedSharedWalCoordination>,
    ) -> Self {
        let fallback = InProcessWalCoordination::new(shared.clone());
        let coordination = Self {
            shared,
            fallback,
            owner: authority.owner_record(),
            authority,
            active_reader: Mutex::new(None),
        };
        coordination.seed_or_sync_authority();
        coordination
    }

    fn authority_is_uninitialized(snapshot: SharedWalCoordinationHeader) -> bool {
        snapshot.max_frame == 0
            && snapshot.nbackfills == 0
            && snapshot.transaction_count == 0
            && snapshot.visibility_generation == 0
            && snapshot.checkpoint_seq == 0
            && snapshot.checkpoint_epoch == 0
            && snapshot.page_size == 0
            && snapshot.salt_1 == 0
            && snapshot.salt_2 == 0
            && snapshot.checksum_1 == 0
            && snapshot.checksum_2 == 0
    }

    fn local_authority_snapshot(&self) -> SharedWalCoordinationHeader {
        let authority_snapshot = self.authority.snapshot();
        let shared = self.shared.read();
        Self::local_authority_snapshot_from_shared(&shared, authority_snapshot)
    }

    fn install_local_snapshot(
        shared: &mut WalFileShared,
        snapshot: SharedWalCoordinationHeader,
        install_header: bool,
    ) {
        shared
            .metadata
            .max_frame
            .store(snapshot.max_frame, Ordering::Release);
        shared
            .metadata
            .nbackfills
            .store(snapshot.nbackfills, Ordering::Release);
        shared.metadata.last_checksum = (snapshot.checksum_1, snapshot.checksum_2);
        shared
            .metadata
            .transaction_count
            .store(snapshot.transaction_count, Ordering::Release);
        shared
            .runtime
            .epoch
            .store(snapshot.checkpoint_epoch, Ordering::Release);
        if install_header {
            let mut header = shared.metadata.wal_header.lock();
            header.checkpoint_seq = snapshot.checkpoint_seq;
            header.page_size = snapshot.page_size;
            header.salt_1 = snapshot.salt_1;
            header.salt_2 = snapshot.salt_2;
            header.checksum_1 = snapshot.checksum_1;
            header.checksum_2 = snapshot.checksum_2;
        }
    }

    fn sync_local_from_authority(&self, snapshot: SharedWalCoordinationHeader) {
        let mut shared = self.shared.write();
        Self::install_local_snapshot(&mut shared, snapshot, snapshot.page_size != 0);
    }

    fn sync_authority_from_local(&self) {
        self.authority
            .install_snapshot(self.local_authority_snapshot());
    }

    fn sync_local_to_zero_frame_authority(&self, snapshot: SharedWalCoordinationHeader) {
        let mut shared = self.shared.write();
        Self::install_local_snapshot(&mut shared, snapshot, true);
        shared.metadata.initialized.store(false, Ordering::Release);
        shared.runtime.frame_cache.lock().clear();
        shared.runtime.overflow_fallback_coverage.lock().clear();
    }

    fn sync_authority_frames_from_local(&self) {
        let entries = {
            let shared = self.shared.read();
            let frame_cache = shared.runtime.frame_cache.lock();
            let mut entries = Vec::new();
            for (&page_id, frames) in frame_cache.iter() {
                for &frame_id in frames {
                    entries.push((frame_id, page_id));
                }
            }
            entries
        };
        let mut entries = entries;
        entries.sort_unstable();
        for (frame_id, page_id) in entries {
            self.authority.record_frame(page_id, frame_id);
        }
    }

    fn repair_or_reseed_authority_from_local_disk_scan(
        &self,
        mut authority_snapshot: SharedWalCoordinationHeader,
    ) {
        self.authority.repair_transient_state_for_exclusive_open();
        if authority_snapshot.nbackfills != 0 {
            // A local WAL scan can rebuild the visible WAL tail, but it cannot
            // prove that positive checkpoint progress is durable in the main DB
            // file. Stay on the conservative reopen path until we implement a
            // SQLite-equivalent recovery protocol for trusting partial-checkpoint state.
            authority_snapshot.nbackfills = 0;
            self.authority.install_snapshot(authority_snapshot);
        }
        let local_snapshot = self.local_authority_snapshot();
        if Self::local_scan_predates_zero_frame_authority(authority_snapshot, local_snapshot) {
            self.sync_local_to_zero_frame_authority(authority_snapshot);
            return;
        }
        if Self::local_scan_cannot_disprove_zero_frame_authority(authority_snapshot, local_snapshot)
        {
            self.sync_local_from_authority(authority_snapshot);
            return;
        }
        if Self::local_scan_cannot_disprove_positive_authority(authority_snapshot, local_snapshot) {
            self.sync_local_from_authority(authority_snapshot);
            return;
        }
        if Self::authority_matches_local_wal_scan(authority_snapshot, local_snapshot) {
            self.sync_local_from_authority(authority_snapshot);
            // Matching header metadata is not enough to trust the durable
            // frame index. A restart or interrupted reopen can leave stale or
            // empty page->frame mappings behind while max_frame/checksums
            // still match the scanned WAL. When both snapshots describe the
            // same visible WAL generation, compare the latest per-page
            // mappings directly and rebuild if they diverge.
            if self.authority.frame_index_overflowed()
                || (self.authority.open_mode() == SharedWalCoordinationOpenMode::Exclusive
                    && !self.authority_frame_index_matches_local_wal_scan(local_snapshot.max_frame))
            {
                self.authority
                    .discard_durable_frame_index_for_exclusive_rebuild();
                self.sync_authority_frames_from_local();
            }
            return;
        }
        // The authority and disk scan are from the same generation (matching
        // checkpoint_seq/salts) but disagree on max_frame or checksums. This
        // happens when a concurrent write advances the authority between the
        // snapshot read and the disk scan.  Or the authority is from a strictly
        // newer generation (higher checkpoint_seq) because the WAL was
        // restarted but the on-disk header hasn't been rewritten yet.
        //
        // In both cases the authority's header fields are at least as current
        // as the disk, so adopt them.  As above, preserve the authority's
        // frame index — it is maintained by writers and must not be replaced
        // with a potentially incomplete reconstruction.
        if Self::authority_is_same_or_newer_generation(authority_snapshot, local_snapshot) {
            self.sync_local_from_authority(authority_snapshot);
            if authority_snapshot.checkpoint_seq == local_snapshot.checkpoint_seq
                && self.authority.frame_index_overflowed()
            {
                self.authority
                    .discard_durable_frame_index_for_exclusive_rebuild();
                self.sync_authority_frames_from_local();
            }
            return;
        }

        self.authority
            .discard_durable_frame_index_for_exclusive_rebuild();
        self.sync_authority_from_local();
        self.sync_authority_frames_from_local();
    }

    fn local_scan_cannot_disprove_zero_frame_authority(
        authority_snapshot: SharedWalCoordinationHeader,
        local_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        !Self::authority_is_uninitialized(authority_snapshot)
            && authority_snapshot.max_frame == 0
            && local_snapshot.max_frame == 0
    }

    fn local_scan_predates_zero_frame_authority(
        authority_snapshot: SharedWalCoordinationHeader,
        local_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        !Self::authority_is_uninitialized(authority_snapshot)
            && authority_snapshot.max_frame == 0
            && local_snapshot.max_frame > 0
            && local_snapshot.checkpoint_seq < authority_snapshot.checkpoint_seq
    }

    fn local_scan_cannot_disprove_positive_authority(
        authority_snapshot: SharedWalCoordinationHeader,
        local_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        authority_snapshot.max_frame > 0
            && local_snapshot.max_frame == 0
            && local_snapshot.checkpoint_seq == authority_snapshot.checkpoint_seq
            && local_snapshot.page_size == authority_snapshot.page_size
            && local_snapshot.salt_1 == authority_snapshot.salt_1
            && local_snapshot.salt_2 == authority_snapshot.salt_2
    }

    /// The authority is from a strictly newer WAL generation (higher
    /// checkpoint_seq), OR from the same generation with at least as many
    /// frames.  In either case the authority's header fields were updated
    /// atomically by writers and are at least as current as a point-in-time
    /// disk scan of the WAL file.
    ///
    /// When the generations match but the authority has a *lower* max_frame,
    /// the authority was likely rolled back or corrupted; the disk scan's
    /// higher max_frame is more accurate, so we must NOT match here.
    fn authority_is_same_or_newer_generation(
        authority_snapshot: SharedWalCoordinationHeader,
        local_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        if Self::authority_is_uninitialized(authority_snapshot) {
            return false;
        }
        // Strictly newer generation — always trust authority.
        if authority_snapshot.checkpoint_seq > local_snapshot.checkpoint_seq {
            return true;
        }
        // Same generation: the authority is atomically updated by writers,
        // so its max_frame is at least as current as what the disk scan
        // observed.  Only match when authority.max_frame >= local to
        // avoid masking a genuinely rolled-back authority.
        authority_snapshot.checkpoint_seq == local_snapshot.checkpoint_seq
            && authority_snapshot.salt_1 == local_snapshot.salt_1
            && authority_snapshot.salt_2 == local_snapshot.salt_2
            && authority_snapshot.max_frame >= local_snapshot.max_frame
    }

    fn authority_matches_local_wal_scan(
        authority_snapshot: SharedWalCoordinationHeader,
        local_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        authority_snapshot.max_frame == local_snapshot.max_frame
            && authority_snapshot.checkpoint_seq == local_snapshot.checkpoint_seq
            && authority_snapshot.page_size == local_snapshot.page_size
            && authority_snapshot.salt_1 == local_snapshot.salt_1
            && authority_snapshot.salt_2 == local_snapshot.salt_2
            && authority_snapshot.checksum_1 == local_snapshot.checksum_1
            && authority_snapshot.checksum_2 == local_snapshot.checksum_2
    }

    fn authority_frame_index_matches_local_wal_scan(&self, max_frame: u64) -> bool {
        self.authority.iter_latest_frames(0, max_frame)
            == self.fallback.iter_latest_frames(0, max_frame)
    }

    fn local_zero_frame_generation_is_initialized(
        &self,
        authority_snapshot: SharedWalCoordinationHeader,
    ) -> bool {
        let shared = self.shared.read();
        if !shared.metadata.initialized.load(Ordering::Acquire) {
            return false;
        }
        Self::local_zero_frame_generation_matches_authority_snapshot(authority_snapshot, &shared)
    }

    fn local_zero_frame_generation_matches_authority_snapshot(
        authority_snapshot: SharedWalCoordinationHeader,
        shared: &WalFileShared,
    ) -> bool {
        let header = shared.metadata.wal_header.lock();
        header.checkpoint_seq == authority_snapshot.checkpoint_seq
            && header.page_size == authority_snapshot.page_size
            && header.salt_1 == authority_snapshot.salt_1
            && header.salt_2 == authority_snapshot.salt_2
    }

    fn authority_needs_local_header_seed(snapshot: SharedWalCoordinationHeader) -> bool {
        Self::authority_is_uninitialized(snapshot) || snapshot.page_size == 0
    }

    /// Called once at `ShmWalCoordination` construction to reconcile the
    /// process-local WAL view (built from a WAL file scan or inherited from
    /// a previous connection) with the shared tshm authority.
    ///
    /// Three cases:
    ///
    /// 1. **Authority uninitialized** (fresh tshm): seed it from our local
    ///    WAL scan — we are the first process.
    ///
    /// 2. **Authority initialized and we opened from a local disk scan**
    ///    (no writer/checkpoint is active): repair transient owner/reader
    ///    state first. If the scan only sees an empty WAL and the durable
    ///    authority is already at frame 0, keep the durable authority because
    ///    the scan cannot prove newer header metadata. Otherwise, if the
    ///    local scan agrees with the WAL-provable subset of the durable
    ///    snapshot, keep the durable authority. If not, discard the durable
    ///    frame index and rebuild it from the local scan.
    ///
    /// 3. **Authority initialized and trustworthy**: adopt the authority's
    ///    snapshot as our local state. If our local view also came from a
    ///    disk scan and the authority's frame index is empty, backfill it
    ///    from our local frame cache.
    fn seed_or_sync_authority(&self) {
        let snapshot = self.authority.snapshot();
        let local_wal_view_loaded_from_disk = self
            .shared
            .read()
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire);
        if Self::authority_is_uninitialized(snapshot) {
            self.sync_authority_from_local();
            self.sync_authority_frames_from_local();
        } else if local_wal_view_loaded_from_disk
            && !self.authority.writer_or_checkpoint_lock_active()
        {
            self.repair_or_reseed_authority_from_local_disk_scan(snapshot);
        } else {
            let needs_zero_frame_header_rewrite = snapshot.max_frame == 0 && {
                let shared = self.shared.read();
                !shared.metadata.initialized.load(Ordering::Acquire)
                    || !Self::local_zero_frame_generation_matches_authority_snapshot(
                        snapshot, &shared,
                    )
            };
            self.sync_local_from_authority(snapshot);
            if needs_zero_frame_header_rewrite {
                self.shared
                    .read()
                    .metadata
                    .initialized
                    .store(false, Ordering::Release);
            }
            if local_wal_view_loaded_from_disk
                && !self.authority.writer_or_checkpoint_lock_active()
                && self.authority.iter_latest_frames(0, u64::MAX).is_empty()
            {
                self.sync_authority_frames_from_local();
            }
        }
    }

    fn restart_snapshot_from_authority(
        &self,
        snapshot: SharedWalCoordinationHeader,
        io: &dyn IO,
    ) -> WalSnapshot {
        let checkpoint_seq = snapshot.checkpoint_seq.wrapping_add(1);
        let salt_1 = snapshot.salt_1.wrapping_add(1);
        let salt_2 = io.generate_random_number() as u32;
        let restarted = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: snapshot.transaction_count,
            visibility_generation: snapshot.visibility_generation,
            checkpoint_seq,
            checkpoint_epoch: snapshot.checkpoint_epoch,
            page_size: snapshot.page_size,
            salt_1,
            salt_2,
            checksum_1: snapshot.checksum_1,
            checksum_2: snapshot.checksum_2,
            reader_slot_count: snapshot.reader_slot_count,
        };

        {
            let mut shared = self.shared.write();
            Self::install_local_snapshot(&mut shared, restarted, true);
            shared.metadata.initialized.store(false, Ordering::Release);
            shared.runtime.frame_cache.lock().clear();
            shared.runtime.overflow_fallback_coverage.lock().clear();
            shared.runtime.read_locks[0].set_value_exclusive(0);
            shared.runtime.read_locks[1].set_value_exclusive(0);
            for lock in &shared.runtime.read_locks[2..] {
                lock.set_value_exclusive(READMARK_NOT_USED);
            }
        }

        self.authority.rollback_frames(0);
        self.authority.install_snapshot(restarted);

        WalSnapshot {
            max_frame: restarted.max_frame,
            nbackfills: restarted.nbackfills,
            last_checksum: (restarted.checksum_1, restarted.checksum_2),
            checkpoint_seq: restarted.checkpoint_seq,
            transaction_count: restarted.transaction_count,
        }
    }

    fn ensure_local_frame_cache_covers_snapshot(
        &self,
        io: &Arc<dyn IO>,
        required_snapshot: WalSnapshot,
    ) -> Result<()> {
        if required_snapshot.max_frame == 0 || !self.authority.frame_index_overflowed() {
            return Ok(());
        }

        let authority_snapshot = self.authority.snapshot();
        if authority_snapshot.checkpoint_seq != required_snapshot.checkpoint_seq {
            return Err(LimboError::Busy);
        }
        if self.overflow_fallback_covers(authority_snapshot, required_snapshot.max_frame) {
            return Ok(());
        }

        let _ = io;
        tracing::debug!(
            required_max_frame = required_snapshot.max_frame,
            authority_max_frame = authority_snapshot.max_frame,
            authority_checkpoint_seq = authority_snapshot.checkpoint_seq,
            "refusing live overflow fallback refresh on a read path because it would require blocking WAL scan I/O"
        );
        Err(LimboError::Busy)
    }
}

#[cfg(host_shared_wal)]
impl WalCoordination for ShmWalCoordination {
    fn load_snapshot(&self) -> WalSnapshot {
        let snapshot = self.authority.snapshot();
        WalSnapshot {
            max_frame: snapshot.max_frame,
            nbackfills: snapshot.nbackfills,
            last_checksum: (snapshot.checksum_1, snapshot.checksum_2),
            checkpoint_seq: snapshot.checkpoint_seq,
            transaction_count: snapshot.transaction_count,
        }
    }

    fn ensure_local_frame_cache_covers(
        &self,
        io: &Arc<dyn IO>,
        snapshot: WalSnapshot,
    ) -> Result<()> {
        self.ensure_local_frame_cache_covers_snapshot(io, snapshot)
    }

    fn publish_commit(&self, commit: WalCommitState) {
        {
            let mut shared = self.shared.write();
            shared
                .metadata
                .max_frame
                .store(commit.max_frame, Ordering::Release);
            shared.metadata.last_checksum = commit.last_checksum;
            shared
                .metadata
                .transaction_count
                .store(commit.transaction_count, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.checksum_1 = commit.last_checksum.0;
            header.checksum_2 = commit.last_checksum.1;
        }
        self.authority.publish_commit(
            commit.max_frame,
            commit.last_checksum.0,
            commit.last_checksum.1,
            commit.transaction_count,
        );
        if self.authority.frame_index_overflowed() {
            let snapshot = self.authority.snapshot();
            let shared = self.shared.read();
            let mut coverage = shared.runtime.overflow_fallback_coverage.lock();
            if coverage.covers(snapshot, commit.max_frame.saturating_sub(1)) {
                coverage.record_snapshot(snapshot, commit.max_frame);
            }
        }
    }

    fn publish_backfill(&self, max_frame: u64) {
        self.shared
            .write()
            .metadata
            .nbackfills
            .store(max_frame, Ordering::Release);
        self.authority.publish_backfill(max_frame);
    }

    fn install_durable_backfill_proof(
        &self,
        nbackfills: u64,
        db_size_pages: u32,
        db_header_crc32c: u32,
        sync_type: FileSyncType,
    ) -> Result<Option<Completion>> {
        let snapshot = self.authority.snapshot();
        turso_assert!(
            (snapshot.nbackfills..=snapshot.max_frame).contains(&nbackfills),
            "durable backfill proof requires nbackfills within the authoritative WAL range",
            {
                "nbackfills": nbackfills,
                "authority_nbackfills": snapshot.nbackfills,
                "authority_max_frame": snapshot.max_frame
            }
        );
        let proof_snapshot = SharedWalCoordinationHeader {
            nbackfills,
            ..snapshot
        };
        self.authority
            .install_backfill_proof(proof_snapshot, db_size_pages, db_header_crc32c);
        Ok(Some(self.authority.begin_sync(sync_type)?))
    }

    fn find_frame(
        &self,
        page_id: u64,
        min_frame: u64,
        max_frame: u64,
        frame_watermark: Option<u64>,
    ) -> Option<u64> {
        // Exhausting the reserved shared index space leaves the authority
        // incomplete. Fall back to the local scanned cache rather than trusting
        // a truncated shared index.
        if self.authority.frame_index_overflowed() {
            return self
                .fallback
                .find_frame(page_id, min_frame, max_frame, frame_watermark);
        }
        self.authority
            .find_frame(page_id, min_frame, max_frame, frame_watermark)
    }

    fn iter_latest_frames(&self, min_frame: u64, max_frame: u64) -> Vec<(u64, u64)> {
        // Same trade-off as find_frame(): if the reserved shared index space is
        // exhausted, keep correctness by consulting the local scanned cache.
        if self.authority.frame_index_overflowed() {
            return self.fallback.iter_latest_frames(min_frame, max_frame);
        }
        self.authority.iter_latest_frames(min_frame, max_frame)
    }

    fn checkpoint_epoch(&self) -> u32 {
        self.authority.checkpoint_epoch()
    }

    fn bump_checkpoint_epoch(&self) -> u32 {
        let prev = self.authority.bump_checkpoint_epoch();
        self.shared
            .write()
            .runtime
            .epoch
            .store(prev + 1, Ordering::Release);
        prev
    }

    fn try_begin_read_tx(&self, snapshot: WalSnapshot) -> Option<ReadGuardKind> {
        turso_assert!(
            snapshot.max_frame <= u32::MAX as u64,
            "max_frame exceeds u32 read mark range"
        );
        let shared = self.shared.read();
        let read_locks = &shared.runtime.read_locks;

        if snapshot.max_frame == snapshot.nbackfills {
            if !read_locks[0].read() {
                return None;
            }
            if self.load_snapshot() != snapshot {
                read_locks[0].unlock();
                return None;
            }
            return Some(ReadGuardKind::DbFile);
        }

        let mut best_idx: i64 = -1;
        let mut best_mark: u32 = 0;
        for (idx, lock) in read_locks.iter().enumerate().take(5).skip(1) {
            let mark = lock.get_value();
            if mark != READMARK_NOT_USED && mark <= snapshot.max_frame as u32 && mark > best_mark {
                best_mark = mark;
                best_idx = idx as i64;
            }
        }

        if best_idx == -1 || (best_mark as u64) < snapshot.max_frame {
            for (idx, lock) in read_locks.iter().enumerate().take(5).skip(1) {
                if !lock.write() {
                    continue;
                }
                lock.set_value_exclusive(snapshot.max_frame as u32);
                best_idx = idx as i64;
                best_mark = snapshot.max_frame as u32;
                read_locks[idx].unlock();
                break;
            }
        }

        if best_idx == -1 || !read_locks[best_idx as usize].read() {
            return None;
        }

        let current_slot_mark = read_locks[best_idx as usize].get_value();
        if current_slot_mark != best_mark || self.load_snapshot() != snapshot {
            read_locks[best_idx as usize].unlock();
            return None;
        }

        let read_mark_index =
            NonZeroUsize::new(best_idx as usize).expect("best_idx checked to be positive");
        let reader = self
            .authority
            .register_reader_for_snapshot(self.owner, snapshot.max_frame)?;
        if self.load_snapshot() != snapshot {
            self.authority.unregister_reader_for_snapshot(reader);
            read_locks[best_idx as usize].unlock();
            return None;
        }

        let mut active_reader = self.active_reader.lock();
        turso_assert!(active_reader.is_none(), "shared reader registration leaked");
        *active_reader = Some(reader);
        Some(ReadGuardKind::ReadMark(read_mark_index))
    }

    fn end_read_tx(&self, guard: ReadGuardKind) {
        if let Some(reader) = self.active_reader.lock().take() {
            self.authority.unregister_reader_for_snapshot(reader);
        }
        self.fallback.end_read_tx(guard);
    }

    fn try_begin_write_tx(&self) -> bool {
        if !self.authority.try_acquire_writer(self.owner) {
            return false;
        }
        if !self.fallback.try_write_lock() {
            self.authority.release_writer(self.owner);
            return false;
        }
        true
    }

    fn end_write_tx(&self) {
        self.fallback.unlock_write_lock();
        self.authority.release_writer(self.owner);
    }

    fn acquire_checkpoint_guard(
        &self,
        mode: CheckpointMode,
    ) -> Result<CoordinationCheckpointGuardKind> {
        if !self.authority.try_acquire_checkpoint(self.owner) {
            return Err(LimboError::Busy);
        }
        let needs_writer = !matches!(mode, CheckpointMode::Passive { .. });
        if needs_writer && !self.authority.try_acquire_writer(self.owner) {
            self.authority.release_checkpoint(self.owner);
            return Err(LimboError::Busy);
        }
        if !self.fallback.try_checkpoint_lock() {
            if needs_writer {
                self.authority.release_writer(self.owner);
            }
            self.authority.release_checkpoint(self.owner);
            return Err(LimboError::Busy);
        }
        match mode {
            CheckpointMode::Passive { .. } => {
                if !self.fallback.try_read_mark_exclusive(0) {
                    self.fallback.unlock_checkpoint_lock();
                    if needs_writer {
                        self.authority.release_writer(self.owner);
                    }
                    self.authority.release_checkpoint(self.owner);
                    return Err(LimboError::Busy);
                }
                Ok(CoordinationCheckpointGuardKind::Read0)
            }
            CheckpointMode::Full | CheckpointMode::Restart | CheckpointMode::Truncate { .. } => {
                if !self.fallback.try_read_mark_exclusive(0) {
                    self.fallback.unlock_checkpoint_lock();
                    self.authority.release_writer(self.owner);
                    self.authority.release_checkpoint(self.owner);
                    return Err(LimboError::Busy);
                }
                if !self.fallback.try_write_lock() {
                    self.fallback.unlock_read_mark(0);
                    self.fallback.unlock_checkpoint_lock();
                    self.authority.release_writer(self.owner);
                    self.authority.release_checkpoint(self.owner);
                    return Err(LimboError::Busy);
                }
                Ok(CoordinationCheckpointGuardKind::Writer)
            }
        }
    }

    fn acquire_vacuum_checkpoint_guard_from_held_lock(
        &self,
    ) -> Result<CoordinationCheckpointGuardKind> {
        if !self.authority.try_acquire_checkpoint(self.owner) {
            self.fallback.unlock_checkpoint_lock();
            return Err(LimboError::Busy);
        }
        if !self.authority.try_acquire_writer(self.owner) {
            self.authority.release_checkpoint(self.owner);
            self.fallback.unlock_checkpoint_lock();
            return Err(LimboError::Busy);
        }
        if !self.fallback.try_read_mark_exclusive(0) {
            self.fallback.unlock_checkpoint_lock();
            self.authority.release_writer(self.owner);
            self.authority.release_checkpoint(self.owner);
            return Err(LimboError::Busy);
        }
        if !self.fallback.try_write_lock() {
            self.fallback.unlock_read_mark(0);
            self.fallback.unlock_checkpoint_lock();
            self.authority.release_writer(self.owner);
            self.authority.release_checkpoint(self.owner);
            return Err(LimboError::Busy);
        }
        Ok(CoordinationCheckpointGuardKind::Writer)
    }

    fn release_checkpoint_guard(&self, guard: CoordinationCheckpointGuardKind) {
        match guard {
            CoordinationCheckpointGuardKind::Writer => {
                self.fallback.unlock_write_lock();
                self.fallback.unlock_read_mark(0);
                self.fallback.unlock_checkpoint_lock();
                self.authority.release_writer(self.owner);
                self.authority.release_checkpoint(self.owner);
            }
            CoordinationCheckpointGuardKind::Read0 => {
                self.fallback.unlock_read_mark(0);
                self.fallback.unlock_checkpoint_lock();
                self.authority.release_checkpoint(self.owner);
            }
        }
    }

    fn determine_max_safe_checkpoint_frame(&self, max_frame: u64) -> u64 {
        turso_assert!(
            max_frame <= u32::MAX as u64,
            "max_frame exceeds u32 read mark range"
        );
        let mut max_safe_frame = max_frame;
        for read_lock_idx in 1..5 {
            let this_mark = self.fallback.read_mark_value(read_lock_idx);
            if this_mark < max_safe_frame as u32 {
                let busy = !self.fallback.try_read_mark_exclusive(read_lock_idx);
                if !busy {
                    let val = if read_lock_idx == 1 {
                        max_safe_frame as u32
                    } else {
                        READMARK_NOT_USED
                    };
                    self.fallback
                        .set_read_mark_value_exclusive(read_lock_idx, val);
                    self.fallback.unlock_read_mark(read_lock_idx);
                } else {
                    max_safe_frame = this_mark as u64;
                }
            }
        }
        match self.authority.min_active_reader_frame() {
            Some(shared_min) => max_safe_frame.min(shared_min),
            None => max_safe_frame,
        }
    }

    fn begin_restart(&self, io: &dyn IO) -> Result<WalSnapshot> {
        for idx in 1..5 {
            if !self.fallback.try_read_mark_exclusive(idx) {
                for held_idx in 1..idx {
                    self.fallback.unlock_read_mark(held_idx);
                }
                return Err(LimboError::Busy);
            }
        }
        // In multi-process mode, readers register with the authority (tshm shared
        // memory), not with fallback OFD byte-range locks. We must also check for
        // active cross-process readers before proceeding with the WAL restart,
        // otherwise we reset the shared WAL state while another process still has
        // an active read transaction, leading to data loss.
        if self.authority.min_active_reader_frame().is_some() {
            for idx in 1..5 {
                self.fallback.unlock_read_mark(idx);
            }
            return Err(LimboError::Busy);
        }
        Ok(self.restart_snapshot_from_authority(self.authority.snapshot(), io))
    }

    fn end_restart(&self) {
        self.fallback.end_restart();
    }

    fn try_restart_log_for_write(&self, io: &dyn IO) -> Result<Option<WalSnapshot>> {
        if !self.fallback.try_upgrade_read_mark(0) {
            return Ok(None);
        }
        let result = self.begin_restart(io);
        self.fallback.downgrade_read_mark(0);
        match result {
            Ok(snapshot) => {
                self.end_restart();
                Ok(Some(snapshot))
            }
            Err(err) => Err(err),
        }
    }

    fn prepare_truncate(&self) -> Result<Arc<dyn File>> {
        self.fallback.prepare_truncate()
    }

    fn wal_header(&self) -> WalHeader {
        let snapshot = self.authority.snapshot();
        let mut header = self.fallback.wal_header();
        if snapshot.page_size == 0 {
            return header;
        }
        header.page_size = snapshot.page_size;
        header.checkpoint_seq = snapshot.checkpoint_seq;
        header.salt_1 = snapshot.salt_1;
        header.salt_2 = snapshot.salt_2;
        header.checksum_1 = snapshot.checksum_1;
        header.checksum_2 = snapshot.checksum_2;
        header
    }

    fn wal_file(&self) -> Result<Arc<dyn File>> {
        self.fallback.wal_file()
    }

    fn shared_wal_state(&self) -> Arc<RwLock<WalFileShared>> {
        self.shared.clone()
    }

    fn wal_is_initialized(&self) -> bool {
        let authority_snapshot = self.authority.snapshot();
        if Self::authority_needs_local_header_seed(authority_snapshot) {
            return self.fallback.wal_is_initialized();
        }
        if authority_snapshot.max_frame > 0 {
            self.sync_local_from_authority(authority_snapshot);
            self.fallback.mark_initialized();
            return true;
        }
        if self.local_zero_frame_generation_is_initialized(authority_snapshot) {
            return true;
        }

        self.sync_local_from_authority(authority_snapshot);
        self.shared
            .read()
            .metadata
            .initialized
            .store(false, Ordering::Release);
        false
    }

    fn prepare_wal_header(&self, io: &dyn IO, page_size: PageSize) -> Option<WalHeader> {
        let authority_snapshot = self.authority.snapshot();
        // A zero-frame authority snapshot after RESTART/TRUNCATE is still
        // authoritative: it carries the latest transaction_count,
        // checkpoint_seq, salts, and checksums for readers. Sync from it
        // before preparing the header so the bytes written to disk belong to
        // the same generation as the authority snapshot.
        if Self::authority_needs_local_header_seed(authority_snapshot) {
            let header = self.fallback.prepare_wal_header(io, page_size);
            if header.is_some() {
                self.sync_authority_from_local();
            }
            return header;
        }
        self.sync_local_from_authority(authority_snapshot);
        let header = self.fallback.prepare_wal_header(io, page_size);
        if header.is_some() {
            self.sync_authority_from_local();
        }
        header
    }

    fn mark_initialized(&self) {
        self.fallback.mark_initialized();
    }

    fn cache_frame(&self, page_id: u64, frame_id: u64) {
        self.fallback.cache_frame(page_id, frame_id);
        self.authority.record_frame(page_id, frame_id);
    }

    fn rollback_cache(&self, max_frame: u64) {
        self.fallback.rollback_cache(max_frame);
        self.authority.rollback_frames(max_frame);
        self.clear_overflow_fallback_coverage();
    }

    fn should_checkpoint_on_close(&self) -> bool {
        self.authority.is_last_process_mapping()
    }

    #[cfg(test)]
    fn backend_name(&self) -> &'static str {
        "tshm"
    }

    #[cfg(test)]
    fn shared_ptr(&self) -> usize {
        Arc::as_ptr(&self.shared) as usize
    }

    #[cfg(test)]
    fn open_mode_name(&self) -> Option<&'static str> {
        Some(match self.authority.open_mode() {
            SharedWalCoordinationOpenMode::Exclusive => "exclusive",
            SharedWalCoordinationOpenMode::MultiProcess => "multiprocess",
        })
    }
}

#[derive(Debug, Clone)]
pub enum CheckpointState {
    Start,
    Processing,
    /// Determine the checkpoint result: update nBackfills, restart log if needed.
    DetermineResult,
    /// Final cleanup: release locks, clear internal state, return result.
    /// WAL truncation (if needed) is handled by pager.rs via truncate_wal() AFTER the DB is synced.
    Finalize {
        checkpoint_result: Option<CheckpointResult>,
    },
}

/// IOV_MAX is 1024 on most systems, lets use 512 to be safe
pub const CKPT_BATCH_PAGES: usize = 512;

/// TODO: *ALL* of these need to be tuned for perf. It is tricky
/// trying to figure out the ideal numbers here to work together concurrently
const MIN_AVG_RUN_FOR_FLUSH: f32 = 32.0;
const MIN_BATCH_LEN_FOR_FLUSH: usize = 512;
const MAX_INFLIGHT_WRITES: usize = 64;
pub const MAX_INFLIGHT_READS: usize = 512;
pub const IOV_MAX: usize = 1024;

type PageId = usize;
struct InflightRead {
    completion: Completion,
    page_id: PageId,
    /// Buffer slot to contain the page content from the WAL read.
    buf: Arc<SpinLock<Option<Arc<Buffer>>>>,
}

/// WriteBatch is a collection of pages that are being checkpointed together. It is used to
/// aggregate contiguous pages into a single write operation to the database file.
#[derive(Default)]
struct WriteBatch {
    /// BTreeMap for sorting during insertion, helps create more efficient `writev` operations.
    items: BTreeMap<PageId, Arc<Buffer>>,
    /// total number of `runs`, each representing a contiguous group of `PageId`s
    run_count: usize,
}

impl WriteBatch {
    fn new() -> Self {
        Self {
            items: BTreeMap::new(),
            run_count: 0,
        }
    }

    #[inline]
    /// Add a pageId + Buffer to the batch of Writes to be submitted.
    fn insert(&mut self, page_id: PageId, buf: Arc<Buffer>) {
        if let std::collections::btree_map::Entry::Occupied(mut e) = self.items.entry(page_id) {
            e.insert(buf);
            return;
        }
        // Single range query to check neighbors
        let start = page_id.saturating_sub(1);
        let end = page_id.saturating_add(1);
        let mut has_left = false;
        let mut has_right = false;

        for (k, _) in self.items.range(start..=end) {
            if *k == page_id.wrapping_sub(1) {
                has_left = true;
            }
            if *k == page_id.wrapping_add(1) {
                has_right = true;
            }
        }
        match (has_left, has_right) {
            (false, false) => self.run_count += 1,
            (true, true) => self.run_count = self.run_count.saturating_sub(1),
            _ => {}
        }
        self.items.insert(page_id, buf);
    }

    #[inline]
    fn len(&self) -> usize {
        self.items.len()
    }
    #[inline]
    fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
    #[inline]
    fn is_full(&self) -> bool {
        self.items.len() >= CKPT_BATCH_PAGES
    }

    #[inline]
    fn avg_run_len(&self) -> f32 {
        if self.run_count == 0 {
            0.0
        } else {
            self.items.len() as f32 / self.run_count as f32
        }
    }

    #[inline]
    fn take(&mut self) -> BTreeMap<PageId, Arc<Buffer>> {
        self.run_count = 0;
        std::mem::take(&mut self.items)
    }

    #[inline]
    fn clear(&mut self) {
        self.items.clear();
        self.run_count = 0;
    }
}

impl std::ops::Deref for WriteBatch {
    type Target = BTreeMap<PageId, Arc<Buffer>>;
    fn deref(&self) -> &Self::Target {
        &self.items
    }
}
impl std::ops::DerefMut for WriteBatch {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.items
    }
}

/// Information and structures for processing a checkpoint operation.
struct OngoingCheckpoint {
    /// Used for benchmarking/debugging a checkpoint operation.
    time: MonotonicInstant,
    /// minimum frame number to be backfilled by this checkpoint operation.
    min_frame: u64,
    /// maximum safe frame number that will be backfilled by this checkpoint operation.
    max_frame: u64,
    /// cursor used to iterate through all the pages that might have a frame in the safe range
    current_page: u64,
    /// State of the checkpoint
    state: CheckpointState,
    /// Batch repreesnts a collection of pages to be backfilled to the DB file.
    pending_writes: WriteBatch,
    /// Read operations currently ongoing.
    inflight_reads: Vec<InflightRead>,
    /// Array of atomic counters representing write operations that are currently in flight.
    inflight_writes: Vec<InflightWriteBatch>,
    /// List of all page_id + frame_id combinations to be backfilled
    pages_to_checkpoint: Vec<(u64, u64)>,
}

struct InflightWriteBatch {
    done: Arc<AtomicBool>,
    err: Arc<crate::sync::OnceLock<CompletionError>>,
}

impl OngoingCheckpoint {
    fn reset(&mut self) {
        self.min_frame = 0;
        self.max_frame = 0;
        self.current_page = 0;
        self.pages_to_checkpoint.clear();
        self.pending_writes.clear();
        self.inflight_reads.clear();
        self.inflight_writes.clear();
        self.state = CheckpointState::Start;
    }

    #[inline]
    /// Whether or not new reads should be issued during checkpoint processing.
    fn should_issue_reads(&self) -> bool {
        (self.current_page as usize) < self.pages_to_checkpoint.len()
            && !self.pending_writes.is_full()
            && self.inflight_reads.len() < MAX_INFLIGHT_READS
    }

    #[inline]
    /// Whether the backfilling/IO process is entirely completed during checkpoint processing.
    fn complete(&self) -> bool {
        (self.current_page as usize) >= self.pages_to_checkpoint.len()
            && self.inflight_reads.is_empty()
            && self.pending_writes.is_empty()
            && self.inflight_writes.is_empty()
    }

    #[inline]
    /// Whether we should flush an exisitng batch of writes and begin concurrently aggregating a new one.
    fn should_flush_batch(&self) -> bool {
        self.pending_writes.is_full()
            || (self.pending_writes.len() >= MIN_BATCH_LEN_FOR_FLUSH
                && self.pending_writes.avg_run_len() >= MIN_AVG_RUN_FOR_FLUSH)
            || ((self.current_page as usize) >= self.pages_to_checkpoint.len()
                && self.inflight_reads.is_empty()
                && !self.pending_writes.is_empty())
    }

    #[inline]
    /// Remove any completed write operations from `inflight_writes`,
    /// returns whether any progress was made.
    fn process_inflight_writes(&mut self) -> bool {
        let before_len = self.inflight_writes.len();
        self.inflight_writes
            .retain(|w| !w.done.load(Ordering::Acquire));
        before_len > self.inflight_writes.len()
    }

    #[inline]
    /// Remove any completed read operations from `inflight_reads`
    /// returns whether any progress was made.
    fn process_pending_reads(&mut self) -> Result<bool> {
        let mut moved = false;
        let mut err: Option<CompletionError> = None;

        self.inflight_reads.retain(|slot| {
            if !slot.completion.finished() {
                return true;
            }
            if slot.completion.succeeded() {
                if let Some(buf) = slot.buf.lock().take() {
                    self.pending_writes.insert(slot.page_id, buf);
                    moved = true;
                } else {
                    err = Some(CompletionError::IOError(std::io::ErrorKind::Other, "read"));
                }
            } else {
                err = Some(
                    slot.completion
                        .get_error()
                        .unwrap_or(CompletionError::IOError(std::io::ErrorKind::Other, "read")),
                );
            }
            false
        });
        if let Some(e) = err {
            return Err(LimboError::CompletionError(e));
        }
        Ok(moved)
    }

    fn first_write_error(&self) -> Option<CompletionError>
    where
        CompletionError: Clone,
    {
        self.inflight_writes
            .iter()
            .find_map(|w| w.err.get().cloned())
    }
}

impl InflightWriteBatch {
    #[inline]
    fn new() -> InflightWriteBatch {
        InflightWriteBatch {
            done: Arc::new(AtomicBool::new(false)),
            err: Arc::new(OnceLock::new()),
        }
    }
}

impl fmt::Debug for OngoingCheckpoint {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("OngoingCheckpoint")
            .field("state", &self.state)
            .field("min_frame", &self.min_frame)
            .field("max_frame", &self.max_frame)
            .field("current_page", &self.current_page)
            .finish()
    }
}

pub struct WalFile {
    io: Arc<dyn IO>,
    buffer_pool: Arc<BufferPool>,
    coordination: Arc<dyn WalCoordination>,

    syncing: Arc<AtomicBool>,
    write_lock_held: AtomicBool,

    ongoing_checkpoint: RwLock<OngoingCheckpoint>,
    checkpoint_threshold: usize,
    /// This is the index to the read_lock in WalFileShared that we are holding. This lock contains
    /// the max frame for this connection.
    max_frame_read_lock_index: AtomicUsize,
    /// Max frame allowed to lookup range=(minframe..max_frame)
    max_frame: AtomicU64,
    /// Start of range to look for frames range=(minframe..max_frame)
    min_frame: AtomicU64,
    /// Check of last frame in WAL, this is a cumulative checksum over all frames in the WAL
    last_checksum: RwLock<(u32, u32)>,
    checkpoint_seq: AtomicU32,
    transaction_count: AtomicU64,

    /// Manages locks needed for checkpointing
    checkpoint_guard: RwLock<Option<CheckpointLocks>>,
    /// Manages locks needed for VACUUM. This is very much similar to `checkpoint_guard`
    /// This lock is to be held by all readers before they can begin. And VACUUM holds it
    /// exclusively. See `install_vacuum_lock_guard` for its lifecycle.
    vacuum_lock_guard: RwLock<Option<VacuumLockGuard>>,

    io_ctx: RwLock<IOContext>,

    /// Set when `write_frame_raw` appends frames without a commit marker
    /// (`db_size == 0`), meaning the coordination backend's max_frame is
    /// behind our connection-local max_frame. Cleared once
    /// `finish_append_frames_commit` publishes the state.
    has_unpublished_frames: AtomicBool,
}

impl fmt::Debug for WalFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WalFile")
            .field("syncing", &self.syncing.load(Ordering::Relaxed))
            .field("page_size", &self.page_size())
            .field("ongoing_checkpoint", &*self.ongoing_checkpoint.read())
            .field("checkpoint_threshold", &self.checkpoint_threshold)
            .field("max_frame_read_lock_index", &self.max_frame_read_lock_index)
            .field("max_frame", &self.max_frame)
            .field("min_frame", &self.min_frame)
            // Excluding other fields
            .finish()
    }
}

/*
* sqlite3/src/wal.c
*
** nBackfill is the number of frames in the WAL that have been written
** back into the database. (We call the act of moving content from WAL to
** database "backfilling".)  The nBackfill number is never greater than
** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
** mxFrame back to zero when the WAL is reset.
**
** nBackfillAttempted is the largest value of nBackfill that a checkpoint
** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
** the nBackfillAttempted is set before any backfilling is done and the
** nBackfill is only set after all backfilling completes.  So if a checkpoint
** crashes, nBackfillAttempted might be larger than nBackfill.  The
** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
**
** The aLock[] field is a set of bytes used for locking.  These bytes should
** never be read or written.
**
** There is one entry in aReadMark[] for each reader lock.  If a reader
** holds read-lock K, then the value in aReadMark[K] is no greater than
** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
** for any aReadMark[] means that entry is unused.  aReadMark[0] is
** a special case; its value is never used and it exists as a place-holder
** to avoid having to offset aReadMark[] indexes by one.  Readers holding
** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
** directly from the database.
**
** The value of aReadMark[K] may only be changed by a thread that
** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
** aReadMark[K] cannot changed while there is a reader is using that mark
** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
**
** The checkpointer may only transfer frames from WAL to database where
** the frame numbers are less than or equal to every aReadMark[] that is
** in use (that is, every aReadMark[j] for which there is a corresponding
** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
** largest value and will increase an unused aReadMark[] to mxFrame if there
** is not already an aReadMark[] equal to mxFrame.  The exception to the
** previous sentence is when nBackfill equals mxFrame (meaning that everything
** in the WAL has been backfilled into the database) then new readers
** will choose aReadMark[0] which has value 0 and hence such reader will
** get all their all content directly from the database file and ignore
** the WAL.
**
** Writers normally append new frames to the end of the WAL.  However,
** if nBackfill equals mxFrame (meaning that all WAL content has been
** written back into the database) and if no readers are using the WAL
** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
** the writer will first "reset" the WAL back to the beginning and start
** writing new content beginning at frame 1.
*/

/// Authoritative WAL metadata currently shared by all connections in a process.
pub struct WalSharedMetadata {
    pub enabled: AtomicBool,
    pub wal_header: Arc<SpinLock<WalHeader>>,
    pub min_frame: AtomicU64,
    pub max_frame: AtomicU64,
    pub nbackfills: AtomicU64,
    pub transaction_count: AtomicU64,
    pub last_checksum: (u32, u32), // Check of last frame in WAL, this is a cumulative checksum over all frames in the WAL
    pub loaded: AtomicBool,
    pub loaded_from_disk_scan: AtomicBool,
    pub initialized: AtomicBool,
}

/// Process-local coordination and caches layered around the shared WAL metadata.
pub struct WalSharedRuntime {
    // Frame cache maps a Page to all the frames it has stored in WAL in ascending order.
    // This is to easily find the frame it must checkpoint each connection if a checkpoint is
    // necessary.
    // One difference between SQLite and limbo is that we will never support multi process, meaning
    // we don't need WAL's index file. So we can do stuff like this without shared memory.
    // TODO: this will need refactoring because this is incredible memory inefficient.
    pub frame_cache: Arc<SpinLock<FxHashMap<u64, Vec<u64>>>>,
    pub file: Option<Arc<dyn File>>,
    /// Read locks advertise the maximum WAL frame a reader may access.
    /// Slot 0 is special, when it is held (shared) the reader bypasses the WAL and uses the main DB file.
    /// When checkpointing, we must acquire the exclusive read lock 0 to ensure that no readers read
    /// from a partially checkpointed db file.
    /// Slots 1‑4 carry a frame‑number in value and may be shared by many readers. Slot 1 is the
    /// default read lock and is to contain the max_frame in WAL.
    pub read_locks: [TursoRwLock; 5],
    /// Lock used by in-place VACUUM to keep new read/write transactions out
    /// while VACUUM is in progress.
    /// Normal WAL transactions hold this shared for the lifetime of their
    /// transaction. VACUUM holds it exclusively until its final truncate
    /// checkpoint has completed.
    pub vacuum_lock: TursoRwLock,
    /// There is only one write allowed in WAL mode. This lock takes care of ensuring there is only
    /// one used.
    pub write_lock: TursoRwLock,

    /// Serialises checkpointer threads, only one checkpoint can be in flight at any time. Blocking and exclusive only
    pub checkpoint_lock: TursoRwLock,
    /// Increments on each checkpoint, used to prevent stale cached pages being used for
    /// backfilling.
    pub epoch: AtomicU32,
    /// Tracks how far the process-local `frame_cache` is known to be complete
    /// for overflow fallback in the current WAL generation.
    pub overflow_fallback_coverage: Arc<SpinLock<OverflowFallbackCoverage>>,
}

/// WalFileShared holds process-wide WAL metadata plus process-local coordination state.
pub struct WalFileShared {
    pub metadata: WalSharedMetadata,
    pub runtime: WalSharedRuntime,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OverflowFallbackCoverage {
    checkpoint_seq: u32,
    salt_1: u32,
    salt_2: u32,
    max_frame: u64,
    valid: bool,
}

impl OverflowFallbackCoverage {
    pub(crate) fn clear(&mut self) {
        *self = Self::default();
    }

    pub(crate) fn record(&mut self, checkpoint_seq: u32, salt_1: u32, salt_2: u32, max_frame: u64) {
        if max_frame == 0 {
            self.clear();
            return;
        }
        self.checkpoint_seq = checkpoint_seq;
        self.salt_1 = salt_1;
        self.salt_2 = salt_2;
        self.max_frame = max_frame;
        self.valid = true;
    }

    #[cfg(host_shared_wal)]
    pub(crate) fn record_snapshot(
        &mut self,
        snapshot: SharedWalCoordinationHeader,
        max_frame: u64,
    ) {
        self.record(
            snapshot.checkpoint_seq,
            snapshot.salt_1,
            snapshot.salt_2,
            max_frame,
        );
    }

    #[cfg(host_shared_wal)]
    pub(crate) fn same_generation(&self, snapshot: SharedWalCoordinationHeader) -> bool {
        self.valid
            && self.checkpoint_seq == snapshot.checkpoint_seq
            && self.salt_1 == snapshot.salt_1
            && self.salt_2 == snapshot.salt_2
    }

    #[cfg(host_shared_wal)]
    pub(crate) fn covers(&self, snapshot: SharedWalCoordinationHeader, max_frame: u64) -> bool {
        self.same_generation(snapshot) && self.max_frame >= max_frame
    }
}

impl fmt::Debug for WalFileShared {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WalFileShared")
            .field("enabled", &self.metadata.enabled.load(Ordering::Relaxed))
            .field("wal_header", &self.metadata.wal_header)
            .field("min_frame", &self.metadata.min_frame)
            .field("max_frame", &self.metadata.max_frame)
            .field("nbackfills", &self.metadata.nbackfills)
            .field("frame_cache", &self.runtime.frame_cache)
            .field("last_checksum", &self.metadata.last_checksum)
            // Excluding `file`, `read_locks`, and `write_lock`
            .finish()
    }
}

#[derive(Debug)]
enum VacuumLockGuard {
    Read { ptr: Arc<RwLock<WalFileShared>> },
    Write { ptr: Arc<RwLock<WalFileShared>> },
}

impl VacuumLockGuard {
    fn try_read(ptr: Arc<RwLock<WalFileShared>>) -> Option<Self> {
        let acquired = {
            let shared = ptr.read();
            shared.runtime.vacuum_lock.read()
        };
        if acquired {
            Some(Self::Read { ptr })
        } else {
            None
        }
    }

    fn try_write(ptr: Arc<RwLock<WalFileShared>>) -> Option<Self> {
        let acquired = {
            let shared = ptr.read();
            shared.runtime.vacuum_lock.write()
        };
        if acquired {
            Some(Self::Write { ptr })
        } else {
            None
        }
    }

    const fn is_read(&self) -> bool {
        matches!(self, Self::Read { .. })
    }

    const fn is_write(&self) -> bool {
        matches!(self, Self::Write { .. })
    }
}

impl Drop for VacuumLockGuard {
    fn drop(&mut self) {
        match self {
            Self::Read { ptr } | Self::Write { ptr } => {
                ptr.read().runtime.vacuum_lock.unlock();
            }
        }
    }
}

#[derive(Clone, Debug)]
/// To manage and ensure that no locks are leaked during checkpointing in
/// the case of errors. It is held by the WalFile while checkpoint is ongoing
/// then transferred to the CheckpointResult if necessary.
enum CheckpointLocks {
    Writer {
        coordination: Arc<dyn WalCoordination>,
    },
    Read0 {
        coordination: Arc<dyn WalCoordination>,
    },
}

/// CheckpointLockSource says whether the checkpoint state machine should acquire checkpoint_lock
/// itself or consume checkpoint_lock already held by the caller.
/// Most of the time, the default `Acquire` is used, except for VACUUM.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum CheckpointLockSource {
    #[default]
    Acquire,
    HeldByCaller,
}

/// Database checkpointers takes the following locks, in order:
/// The exclusive CHECKPOINTER lock.
/// The exclusive WRITER lock (FULL, RESTART and TRUNCATE only).
/// Exclusive lock on read-mark slots 1-N. These are immediately released after being taken.
/// Exclusive lock on read-mark 0.
/// Exclusive lock on read-mark slots 1-N again. These are immediately released after being taken (RESTART and TRUNCATE only).
/// All of the above use blocking locks.
impl CheckpointLocks {
    fn new(coordination: Arc<dyn WalCoordination>, mode: CheckpointMode) -> Result<Self> {
        let guard = coordination.acquire_checkpoint_guard(mode)?;
        Ok(match guard {
            CoordinationCheckpointGuardKind::Read0 => Self::Read0 { coordination },
            CoordinationCheckpointGuardKind::Writer => Self::Writer { coordination },
        })
    }

    /// Build checkpoint ownership from a checkpoint_lock that VACUUM already
    /// holds. This consumes that raw lock ownership: on success the
    /// returned guard owns checkpoint/read0/write as appropriate, and on error
    /// the coordination backend releases the held checkpoint lock before
    /// returning.
    fn from_held_vacuum_checkpoint_lock(coordination: Arc<dyn WalCoordination>) -> Result<Self> {
        let guard = coordination.acquire_vacuum_checkpoint_guard_from_held_lock()?;
        Ok(match guard {
            CoordinationCheckpointGuardKind::Read0 => Self::Read0 { coordination },
            CoordinationCheckpointGuardKind::Writer => Self::Writer { coordination },
        })
    }
}

impl Drop for CheckpointLocks {
    fn drop(&mut self) {
        match self {
            CheckpointLocks::Writer { coordination } => {
                coordination.release_checkpoint_guard(CoordinationCheckpointGuardKind::Writer);
            }
            CheckpointLocks::Read0 { coordination } => {
                coordination.release_checkpoint_guard(CoordinationCheckpointGuardKind::Read0);
            }
        }
    }
}

/// Result of try_begin_read_tx - either success or a retriable condition.
enum TryBeginReadResult {
    /// Successfully started read transaction, returns whether DB changed
    Ok(bool),
    /// Transient condition, caller should retry immediately (like SQLite's WAL_RETRY)
    Retry,
    /// Non-retriable failure while preparing the local WAL view.
    Err(LimboError),
    /// We could get a lock / source snapshot for readers because WAL is exclusively held by
    /// other transaction.
    /// This usually happens during VACUUM when it holds the vacuum lock exclusively.
    /// Retrying will not help until VACUUM releases; caller should surface Busy
    /// to the client rather than spin.
    Busy,
}

impl WalFile {
    /// Load the authoritative WAL snapshot through the coordination backend.
    fn load_coordination_snapshot(&self) -> WalSnapshot {
        self.coordination.load_snapshot()
    }

    /// Reconstruct the connection-local WAL state stored on this `WalFile`.
    fn connection_state(&self) -> WalConnectionState {
        WalConnectionState::new(
            WalSnapshot {
                max_frame: self.max_frame.load(Ordering::Acquire),
                nbackfills: self.min_frame.load(Ordering::Acquire).saturating_sub(1),
                last_checksum: *self.last_checksum.read(),
                checkpoint_seq: self.checkpoint_seq.load(Ordering::Acquire),
                transaction_count: self.transaction_count.load(Ordering::Acquire),
            },
            ReadGuardKind::from_lock_index(self.max_frame_read_lock_index.load(Ordering::Acquire)),
        )
    }

    /// Persist a connection-local WAL snapshot bundle back into the legacy fields on `WalFile`.
    fn install_connection_state(&self, state: WalConnectionState) {
        self.max_frame
            .store(state.snapshot.max_frame, Ordering::Release);
        self.min_frame
            .store(state.snapshot.min_frame(), Ordering::Release);
        *self.last_checksum.write() = state.snapshot.last_checksum;
        self.checkpoint_seq
            .store(state.snapshot.checkpoint_seq, Ordering::Release);
        self.transaction_count
            .store(state.snapshot.transaction_count, Ordering::Release);
        self.max_frame_read_lock_index
            .store(state.read_guard.lock_index(), Ordering::Release);
    }

    /// Compare a freshly loaded shared snapshot against the connection's current snapshot.
    fn db_changed_against(&self, snapshot: WalSnapshot, local_state: WalConnectionState) -> bool {
        snapshot != local_state.snapshot
    }

    fn has_vacuum_read_lock_guard(&self) -> bool {
        self.vacuum_lock_guard
            .read()
            .as_ref()
            .is_some_and(VacuumLockGuard::is_read)
    }

    // VACUUM lock guard lifecycle:
    // - Normal readers install a read guard in `try_begin_read_tx` after the
    //   read-mark slot is selected; `end_read_tx` releases that guard through
    //   `release_vacuum_read_lock_guard`.
    // - Normal writers do not install their own VACUUM guard. They are an
    //   upgrade of an existing read transaction, so their guard is still the
    //   read guard owned by the read transaction.
    // - In-place VACUUM installs a write guard and takes the WAL write lock in
    //   `begin_vacuum_blocking_tx`. `end_write_tx` releases the WAL write lock, and
    //   `release_vacuum_lock` releases the write guard.
    fn install_vacuum_lock_guard(&self, guard: VacuumLockGuard) {
        let mut slot = self.vacuum_lock_guard.write();
        turso_assert!(slot.is_none(), "VACUUM lock guard is already installed");
        *slot = Some(guard);
    }

    fn release_vacuum_read_lock_guard(&self) {
        let guard = {
            let mut slot = self.vacuum_lock_guard.write();
            turso_assert!(
                slot.as_ref().is_some_and(VacuumLockGuard::is_read),
                "VACUUM read lock guard is not held"
            );
            slot.take()
                .expect("VACUUM read lock guard should be present after kind check")
        };
        drop(guard);
    }

    fn release_vacuum_write_lock_guard(&self) {
        let guard = {
            let mut slot = self.vacuum_lock_guard.write();
            turso_assert!(
                slot.as_ref().is_some_and(VacuumLockGuard::is_write),
                "VACUUM write lock guard is not held"
            );
            slot.take()
                .expect("VACUUM write lock guard should be present after kind check")
        };
        drop(guard);
    }

    /// Try to begin a read transaction. Returns Retry for transient conditions
    /// that should be retried immediately, Ok for success.
    fn try_begin_read_tx(&self) -> TryBeginReadResult {
        turso_assert!(
            self.max_frame_read_lock_index
                .load(Ordering::Acquire)
                .eq(&NO_LOCK_HELD),
            "cannot start a new read tx without ending an existing one",
            { "lock_value": self.max_frame_read_lock_index.load(Ordering::Acquire), "expected": NO_LOCK_HELD }
        );
        turso_assert!(
            self.vacuum_lock_guard.read().is_none(),
            "VACUUM lock guard already held"
        );

        // Before we can start the txn, we must first take read lock on the vacuum. If we cannot,
        // then vacuum is already in progress. Once we acquire a read lock, this would prevent
        // vacuum to run till the lock is released.
        let Some(vacuum_lock_guard) =
            VacuumLockGuard::try_read(self.coordination.shared_wal_state())
        else {
            tracing::debug!("begin_read_tx: VACUUM holds the vacuum lock, returning Busy");
            return TryBeginReadResult::Busy;
        };

        // Snapshot the shared WAL state. We haven't taken a read lock yet, so we need
        // to validate these values later.
        let shared_snapshot = self.load_coordination_snapshot();
        tracing::debug!(
            "try_begin_read_tx: shared_max={}, nbackfills={}, last_checksum={:?}, checkpoint_seq={:?}, transaction_count={}",
            shared_snapshot.max_frame,
            shared_snapshot.nbackfills,
            shared_snapshot.last_checksum,
            shared_snapshot.checkpoint_seq,
            shared_snapshot.transaction_count
        );
        if let Err(err) = self
            .coordination
            .ensure_local_frame_cache_covers(&self.io, shared_snapshot)
        {
            return match err {
                LimboError::Busy => TryBeginReadResult::Retry,
                other => TryBeginReadResult::Err(other),
            };
        }

        // Check if database changed since this connection's last read transaction.
        // If it has, the connection will invalidate its page cache.
        let db_changed = self.db_changed_against(shared_snapshot, self.connection_state());

        tracing::debug!("try_begin_read_tx: db_changed={}", db_changed);

        // If WAL is fully checkpointed (shared_max == nbackfills), readers can ignore
        // the WAL and read directly from the DB file by holding read_locks[0].
        if shared_snapshot.max_frame == shared_snapshot.nbackfills {
            tracing::debug!(
                "begin_read_tx: WAL fully checkpointed, shared_max={}, nbackfills={}",
                shared_snapshot.max_frame,
                shared_snapshot.nbackfills
            );
        }

        let Some(read_guard) = self.coordination.try_begin_read_tx(shared_snapshot) else {
            return TryBeginReadResult::Retry;
        };
        self.install_vacuum_lock_guard(vacuum_lock_guard);
        self.install_connection_state(WalConnectionState::new(shared_snapshot, read_guard));
        tracing::debug!(
            "begin_read_tx(min={}, max={}, slot={}, max_frame_in_wal={})",
            self.min_frame.load(Ordering::Acquire),
            self.max_frame.load(Ordering::Acquire),
            read_guard.lock_index(),
            shared_snapshot.max_frame
        );
        TryBeginReadResult::Ok(db_changed)
    }
}

impl Wal for WalFile {
    fn begin_read_tx(&self) -> Result<bool> {
        // Implement progressive backoff because transient lock contention
        // should resolve quickly, but under heavy contention busy-spinning wastes
        // CPU. SQLite uses quadratic backoff after 5 retries, with total delay
        // up to ~10 seconds before giving up, so we just mirror SQLite's implementation
        // here.
        let mut cnt = 0u32;
        loop {
            tracing::trace!("begin_read_tx: cnt={cnt}");
            match self.try_begin_read_tx() {
                TryBeginReadResult::Ok(changed) => return Ok(changed),
                TryBeginReadResult::Err(err) => return Err(err),
                TryBeginReadResult::Busy => return Err(LimboError::Busy),
                TryBeginReadResult::Retry => {
                    cnt += 1;
                    if cnt > 100 {
                        return Err(LimboError::Busy);
                    }
                    // Progressive backoff: first 5 retries are immediate, then we
                    // start yielding/sleeping with increasing delays.
                    if cnt > 5 {
                        if cnt < 10 {
                            // Retries 6-9: yield to scheduler (minimal delay)
                            self.io.yield_now();
                        } else {
                            // Retries 10+: quadratic backoff in microseconds
                            // Formula matches SQLite: (cnt-9)^2 * 39 microseconds
                            let delay_us = ((cnt - 9) * (cnt - 9) * 39) as u64;
                            self.io.sleep(std::time::Duration::from_micros(delay_us));
                        }
                    }
                    continue;
                }
            }
        }
    }

    fn mvcc_refresh_if_db_changed(&self) -> bool {
        WalFile::mvcc_refresh_if_db_changed(self)
    }

    /// End a read transaction.
    #[inline(always)]
    #[instrument(skip_all, level = Level::DEBUG)]
    fn end_read_tx(&self) {
        let slot = self.max_frame_read_lock_index.load(Ordering::Acquire);
        if slot != NO_LOCK_HELD {
            self.coordination
                .end_read_tx(ReadGuardKind::from_lock_index(slot));
            self.max_frame_read_lock_index
                .store(NO_LOCK_HELD, Ordering::Release);
            self.release_vacuum_read_lock_guard();
            tracing::debug!("end_read_tx(slot={slot})");
        } else {
            // if NO_LOCK_HELD, then we must not have vacuum lock either.
            turso_assert!(
                !self.has_vacuum_read_lock_guard(),
                "vacuum read lock guard held without setting lock slot NO_LOCK_HELD"
            );
            tracing::debug!("end_read_tx(slot=no_lock)");
        }
    }

    /// Begin a write transaction
    #[instrument(skip_all, level = Level::DEBUG)]
    fn begin_write_tx(&self, allowed_auto_actions: WalAutoActions) -> Result<()> {
        tracing::debug!("begin_write_tx");
        let begin_write_result: Result<()> = {
            // sqlite/src/wal.c 3702
            // Cannot start a write transaction without first holding a read
            // transaction.
            // assert(pWal->readLock >= 0);
            // assert(pWal->writeLock == 0 && pWal->iReCksum == 0);
            turso_assert!(
                self.max_frame_read_lock_index.load(Ordering::Acquire) != NO_LOCK_HELD,
                "must have a read transaction to begin a write transaction"
            );
            turso_assert!(
                !self.holds_write_lock(),
                "write lock already held by this connection"
            );
            if !self.coordination.try_begin_write_tx() {
                return Err(LimboError::Busy);
            }
            let db_changed =
                self.db_changed_against(self.load_coordination_snapshot(), self.connection_state());
            if db_changed {
                // Snapshot is stale, give up and let caller retry from scratch.
                // Return BusySnapshot instead of Busy so the caller knows it must
                // restart the read transaction to get a fresh snapshot.
                // Retrying with busy_timeout will NEVER HELP.
                tracing::debug!(
                    "unable to upgrade transaction from read to write: snapshot is stale, give up and let caller retry from scratch, self.max_frame={}, shared_max={}",
                    self.max_frame.load(Ordering::Acquire),
                    self.load_coordination_snapshot().max_frame
                );
                self.coordination.end_write_tx();
                return Err(LimboError::BusySnapshot);
            }

            Ok(())
        };
        begin_write_result?;
        if self
            .write_lock_held
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            self.coordination.end_write_tx();
            turso_assert!(
                false,
                "begin_write_tx called while write lock already held according to connection state"
            );
        }

        if !allowed_auto_actions.contains(WalAutoActions::Restart) {
            return Ok(());
        }

        let result = self.try_restart_log_before_write();
        if let Err(LimboError::Busy) | Ok(()) = &result {
            // it's fine if we were unable to restart WAL file due to Busy errors
            return Ok(());
        }

        // don't forget to release the write-lock if
        self.coordination.end_write_tx();
        turso_assert!(
            self.write_lock_held
                .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
                .is_ok(),
            "end_write_tx called while write lock not held according to connection state"
        );

        Err(result.expect_err("Ok case handled above"))
    }

    /// End a write transaction
    #[instrument(skip_all, level = Level::DEBUG)]
    fn end_write_tx(&self) {
        turso_assert!(
            self.write_lock_held
                .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
                .is_ok(),
            "end_write_tx called while write lock not held according to connection state"
        );
        self.coordination.end_write_tx();
    }

    /// Returns true if this WAL instance currently holds a read lock.
    fn holds_read_lock(&self) -> bool {
        self.max_frame_read_lock_index.load(Ordering::Acquire) != NO_LOCK_HELD
    }

    /// Returns true if this WAL instance currently holds the write lock.
    fn holds_write_lock(&self) -> bool {
        self.write_lock_held.load(Ordering::Acquire)
    }

    fn should_checkpoint_on_close(&self) -> bool {
        self.coordination.should_checkpoint_on_close()
    }

    /// Find the latest frame containing a page.
    #[instrument(skip_all, level = Level::DEBUG)]
    fn find_frame(&self, page_id: u64, frame_watermark: Option<u64>) -> Result<Option<u64>> {
        #[cfg(not(feature = "conn_raw_api"))]
        turso_assert!(
            frame_watermark.is_none(),
            "unexpected use of frame_watermark optional argument"
        );

        turso_assert!(
            frame_watermark.unwrap_or(0) <= self.max_frame.load(Ordering::Acquire),
            "frame_watermark must be <= than current WAL max_frame value"
        );

        // we can guarantee correctness of the method, only if frame_watermark is strictly after the current checkpointed prefix
        //
        // if it's not, than pages from WAL range [frame_watermark..nBackfill] are already in the DB file,
        // and in case if page first occurrence in WAL was after frame_watermark - we will be unable to read proper previous version of the page
        let nbackfills = self.load_coordination_snapshot().nbackfills;
        turso_assert!(
            frame_watermark.is_none() || frame_watermark.unwrap() >= nbackfills,
            "frame_watermark must be >= than current WAL backfill amount",
            { "frame_watermark": frame_watermark, "nbackfills": nbackfills }
        );

        // if we are holding read_lock 0 and didn't write anything to the WAL, skip and read right from db file.
        //
        // note, that max_frame_read_lock_index is set to 0 only when shared_max_frame == nbackfill in which case
        // min_frame is set to nbackfill + 1 and max_frame is set to shared_max_frame
        //
        // by default, SQLite tries to restart log file in this case - but for now let's keep it simple in the turso-db
        if self.max_frame_read_lock_index.load(Ordering::Acquire) == 0
            && self.max_frame.load(Ordering::Acquire) < self.min_frame.load(Ordering::Acquire)
        {
            tracing::debug!(
                "find_frame(page_id={}, frame_watermark={:?}): max_frame is 0 - read from DB file",
                page_id,
                frame_watermark,
            );
            return Ok(None);
        }
        let min_frame = self.min_frame.load(Ordering::Acquire);
        let max_frame = self.max_frame.load(Ordering::Acquire);
        self.coordination.ensure_local_frame_cache_covers(
            &self.io,
            WalSnapshot {
                max_frame,
                nbackfills: self.min_frame.load(Ordering::Acquire).saturating_sub(1),
                last_checksum: *self.last_checksum.read(),
                checkpoint_seq: self.coordination.wal_header().checkpoint_seq,
                transaction_count: self.transaction_count.load(Ordering::Acquire),
            },
        )?;
        tracing::debug!(
            "find_frame(page_id={}, frame_watermark={:?}): min_frame={}, max_frame={}",
            page_id,
            frame_watermark,
            min_frame,
            max_frame
        );
        let frame = self
            .coordination
            .find_frame(page_id, min_frame, max_frame, frame_watermark);
        if let Some(frame) = frame {
            tracing::debug!(
                "find_frame(page_id={}, frame_watermark={:?}): found frame={}",
                page_id,
                frame_watermark,
                frame
            );
        }
        Ok(frame)
    }

    /// Read a frame from the WAL.
    #[instrument(skip_all, level = Level::DEBUG)]
    fn read_frame(
        &self,
        frame_id: u64,
        page: PageRef,
        buffer_pool: Arc<BufferPool>,
    ) -> Result<Completion> {
        tracing::debug!(
            "read_frame(page_idx = {}, frame_id = {})",
            page.get().id,
            frame_id
        );
        let offset = self.frame_offset(frame_id);
        page.set_locked();
        let frame = page.clone();
        let page_idx = page.get().id;
        let epoch_at_issue = self.coordination.checkpoint_epoch();
        let complete = Box::new(move |res: Result<(Arc<Buffer>, i32), CompletionError>| {
            let Ok((buf, bytes_read)) = res else {
                tracing::debug!(err = ?res.unwrap_err());
                page.clear_locked();
                page.clear_wal_tag();
                return None; // IO error already captured in completion
            };
            let buf_len = buf.len();
            if bytes_read != buf_len as i32 {
                tracing::debug!(
                    "WAL short read at offset {offset}, page {page_idx}, frame_id={frame_id}: expected {buf_len} bytes, got {bytes_read}"
                );
                page.clear_locked();
                page.clear_wal_tag();
                return Some(CompletionError::ShortReadWalFrame {
                    offset,
                    expected: buf_len,
                    actual: bytes_read as usize,
                });
            }
            let cloned = frame.clone();
            finish_read_page(page.get().id, buf, cloned);
            frame.set_wal_tag(frame_id, epoch_at_issue);
            None
        });
        // important not to hold shared state locks beyond this point to avoid deadlock with
        // completions that re-enter WAL state while a writer is waiting.
        let file = self.coordination.wal_file()?;
        begin_read_wal_frame(
            file.as_ref(),
            offset + WAL_FRAME_HEADER_SIZE as u64,
            buffer_pool,
            complete,
            page_idx,
            &self.io_ctx.read(),
        )
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    fn read_frames_batch(
        &self,
        start_frame: u64,
        pages: &[PageRef],
        buffer_pool: Arc<BufferPool>,
        scratch_buf: Option<Arc<Buffer>>,
    ) -> Result<Completion> {
        turso_assert!(
            !pages.is_empty(),
            "read_frames_batch requires at least one page"
        );
        let page_size = self.page_size() as usize;
        turso_assert!(page_size > 0, "WAL page size must be initialized");
        let frame_size = WAL_FRAME_HEADER_SIZE + page_size;
        let count = pages.len();
        let total = frame_size * count;
        let offset = self.frame_offset(start_frame);
        if let Some(buf) = &scratch_buf {
            turso_assert!(
                buf.len() == total,
                "read_frames_batch scratch_buf size must match expected pread length",
                { "buf_len": buf.len(), "expected": total }
            );
        }

        // Lock each target page and pre-allocate its destination buffer so the
        // completion callback only parses headers, decrypts/verifies, and copies.
        let mut slots: Vec<(PageRef, Arc<Buffer>)> = Vec::with_capacity(count);
        for page in pages.iter() {
            #[cfg(debug_assertions)]
            {
                turso_assert!(
                    !page.is_locked(), "read_frames_batch target page must not already be locked",
                    { "page_id": page.get().id }
                );
                turso_assert!(
                    !page.is_loaded(), "read_frames_batch target page must be an unloaded scratch page",
                    { "page_id": page.get().id }
                );
                turso_assert!(
                    page.get().buffer.is_none(),
                    "read_frames_batch target page must not already retain a buffer",
                    { "page_id": page.get().id }
                );
            }
            page.set_locked();
            slots.push((page.clone(), Arc::new(buffer_pool.get_page())));
        }

        let epoch = self.coordination.checkpoint_epoch();
        let enc_or_csum = self.io_ctx.read().encryption_or_checksum().clone();
        let raw_buf = scratch_buf.unwrap_or_else(|| Arc::new(Buffer::new_temporary(total)));

        let complete = Box::new(move |res: Result<(Arc<Buffer>, i32), CompletionError>| {
            let clear_slots_on_err = |slots: &[(PageRef, Arc<Buffer>)]| {
                for (page, _) in slots {
                    page.clear_locked();
                    page.clear_wal_tag();
                }
            };

            let Ok((buf, bytes_read)) = res else {
                tracing::debug!(err = ?res.unwrap_err());
                clear_slots_on_err(&slots);
                return None;
            };
            if bytes_read != total as i32 {
                tracing::debug!(
                    "short read on WAL batch at offset {offset}: expected {total} bytes, got {bytes_read}"
                );
                clear_slots_on_err(&slots);
                return Some(CompletionError::ShortReadWalFrame {
                    offset,
                    expected: total,
                    actual: bytes_read as usize,
                });
            }
            let raw = buf.as_slice();
            for (i, (page, page_buf)) in slots.iter().enumerate() {
                let frame_start = i * frame_size;
                let frame = &raw[frame_start..frame_start + frame_size];
                let (header, page_body) = sqlite3_ondisk::parse_wal_frame_header(frame);
                let expected_page_id = page.get().id;
                if header.page_number as usize != expected_page_id {
                    mark_unlikely();
                    tracing::error!(
                        frame_id = start_frame + i as u64,
                        expected = expected_page_id,
                        got = header.page_number,
                        "WAL batch frame page_no mismatch"
                    );
                    clear_slots_on_err(&slots);
                    return Some(CompletionError::WalFramePageMismatch {
                        frame_id: start_frame + i as u64,
                        expected: expected_page_id,
                        actual: header.page_number,
                    });
                }

                let body_slice = page_buf.as_mut_slice();
                turso_assert!(
                    body_slice.len() == page_size,
                    "read_frames_batch buffer size must match WAL page size",
                    { "buffer_len": body_slice.len(), "page_size": page_size }
                );
                body_slice.copy_from_slice(page_body);

                match &enc_or_csum {
                    EncryptionOrChecksum::Encryption(ctx) => {
                        match ctx.decrypt_page(body_slice, expected_page_id) {
                            Ok(decrypted) => body_slice.copy_from_slice(&decrypted),
                            Err(e) => {
                                mark_unlikely();
                                tracing::error!(
                                    "Failed to decrypt WAL batch frame for page_idx={expected_page_id}: {e}"
                                );
                                clear_slots_on_err(&slots);
                                return Some(CompletionError::DecryptionError {
                                    page_idx: expected_page_id,
                                });
                            }
                        }
                    }
                    EncryptionOrChecksum::Checksum(ctx) => {
                        if let Err(e) = ctx.verify_checksum(body_slice, expected_page_id) {
                            mark_unlikely();
                            tracing::error!(
                                "Failed to verify checksum for page_id={expected_page_id}: {e}"
                            );
                            clear_slots_on_err(&slots);
                            return Some(e);
                        }
                    }
                    EncryptionOrChecksum::None => {}
                }
            }

            for (i, (page, page_buf)) in slots.iter().enumerate() {
                let page_id = page.get().id;
                finish_read_page(page_id, page_buf.clone(), page.clone());
                page.set_wal_tag(start_frame + i as u64, epoch);
            }
            None
        });

        let c = Completion::new_read(raw_buf, complete);
        let file = self.coordination.wal_file()?;
        file.pread(offset, c)
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    // todo(sivukhin): change API to accept Buffer or some other owned type
    // this method involves IO and cross "async" boundary - so juggling with references is bad and dangerous
    fn read_frame_raw(&self, frame_id: u64, frame: &mut [u8]) -> Result<Completion> {
        tracing::debug!("read_frame_raw({})", frame_id);
        let offset = self.frame_offset(frame_id);

        // HACK: *mut u8 can't be Sent between threads safely, cast it to usize then
        // for the time of writing this comment - this is *safe* as all callers immediately call synchronous method wait_for_completion and hold necessary references
        let (frame_ptr, frame_len) = (frame.as_mut_ptr() as usize, frame.len());

        let encryption_ctx = {
            let io_ctx = self.io_ctx.read();
            io_ctx.encryption_context().cloned()
        };
        let complete = Box::new(move |res: Result<(Arc<Buffer>, i32), CompletionError>| {
            let Ok((buf, bytes_read)) = res else {
                return None; // IO error already captured in completion
            };
            let buf_len = buf.len();
            if bytes_read != buf_len as i32 {
                tracing::debug!(
                    "short read on WAL frame {frame_id} at offset {offset}: expected {buf_len} bytes, got {bytes_read}"
                );
                return Some(CompletionError::ShortReadWalFrame {
                    offset,
                    expected: buf_len,
                    actual: bytes_read as usize,
                });
            }
            let buf_ptr = buf.as_ptr();
            let frame_ptr = frame_ptr as *mut u8;
            let frame_ref: &mut [u8] =
                unsafe { std::slice::from_raw_parts_mut(frame_ptr, frame_len) };

            // Copy the just-read WAL frame into the destination buffer
            unsafe {
                std::ptr::copy_nonoverlapping(buf_ptr, frame_ptr, frame_len);
            }

            // Now parse the header from the freshly-copied data
            let (header, raw_page) = sqlite3_ondisk::parse_wal_frame_header(frame_ref);

            if let Some(ctx) = encryption_ctx.clone() {
                match ctx.decrypt_page(raw_page, header.page_number as usize) {
                    Ok(decrypted_data) => {
                        turso_assert!(
                            (frame_len - WAL_FRAME_HEADER_SIZE) == decrypted_data.len(),
                            "frame_len minus header_size does not equal expected decrypted data length",
                            { "frame_len_minus_header": frame_len - WAL_FRAME_HEADER_SIZE, "decrypted_data_len": decrypted_data.len() }
                        );
                        frame_ref[WAL_FRAME_HEADER_SIZE..].copy_from_slice(&decrypted_data);
                    }
                    Err(_) => {
                        tracing::debug!("Failed to decrypt page data for frame_id={frame_id}");
                    }
                }
            }
            None
        });
        let file = self.coordination.wal_file()?;
        let c = begin_read_wal_frame_raw(&self.buffer_pool, file.as_ref(), offset, complete)?;
        Ok(c)
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    // todo(sivukhin): change API to accept Buffer or some other owned type
    // this method involves IO and cross "async" boundary - so juggling with references is bad and dangerous
    fn write_frame_raw(
        &self,
        buffer_pool: Arc<BufferPool>,
        frame_id: u64,
        page_id: u64,
        db_size: u64,
        page: &[u8],
        sync_type: FileSyncType,
    ) -> Result<()> {
        let Some(page_size) = PageSize::new(page.len() as u32) else {
            bail_corrupt_error!("invalid page size: {}", page.len());
        };
        self.ensure_header_if_needed(page_size, sync_type)?;
        tracing::debug!("write_raw_frame({})", frame_id);
        // if page_size wasn't initialized before - we will initialize it during that raw write
        if self.page_size() != 0 && page.len() != self.page_size() as usize {
            return Err(LimboError::InvalidArgument(format!(
                "unexpected page size in frame: got={}, expected={}",
                page.len(),
                self.page_size(),
            )));
        }
        if frame_id > self.max_frame.load(Ordering::Acquire) + 1 {
            // attempt to write frame out of sequential order - error out
            return Err(LimboError::InvalidArgument(format!(
                "frame_id is beyond next frame in the WAL: frame_id={}, max_frame={}",
                frame_id,
                self.max_frame.load(Ordering::Acquire)
            )));
        }
        if frame_id <= self.max_frame.load(Ordering::Acquire) {
            // just validate if page content from the frame matches frame in the WAL
            let offset = self.frame_offset(frame_id);
            let conflict = Arc::new(Mutex::new(false));

            // HACK: *mut u8 can't be shared between threads safely, cast it to usize then
            // for the time of writing this comment - this is *safe* as the function immediately call synchronous method wait_for_completion and hold necessary references
            let (page_ptr, page_len) = (page.as_ptr() as usize, page.len());

            let complete = Box::new({
                let conflict = conflict.clone();
                move |res: Result<(Arc<Buffer>, i32), CompletionError>| {
                    let Ok((buf, bytes_read)) = res else {
                        return None; // IO error already captured in completion
                    };
                    let buf_len = buf.len();
                    if bytes_read != buf_len as i32 {
                        tracing::debug!(
                            "short read on WAL frame validation at offset {offset}, page_id={page_id}: expected {buf_len} bytes, got {bytes_read}"
                        );
                        return Some(CompletionError::ShortReadWalFrame {
                            offset,
                            expected: buf_len,
                            actual: bytes_read as usize,
                        });
                    }
                    let page = unsafe { std::slice::from_raw_parts(page_ptr as *mut u8, page_len) };
                    if buf.as_slice() != page {
                        *conflict.lock() = true;
                    }
                    None
                }
            });
            let file = self.coordination.wal_file()?;
            let c = begin_read_wal_frame(
                file.as_ref(),
                offset + WAL_FRAME_HEADER_SIZE as u64,
                buffer_pool,
                complete,
                page_id as usize,
                &self.io_ctx.read(),
            )?;
            self.io.wait_for_completion(c)?;
            return if *conflict.lock() {
                Err(LimboError::Conflict(format!(
                    "frame content differs from the WAL: frame_id={frame_id}"
                )))
            } else {
                Ok(())
            };
        }

        // perform actual write
        let offset = self.frame_offset(frame_id);
        let header = self.coordination.wal_header();
        let file = self.coordination.wal_file()?;
        let checksums = *self.last_checksum.read();
        let (checksums, frame_bytes) = prepare_wal_frame(
            &self.buffer_pool,
            &header,
            checksums,
            header.page_size,
            page_id as u32,
            db_size as u32,
            page,
        );
        let c = Completion::new_write(|_| {});
        let c = file.pwrite(offset, frame_bytes, c)?;
        self.io.wait_for_completion(c)?;
        self.complete_append_frame(page_id, frame_id, checksums);
        if db_size > 0 {
            self.finish_append_frames_commit()?;
        } else {
            self.has_unpublished_frames.store(true, Ordering::Release);
        }
        Ok(())
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    fn should_checkpoint(&self) -> bool {
        let snapshot = self.load_coordination_snapshot();
        snapshot.max_frame as usize > self.checkpoint_threshold + snapshot.nbackfills as usize
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    fn checkpoint(
        &self,
        pager: &Pager,
        mode: CheckpointMode,
    ) -> Result<IOResult<CheckpointResult>> {
        self.checkpoint_inner(pager, mode, CheckpointLockSource::Acquire)
            .inspect_err(|e| {
                tracing::debug!("WAL checkpoint failed: {e}");
                let _ = self.checkpoint_guard.write().take();
                self.ongoing_checkpoint.write().state = CheckpointState::Start;
            })
    }

    fn vacuum_checkpoint_with_held_lock(
        &self,
        pager: &Pager,
    ) -> Result<IOResult<CheckpointResult>> {
        self.checkpoint_inner(
            pager,
            CheckpointMode::Truncate {
                upper_bound_inclusive: None,
            },
            CheckpointLockSource::HeldByCaller,
        )
        .inspect_err(|e| {
            tracing::debug!("WAL checkpoint failed: {e}");
            let _ = self.checkpoint_guard.write().take();
            self.ongoing_checkpoint.write().state = CheckpointState::Start;
        })
    }

    fn install_durable_backfill_proof(
        &self,
        max_frame: u64,
        db_size_pages: u32,
        db_header_crc32c: u32,
        sync_type: FileSyncType,
    ) -> Result<Option<Completion>> {
        self.coordination.install_durable_backfill_proof(
            max_frame,
            db_size_pages,
            db_header_crc32c,
            sync_type,
        )
    }

    fn publish_backfill(&self, max_frame: u64) {
        self.coordination.publish_backfill(max_frame);
    }

    #[instrument(err, skip_all, level = Level::DEBUG)]
    fn sync(&self, sync_type: FileSyncType) -> Result<Completion> {
        tracing::debug!("wal_sync");
        let syncing = self.syncing.clone();
        let completion = Completion::new_sync(move |result| {
            tracing::debug!("wal_sync finish");
            if let Err(err) = result {
                tracing::debug!("wal_sync failed: {err}");
            }
            syncing.store(false, Ordering::Release);
        });
        let file = self.coordination.wal_file()?;
        self.syncing.store(true, Ordering::Release);
        let c = file.sync(completion, sync_type)?;
        Ok(c)
    }

    // Currently used for assertion purposes
    fn is_syncing(&self) -> bool {
        self.syncing.load(Ordering::Acquire)
    }

    fn get_max_frame_in_wal(&self) -> u64 {
        self.load_coordination_snapshot().max_frame
    }

    fn get_checkpoint_seq(&self) -> u32 {
        self.load_coordination_snapshot().checkpoint_seq
    }

    fn get_max_frame(&self) -> u64 {
        self.max_frame.load(Ordering::Acquire)
    }

    fn get_min_frame(&self) -> u64 {
        self.min_frame.load(Ordering::Acquire)
    }

    fn get_last_checksum(&self) -> (u32, u32) {
        *self.last_checksum.read()
    }
    #[instrument(skip_all, level = Level::DEBUG)]

    fn rollback(&self, rollback_to: Option<RollbackTo>) {
        let is_savepoint = rollback_to.is_some();
        let snapshot = self.load_coordination_snapshot();
        let max_frame = rollback_to
            .as_ref()
            .map(|r| r.frame)
            .unwrap_or(snapshot.max_frame);
        let last_checksum = rollback_to
            .as_ref()
            .map(|r| r.checksum)
            .unwrap_or(snapshot.last_checksum);
        // Savepoints can be opened on a stale connection-local WAL snapshot.
        // Do not let that rollback remove frame-cache mappings for frames that
        // are already globally committed by another connection.
        let cache_rollback_frame = if is_savepoint {
            max_frame.max(snapshot.max_frame)
        } else {
            max_frame
        };
        self.coordination.rollback_cache(cache_rollback_frame);
        *self.last_checksum.write() = last_checksum;
        self.max_frame.store(max_frame, Ordering::Release);
        if !is_savepoint {
            self.reset_internal_states();
        }
    }

    fn abort_checkpoint(&self) {
        let _ = self.checkpoint_guard.write().take();
        self.reset_internal_states();
    }

    fn try_begin_vacuum_checkpoint_lock(&self) -> Result<()> {
        self.with_shared(|shared| {
            if !shared.runtime.checkpoint_lock.write() {
                return Err(LimboError::Busy);
            }
            Ok(())
        })
    }

    fn release_vacuum_checkpoint_lock(&self) {
        self.with_shared(|shared| {
            shared.runtime.checkpoint_lock.unlock();
        });
    }

    fn begin_vacuum_blocking_tx(&self) -> Result<()> {
        turso_assert!(
            self.max_frame_read_lock_index.load(Ordering::Acquire) == NO_LOCK_HELD,
            "begin_vacuum_blocking_tx: must not already hold a read lock"
        );
        turso_assert!(
            !self.holds_write_lock(),
            "begin_vacuum_blocking_tx: must not already hold the write lock"
        );
        turso_assert!(
            self.vacuum_lock_guard.read().is_none(),
            "VACUUM lock guard already held"
        );

        let Some(vacuum_lock_guard) =
            VacuumLockGuard::try_write(self.coordination.shared_wal_state())
        else {
            return Err(LimboError::Busy);
        };

        // This block is purely an invariant check. The exclusive VACUUM lock can be held
        // only if we don't have any other active locks.
        self.with_shared(|shared| {
            for idx in 0..shared.runtime.read_locks.len() {
                // iff there are no read locks active, only then we should be able to
                // acquire the write lock
                turso_assert!(
                    shared.runtime.read_locks[idx].write(),
                    "begin_vacuum_blocking_tx: read lock held after VACUUM lock acquired",
                    { "read_lock_idx": idx }
                );
                shared.runtime.read_locks[idx].unlock();
            }
        });

        // Install connection state with a fresh snapshot.
        let snapshot = self.load_coordination_snapshot();
        self.install_connection_state(WalConnectionState::new(snapshot, ReadGuardKind::None));
        turso_assert!(
            self.with_shared(|shared| shared.runtime.write_lock.write()),
            "begin_vacuum_blocking_tx: write lock held after VACUUM lock acquired"
        );
        if self
            .write_lock_held
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            turso_assert!(
                false,
                "begin_vacuum_blocking_tx: write_lock_held already set"
            );
        }
        self.install_vacuum_lock_guard(vacuum_lock_guard);
        Ok(())
    }

    fn release_vacuum_lock(&self) {
        // This drops the stop-the-world gate after VACUUM is one.
        // Only after this new readers can proceed.
        turso_assert!(
            !self.holds_write_lock(),
            "release_vacuum_lock called while source write lock is still held"
        );
        self.release_vacuum_write_lock_guard();
    }

    #[instrument(skip_all, level = Level::DEBUG)]
    fn finish_append_frames_commit(&self) -> Result<()> {
        let max_frame = self.max_frame.load(Ordering::Acquire);
        let last_checksum = *self.last_checksum.read();
        tracing::trace!(max_frame, ?last_checksum);
        let transaction_count = self.transaction_count.fetch_add(1, Ordering::AcqRel) + 1;
        self.coordination.publish_commit(WalCommitState {
            max_frame,
            last_checksum,
            transaction_count,
        });
        self.has_unpublished_frames.store(false, Ordering::Release);
        Ok(())
    }

    fn changed_pages_after(&self, frame_watermark: u64) -> Result<Vec<u32>> {
        let frame_count = self.get_max_frame();
        let page_size = self.page_size();
        let mut frame = vec![0u8; page_size as usize + WAL_FRAME_HEADER_SIZE];
        let mut seen = FxHashSet::default();
        turso_assert!(
            frame_count >= frame_watermark,
            "frame_count must be not less than frame_watermark",
            { "frame_count": frame_count, "frame_watermark": frame_watermark }
        );
        let mut pages = Vec::with_capacity((frame_count - frame_watermark) as usize);
        for frame_no in frame_watermark + 1..=frame_count {
            let c = self.read_frame_raw(frame_no, &mut frame)?;
            self.io.wait_for_completion(c)?;
            let (header, _) = sqlite3_ondisk::parse_wal_frame_header(&frame);
            if seen.insert(header.page_number) {
                pages.push(header.page_number);
            }
        }
        Ok(pages)
    }

    fn prepare_wal_start(&self, page_size: PageSize) -> Result<Option<Completion>> {
        if self.coordination.wal_is_initialized() {
            return Ok(None);
        }
        tracing::debug!("ensure_header_if_needed");
        let Some(header) = self
            .coordination
            .prepare_wal_header(self.io.as_ref(), page_size)
        else {
            return Ok(None);
        };
        *self.last_checksum.write() = (header.checksum_1, header.checksum_2);

        self.max_frame.store(0, Ordering::Release);
        let file = self.coordination.wal_file()?;
        let header_c = sqlite3_ondisk::begin_write_wal_header(file.as_ref(), &header)?;

        // After a RESTART or try_restart_log_before_write the WAL file may
        // still contain orphaned frames from the previous epoch. Truncate
        // them so that classify_authority_snapshot_against_wal does not see a
        // length mismatch and unnecessarily fall back to a full disk scan
        // (which can race with concurrent writers and corrupt the authority).
        let should_skip_truncate = match file.size() {
            Ok(size) => size <= WAL_HEADER_SIZE as u64,
            Err(_) => {
                tracing::warn!("Failed to get WAL file size");
                true
            }
        };
        if !should_skip_truncate {
            let trunc_c = file.truncate(
                WAL_HEADER_SIZE as u64,
                Completion::new_trunc(|res| {
                    if let Err(err) = res {
                        tracing::warn!("WAL truncate of orphaned frames failed: {err}");
                    }
                }),
            )?;
            let mut group = CompletionGroup::new(|_| {});
            group.add(&header_c);
            group.add(&trunc_c);
            Ok(Some(group.build()))
        } else {
            Ok(Some(header_c))
        }
    }

    fn prepare_wal_finish(&self, sync_type: FileSyncType) -> Result<Completion> {
        let file = self.coordination.wal_file()?;
        let coordination = self.coordination.clone();
        let c = file.sync(
            Completion::new_sync(move |_| {
                coordination.mark_initialized();
            }),
            sync_type,
        )?;
        Ok(c)
    }

    /// Prepares a batch of dirty pages as WAL frames without modifying WAL state.
    ///
    /// This is the first phase of a three-phase commit protocol:
    /// 1. prepare (`prepare_frames`) - serialize frames, compute checksums
    /// 2. write + fsync - caller submits I/O and waits for durability
    /// 3. commit/finalize (`commit_prepared_frames`) - update WAL index and page metadata
    ///
    /// WAL frames form a checksum chain for corruption detection. When writing
    /// multiple batches in a single transaction, pass the previous batch via `prev`
    /// to continue the chain. For the first batch, pass `None` to start from
    /// the committed WAL state.
    fn prepare_frames(
        &self,
        pages: &[PageRef],
        page_sz: PageSize,
        db_size_on_commit: Option<u32>,
        prev: Option<&PreparedFrames>,
    ) -> Result<PreparedFrames> {
        turso_assert!(
            !pages.is_empty(),
            "prepare_frames requires at least one page"
        );
        turso_assert!(
            pages.len() <= IOV_MAX,
            "supported up to IOV_MAX pages at once"
        );
        turso_assert!(
            self.coordination.wal_is_initialized(),
            "WAL must be initialized"
        );

        let header = self.coordination.wal_header();
        let epoch = self.coordination.checkpoint_epoch();

        turso_assert!(
            header.page_size == page_sz.get(),
            "page size mismatch between header and requested",
            { "header_page_size": header.page_size, "requested_page_size": page_sz.get() }
        );

        // Either chain from previous batch of PreparedFrames or use committed WAL state.
        // For the first batch, also check the authority's max_frame to handle
        // cross-process WAL restarts where our local max_frame is stale.
        let (mut rolling_checksum, mut next_frame_id) = match prev {
            Some(p) => (p.final_checksum, p.final_max_frame + 1),
            None => {
                let snapshot = self.load_coordination_snapshot();
                let local_state = self.connection_state();
                let local_prepared_zero_frame_header = snapshot.max_frame == 0
                    && self.coordination.wal_is_initialized()
                    && local_state.snapshot.max_frame == 0
                    && local_state.snapshot.checkpoint_seq == snapshot.checkpoint_seq
                    && local_state.snapshot.transaction_count == snapshot.transaction_count
                    && local_state.snapshot.last_checksum != snapshot.last_checksum;
                if local_prepared_zero_frame_header {
                    // We already prepared the WAL header for the current
                    // zero-frame generation locally, but the authority snapshot
                    // still carries the pre-header checksum until the first
                    // commit publishes it. Seed the checksum chain from the
                    // prepared local header, not the stale authority checksum.
                    (
                        local_state.snapshot.last_checksum,
                        local_state.snapshot.max_frame + 1,
                    )
                } else if snapshot != local_state.snapshot {
                    if self.has_unpublished_frames.load(Ordering::Acquire) {
                        // write_frame_raw appended frames without a commit
                        // marker (db_size == 0), so the coordination backend's
                        // max_frame is behind our local max_frame. Chain from
                        // local state so we don't overwrite those frames.
                        (
                            local_state.snapshot.last_checksum,
                            local_state.snapshot.max_frame + 1,
                        )
                    } else {
                        // The current generation was restarted/truncated back to
                        // frame 0 or another process changed the durable WAL
                        // state. Re-seed this connection from the authoritative
                        // snapshot so replacement generations after
                        // RESTART/TRUNCATE do not append using stale local state.
                        self.install_connection_state(local_state.with_snapshot(snapshot));
                        (snapshot.last_checksum, snapshot.max_frame + 1)
                    }
                } else {
                    (
                        local_state.snapshot.last_checksum,
                        local_state.snapshot.max_frame + 1,
                    )
                }
            }
        };

        let first_frame_id = next_frame_id;

        let mut bufs: Vec<Arc<Buffer>> = Vec::with_capacity(pages.len());
        let mut metadata = Vec::with_capacity(pages.len());

        for (idx, page) in pages.iter().enumerate() {
            let page_id = page.get().id;
            let plain = page.get_contents().as_ptr();

            let data: Cow<[u8]> = {
                let io_ctx = self.io_ctx.read();
                match io_ctx.encryption_or_checksum() {
                    EncryptionOrChecksum::Encryption(ctx) => {
                        Cow::Owned(ctx.encrypt_page(plain, page_id)?)
                    }
                    EncryptionOrChecksum::Checksum(ctx) => {
                        ctx.add_checksum_to_page(plain, page_id)?;
                        Cow::Borrowed(plain)
                    }
                    EncryptionOrChecksum::None => Cow::Borrowed(plain),
                }
            };

            // if DB size is included for commit frame, it will need to be included only in the last frame of the batch.
            // however it might not be present in this batch so we cannot assert its presence
            let frame_db_size = if idx + 1 == pages.len() {
                db_size_on_commit.unwrap_or(0)
            } else {
                0
            };
            let (checksum, frame_buf) = prepare_wal_frame(
                &self.buffer_pool,
                &header,
                rolling_checksum,
                header.page_size,
                page_id as u32,
                frame_db_size,
                &data,
            );
            bufs.push(frame_buf);
            metadata.push((page.clone(), next_frame_id, checksum));
            rolling_checksum = checksum;
            next_frame_id += 1;
        }
        let offset = self.frame_offset(first_frame_id);
        Ok(PreparedFrames {
            offset,
            bufs,
            metadata,
            final_checksum: rolling_checksum,
            final_max_frame: next_frame_id - 1,
            epoch,
        })
    }

    /// For each prepared frame, update in-memory WAL index and rolling checksum.
    /// and advance max_frame to make frames visible to readers.
    fn commit_prepared_frames(&self, batches: &[PreparedFrames]) {
        for batch in batches {
            for (page, frame_id, checksum) in &batch.metadata {
                // Update WAL index mapping page -> frame
                self.complete_append_frame(page.get().id as u64, *frame_id, *checksum);
            }
            // Update rolling checksum
            *self.last_checksum.write() = batch.final_checksum;
            // Advance max_frame and make frames visible to readers
            self.max_frame
                .store(batch.final_max_frame, Ordering::Release);
        }
    }

    /// Mark pages clean and set WAL tags after durable commit.
    fn finalize_committed_pages(&self, prepared: &[PreparedFrames]) {
        for batch in prepared {
            for (page, frame_id, _) in &batch.metadata {
                page.clear_dirty();
                page.set_wal_tag(*frame_id, batch.epoch);
            }
        }
    }

    /// Get WAL file for durable writes.
    fn wal_file(&self) -> Result<Arc<dyn File>> {
        self.coordination.wal_file()
    }

    /// Use pwritev to append many frames to the log at once.
    ///
    /// # Safety:
    /// this method should only be used for cacheflush/spilling,
    /// the commit path should use prepare_frames + commit_prepared_frames instead,
    /// as it prevents prematurely modifing WAL state before durability is ensured.
    fn append_frames_vectored(&self, pages: Vec<PageRef>, page_sz: PageSize) -> Result<Completion> {
        turso_assert!(
            pages.len() <= IOV_MAX,
            "we limit number of iovecs to IOV_MAX"
        );
        turso_assert!(
            self.coordination.wal_is_initialized(),
            "WAL must be prepared with prepare_wal_start/prepare_wal_finish method"
        );

        let header = self.coordination.wal_header();
        let shared_page_size = header.page_size;
        let epoch = self.coordination.checkpoint_epoch();
        turso_assert!(
            shared_page_size == page_sz.get(),
            "page size mismatch, tried to change page size after WAL header was already initialized",
            { "shared_page_size": shared_page_size, "page_size": page_sz.get() }
        );

        // Prepare write buffers and bookkeeping
        let mut iovecs: Vec<Arc<Buffer>> = Vec::with_capacity(pages.len());
        let mut page_frame_and_checksum: Vec<(PageRef, u64, (u32, u32))> =
            Vec::with_capacity(pages.len());

        // Rolling checksum input to each frame build
        let mut rolling_checksum: (u32, u32) = *self.last_checksum.read();

        let mut next_frame_id = self.max_frame.load(Ordering::Acquire) + 1;
        // Build every frame in order, updating the rolling checksum
        for page in pages.iter() {
            tracing::debug!("append_frames_vectored: page_id={}", page.get().id);
            let page_id = page.get().id;
            let plain = page.get_contents().as_ptr();

            let data_to_write: std::borrow::Cow<[u8]> = {
                let io_ctx = self.io_ctx.read();
                match &io_ctx.encryption_or_checksum() {
                    EncryptionOrChecksum::Encryption(ctx) => {
                        Cow::Owned(ctx.encrypt_page(plain, page_id)?)
                    }
                    EncryptionOrChecksum::Checksum(ctx) => {
                        ctx.add_checksum_to_page(plain, page_id)?;
                        Cow::Borrowed(plain)
                    }
                    EncryptionOrChecksum::None => Cow::Borrowed(plain),
                }
            };

            let frame_db_size = 0; // this method is not used for the commit path
            let (new_checksum, frame_bytes) = prepare_wal_frame(
                &self.buffer_pool,
                &header,
                rolling_checksum,
                shared_page_size,
                page_id as u32,
                frame_db_size,
                &data_to_write,
            );
            iovecs.push(frame_bytes);

            // (page, assigned_frame_id, cumulative_checksum_at_this_frame)
            page_frame_and_checksum.push((page.clone(), next_frame_id, new_checksum));

            // Advance for the next frame
            rolling_checksum = new_checksum;
            next_frame_id += 1;
        }

        let first_frame_id = self.max_frame.load(Ordering::Acquire) + 1;
        let start_off = self.frame_offset(first_frame_id);

        // single completion for the whole batch
        let total_len: i32 = iovecs.iter().map(|b| b.len() as i32).sum();
        let page_frame_for_cb = page_frame_and_checksum.clone();
        let cmp = move |res: Result<i32, CompletionError>| {
            let Ok(bytes_written) = res else {
                return;
            };
            turso_assert!(
                bytes_written == total_len,
                "pwritev wrote unexpected number of bytes",
                { "bytes_written": bytes_written, "expected": total_len }
            );

            for (page, fid, _csum) in &page_frame_for_cb {
                page.clear_dirty();
                page.set_wal_tag(*fid, epoch);
            }
        };

        let c = Completion::new_write(cmp);

        let file = self.coordination.wal_file()?;
        let c = file.pwritev(start_off, iovecs, c)?;

        self.io.drain_completions(std::slice::from_ref(&c))?;

        for (page, fid, csum) in &page_frame_and_checksum {
            self.complete_append_frame(page.get().id as u64, *fid, *csum);
        }

        Ok(c)
    }

    #[cfg(any(test, debug_assertions))]
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn set_io_context(&self, ctx: IOContext) {
        *self.io_ctx.write() = ctx;
    }

    fn update_max_frame(&self) {
        let new_max_frame = self.load_coordination_snapshot().max_frame;
        self.max_frame.store(new_max_frame, Ordering::Release);
    }

    fn truncate_wal(
        &self,
        result: &mut CheckpointResult,
        sync_type: FileSyncType,
    ) -> Result<IOResult<()>> {
        self.truncate_log(result, sync_type)
    }
}

impl WalFile {
    #[cfg(host_shared_wal)]
    pub(crate) fn new_with_shared_coordination(
        io: Arc<dyn IO>,
        shared: Arc<RwLock<WalFileShared>>,
        authority: Arc<MappedSharedWalCoordination>,
        _last_checksum_and_max_frame: ((u32, u32), u64),
        buffer_pool: Arc<BufferPool>,
    ) -> Self {
        let coordination: Arc<dyn WalCoordination> =
            Arc::new(ShmWalCoordination::new(shared, authority));
        let snapshot = coordination.load_snapshot();
        Self::new_with_coordination(
            io,
            coordination,
            (snapshot.last_checksum, snapshot.max_frame),
            buffer_pool,
        )
    }

    pub fn new(
        io: Arc<dyn IO>,
        shared: Arc<RwLock<WalFileShared>>,
        (last_checksum, max_frame): ((u32, u32), u64),
        buffer_pool: Arc<BufferPool>,
    ) -> Self {
        let coordination: Arc<dyn WalCoordination> =
            Arc::new(InProcessWalCoordination::new(shared));
        Self::new_with_coordination(io, coordination, (last_checksum, max_frame), buffer_pool)
    }

    /// Construct a WAL using an explicit coordination backend.
    fn new_with_coordination(
        io: Arc<dyn IO>,
        coordination: Arc<dyn WalCoordination>,
        (last_checksum, max_frame): ((u32, u32), u64),
        buffer_pool: Arc<BufferPool>,
    ) -> Self {
        let now = io.current_time_monotonic();
        Self {
            io,
            coordination,
            // default to max frame in WAL, so that when we read schema we can read from WAL too if it's there.
            max_frame: AtomicU64::new(max_frame),
            ongoing_checkpoint: RwLock::new(OngoingCheckpoint {
                time: now,
                pending_writes: WriteBatch::new(),
                inflight_writes: Vec::new(),
                state: CheckpointState::Start,
                min_frame: 0,
                max_frame: 0,
                current_page: 0,
                pages_to_checkpoint: Vec::new(),
                inflight_reads: Vec::with_capacity(MAX_INFLIGHT_READS),
            }),
            checkpoint_threshold: 1000,
            buffer_pool,
            checkpoint_seq: AtomicU32::new(0),
            syncing: Arc::new(AtomicBool::new(false)),
            write_lock_held: AtomicBool::new(false),
            vacuum_lock_guard: RwLock::new(None),
            min_frame: AtomicU64::new(0),
            transaction_count: AtomicU64::new(0),
            max_frame_read_lock_index: AtomicUsize::new(NO_LOCK_HELD),
            last_checksum: RwLock::new(last_checksum),
            checkpoint_guard: RwLock::new(None),
            io_ctx: RwLock::new(IOContext::default()),
            has_unpublished_frames: AtomicBool::new(false),
        }
    }

    #[cfg(test)]
    pub(crate) fn shared_ptr(&self) -> usize {
        self.coordination.shared_ptr()
    }

    #[cfg(test)]
    pub(crate) fn coordination_backend_name(&self) -> &'static str {
        self.coordination.backend_name()
    }

    #[cfg(test)]
    pub(crate) fn coordination_open_mode_name(&self) -> Option<&'static str> {
        self.coordination.open_mode_name()
    }

    fn with_shared<F, R>(&self, func: F) -> R
    where
        F: FnOnce(&WalFileShared) -> R,
    {
        let shared = self.coordination.shared_wal_state();
        let guard = shared.read();
        func(&guard)
    }

    fn page_size(&self) -> u32 {
        self.coordination.wal_header().page_size
    }

    fn frame_offset(&self, frame_id: u64) -> u64 {
        turso_assert_greater_than!(frame_id, 0, "Frame ID must be 1-based");
        let page_offset = (frame_id - 1) * (self.page_size() + WAL_FRAME_HEADER_SIZE as u32) as u64;
        WAL_HEADER_SIZE as u64 + page_offset
    }

    fn increment_checkpoint_epoch(&self) {
        let prev = self.coordination.bump_checkpoint_epoch();
        tracing::debug!("increment checkpoint epoch: prev={}", prev);
    }

    fn complete_append_frame(&self, page_id: u64, frame_id: u64, checksums: (u32, u32)) {
        *self.last_checksum.write() = checksums;
        self.max_frame.store(frame_id, Ordering::Release);
        self.coordination.cache_frame(page_id, frame_id);
    }

    /// Reset connection-private WAL state.
    fn reset_internal_states(&self) {
        self.ongoing_checkpoint.write().reset();
        self.syncing.store(false, Ordering::Release);
    }

    /// the WAL file has been truncated and we are writing the first
    /// frame since then. We need to ensure that the header is initialized.
    fn ensure_header_if_needed(&self, page_size: PageSize, sync_type: FileSyncType) -> Result<()> {
        let Some(c) = self.prepare_wal_start(page_size)? else {
            return Ok(());
        };
        self.io.wait_for_completion(c)?;
        let c = self.prepare_wal_finish(sync_type)?;
        self.io.wait_for_completion(c)?;
        Ok(())
    }

    fn checkpoint_inner(
        &self,
        pager: &Pager,
        mode: CheckpointMode,
        lock_source: CheckpointLockSource,
    ) -> Result<IOResult<CheckpointResult>> {
        loop {
            let state = self.ongoing_checkpoint.read().state.clone();
            tracing::debug!(?state);
            match state {
                // Acquire the relevant exclusive locks and checkpoint_lock
                // so no other checkpointer can run. fsync WAL if there are unapplied frames.
                // Decide the largest frame we are allowed to back‑fill.
                CheckpointState::Start => {
                    let snapshot = self.load_coordination_snapshot();
                    let max_frame = snapshot.max_frame;
                    let nbackfills = snapshot.nbackfills;
                    tracing::debug!("shared_wal: max_frame={max_frame}, nbackfills={nbackfills}");
                    let needs_backfill = max_frame > nbackfills;
                    if matches!(lock_source, CheckpointLockSource::HeldByCaller) {
                        turso_assert!(
                            needs_backfill,
                            "held checkpoint-lock path requires WAL frames to backfill",
                            { "max_frame": max_frame, "nbackfills": nbackfills }
                        );
                    }
                    if !needs_backfill && !mode.should_restart_log() {
                        // there are no frames to copy over and we don't need to reset
                        // the log so we can return early success.
                        return Ok(IOResult::Done(CheckpointResult::new(
                            max_frame, nbackfills, 0,
                        )));
                    }
                    // acquire the appropriate exclusive locks depending on the checkpoint mode
                    self.acquire_proper_checkpoint_guard(mode, lock_source)?;
                    let mut max_frame = self.determine_max_safe_checkpoint_frame();

                    if let CheckpointMode::Truncate {
                        upper_bound_inclusive: Some(upper_bound),
                    } = mode
                    {
                        if max_frame > upper_bound {
                            tracing::debug!(
                                "abort checkpoint because latest frame in WAL is greater than upper_bound in TRUNCATE mode: {max_frame} != {upper_bound}"
                            );
                            return Err(LimboError::Busy);
                        }
                    }
                    if let CheckpointMode::Passive {
                        upper_bound_inclusive: Some(upper_bound),
                    } = mode
                    {
                        max_frame = max_frame.min(upper_bound);
                    }

                    {
                        let mut oc = self.ongoing_checkpoint.write();
                        oc.max_frame = max_frame;
                        oc.min_frame = nbackfills + 1;
                    }
                    let (oc_min_frame, oc_max_frame) = {
                        let oc = self.ongoing_checkpoint.read();
                        (oc.min_frame, oc.max_frame)
                    };
                    self.coordination.ensure_local_frame_cache_covers(
                        &self.io,
                        WalSnapshot {
                            max_frame: oc_max_frame,
                            ..self.load_coordination_snapshot()
                        },
                    )?;
                    tracing::debug!(
                        "checkpoint_inner::Start: min_frame={oc_min_frame}, max_frame={oc_max_frame}"
                    );
                    let mut to_checkpoint = self
                        .coordination
                        .iter_latest_frames(oc_min_frame, oc_max_frame);
                    // sort by frame_id for read locality
                    to_checkpoint.sort_unstable_by(|a, b| (a.1, a.0).cmp(&(b.1, b.0)));
                    {
                        let mut oc = self.ongoing_checkpoint.write();
                        oc.pages_to_checkpoint = to_checkpoint;
                        oc.current_page = 0;
                        oc.inflight_writes.clear();
                        oc.inflight_reads.clear();
                        oc.state = CheckpointState::Processing;
                        oc.time = self.io.current_time_monotonic();
                    }
                    tracing::trace!(
                        "checkpoint_start(min_frame={}, max_frame={})",
                        oc_min_frame,
                        oc_max_frame,
                    );
                }
                // For locality, reading is ordered by frame ID, and writing ordered by page ID.
                // the more consecutive page ID's that we submit together, the fewer overall
                // write/writev syscalls made. All I/O during checkpointing is now in a single step
                // to prevent serialization, and we try to issue reads and flush batches concurrently
                // if at all possible, at the cost of some batching potential.
                CheckpointState::Processing => {
                    // Gather I/O completions using a completion group
                    let mut nr_completions = 0;
                    let mut group = CompletionGroup::new(|_| {});
                    let mut ongoing_chkpt = self.ongoing_checkpoint.write();

                    // Check and clean any completed writes from pending flush
                    if ongoing_chkpt.process_inflight_writes() {
                        tracing::trace!("Completed a write batch");
                    }
                    // Process completed reads into current batch
                    if ongoing_chkpt.process_pending_reads()? {
                        tracing::trace!("Drained reads into batch");
                    }
                    if let Some(e) = ongoing_chkpt.first_write_error() {
                        mark_unlikely();
                        // cancel everything still in-flight to avoid leaks
                        let to_cancel: Vec<Completion> = ongoing_chkpt
                            .inflight_reads
                            .iter()
                            .map(|r| r.completion.clone())
                            .collect();
                        pager.io.cancel(&to_cancel)?;
                        pager.io.drain_completions(&to_cancel)?;
                        return Err(LimboError::CompletionError(e));
                    }
                    let epoch = self.coordination.checkpoint_epoch();
                    // Issue reads until we hit limits
                    'inner: while ongoing_chkpt.should_issue_reads() {
                        let (page_id, target_frame) = {
                            ongoing_chkpt.pages_to_checkpoint[ongoing_chkpt.current_page as usize]
                        };
                        if let Some(cached_page) =
                            pager.cache_get_for_checkpoint(page_id as usize, target_frame, epoch)?
                        {
                            let buffer = cached_page
                                .get_contents()
                                .buffer
                                .as_ref()
                                .expect("buffer missing")
                                .clone();
                            // We debug assert that the cached page has the
                            // exact contents as one read from the WAL.
                            #[cfg(debug_assertions)]
                            {
                                let mut raw =
                                    vec![0u8; self.page_size() as usize + WAL_FRAME_HEADER_SIZE];
                                self.io.wait_for_completion(
                                    self.read_frame_raw(target_frame, &mut raw)?,
                                )?;
                                let (_, wal_page) = sqlite3_ondisk::parse_wal_frame_header(&raw);
                                let cached = buffer.as_slice();
                                turso_assert!(wal_page == cached, "cached page content differs from WAL read", { "page_id": page_id, "frame_id": target_frame });
                            }
                            {
                                ongoing_chkpt
                                    .pending_writes
                                    .insert(page_id as usize, buffer);
                                // signify that a cached page was used, so it can be unpinned
                                let current = ongoing_chkpt.current_page as usize;
                                ongoing_chkpt.pages_to_checkpoint[current] =
                                    (page_id, target_frame);
                                ongoing_chkpt.current_page += 1;
                            }
                            continue 'inner;
                        }
                        // Issue read if page wasn't found in the page cache or doesnt meet
                        // the frame requirements
                        let inflight =
                            self.issue_wal_read_into_buffer(page_id as usize, target_frame)?;
                        group.add(&inflight.completion);
                        nr_completions += 1;
                        ongoing_chkpt.inflight_reads.push(inflight);
                        ongoing_chkpt.current_page += 1;
                    }

                    // Start a write if batch is ready and we're not at write limit
                    let should_flush = ongoing_chkpt.inflight_writes.len() < MAX_INFLIGHT_WRITES
                        && ongoing_chkpt.should_flush_batch();
                    if should_flush {
                        let batch_map = ongoing_chkpt.pending_writes.take();
                        if !batch_map.is_empty() {
                            let new_write = InflightWriteBatch::new();
                            for c in write_pages_vectored(
                                pager,
                                batch_map,
                                new_write.done.clone(),
                                new_write.err.clone(),
                            )? {
                                group.add(&c);
                                nr_completions += 1;
                            }
                            ongoing_chkpt.inflight_writes.push(new_write);
                        }
                    }
                    if nr_completions > 0 {
                        io_yield_one!(group.build());
                    } else if ongoing_chkpt.complete() {
                        ongoing_chkpt.state = CheckpointState::DetermineResult;
                    } else {
                        // This should be impossible now so we treat it as logic error.
                        mark_unlikely();
                        return Err(LimboError::InternalError(
                            "checkpoint stuck: no inflight completions but not complete".into(),
                        ));
                    }
                }
                // All eligible frames copied to the db file.
                // Compute checkpoint result, update nBackfills, restart log if needed.
                CheckpointState::DetermineResult => {
                    let mut ongoing_chkpt = self.ongoing_checkpoint.write();
                    turso_assert!(
                        ongoing_chkpt.complete(),
                        "checkpoint pending flush must have finished"
                    );
                    let wal_max_frame = self.load_coordination_snapshot().max_frame;
                    let wal_total_backfilled = ongoing_chkpt.max_frame;
                    // Record two num pages fields to return as checkpoint result to caller.
                    // Ref: pnLog, pnCkpt on https://www.sqlite.org/c3ref/wal_checkpoint_v2.html

                    // the total # of frames we actually backfilled
                    let wal_checkpoint_backfilled =
                        wal_total_backfilled.saturating_sub(ongoing_chkpt.min_frame - 1);

                    let checkpoint_result = CheckpointResult::new(
                        wal_max_frame,
                        wal_total_backfilled,
                        wal_checkpoint_backfilled,
                    );
                    tracing::debug!("checkpoint_result={:?}, mode={:?}", checkpoint_result, mode);
                    if mode.require_all_backfilled() && !checkpoint_result.everything_backfilled() {
                        return Err(LimboError::Busy);
                    }
                    if mode.should_restart_log() {
                        turso_assert!(
                            matches!(
                                *self.checkpoint_guard.read(),
                                Some(CheckpointLocks::Writer { .. })
                            ),
                            "We must hold writer and checkpoint locks to restart the log",
                            { "checkpoint_guard": *self.checkpoint_guard.read() }
                        );
                        self.restart_log()?;
                    }
                    ongoing_chkpt.state = CheckpointState::Finalize {
                        checkpoint_result: Some(checkpoint_result),
                    };
                }
                CheckpointState::Finalize { .. } => {
                    // NOTE: For TRUNCATE mode, WAL truncation is NOT done here.
                    // It is deferred to pager.rs after the DB file has been synced,
                    // at which point it calls truncate_wal().
                    // This ensures data durability: if a crash occurs after WAL truncation
                    // but before DB sync, the data would be lost. By truncating the WAL
                    // only after the DB is safely synced, we guarantee recoverability.
                    if mode.should_restart_log() {
                        Self::unlock_after_restart(&self.coordination, None);
                    }
                    let mut checkpoint_result = {
                        let mut oc = self.ongoing_checkpoint.write();
                        let CheckpointState::Finalize {
                            checkpoint_result, ..
                        } = &mut oc.state
                        else {
                            panic!("unexpected state");
                        };
                        checkpoint_result.take().unwrap()
                    };
                    // increment wal epoch to ensure no stale pages are used for backfilling
                    self.increment_checkpoint_epoch();

                    tracing::debug!("checkpoint_result={:?}", checkpoint_result);
                    // we cannot truncate the db file here because we are currently inside a
                    // mut borrow of pager.wal, and accessing the header will attempt a borrow
                    // during 'read_page', so the caller will use the result to determine if:
                    // a. the max frame == num wal frames (everything backfilled)
                    // b. the max frame > 0 (we have something to truncate)
                    if checkpoint_result.should_truncate() {
                        checkpoint_result.maybe_guard = self.checkpoint_guard.write().take();
                    } else {
                        let _ = self.checkpoint_guard.write().take();
                    }
                    {
                        let mut oc = self.ongoing_checkpoint.write();
                        oc.inflight_writes.clear();
                        oc.pending_writes.clear();
                        oc.pages_to_checkpoint.clear();
                        oc.current_page = 0;
                    }
                    let oc_time = self.ongoing_checkpoint.read().time;
                    tracing::debug!(
                        "total time spent checkpointing: {:?}",
                        self.io
                            .current_time_monotonic()
                            .duration_since(oc_time)
                            .as_millis()
                    );
                    self.ongoing_checkpoint.write().state = CheckpointState::Start;
                    return Ok(IOResult::Done(checkpoint_result));
                }
            }
        }
    }

    /// Coordinate what the maximum safe frame is for us to backfill when checkpointing.
    /// We can never backfill a frame with a higher number than any reader's read mark,
    /// because we might overwrite content the reader is reading from the database file.
    ///
    /// A checkpoint must never overwrite a page in the main DB file if some
    /// active reader might still need to read that page from the WAL.  
    /// Concretely: the checkpoint may only copy frames `<= aReadMark[k]` for
    /// every in-use reader slot `k > 0`.
    ///
    /// `read_locks[0]` is special: readers holding slot 0 ignore the WAL entirely
    /// (they read only the DB file). Its value is a placeholder and does not
    /// constrain `mxSafeFrame`.
    ///
    /// For each slot 1..N:
    /// - If we can acquire the write lock (slot is free):
    ///   - Slot 1: Set to mxSafeFrame (allowing new readers to see up to this point)
    ///   - Slots 2+: Set to READMARK_NOT_USED (freeing the slot)
    /// - If we cannot acquire the lock (SQLITE_BUSY):
    ///   - Lower mxSafeFrame to that reader's mark
    ///   - In PASSIVE mode: Already have no busy handler, continue scanning
    ///   - In FULL/RESTART/TRUNCATE: Disable busy handler for remaining slots
    ///
    /// Locking behavior:
    /// - PASSIVE: Never waits, no busy handler (xBusy==NULL)
    /// - FULL/RESTART/TRUNCATE: May wait via busy handler, but after first BUSY,
    ///   switches to non-blocking for remaining slots
    ///
    /// We never modify slot values while a reader holds that slot's lock.
    /// TOOD: implement proper BUSY handling behavior
    fn determine_max_safe_checkpoint_frame(&self) -> u64 {
        self.coordination
            .determine_max_safe_checkpoint_frame(self.load_coordination_snapshot().max_frame)
    }

    /// attempt to restart WAL header before write in order to keep WAL file size under the control
    /// The conditions for WAL restart are following:
    /// 1. we can do that only under write transaction
    /// 2. max_frame_read_lock_index == 0 - this means that transaction was initiated to read data from DB file
    /// 3. nbackfills > 0 - otherwise nothing was backfilled and there is no reason to truncate header
    /// 4. max_frame == nbackfills - otherwise there are some non-checkpointed frames in the WAL and we can't truncate the log
    pub fn try_restart_log_before_write(&self) -> Result<()> {
        let max_frame_read_lock_index = self.max_frame_read_lock_index.load(Ordering::Acquire);
        if max_frame_read_lock_index != 0 {
            tracing::debug!(
                "try_restart_log_before_write: max_frame_read_lock_index={max_frame_read_lock_index}, writer use WAL - can't restart the log"
            );
            return Ok(());
        }
        let snapshot = self.load_coordination_snapshot();
        let max_frame = snapshot.max_frame;
        let nbackfills = snapshot.nbackfills;
        if nbackfills == 0 {
            tracing::debug!(
                "try_restart_log_before_write: nbackfills={nbackfills}, nothing were backfilled - can't restart the log"
            );
            return Ok(());
        }
        turso_assert!(
            max_frame >= nbackfills,
            "backfills can't be more than max_frame"
        );
        if max_frame != nbackfills {
            tracing::debug!(
                "try_restart_log_before_write: max_frame={max_frame}, nbackfills={nbackfills}, not everything is backfilled to the DB file - can't restart the log"
            );
            return Ok(());
        }
        let Some(snapshot) = self
            .coordination
            .try_restart_log_for_write(self.io.as_ref())?
        else {
            return Ok(());
        };
        self.apply_restart_snapshot(snapshot);
        self.increment_checkpoint_epoch();
        let result = Ok(());
        tracing::debug!("try_restart_log_before_write: result={:?}", result);
        result
    }

    fn restart_log(&self) -> Result<()> {
        tracing::debug!("restart_log");
        let snapshot = self.coordination.begin_restart(self.io.as_ref())?;
        self.apply_restart_snapshot(snapshot);
        Ok(())
    }

    /// Truncate WAL file to zero and sync it. Called by pager AFTER DB file is synced.
    fn truncate_log(
        &self,
        result: &mut CheckpointResult,
        sync_type: FileSyncType,
    ) -> Result<IOResult<()>> {
        let file = self.coordination.prepare_truncate()?;

        if !result.wal_truncate_sent {
            let c = Completion::new_trunc({
                move |res| {
                    if let Err(err) = res {
                        tracing::debug!("WAL truncate failed: {err}")
                    } else {
                        tracing::trace!("WAL file truncated to 0 B");
                    }
                }
            });
            let c = file.truncate(0, c)?;
            result.wal_truncate_sent = true;
            // after truncation - there will be nothing in the WAL
            result.wal_max_frame = 0;
            result.wal_total_backfilled = 0;
            io_yield_one!(c);
        } else if !result.wal_sync_sent {
            let c = file.sync(
                Completion::new_sync(move |res| {
                    if let Err(err) = res {
                        tracing::debug!("WAL sync failed: {err}")
                    } else {
                        tracing::trace!("WAL file synced after truncation");
                    }
                }),
                sync_type,
            )?;
            result.wal_sync_sent = true;
            io_yield_one!(c);
        }
        Ok(IOResult::Done(()))
    }

    fn apply_restart_snapshot(&self, snapshot: WalSnapshot) {
        *self.last_checksum.write() = snapshot.last_checksum;
        self.max_frame.store(snapshot.max_frame, Ordering::Release);
        self.min_frame.store(0, Ordering::Release);
        self.checkpoint_seq
            .store(snapshot.checkpoint_seq, Ordering::Release);
    }

    // unlock shared read locks taken by RESTART/TRUNCATE checkpoint modes
    fn unlock_after_restart(coordination: &Arc<dyn WalCoordination>, e: Option<&LimboError>) {
        coordination.end_restart();
        if let Some(e) = e {
            mark_unlikely();
            tracing::debug!(
                "Failed to restart WAL header: {:?}, releasing read locks",
                e
            );
        }
    }

    fn acquire_proper_checkpoint_guard(
        &self,
        mode: CheckpointMode,
        lock_source: CheckpointLockSource,
    ) -> Result<()> {
        let needs_new_guard = {
            let guard = self.checkpoint_guard.read();
            !matches!(
                (&*guard, mode),
                (
                    Some(CheckpointLocks::Read0 { .. }),
                    CheckpointMode::Passive { .. },
                ) | (
                    Some(CheckpointLocks::Writer { .. }),
                    CheckpointMode::Restart | CheckpointMode::Truncate { .. },
                ),
            )
        };
        if needs_new_guard {
            // Drop any existing guard
            if self.checkpoint_guard.read().is_some() {
                let _ = self.checkpoint_guard.write().take();
            }
            let guard = match lock_source {
                CheckpointLockSource::Acquire => {
                    CheckpointLocks::new(self.coordination.clone(), mode)?
                }
                CheckpointLockSource::HeldByCaller => {
                    CheckpointLocks::from_held_vacuum_checkpoint_lock(self.coordination.clone())?
                }
            };
            *self.checkpoint_guard.write() = Some(guard);
        }
        Ok(())
    }

    fn issue_wal_read_into_buffer(&self, page_id: usize, frame_id: u64) -> Result<InflightRead> {
        let offset = self.frame_offset(frame_id);
        let buf_slot = Arc::new(SpinLock::new(None));
        tracing::debug!(
            "Issuing WAL read: page_id={}, frame_id={}, offset={}",
            page_id,
            frame_id,
            offset
        );

        let complete = {
            let buf_slot = buf_slot.clone();
            Box::new(move |res: Result<(Arc<Buffer>, i32), CompletionError>| {
                let Ok((buf, read)) = res else {
                    return None;
                };
                let buf_len = buf.len();
                turso_assert!(
                    read == buf_len as i32,
                    "read bytes does not match expected buffer length",
                    { "read": read, "expected": buf_len, "frame_id": frame_id }
                );
                *buf_slot.lock() = Some(buf);
                None
            })
        };
        // schedule read of the page payload
        let file = self.coordination.wal_file()?;
        let c = begin_read_wal_frame(
            file.as_ref(),
            offset + WAL_FRAME_HEADER_SIZE as u64,
            self.buffer_pool.clone(),
            complete,
            page_id,
            &self.io_ctx.read(),
        )?;

        Ok(InflightRead {
            completion: c,
            page_id,
            buf: buf_slot,
        })
    }

    /// MVCC helper: check if WAL state changed and refresh local snapshot without starting a read tx.
    /// FIXME: this isn't TOCTOU safe because we're not taking WAL read locks.
    ///
    /// This is only used to invalidate page cache, so false positives are sort of acceptable since
    /// MVCC reads currently don't read from WAL frames ever.
    /// FIXME: MVCC should start using pager read transactions anyway so that we can get rid of
    /// the stop-the-world MVCC checkpoint that blocks all reads.
    pub fn mvcc_refresh_if_db_changed(&self) -> bool {
        let snapshot = self.load_coordination_snapshot();
        let local_state = self.connection_state();
        let changed = self.db_changed_against(snapshot, local_state);
        if changed {
            self.install_connection_state(local_state.with_snapshot(snapshot));
        }
        changed
    }
}

#[cfg(host_shared_wal)]
fn read_exact_bytes_from_file(
    io: &Arc<dyn IO>,
    file: &Arc<dyn File>,
    offset: u64,
    len: usize,
) -> Result<Option<Vec<u8>>> {
    let read_buf = Arc::new(Buffer::new_temporary(len));
    let bytes_read = Arc::new(AtomicUsize::new(usize::MAX));
    let c = file.pread(
        offset,
        Completion::new_read(read_buf.clone(), {
            let bytes_read = bytes_read.clone();
            Box::new(move |res| {
                if let Ok((_buf, count)) = res {
                    bytes_read.store(count as usize, Ordering::Release);
                }
                None
            })
        }),
    )?;
    io.wait_for_completion(c)?;
    if bytes_read.load(Ordering::Acquire) != len {
        return Ok(None);
    }
    Ok(Some(read_buf.as_slice()[..len].to_vec()))
}

#[cfg(host_shared_wal)]
fn read_validated_wal_header_from_file(
    io: &Arc<dyn IO>,
    file: &Arc<dyn File>,
) -> Result<Option<WalHeader>> {
    let Some(bytes) = read_exact_bytes_from_file(io, file, 0, WAL_HEADER_SIZE)? else {
        return Ok(None);
    };
    let header = WalHeader {
        magic: u32::from_be_bytes(bytes[0..4].try_into().unwrap()),
        file_format: u32::from_be_bytes(bytes[4..8].try_into().unwrap()),
        page_size: u32::from_be_bytes(bytes[8..12].try_into().unwrap()),
        checkpoint_seq: u32::from_be_bytes(bytes[12..16].try_into().unwrap()),
        salt_1: u32::from_be_bytes(bytes[16..20].try_into().unwrap()),
        salt_2: u32::from_be_bytes(bytes[20..24].try_into().unwrap()),
        checksum_1: u32::from_be_bytes(bytes[24..28].try_into().unwrap()),
        checksum_2: u32::from_be_bytes(bytes[28..32].try_into().unwrap()),
    };
    if !matches!(header.magic, WAL_MAGIC_LE | WAL_MAGIC_BE) {
        return Ok(None);
    }
    if PageSize::new(header.page_size).is_none() {
        return Ok(None);
    }
    let use_native_endian = cfg!(target_endian = "big") == ((header.magic & 1) != 0);
    let calc = checksum_wal(
        &bytes[..WAL_HEADER_SIZE - 8],
        &header,
        (0, 0),
        use_native_endian,
    );
    if calc != (header.checksum_1, header.checksum_2) {
        return Ok(None);
    }
    Ok(Some(header))
}

#[cfg(host_shared_wal)]
fn wal_header_matches_authority_snapshot(
    wal_header: WalHeader,
    snapshot: SharedWalCoordinationHeader,
) -> bool {
    wal_header.page_size == snapshot.page_size
        && wal_header.checkpoint_seq == snapshot.checkpoint_seq
        && wal_header.salt_1 == snapshot.salt_1
        && wal_header.salt_2 == snapshot.salt_2
}

pub(crate) fn database_identity_from_header_bytes(header_bytes: &[u8]) -> Result<(u32, u32)> {
    if header_bytes.len() < DatabaseHeader::SIZE {
        return Err(LimboError::Corrupt(format!(
            "database header must be at least {} bytes, got {}",
            DatabaseHeader::SIZE,
            header_bytes.len()
        )));
    }
    if header_bytes[0..16] != *b"SQLite format 3\0" {
        return Err(LimboError::Corrupt("database header magic mismatch".into()));
    }
    let db_size_pages = u32::from_be_bytes(header_bytes[28..32].try_into().unwrap());
    let header_crc32c = crc32c::crc32c(&header_bytes[..DatabaseHeader::SIZE]);
    Ok((db_size_pages, header_crc32c))
}

fn read_database_identity_from_storage(
    io: &Arc<dyn IO>,
    db_file: &Arc<dyn DatabaseStorage>,
) -> Result<Option<(u32, u32)>> {
    let read_buf = Arc::new(Buffer::new_temporary(PageSize::MIN as usize));
    let bytes_read = Arc::new(AtomicUsize::new(usize::MAX));
    let c = db_file.read_header(Completion::new_read(read_buf.clone(), {
        let bytes_read = bytes_read.clone();
        Box::new(move |res| {
            if let Ok((_buf, count)) = res {
                bytes_read.store(count as usize, Ordering::Release);
            }
            None
        })
    }))?;
    io.wait_for_completion(c)?;
    if bytes_read.load(Ordering::Acquire) < DatabaseHeader::SIZE {
        return Ok(None);
    }
    Ok(Some(database_identity_from_header_bytes(
        &read_buf.as_slice()[..DatabaseHeader::SIZE],
    )?))
}

#[cfg(all(test, host_shared_wal))]
fn read_database_identity_from_file_path(
    io: &Arc<dyn IO>,
    wal_path: &str,
) -> Result<Option<(u32, u32)>> {
    let db_path = wal_path
        .strip_suffix("-wal")
        .unwrap_or(wal_path)
        .to_string();
    let file = match io.open_file(&db_path, crate::OpenFlags::None, false) {
        Ok(file) => file,
        Err(LimboError::CompletionError(CompletionError::IOError(
            std::io::ErrorKind::NotFound,
            _,
        ))) => return Ok(None),
        Err(err) => return Err(err),
    };
    let Some(bytes) = read_exact_bytes_from_file(io, &file, 0, DatabaseHeader::SIZE)? else {
        return Ok(None);
    };
    Ok(Some(database_identity_from_header_bytes(&bytes)?))
}

#[cfg(host_shared_wal)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuthoritySnapshotValidation {
    Trusted,
    RebuildFromDisk(AuthoritySnapshotRebuildReason),
}

#[cfg(host_shared_wal)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AuthoritySnapshotRebuildReason {
    WalHeaderUnreadable,
    WalHeaderMismatch,
    WalTooShortForSnapshot,
    WalLengthMismatch,
    LastFrameMissing,
    LastFrameNotCommit,
    LastFrameSaltMismatch,
    LastFrameChecksumMismatch,
}

#[cfg(host_shared_wal)]
fn classify_authority_snapshot_against_wal(
    io: &Arc<dyn IO>,
    file: &Arc<dyn File>,
    snapshot: SharedWalCoordinationHeader,
) -> Result<AuthoritySnapshotValidation> {
    let wal_size = file.size()?;
    if snapshot.max_frame == 0 {
        if wal_size == 0 {
            return Ok(AuthoritySnapshotValidation::Trusted);
        }
        if wal_size == WAL_HEADER_SIZE as u64 {
            let Some(wal_header) = read_validated_wal_header_from_file(io, file)? else {
                return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
                    AuthoritySnapshotRebuildReason::WalHeaderUnreadable,
                ));
            };
            return Ok(
                if wal_header_matches_authority_snapshot(wal_header, snapshot) {
                    AuthoritySnapshotValidation::Trusted
                } else {
                    AuthoritySnapshotValidation::RebuildFromDisk(
                        AuthoritySnapshotRebuildReason::WalHeaderMismatch,
                    )
                },
            );
        }
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::WalLengthMismatch,
        ));
    }

    if wal_size < WAL_HEADER_SIZE as u64 {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::WalTooShortForSnapshot,
        ));
    }

    let Some(wal_header) = read_validated_wal_header_from_file(io, file)? else {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::WalHeaderUnreadable,
        ));
    };
    if !wal_header_matches_authority_snapshot(wal_header, snapshot) {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::WalHeaderMismatch,
        ));
    }

    let frame_size = WAL_FRAME_HEADER_SIZE as u64 + wal_header.page_size as u64;
    let expected_wal_len = WAL_HEADER_SIZE as u64 + snapshot.max_frame * frame_size;
    if wal_size != expected_wal_len {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::WalLengthMismatch,
        ));
    }

    let last_frame_offset = WAL_HEADER_SIZE as u64 + (snapshot.max_frame - 1) * frame_size;
    let Some(frame_bytes) =
        read_exact_bytes_from_file(io, file, last_frame_offset, frame_size as usize)?
    else {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::LastFrameMissing,
        ));
    };
    let (frame_header, _) = sqlite3_ondisk::parse_wal_frame_header(&frame_bytes);
    if !frame_header.is_commit_frame() {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::LastFrameNotCommit,
        ));
    }
    if frame_header.salt_1 != snapshot.salt_1 || frame_header.salt_2 != snapshot.salt_2 {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::LastFrameSaltMismatch,
        ));
    }
    if frame_header.checksum_1 != snapshot.checksum_1
        || frame_header.checksum_2 != snapshot.checksum_2
    {
        return Ok(AuthoritySnapshotValidation::RebuildFromDisk(
            AuthoritySnapshotRebuildReason::LastFrameChecksumMismatch,
        ));
    }
    Ok(AuthoritySnapshotValidation::Trusted)
}

impl WalFileShared {
    pub fn last_checksum_and_max_frame(&self) -> ((u32, u32), u64) {
        (
            self.metadata.last_checksum,
            self.metadata.max_frame.load(Ordering::Acquire),
        )
    }

    #[cfg(host_shared_wal)]
    pub(crate) fn open_shared_from_authority_if_exists(
        io: &Arc<dyn IO>,
        path: &str,
        flags: crate::OpenFlags,
        authority: &Arc<MappedSharedWalCoordination>,
        db_file: &Arc<dyn DatabaseStorage>,
    ) -> Result<Arc<RwLock<WalFileShared>>> {
        let snapshot = authority.snapshot();
        let file = match io.open_file(path, flags, false) {
            Ok(file) => file,
            Err(LimboError::CompletionError(CompletionError::IOError(
                std::io::ErrorKind::NotFound,
                _,
            ))) if flags.contains(crate::OpenFlags::ReadOnly) => {
                return Ok(WalFileShared::new_noop());
            }
            Err(e) => return Err(e),
        };
        let wal_size = file.size()?;

        match classify_authority_snapshot_against_wal(io, &file, snapshot)? {
            AuthoritySnapshotValidation::Trusted => {}
            AuthoritySnapshotValidation::RebuildFromDisk(reason) => {
                tracing::debug!(
                    ?reason,
                    "rebuilding WAL state from disk because persisted authority is not provably reusable"
                );
                return sqlite3_ondisk::build_shared_wal(&file, io);
            }
        }
        if authority.frame_index_overflowed() {
            tracing::debug!(
                "rebuilding WAL state from disk because the persisted tshm frame index is marked overflowed"
            );
            return sqlite3_ondisk::build_shared_wal(&file, io);
        }
        if snapshot.nbackfills != 0
            && authority.open_mode() == SharedWalCoordinationOpenMode::Exclusive
        {
            tracing::debug!(
                nbackfills = snapshot.nbackfills,
                max_frame = snapshot.max_frame,
                "rebuilding WAL state from disk because an exclusive reopen must conservatively clear published backfill progress"
            );
            return sqlite3_ondisk::build_shared_wal(&file, io);
        }
        if snapshot.max_frame > snapshot.nbackfills
            && authority
                .iter_latest_frames(0, snapshot.max_frame)
                .is_empty()
        {
            tracing::debug!(
                max_frame = snapshot.max_frame,
                nbackfills = snapshot.nbackfills,
                "rebuilding WAL state from disk because the persisted tshm frame index has no entries for a visible WAL tail"
            );
            return sqlite3_ondisk::build_shared_wal(&file, io);
        }
        if snapshot.nbackfills != 0 {
            let Some((db_size_pages, db_header_crc32c)) =
                read_database_identity_from_storage(io, db_file)?
            else {
                tracing::debug!(
                    nbackfills = snapshot.nbackfills,
                    "rebuilding WAL state from disk because the main database header is unavailable for backfill-proof validation"
                );
                return sqlite3_ondisk::build_shared_wal(&file, io);
            };
            if !authority.validate_backfill_proof(snapshot, db_size_pages, db_header_crc32c) {
                tracing::debug!(
                    nbackfills = snapshot.nbackfills,
                    "rebuilding WAL state from disk because persisted tshm backfill proof is not valid for the current database header"
                );
                return sqlite3_ondisk::build_shared_wal(&file, io);
            }
        }
        let wal_is_initialized = wal_size >= WAL_HEADER_SIZE as u64;

        let wal_header = WalHeader {
            page_size: snapshot.page_size,
            checkpoint_seq: snapshot.checkpoint_seq,
            salt_1: snapshot.salt_1,
            salt_2: snapshot.salt_2,
            checksum_1: snapshot.checksum_1,
            checksum_2: snapshot.checksum_2,
            ..WalHeader::new()
        };
        let read_locks = array::from_fn(|_| TursoRwLock::new());
        for (i, lock) in read_locks.iter().enumerate() {
            lock.write();
            lock.set_value_exclusive(if i < 2 { 0 } else { READMARK_NOT_USED });
            lock.unlock();
        }

        let shared = WalFileShared {
            metadata: WalSharedMetadata {
                enabled: AtomicBool::new(true),
                wal_header: Arc::new(SpinLock::new(wal_header)),
                min_frame: AtomicU64::new(0),
                max_frame: AtomicU64::new(snapshot.max_frame),
                nbackfills: AtomicU64::new(snapshot.nbackfills),
                transaction_count: AtomicU64::new(snapshot.transaction_count),
                last_checksum: (snapshot.checksum_1, snapshot.checksum_2),
                loaded: AtomicBool::new(true),
                loaded_from_disk_scan: AtomicBool::new(false),
                initialized: AtomicBool::new(wal_is_initialized),
            },
            runtime: WalSharedRuntime {
                frame_cache: Arc::new(SpinLock::new(FxHashMap::default())),
                file: Some(file),
                read_locks,
                vacuum_lock: TursoRwLock::new(),
                write_lock: TursoRwLock::new(),
                checkpoint_lock: TursoRwLock::new(),
                epoch: AtomicU32::new(snapshot.checkpoint_epoch),
                overflow_fallback_coverage: Arc::new(SpinLock::new(
                    OverflowFallbackCoverage::default(),
                )),
            },
        };
        Ok(Arc::new(RwLock::new(shared)))
    }

    pub fn open_shared_if_exists(
        io: &Arc<dyn IO>,
        path: &str,
        flags: crate::OpenFlags,
    ) -> Result<Arc<RwLock<WalFileShared>>> {
        let file = match io.open_file(path, flags, false) {
            Ok(file) => file,
            Err(LimboError::CompletionError(CompletionError::IOError(
                std::io::ErrorKind::NotFound,
                _,
            ))) if flags.contains(crate::OpenFlags::ReadOnly) => {
                // In readonly mode, if the WAL file doesn't exist, we just return a noop WAL
                // since there's nothing to read from.
                return Ok(WalFileShared::new_noop());
            }
            Err(e) => return Err(e),
        };
        let wal_file_shared = sqlite3_ondisk::build_shared_wal(&file, io)?;
        turso_assert!(
            wal_file_shared
                .try_read()
                .is_some_and(|wfs| wfs.metadata.loaded.load(Ordering::Acquire)),
            "Unable to read WAL shared state"
        );
        Ok(wal_file_shared)
    }

    pub fn is_initialized(&self) -> Result<bool> {
        Ok(self.metadata.initialized.load(Ordering::Acquire))
    }

    pub fn new_noop() -> Arc<RwLock<WalFileShared>> {
        let wal_header = WalHeader::new();
        let read_locks = array::from_fn(|_| TursoRwLock::new());
        for (i, lock) in read_locks.iter().enumerate() {
            lock.write();
            lock.set_value_exclusive(if i < 2 { 0 } else { READMARK_NOT_USED });
            lock.unlock();
        }
        let shared = WalFileShared {
            metadata: WalSharedMetadata {
                enabled: AtomicBool::new(false),
                wal_header: Arc::new(SpinLock::new(wal_header)),
                min_frame: AtomicU64::new(0),
                max_frame: AtomicU64::new(0),
                nbackfills: AtomicU64::new(0),
                transaction_count: AtomicU64::new(0),
                last_checksum: (0, 0),
                loaded: AtomicBool::new(true),
                loaded_from_disk_scan: AtomicBool::new(false),
                initialized: AtomicBool::new(false),
            },
            runtime: WalSharedRuntime {
                frame_cache: Arc::new(SpinLock::new(FxHashMap::default())),
                file: None,
                read_locks,
                vacuum_lock: TursoRwLock::new(),
                write_lock: TursoRwLock::new(),
                checkpoint_lock: TursoRwLock::new(),
                epoch: AtomicU32::new(0),
                overflow_fallback_coverage: Arc::new(SpinLock::new(
                    OverflowFallbackCoverage::default(),
                )),
            },
        };
        Arc::new(RwLock::new(shared))
    }

    #[cfg(test)]
    pub(super) fn new_shared(file: Arc<dyn File>) -> Result<Arc<RwLock<WalFileShared>>> {
        let wal_header = WalHeader::new();
        let read_locks = array::from_fn(|_| TursoRwLock::new());
        // slot zero is always zero as it signifies that reads can be done from the db file
        // directly, and slot 1 is the default read mark containing the max frame. in this case
        // our max frame is zero so both slots 0 and 1 begin at 0
        for (i, lock) in read_locks.iter().enumerate() {
            lock.write();
            lock.set_value_exclusive(if i < 2 { 0 } else { READMARK_NOT_USED });
            lock.unlock();
        }
        let shared = WalFileShared {
            metadata: WalSharedMetadata {
                enabled: AtomicBool::new(true),
                wal_header: Arc::new(SpinLock::new(wal_header)),
                min_frame: AtomicU64::new(0),
                max_frame: AtomicU64::new(0),
                nbackfills: AtomicU64::new(0),
                transaction_count: AtomicU64::new(0),
                last_checksum: (0, 0),
                loaded: AtomicBool::new(true),
                loaded_from_disk_scan: AtomicBool::new(false),
                initialized: AtomicBool::new(false),
            },
            runtime: WalSharedRuntime {
                frame_cache: Arc::new(SpinLock::new(FxHashMap::default())),
                file: Some(file),
                read_locks,
                vacuum_lock: TursoRwLock::new(),
                write_lock: TursoRwLock::new(),
                checkpoint_lock: TursoRwLock::new(),
                epoch: AtomicU32::new(0),
                overflow_fallback_coverage: Arc::new(SpinLock::new(
                    OverflowFallbackCoverage::default(),
                )),
            },
        };
        Ok(Arc::new(RwLock::new(shared)))
    }

    pub fn page_size(&self) -> u32 {
        self.metadata.wal_header.lock().page_size
    }

    /// Called after a successful RESTART/TRUNCATE mode checkpoint
    /// when all frames are back‑filled.
    ///
    /// sqlite3/src/wal.c
    /// The following is guaranteed when this function is called:
    ///
    ///   a) the WRITER lock is held,
    ///   b) the entire log file has been checkpointed, and
    ///   c) any existing readers are reading exclusively from the database
    ///      file - there are no readers that may attempt to read a frame from
    ///      the log file.
    ///
    /// This function updates the shared-memory structures so that the next
    /// client to write to the database (which may be this one) does so by
    /// writing frames into the start of the log file.
    fn restart_wal_header(&mut self, io: &dyn IO) {
        {
            let mut hdr = self.metadata.wal_header.lock();
            hdr.checkpoint_seq = hdr.checkpoint_seq.wrapping_add(1);
            // keep hdr.magic, hdr.file_format, hdr.page_size as-is
            hdr.salt_1 = hdr.salt_1.wrapping_add(1);
            hdr.salt_2 = io.generate_random_number() as u32;

            self.metadata.max_frame.store(0, Ordering::Release);
            self.metadata.nbackfills.store(0, Ordering::Release);
            self.metadata.last_checksum = (hdr.checksum_1, hdr.checksum_2);
            // `prepare_wal_start` (used in the `commit_dirty_pages_inner`) do the work only if WAL is not initialized yet (so, self.initialized is false)
            // we change WAL state here, so on next write attempt `prepare_wal_start` will update WAL header
            self.metadata.initialized.store(false, Ordering::Release);
        }

        self.runtime.frame_cache.lock().clear();
        // read-marks
        self.runtime.read_locks[0].set_value_exclusive(0);
        self.runtime.read_locks[1].set_value_exclusive(0);
        for lock in &self.runtime.read_locks[2..] {
            lock.set_value_exclusive(READMARK_NOT_USED);
        }
    }
}

#[cfg(test)]
pub mod test {
    #[cfg(host_shared_wal)]
    use super::{
        classify_authority_snapshot_against_wal, AuthoritySnapshotRebuildReason,
        AuthoritySnapshotValidation, ShmWalCoordination,
    };
    use super::{
        CheckpointLocks, InProcessWalCoordination, ReadGuardKind, RollbackTo, TryBeginReadResult,
        Wal, WalAutoActions, WalCommitState, WalConnectionState, WalCoordination, WalFile,
        WalSnapshot, NO_LOCK_HELD,
    };
    #[cfg(host_shared_wal)]
    use crate::storage::shared_wal_coordination::{
        MappedSharedWalCoordination, SharedWalCoordinationHeader, SharedWalCoordinationOpenMode,
    };
    use crate::sync::{atomic::Ordering, Arc};
    use crate::sync::{Mutex, RwLock};
    use crate::{
        io::FileSyncType,
        storage::{
            buffer_pool::BufferPool,
            database::{DatabaseFile, DatabaseStorage},
            pager::{allocate_new_page, PageRef},
            sqlite3_ondisk::{self, PageSize, WAL_HEADER_SIZE},
            wal::READMARK_NOT_USED,
        },
        types::IOResult,
        util::IOExt,
        Buffer, CheckpointMode, CheckpointResult, Completion, CompletionError, Connection,
        Database, File, LimboError, MemoryIO, OpenFlags, PlatformIO, SyncMode, WalFileShared, IO,
    };
    use std::num::NonZeroUsize;
    #[cfg(unix)]
    use std::os::unix::fs::MetadataExt;
    /// Returns an IO backend that supports shared WAL coordination on the host.
    /// On Windows the default `PlatformIO` (`WindowsIO`) lacks the byte-locking
    /// and mapping primitives, so the experimental IOCP backend is used when
    /// the `experimental_win_iocp` feature is enabled.
    fn shared_wal_test_io() -> Arc<dyn IO> {
        #[cfg(all(target_os = "windows", feature = "experimental_win_iocp"))]
        {
            Arc::new(crate::WindowsIOCP::new().unwrap())
        }
        #[cfg(not(all(target_os = "windows", feature = "experimental_win_iocp")))]
        {
            Arc::new(PlatformIO::new().unwrap())
        }
    }

    #[allow(clippy::arc_with_non_send_sync)]
    pub(crate) fn get_database() -> (Arc<Database>, std::path::PathBuf) {
        let mut path = tempfile::tempdir().unwrap().keep();
        let dbpath = path.clone();
        path.push("test.db");
        {
            let connection = rusqlite::Connection::open(&path).unwrap();
            connection
                .pragma_update(None, "journal_mode", "wal")
                .unwrap();
        }
        let io = shared_wal_test_io();
        let db = Database::open_file_with_flags(
            io.clone(),
            path.to_str().unwrap(),
            crate::OpenFlags::default(),
            crate::DatabaseOpts::new().with_multiprocess_wal(true),
            None,
        )
        .unwrap();
        // db + tmp directory
        (db, dbpath)
    }

    struct DeferredReadFile {
        inner: Arc<dyn File>,
        pending_reads: Mutex<Vec<(u64, Completion)>>,
    }

    impl DeferredReadFile {
        fn new(inner: Arc<dyn File>) -> Self {
            Self {
                inner,
                pending_reads: Mutex::new(Vec::new()),
            }
        }

        fn complete_pending_reads(&self) {
            let pending_reads = std::mem::take(&mut *self.pending_reads.lock());
            for (pos, completion) in pending_reads {
                std::mem::drop(self.inner.pread(pos, completion).unwrap());
            }
        }
    }

    impl File for DeferredReadFile {
        fn lock_file(&self, exclusive: bool) -> crate::Result<()> {
            self.inner.lock_file(exclusive)
        }

        fn unlock_file(&self) -> crate::Result<()> {
            self.inner.unlock_file()
        }

        fn pread(&self, pos: u64, c: Completion) -> crate::Result<Completion> {
            self.pending_reads.lock().push((pos, c.clone()));
            Ok(c)
        }

        fn pwrite(
            &self,
            pos: u64,
            buffer: Arc<Buffer>,
            c: Completion,
        ) -> crate::Result<Completion> {
            self.inner.pwrite(pos, buffer, c)
        }

        fn sync(
            &self,
            c: Completion,
            sync_type: crate::io::FileSyncType,
        ) -> crate::Result<Completion> {
            self.inner.sync(c, sync_type)
        }

        fn size(&self) -> crate::Result<u64> {
            self.inner.size()
        }

        fn truncate(&self, len: u64, c: Completion) -> crate::Result<Completion> {
            self.inner.truncate(len, c)
        }
    }
    #[test]
    fn test_truncate_file() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();
        conn.execute("create table test (id integer primary key, value text)")
            .unwrap();
        let _ = conn.execute("insert into test (value) values ('test1'), ('test2'), ('test3')");
        let wal = db.shared_wal.write();
        let wal_file = wal.runtime.file.as_ref().unwrap().clone();
        let done = Arc::new(Mutex::new(false));
        let _done = done.clone();
        let _ = wal_file.truncate(
            WAL_HEADER_SIZE as u64,
            Completion::new_trunc(move |_| {
                *_done.lock() = true;
            }),
        );
        assert!(wal_file.size().unwrap() == WAL_HEADER_SIZE as u64);
        assert!(*done.lock());
    }

    #[test]
    fn test_wal_truncate_checkpoint() {
        let (db, path) = get_database();
        let mut walpath = path.clone().into_os_string().into_string().unwrap();
        walpath.push_str("/test.db-wal");
        let walpath = std::path::PathBuf::from(walpath);

        let conn = db.connect().unwrap();
        conn.execute("create table test (id integer primary key, value text)")
            .unwrap();
        for _i in 0..25 {
            let _ = conn.execute("insert into test (value) values (randomblob(1024)), (randomblob(1024)), (randomblob(1024))");
        }
        let pager = conn.pager.load();
        let _ = pager.cacheflush();

        let stat = std::fs::metadata(&walpath).unwrap();
        let meta_before = std::fs::metadata(&walpath).unwrap();
        let bytes_before = meta_before.len();
        run_checkpoint_until_done(
            &pager,
            CheckpointMode::Truncate {
                upper_bound_inclusive: None,
            },
        );

        assert_eq!(pager.wal_state().unwrap().max_frame, 0);

        tracing::debug!("wal filepath: {walpath:?}, size: {}", stat.len());
        let meta_after = std::fs::metadata(&walpath).unwrap();
        let bytes_after = meta_after.len();
        assert_ne!(
            bytes_before, bytes_after,
            "WAL file should not have been empty before checkpoint"
        );
        assert_eq!(
            bytes_after, 0,
            "WAL file should be truncated to 0 bytes, but is {bytes_after} bytes",
        );
        std::fs::remove_dir_all(path).unwrap();
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "shutdown checkpoint does not truncate the WAL file to zero on Windows"
    )]
    fn test_shutdown_checkpoint_truncates_after_restart() {
        let (db, path) = get_database();
        let mut walpath = path.clone().into_os_string().into_string().unwrap();
        walpath.push_str("/test.db-wal");
        let walpath = std::path::PathBuf::from(walpath);

        let conn = db.connect().unwrap();
        conn.execute("create table test (id integer primary key, value text)")
            .unwrap();
        conn.execute("insert into test (value) values ('v1'), ('v2')")
            .unwrap();

        let pager = conn.pager.load();
        run_checkpoint_until_done(&pager, CheckpointMode::Restart);

        let bytes_before = std::fs::metadata(&walpath).unwrap().len();
        assert!(
            bytes_before > 0,
            "WAL should still have data after RESTART checkpoint"
        );

        conn.close().unwrap();

        let bytes_after = std::fs::metadata(&walpath).unwrap().len();
        assert_eq!(
            bytes_after, 0,
            "Shutdown checkpoint should truncate WAL after RESTART, but WAL is {bytes_after} bytes",
        );
        std::fs::remove_dir_all(path).unwrap();
    }

    fn bulk_inserts(conn: &Arc<Connection>, n_txns: usize, rows_per_txn: usize) {
        for _ in 0..n_txns {
            conn.execute("begin transaction").unwrap();
            for i in 0..rows_per_txn {
                conn.execute(format!("insert into test(value) values ('v{i}')"))
                    .unwrap();
            }
            conn.execute("commit").unwrap();
        }
    }

    fn count_test_table(conn: &Arc<Connection>) -> i64 {
        let mut stmt = conn.prepare("select count(*) from test").unwrap();
        let mut count: i64 = 0;
        stmt.run_with_row_callback(|row| {
            count = row.get(0).unwrap();
            Ok(())
        })
        .unwrap();
        count
    }

    fn run_checkpoint_until_done(pager: &crate::Pager, mode: CheckpointMode) -> CheckpointResult {
        // Use pager.checkpoint() instead of wal.checkpoint() directly because
        // WAL truncation (for TRUNCATE mode) now happens in pager's TruncateWalFile phase.
        pager
            .io
            .block(|| pager.checkpoint(mode, crate::SyncMode::Full, true))
            .unwrap()
    }

    fn run_wal_checkpoint_until_done(
        db: &Database,
        pager: &crate::Pager,
        mode: CheckpointMode,
    ) -> CheckpointResult {
        let wal = pager.wal.as_ref().expect("wal should be present");
        loop {
            match wal.checkpoint(pager, mode) {
                Ok(IOResult::IO(io)) => io.wait(db.io.as_ref()).unwrap(),
                Ok(IOResult::Done(result)) => return result,
                Err(err) => panic!("checkpoint should succeed: {err:?}"),
            }
        }
    }

    #[test]
    fn test_wal_checkpoint_defers_backfill_publication_until_db_sync() {
        let (db, _path) = get_database();
        let wal_shared = db.shared_wal.clone();
        let conn = db.connect().unwrap();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 8, 2);

        let pager = conn.pager.load();
        let result = run_wal_checkpoint_until_done(&db, &pager, CheckpointMode::Full);
        assert!(
            result.wal_total_backfilled > 0,
            "checkpoint setup should backfill frames before DB sync"
        );
        assert_eq!(
            wal_shared.read().metadata.nbackfills.load(Ordering::SeqCst),
            0,
            "wal.checkpoint() must not publish positive nbackfills before DB sync completes"
        );
    }

    #[test]
    fn test_checkpoint_sync_mode_off_leaves_backfill_unpublished() {
        let (db, _path) = get_database();
        let wal_shared = db.shared_wal.clone();
        let conn = db.connect().unwrap();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 8, 2);

        let pager = conn.pager.load();
        let result = pager
            .io
            .block(|| pager.checkpoint(CheckpointMode::Full, SyncMode::Off, true))
            .unwrap();
        assert!(
            result.wal_total_backfilled > 0,
            "sync-mode-off checkpoint setup should still backfill frames into the DB file"
        );
        assert_eq!(
            wal_shared.read().metadata.nbackfills.load(Ordering::SeqCst),
            0,
            "SyncMode::Off must not publish positive nbackfills as durable shared state"
        );
    }

    fn make_test_wal() -> (Arc<RwLock<WalFileShared>>, WalFile) {
        let io = shared_wal_test_io();
        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        let shared = WalFileShared::new_noop();
        let coordination: Arc<dyn WalCoordination> =
            Arc::new(InProcessWalCoordination::new(shared.clone()));
        let wal = WalFile::new_with_coordination(io, coordination, ((0, 0), 0), buffer_pool);
        (shared, wal)
    }

    fn make_test_wal_from_shared(shared: Arc<RwLock<WalFileShared>>) -> WalFile {
        let io = shared_wal_test_io();
        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        let snapshot = shared.read().last_checksum_and_max_frame();
        WalFile::new(io, shared, snapshot, buffer_pool)
    }

    fn make_initialized_memory_wal(page_size: u32) -> (Arc<dyn IO>, Arc<BufferPool>, WalFile) {
        let io: Arc<dyn IO> = Arc::new(MemoryIO::new());
        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        buffer_pool
            .finalize_with_page_size(page_size as usize)
            .unwrap();
        let file = io
            .open_file("direct-batch-read.db-wal", OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let wal = WalFile::new(io.clone(), shared, ((0, 0), 0), buffer_pool.clone());
        let page_size = PageSize::new(page_size).unwrap();

        if let Some(c) = wal.prepare_wal_start(page_size).unwrap() {
            io.wait_for_completion(c).unwrap();
        }
        let c = wal.prepare_wal_finish(FileSyncType::Fsync).unwrap();
        io.wait_for_completion(c).unwrap();

        (io, buffer_pool, wal)
    }

    fn page_with_pattern(page_id: i64, seed: u8, buffer_pool: &Arc<BufferPool>) -> PageRef {
        let page = allocate_new_page(page_id, buffer_pool);
        for (idx, byte) in page.get_contents().as_ptr().iter_mut().enumerate() {
            *byte = seed.wrapping_add(idx as u8).wrapping_add(page_id as u8);
        }
        page
    }

    fn append_test_pages(
        io: &Arc<dyn IO>,
        wal: &WalFile,
        page_size: u32,
        pages: &[PageRef],
    ) -> Vec<Vec<u8>> {
        let prepared = wal
            .prepare_frames(pages, PageSize::new(page_size).unwrap(), Some(99), None)
            .unwrap();
        let expected = pages
            .iter()
            .map(|page| page.get_contents().as_ptr().to_vec())
            .collect::<Vec<_>>();

        let file = wal.wal_file().unwrap();
        let c = file
            .pwritev(
                prepared.offset,
                prepared.bufs.clone(),
                Completion::new_write(|_| {}),
            )
            .unwrap();
        io.wait_for_completion(c).unwrap();
        wal.commit_prepared_frames(&[prepared]);
        wal.finish_append_frames_commit().unwrap();
        expected
    }

    fn wait_for_completion_error(io: &Arc<dyn IO>, completion: Completion) -> CompletionError {
        match io.wait_for_completion(completion) {
            Err(LimboError::CompletionError(err)) => err,
            other => panic!("expected completion error, got {other:?}"),
        }
    }

    #[test]
    fn read_frames_batch_reads_contiguous_wal_frames_directly() {
        let page_size = 512;
        let (io, buffer_pool, wal) = make_initialized_memory_wal(page_size);
        let source_pages = vec![
            page_with_pattern(2, 0x10, &buffer_pool),
            page_with_pattern(3, 0x20, &buffer_pool),
            page_with_pattern(4, 0x30, &buffer_pool),
            page_with_pattern(5, 0x40, &buffer_pool),
        ];
        let expected = append_test_pages(&io, &wal, page_size, &source_pages);

        let target_pages = vec![
            Arc::new(crate::Page::new(2)),
            Arc::new(crate::Page::new(3)),
            Arc::new(crate::Page::new(4)),
            Arc::new(crate::Page::new(5)),
        ];
        let c = wal
            .read_frames_batch(1, &target_pages, buffer_pool, None)
            .unwrap();
        io.wait_for_completion(c).unwrap();

        for (idx, page) in target_pages.iter().enumerate() {
            assert!(page.is_loaded(), "page {} should be loaded", page.get().id);
            assert!(!page.is_locked(), "page {} lock leaked", page.get().id);
            assert_eq!(page.wal_tag_pair(), ((idx + 1) as u64, 0));
            assert_eq!(page.get_contents().as_ptr(), expected[idx].as_slice());
        }
    }

    #[test]
    fn read_frames_batch_can_start_from_middle_frame() {
        let page_size = 512;
        let (io, buffer_pool, wal) = make_initialized_memory_wal(page_size);
        let source_pages = vec![
            page_with_pattern(10, 0x01, &buffer_pool),
            page_with_pattern(11, 0x02, &buffer_pool),
            page_with_pattern(12, 0x03, &buffer_pool),
            page_with_pattern(13, 0x04, &buffer_pool),
        ];
        let expected = append_test_pages(&io, &wal, page_size, &source_pages);

        let target_pages = vec![
            Arc::new(crate::Page::new(11)),
            Arc::new(crate::Page::new(12)),
            Arc::new(crate::Page::new(13)),
        ];
        let c = wal
            .read_frames_batch(2, &target_pages, buffer_pool, None)
            .unwrap();
        io.wait_for_completion(c).unwrap();

        for (idx, page) in target_pages.iter().enumerate() {
            assert!(page.is_loaded(), "page {} should be loaded", page.get().id);
            assert!(!page.is_locked(), "page {} lock leaked", page.get().id);
            assert_eq!(page.wal_tag_pair(), ((idx + 2) as u64, 0));
            assert_eq!(page.get_contents().as_ptr(), expected[idx + 1].as_slice());
        }
    }

    #[test]
    fn read_frames_batch_follows_physical_frame_order_not_page_id_order() {
        let page_size = 512;
        let (io, buffer_pool, wal) = make_initialized_memory_wal(page_size);
        let source_pages = vec![
            page_with_pattern(7, 0x71, &buffer_pool),
            page_with_pattern(2, 0x22, &buffer_pool),
            page_with_pattern(5, 0x55, &buffer_pool),
            page_with_pattern(9, 0x99, &buffer_pool),
        ];
        let expected = append_test_pages(&io, &wal, page_size, &source_pages);

        let target_pages = vec![
            Arc::new(crate::Page::new(7)),
            Arc::new(crate::Page::new(2)),
            Arc::new(crate::Page::new(5)),
            Arc::new(crate::Page::new(9)),
        ];
        let c = wal
            .read_frames_batch(1, &target_pages, buffer_pool, None)
            .unwrap();
        io.wait_for_completion(c).unwrap();

        for (idx, page) in target_pages.iter().enumerate() {
            assert_eq!(
                page.get_contents().as_ptr(),
                expected[idx].as_slice(),
                "frame-order read should preserve page {} contents",
                page.get().id
            );
            assert_eq!(page.wal_tag_pair(), ((idx + 1) as u64, 0));
        }
    }

    #[test]
    fn read_frames_batch_short_read_errors_and_clears_page_locks() {
        let page_size = 512;
        let (io, buffer_pool, wal) = make_initialized_memory_wal(page_size);
        let source_pages = vec![
            page_with_pattern(20, 0x20, &buffer_pool),
            page_with_pattern(21, 0x21, &buffer_pool),
        ];
        append_test_pages(&io, &wal, page_size, &source_pages);

        let target_pages = vec![
            Arc::new(crate::Page::new(20)),
            Arc::new(crate::Page::new(21)),
            Arc::new(crate::Page::new(22)),
        ];
        let c = wal
            .read_frames_batch(1, &target_pages, buffer_pool, None)
            .unwrap();
        let err = wait_for_completion_error(&io, c);

        assert!(
            matches!(err, CompletionError::ShortReadWalFrame { .. }),
            "unexpected error: {err:?}"
        );
        for page in &target_pages {
            assert!(!page.is_locked(), "page {} lock leaked", page.get().id);
            assert!(
                !page.is_loaded(),
                "page {} should not be loaded",
                page.get().id
            );
            assert!(
                !page.has_wal_tag(),
                "page {} should not be tagged",
                page.get().id
            );
        }
    }

    #[test]
    fn read_frames_batch_page_number_mismatch_returns_error_not_panic() {
        let page_size = 512;
        let (io, buffer_pool, wal) = make_initialized_memory_wal(page_size);
        let source_pages = vec![
            page_with_pattern(30, 0x30, &buffer_pool),
            page_with_pattern(31, 0x31, &buffer_pool),
        ];
        append_test_pages(&io, &wal, page_size, &source_pages);

        let target_pages = vec![
            Arc::new(crate::Page::new(30)),
            Arc::new(crate::Page::new(99)),
        ];
        let c = wal
            .read_frames_batch(1, &target_pages, buffer_pool, None)
            .unwrap();
        let err = wait_for_completion_error(&io, c);

        assert!(
            matches!(
                err,
                CompletionError::WalFramePageMismatch {
                    frame_id: 2,
                    expected: 99,
                    actual: 31
                }
            ),
            "unexpected error: {err:?}"
        );
        for page in &target_pages {
            assert!(!page.is_locked(), "page {} lock leaked", page.get().id);
            assert!(
                !page.is_loaded(),
                "page {} should not be loaded",
                page.get().id
            );
            assert!(
                !page.has_wal_tag(),
                "page {} should not be tagged",
                page.get().id
            );
            assert!(
                page.get().buffer.is_none(),
                "page {} should not retain a buffer",
                page.get().id
            );
        }
    }

    fn set_shared_snapshot(shared: &Arc<RwLock<WalFileShared>>, snapshot: WalSnapshot) {
        let mut guard = shared.write();
        guard
            .metadata
            .max_frame
            .store(snapshot.max_frame, Ordering::Release);
        guard
            .metadata
            .nbackfills
            .store(snapshot.nbackfills, Ordering::Release);
        guard.metadata.last_checksum = snapshot.last_checksum;
        guard.metadata.wal_header.lock().checkpoint_seq = snapshot.checkpoint_seq;
        guard
            .metadata
            .transaction_count
            .store(snapshot.transaction_count, Ordering::Release);
    }

    fn make_test_coordination(shared: &Arc<RwLock<WalFileShared>>) -> InProcessWalCoordination {
        InProcessWalCoordination::new(shared.clone())
    }

    #[cfg(host_shared_wal)]
    fn make_test_shm_coordination(
        shared: &Arc<RwLock<WalFileShared>>,
        path: &std::path::Path,
    ) -> (Arc<MappedSharedWalCoordination>, ShmWalCoordination) {
        let io = shared_wal_test_io();
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, path, 64).unwrap());
        let coordination = ShmWalCoordination::new(shared.clone(), authority.clone());
        (authority, coordination)
    }

    #[cfg(host_shared_wal)]
    fn active_shared_reader_slot_count(authority: &MappedSharedWalCoordination) -> usize {
        let reader_slot_count = authority.snapshot().reader_slot_count;
        (0..reader_slot_count)
            .filter(|&slot_index| authority.reader_owner(slot_index).is_some())
            .count()
    }

    #[cfg(host_shared_wal)]
    fn write_test_wal_with_single_commit_frame(
        io: &Arc<dyn IO>,
        wal_path: &std::path::Path,
    ) -> SharedWalCoordinationHeader {
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let mut wal_header = sqlite3_ondisk::WalHeader {
            page_size: 4096,
            checkpoint_seq: 5,
            salt_1: 17,
            salt_2: 23,
            ..sqlite3_ondisk::WalHeader::new()
        };
        let use_native_endian = cfg!(target_endian = "big") == ((wal_header.magic & 1) != 0);
        let mut header_prefix = [0u8; WAL_HEADER_SIZE - 8];
        header_prefix[0..4].copy_from_slice(&wal_header.magic.to_be_bytes());
        header_prefix[4..8].copy_from_slice(&wal_header.file_format.to_be_bytes());
        header_prefix[8..12].copy_from_slice(&wal_header.page_size.to_be_bytes());
        header_prefix[12..16].copy_from_slice(&wal_header.checkpoint_seq.to_be_bytes());
        header_prefix[16..20].copy_from_slice(&wal_header.salt_1.to_be_bytes());
        header_prefix[20..24].copy_from_slice(&wal_header.salt_2.to_be_bytes());
        let header_checksum =
            sqlite3_ondisk::checksum_wal(&header_prefix, &wal_header, (0, 0), use_native_endian);
        wal_header.checksum_1 = header_checksum.0;
        wal_header.checksum_2 = header_checksum.1;

        io.wait_for_completion(
            sqlite3_ondisk::begin_write_wal_header(file.as_ref(), &wal_header).unwrap(),
        )
        .unwrap();

        let buffer_pool = BufferPool::begin_init(io, BufferPool::TEST_ARENA_SIZE);
        buffer_pool
            .finalize_with_page_size(wal_header.page_size as usize)
            .unwrap();
        #[allow(unused_mut)]
        let mut page = vec![0x5a; wal_header.page_size as usize];
        #[cfg(feature = "checksum")]
        crate::storage::checksum::ChecksumContext::new()
            .add_checksum_to_page(&mut page, 7)
            .unwrap();
        let (frame_checksum, frame_buf) = sqlite3_ondisk::prepare_wal_frame(
            &buffer_pool,
            &wal_header,
            header_checksum,
            wal_header.page_size,
            7,
            1,
            &page,
        );
        let c = file
            .pwrite(
                WAL_HEADER_SIZE as u64,
                frame_buf,
                Completion::new_write(|_| {}),
            )
            .unwrap();
        io.wait_for_completion(c).unwrap();
        let c = file
            .sync(Completion::new_sync(|_| {}), crate::io::FileSyncType::Fsync)
            .unwrap();
        io.wait_for_completion(c).unwrap();

        SharedWalCoordinationHeader {
            max_frame: 1,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 3,
            checkpoint_seq: wal_header.checkpoint_seq,
            checkpoint_epoch: 7,
            page_size: wal_header.page_size,
            salt_1: wal_header.salt_1,
            salt_2: wal_header.salt_2,
            checksum_1: frame_checksum.0,
            checksum_2: frame_checksum.1,
            reader_slot_count: 64,
        }
    }

    #[cfg(host_shared_wal)]
    fn open_test_db_file_for_wal(
        io: &Arc<dyn IO>,
        wal_path: &std::path::Path,
    ) -> Arc<dyn DatabaseStorage> {
        let db_path = wal_path.with_extension("db");
        Arc::new(DatabaseFile::new(
            io.open_file(db_path.to_str().unwrap(), crate::OpenFlags::Create, false)
                .unwrap(),
        ))
    }

    #[test]
    #[cfg(host_shared_wal)]
    fn test_read_frame_keeps_epoch_from_issue_time() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("epoch-race.db-wal");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);

        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file.clone()).unwrap();
        let deferred_file = Arc::new(DeferredReadFile::new(file));
        {
            let mut shared = shared.write();
            shared.runtime.file = Some(deferred_file.clone());
            shared
                .runtime
                .epoch
                .store(snapshot.checkpoint_epoch, Ordering::Release);
        }

        let coordination: Arc<dyn WalCoordination> = Arc::new(make_test_coordination(&shared));
        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        buffer_pool
            .finalize_with_page_size(snapshot.page_size as usize)
            .unwrap();
        let wal = WalFile::new_with_coordination(
            io.clone(),
            coordination,
            (
                (snapshot.checksum_1, snapshot.checksum_2),
                snapshot.max_frame,
            ),
            buffer_pool.clone(),
        );

        let page = Arc::new(crate::storage::pager::Page::new(7));
        let issued_epoch = wal.coordination.checkpoint_epoch();
        let completion = wal.read_frame(1, page.clone(), buffer_pool).unwrap();

        wal.increment_checkpoint_epoch();
        deferred_file.complete_pending_reads();
        io.wait_for_completion(completion).unwrap();

        assert_eq!(
            page.wal_tag_pair(),
            (1, issued_epoch),
            "WAL reads must retain the epoch from when the read was issued"
        );
    }

    #[cfg(test)]
    fn read_slots_with_readers(shared: &WalFileShared) -> Vec<usize> {
        shared
            .runtime
            .read_locks
            .iter()
            .enumerate()
            .filter_map(|(slot, lock)| {
                let state = lock.0.load(Ordering::Acquire);
                let has_readers = (state & super::TursoRwLock::READER_COUNT_MASK) != 0;
                has_readers.then_some(slot)
            })
            .collect()
    }

    fn wal_header_snapshot(shared: &Arc<RwLock<WalFileShared>>) -> (u32, u32, u32, u32) {
        // (checkpoint_seq, salt1, salt2, page_size)
        let shared_guard = shared.read();
        let hdr = shared_guard.metadata.wal_header.lock();
        (hdr.checkpoint_seq, hdr.salt_1, hdr.salt_2, hdr.page_size)
    }

    #[test]
    fn test_wal_connection_state_round_trip() {
        let (_shared, wal) = make_test_wal();
        let state = WalConnectionState::new(
            WalSnapshot {
                max_frame: 11,
                nbackfills: 7,
                last_checksum: (31, 47),
                checkpoint_seq: 5,
                transaction_count: 13,
            },
            ReadGuardKind::ReadMark(NonZeroUsize::new(3).unwrap()),
        );

        wal.install_connection_state(state);

        assert_eq!(wal.connection_state(), state);
        assert_eq!(wal.connection_state().snapshot.min_frame(), 8);
    }

    #[test]
    fn test_wal_explicit_backend_constructor_does_not_keep_shared_handle() {
        let io = shared_wal_test_io();
        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        let shared = WalFileShared::new_noop();
        let coordination: Arc<dyn WalCoordination> =
            Arc::new(InProcessWalCoordination::new(shared.clone()));

        assert_eq!(Arc::strong_count(&shared), 2);

        let _wal = WalFile::new_with_coordination(io, coordination, ((0, 0), 0), buffer_pool);

        assert_eq!(Arc::strong_count(&shared), 2);
    }

    #[test]
    fn test_mvcc_refresh_updates_snapshot_without_changing_read_guard() {
        let (shared, wal) = make_test_wal();
        let initial = WalSnapshot {
            max_frame: 4,
            nbackfills: 2,
            last_checksum: (9, 10),
            checkpoint_seq: 1,
            transaction_count: 3,
        };
        set_shared_snapshot(&shared, initial);
        wal.install_connection_state(WalConnectionState::new(
            initial,
            ReadGuardKind::ReadMark(NonZeroUsize::new(2).unwrap()),
        ));

        assert!(!wal.mvcc_refresh_if_db_changed());

        let updated = WalSnapshot {
            max_frame: 8,
            nbackfills: 5,
            last_checksum: (21, 34),
            checkpoint_seq: 7,
            transaction_count: 4,
        };
        set_shared_snapshot(&shared, updated);

        assert!(wal.mvcc_refresh_if_db_changed());
        assert_eq!(
            wal.connection_state(),
            WalConnectionState::new(
                updated,
                ReadGuardKind::ReadMark(NonZeroUsize::new(2).unwrap())
            )
        );
    }

    #[test]
    fn test_in_process_coordination_uses_shared_authority() {
        let (shared, _wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);
        let snapshot = WalSnapshot {
            max_frame: 9,
            nbackfills: 3,
            last_checksum: (55, 89),
            checkpoint_seq: 7,
            transaction_count: 11,
        };
        set_shared_snapshot(&shared, snapshot);
        {
            let guard = shared.write();
            guard.runtime.epoch.store(5, Ordering::Release);
            guard.runtime.frame_cache.lock().extend([
                (1, vec![1, 4, 8]),
                (2, vec![2, 6]),
                (3, vec![3]),
            ]);
        }

        assert_eq!(coordination.load_snapshot(), snapshot);
        assert_eq!(coordination.checkpoint_epoch(), 5);
        assert_eq!(coordination.find_frame(1, 4, 9, None), Some(8));
        assert_eq!(coordination.find_frame(2, 4, 9, Some(5)), Some(2));
        assert_eq!(coordination.iter_latest_frames(4, 9), vec![(1, 8), (2, 6)]);

        coordination.publish_commit(WalCommitState {
            max_frame: 12,
            last_checksum: (144, 233),
            transaction_count: 12,
        });
        let published = coordination.load_snapshot();
        assert_eq!(published.max_frame, 12);
        assert_eq!(published.last_checksum, (144, 233));
        assert_eq!(published.transaction_count, 12);
        assert_eq!(published.nbackfills, snapshot.nbackfills);
        assert_eq!(published.checkpoint_seq, snapshot.checkpoint_seq);
    }

    #[test]
    fn test_in_process_coordination_publishes_checkpoint_and_restart_state() {
        let (shared, _wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);
        let io = PlatformIO::new().unwrap();
        let snapshot = WalSnapshot {
            max_frame: 9,
            nbackfills: 3,
            last_checksum: (55, 89),
            checkpoint_seq: 7,
            transaction_count: 11,
        };
        set_shared_snapshot(&shared, snapshot);
        {
            let guard = shared.write();
            let mut header = guard.metadata.wal_header.lock();
            header.page_size = 4096;
            header.checksum_1 = 144;
            header.checksum_2 = 233;
            guard.metadata.initialized.store(true, Ordering::Release);
            guard.runtime.epoch.store(5, Ordering::Release);
            guard
                .runtime
                .frame_cache
                .lock()
                .extend([(1, vec![1, 4, 8]), (2, vec![2, 6])]);
        }

        coordination.publish_backfill(8);
        assert_eq!(coordination.load_snapshot().nbackfills, 8);
        assert_eq!(coordination.bump_checkpoint_epoch(), 5);
        assert_eq!(coordination.checkpoint_epoch(), 6);

        assert!(coordination.try_read_mark_exclusive(0));
        let restarted = coordination.begin_restart(&io).unwrap();
        coordination.end_restart();
        coordination.unlock_read_mark(0);

        assert_eq!(restarted.max_frame, 0);
        assert_eq!(restarted.nbackfills, 0);
        assert_eq!(restarted.last_checksum, (144, 233));
        assert_eq!(restarted.checkpoint_seq, 8);
        assert_eq!(restarted.transaction_count, 11);

        let guard = shared.read();
        assert_eq!(guard.runtime.read_locks[0].get_value(), 0);
        assert_eq!(guard.runtime.read_locks[1].get_value(), 0);
        for lock in &guard.runtime.read_locks[2..] {
            assert_eq!(lock.get_value(), READMARK_NOT_USED);
        }
        assert!(guard.runtime.frame_cache.lock().is_empty());
        assert!(!guard.metadata.initialized.load(Ordering::Acquire));
    }

    #[test]
    fn test_in_process_coordination_manages_frame_cache() {
        let (shared, _wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);

        coordination.cache_frame(7, 2);
        coordination.cache_frame(7, 5);
        coordination.cache_frame(9, 4);

        assert_eq!(coordination.find_frame(7, 0, 5, None), Some(5));
        assert_eq!(coordination.iter_latest_frames(0, 5), vec![(7, 5), (9, 4)]);

        coordination.rollback_cache(4);

        assert_eq!(coordination.find_frame(7, 0, 5, None), Some(2));
        assert_eq!(coordination.iter_latest_frames(0, 5), vec![(7, 2), (9, 4)]);
        assert_eq!(
            shared.read().runtime.frame_cache.lock().get(&7),
            Some(&vec![2])
        );
    }

    #[test]
    fn test_savepoint_rollback_preserves_committed_frame_cache() {
        let (shared, wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);
        set_shared_snapshot(
            &shared,
            WalSnapshot {
                max_frame: 25,
                nbackfills: 0,
                last_checksum: (55, 89),
                checkpoint_seq: 1,
                transaction_count: 3,
            },
        );

        coordination.cache_frame(7, 10);
        coordination.cache_frame(9, 20);
        coordination.cache_frame(11, 30);
        wal.max_frame.store(30, Ordering::Release);

        wal.rollback(Some(RollbackTo {
            frame: 10,
            checksum: (13, 21),
        }));

        assert_eq!(coordination.find_frame(7, 0, 30, None), Some(10));
        assert_eq!(coordination.find_frame(9, 0, 30, None), Some(20));
        assert_eq!(coordination.find_frame(11, 0, 30, None), None);
        assert_eq!(wal.get_max_frame(), 10);
    }

    #[test]
    fn test_in_process_coordination_transaction_guards() {
        let (shared, _wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);

        let db_file_snapshot = WalSnapshot {
            max_frame: 0,
            nbackfills: 0,
            last_checksum: (0, 0),
            checkpoint_seq: 0,
            transaction_count: 0,
        };
        set_shared_snapshot(&shared, db_file_snapshot);
        let read_guard = coordination.try_begin_read_tx(db_file_snapshot).unwrap();
        assert_eq!(read_guard, ReadGuardKind::DbFile);
        coordination.end_read_tx(read_guard);

        let wal_snapshot = WalSnapshot {
            max_frame: 5,
            nbackfills: 2,
            last_checksum: (11, 13),
            checkpoint_seq: 1,
            transaction_count: 2,
        };
        set_shared_snapshot(&shared, wal_snapshot);
        let read_guard = coordination.try_begin_read_tx(wal_snapshot).unwrap();
        assert!(matches!(read_guard, ReadGuardKind::ReadMark(_)));
        coordination.end_read_tx(read_guard);

        assert!(coordination.try_begin_write_tx());
        assert!(!coordination.try_begin_write_tx());
        coordination.end_write_tx();
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_uses_shared_authority() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();
        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        let snapshot = WalSnapshot {
            max_frame: 14,
            nbackfills: 8,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, snapshot);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = snapshot.last_checksum.0;
            header.checksum_2 = snapshot.last_checksum.1;
        }

        let (_authority_a, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        let (authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);
        coordination_a.cache_frame(7, 2);
        coordination_a.cache_frame(9, 4);
        coordination_a.cache_frame(7, 5);

        assert_eq!(coordination_b.load_snapshot(), snapshot);
        assert_eq!(coordination_b.wal_header().page_size, 4096);
        assert_eq!(coordination_b.wal_header().salt_1, 17);
        assert_eq!(coordination_b.wal_header().salt_2, 23);
        assert_eq!(coordination_b.find_frame(7, 0, 5, None), Some(5));
        assert_eq!(
            coordination_b.iter_latest_frames(0, 5),
            vec![(7, 5), (9, 4)]
        );
        assert_eq!(coordination_a.checkpoint_epoch(), 0);
        assert_eq!(coordination_b.bump_checkpoint_epoch(), 0);
        assert_eq!(coordination_a.checkpoint_epoch(), 1);

        assert!(coordination_a.try_begin_write_tx());
        assert!(!coordination_b.try_begin_write_tx());
        coordination_a.end_write_tx();

        let read_guard = coordination_a.try_begin_read_tx(snapshot).unwrap();
        assert_eq!(
            authority_b.min_active_reader_frame(),
            Some(snapshot.max_frame)
        );
        coordination_a.end_read_tx(read_guard);
        assert_eq!(authority_b.min_active_reader_frame(), None);

        coordination_b.publish_commit(WalCommitState {
            max_frame: 21,
            last_checksum: (55, 89),
            transaction_count: 10,
        });
        assert_eq!(
            coordination_a.load_snapshot(),
            WalSnapshot {
                max_frame: 21,
                nbackfills: 8,
                last_checksum: (55, 89),
                checkpoint_seq: 5,
                transaction_count: 10,
            }
        );

        coordination_b.rollback_cache(4);
        assert_eq!(coordination_a.find_frame(7, 0, 5, None), Some(2));
        assert_eq!(
            coordination_a.iter_latest_frames(0, 5),
            vec![(7, 2), (9, 4)]
        );
        assert!(shm_path.exists());
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_many_same_snapshot_readers_share_one_published_slot() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-many-same-snapshot-readers.db-wal");
        let shm_path = dir.path().join("test-many-same-snapshot-readers.db-tshm");
        let io = shared_wal_test_io();
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let snapshot = WalSnapshot {
            max_frame: 9,
            nbackfills: 2,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared, snapshot);
        {
            let shared = shared.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = snapshot.last_checksum.0;
            header.checksum_2 = snapshot.last_checksum.1;
        }

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let mut readers = Vec::new();
        for _ in 0..128 {
            let coordination = ShmWalCoordination::new(shared.clone(), authority.clone());
            let read_guard = coordination
                .try_begin_read_tx(snapshot)
                .expect("same-snapshot readers should share a published reader barrier");
            readers.push((coordination, read_guard));
        }

        assert_eq!(
            authority.min_active_reader_frame(),
            Some(snapshot.max_frame)
        );
        assert_eq!(
            active_shared_reader_slot_count(&authority),
            1,
            "same-snapshot readers should collapse onto one shared reader slot"
        );

        for (coordination, read_guard) in readers {
            coordination.end_read_tx(read_guard);
        }
        assert_eq!(authority.min_active_reader_frame(), None);
        assert_eq!(active_shared_reader_slot_count(&authority), 0);
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_uses_one_published_slot_per_active_snapshot_generation() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-mixed-snapshot-readers.db-wal");
        let shm_path = dir.path().join("test-mixed-snapshot-readers.db-tshm");
        let io = shared_wal_test_io();
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let snapshot_a = WalSnapshot {
            max_frame: 5,
            nbackfills: 2,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared, snapshot_a);
        {
            let shared = shared.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = snapshot_a.last_checksum.0;
            header.checksum_2 = snapshot_a.last_checksum.1;
        }

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let reader_a1 = ShmWalCoordination::new(shared.clone(), authority.clone());
        let guard_a1 = reader_a1.try_begin_read_tx(snapshot_a).unwrap();
        let reader_a2 = ShmWalCoordination::new(shared.clone(), authority.clone());
        let guard_a2 = reader_a2.try_begin_read_tx(snapshot_a).unwrap();
        assert_eq!(
            authority.min_active_reader_frame(),
            Some(snapshot_a.max_frame)
        );
        assert_eq!(active_shared_reader_slot_count(&authority), 1);

        let snapshot_b = WalSnapshot {
            max_frame: 9,
            nbackfills: 2,
            last_checksum: (41, 43),
            checkpoint_seq: 5,
            transaction_count: 10,
        };
        reader_a1.publish_commit(WalCommitState {
            max_frame: snapshot_b.max_frame,
            last_checksum: snapshot_b.last_checksum,
            transaction_count: snapshot_b.transaction_count,
        });

        let reader_b1 = ShmWalCoordination::new(shared.clone(), authority.clone());
        let guard_b1 = reader_b1.try_begin_read_tx(snapshot_b).unwrap();
        let reader_b2 = ShmWalCoordination::new(shared, authority.clone());
        let guard_b2 = reader_b2.try_begin_read_tx(snapshot_b).unwrap();

        assert_eq!(
            active_shared_reader_slot_count(&authority),
            2,
            "distinct live snapshots should each publish one shared reader slot"
        );
        assert_eq!(
            authority.min_active_reader_frame(),
            Some(snapshot_a.max_frame),
            "checkpoint barrier should stay pinned to the oldest active snapshot"
        );

        reader_a1.end_read_tx(guard_a1);
        reader_a2.end_read_tx(guard_a2);
        assert_eq!(
            authority.min_active_reader_frame(),
            Some(snapshot_b.max_frame)
        );
        assert_eq!(active_shared_reader_slot_count(&authority), 1);

        reader_b1.end_read_tx(guard_b1);
        reader_b2.end_read_tx(guard_b2);
        assert_eq!(authority.min_active_reader_frame(), None);
        assert_eq!(active_shared_reader_slot_count(&authority), 0);
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_shared_index_grows_past_old_fixed_limit() {
        const OLD_FIXED_LIMIT: u64 = 65_536;

        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();
        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        let snapshot = WalSnapshot {
            max_frame: OLD_FIXED_LIMIT + 2,
            nbackfills: 0,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: OLD_FIXED_LIMIT + 2,
        };
        set_shared_snapshot(&shared_a, snapshot);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = snapshot.last_checksum.0;
            header.checksum_2 = snapshot.last_checksum.1;
        }

        let (_authority_a, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        let (_authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);

        coordination_a.cache_frame(7, 2);
        for frame_id in 3..=OLD_FIXED_LIMIT + 1 {
            coordination_a.cache_frame(100 + (frame_id % 31), frame_id);
        }
        coordination_a.cache_frame(7, OLD_FIXED_LIMIT + 2);

        assert_eq!(
            coordination_b.find_frame(7, 0, OLD_FIXED_LIMIT + 2, None),
            Some(OLD_FIXED_LIMIT + 2)
        );
        assert_eq!(
            coordination_b.find_frame(7, 0, OLD_FIXED_LIMIT + 2, Some(OLD_FIXED_LIMIT + 1)),
            Some(2)
        );
        assert!(coordination_b
            .iter_latest_frames(0, OLD_FIXED_LIMIT + 2)
            .contains(&(7, OLD_FIXED_LIMIT + 2)));
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_restart_uses_authority_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = PlatformIO::new().unwrap();
        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        let snapshot = WalSnapshot {
            max_frame: 12,
            nbackfills: 12,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, snapshot);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = snapshot.last_checksum.0;
            header.checksum_2 = snapshot.last_checksum.1;
            shared.metadata.initialized.store(true, Ordering::Release);
            shared.runtime.epoch.store(5, Ordering::Release);
        }

        let (_authority_a, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        let (_authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);
        coordination_a.cache_frame(7, 2);
        coordination_a.cache_frame(9, 4);

        {
            let mut shared = shared_b.write();
            shared.metadata.max_frame.store(99, Ordering::Release);
            shared.metadata.nbackfills.store(77, Ordering::Release);
            shared.metadata.last_checksum = (1, 2);
            shared
                .metadata
                .transaction_count
                .store(42, Ordering::Release);
            shared.runtime.epoch.store(99, Ordering::Release);
            shared.metadata.initialized.store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.checkpoint_seq = 88;
            header.page_size = 2048;
            header.salt_1 = 91;
            header.salt_2 = 92;
            header.checksum_1 = 93;
            header.checksum_2 = 94;
        }

        assert!(coordination_b.fallback.try_read_mark_exclusive(0));
        let restarted = coordination_b.begin_restart(&io).unwrap();
        coordination_b.end_restart();
        coordination_b.fallback.unlock_read_mark(0);

        assert_eq!(
            restarted,
            WalSnapshot {
                max_frame: 0,
                nbackfills: 0,
                last_checksum: snapshot.last_checksum,
                checkpoint_seq: snapshot.checkpoint_seq.wrapping_add(1),
                transaction_count: snapshot.transaction_count,
            }
        );
        assert_eq!(
            coordination_a.load_snapshot(),
            WalSnapshot {
                max_frame: 0,
                nbackfills: 0,
                last_checksum: snapshot.last_checksum,
                checkpoint_seq: snapshot.checkpoint_seq.wrapping_add(1),
                transaction_count: snapshot.transaction_count,
            }
        );
        let header = coordination_a.wal_header();
        assert_eq!(header.page_size, 4096);
        assert_eq!(
            header.checkpoint_seq,
            snapshot.checkpoint_seq.wrapping_add(1)
        );
        assert_eq!(header.salt_1, 18);
        assert_ne!(header.salt_2, 23);
        assert_eq!(header.checksum_1, snapshot.last_checksum.0);
        assert_eq!(header.checksum_2, snapshot.last_checksum.1);
        assert_eq!(coordination_a.iter_latest_frames(0, u64::MAX), Vec::new());
        assert_eq!(coordination_a.checkpoint_epoch(), 5);

        let shared = shared_b.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 0);
        assert_eq!(shared.metadata.nbackfills.load(Ordering::Acquire), 0);
        assert_eq!(shared.metadata.last_checksum, snapshot.last_checksum);
        assert_eq!(
            shared.metadata.transaction_count.load(Ordering::Acquire),
            snapshot.transaction_count
        );
        assert_eq!(shared.runtime.epoch.load(Ordering::Acquire), 5);
        assert!(!shared.metadata.initialized.load(Ordering::Acquire));
        assert!(shared.runtime.frame_cache.lock().is_empty());
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_exclusive_reopen_reuses_persisted_authority() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        {
            let file = io
                .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
                .unwrap();
            let shared = WalFileShared::new_shared(file).unwrap();
            let snapshot = WalSnapshot {
                max_frame: 12,
                nbackfills: 8,
                last_checksum: (31, 37),
                checkpoint_seq: 5,
                transaction_count: 9,
            };
            set_shared_snapshot(&shared, snapshot);
            {
                let shared = shared.write();
                let mut header = shared.metadata.wal_header.lock();
                header.page_size = 4096;
                header.salt_1 = 17;
                header.salt_2 = 23;
                header.checksum_1 = snapshot.last_checksum.0;
                header.checksum_2 = snapshot.last_checksum.1;
            }

            let (authority, coordination) = make_test_shm_coordination(&shared, &shm_path);
            coordination.cache_frame(7, 2);
            coordination.cache_frame(7, 5);
            assert_eq!(
                authority.open_mode(),
                SharedWalCoordinationOpenMode::Exclusive
            );
            assert_eq!(coordination.load_snapshot(), snapshot);
            assert_eq!(coordination.find_frame(7, 0, 5, None), Some(5));
        }

        let reopened_file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let reopened_shared = WalFileShared::new_shared(reopened_file).unwrap();
        let (reopened_authority, reopened_coordination) =
            make_test_shm_coordination(&reopened_shared, &shm_path);

        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );
        assert_eq!(
            reopened_coordination.load_snapshot(),
            WalSnapshot {
                max_frame: 12,
                nbackfills: 8,
                last_checksum: (31, 37),
                checkpoint_seq: 5,
                transaction_count: 9,
            }
        );
        assert_eq!(
            reopened_coordination.iter_latest_frames(0, u64::MAX),
            vec![(7, 5)]
        );
        assert_eq!(reopened_authority.min_active_reader_frame(), None);
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_reuses_trusted_snapshot_after_exclusive_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        {
            let authority =
                Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
            authority.install_snapshot(snapshot);
            authority.record_frame(7, 1);
        }
        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();

        let shared = shared.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 1);
        assert_eq!(shared.metadata.nbackfills.load(Ordering::Acquire), 0);
        assert_eq!(
            shared.metadata.transaction_count.load(Ordering::Acquire),
            snapshot.transaction_count
        );
        assert_eq!(
            shared.metadata.last_checksum,
            (snapshot.checksum_1, snapshot.checksum_2)
        );
        assert_eq!(
            shared.runtime.epoch.load(Ordering::Acquire),
            snapshot.checkpoint_epoch
        );
        assert!(shared.metadata.initialized.load(Ordering::Acquire));
        assert!(!shared
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
        assert!(shared.runtime.frame_cache.lock().is_empty());
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_live_overflow_returns_busy_without_runtime_disk_scan() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-live-overflow.db-wal");
        let shm_path = dir.path().join("test-live-overflow.db-tshm");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        authority.install_snapshot(snapshot);
        authority.record_frame(7, 1);

        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();
        assert!(shared.read().runtime.frame_cache.lock().is_empty());

        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        buffer_pool.finalize_with_page_size(4096).unwrap();
        let wal = WalFile::new_with_shared_coordination(
            io.clone(),
            shared.clone(),
            reopened_authority.clone(),
            ((0, 0), 0),
            buffer_pool,
        );

        wal.begin_read_tx().unwrap();
        reopened_authority.mark_frame_index_overflowed_for_tests();

        assert!(
            matches!(wal.find_frame(7, None), Err(LimboError::Busy)),
            "page lookup must refuse the overflowed path instead of rescanning the WAL synchronously"
        );
        assert!(
            shared.read().runtime.frame_cache.lock().is_empty(),
            "refusing the overflow refresh must leave the local fallback cache untouched"
        );

        wal.end_read_tx();
        assert!(
            matches!(wal.begin_read_tx(), Err(LimboError::Busy)),
            "new readers must also refuse an uncovered overflowed frame index without blocking"
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_exclusive_rebuilds_positive_snapshot_from_disk() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-exclusive-positive.db-wal");
        let shm_path = dir.path().join("test-exclusive-positive.db-tshm");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        {
            let authority =
                Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
            authority.install_snapshot(SharedWalCoordinationHeader {
                nbackfills: snapshot.max_frame,
                ..snapshot
            });
            authority.record_frame(7, 1);
            assert_eq!(
                authority.open_mode(),
                SharedWalCoordinationOpenMode::Exclusive
            );
        }

        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();

        let shared = shared.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 1);
        assert_eq!(shared.metadata.nbackfills.load(Ordering::Acquire), 0);
        assert!(shared
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
        assert_eq!(
            shared.runtime.frame_cache.lock().get(&7).cloned(),
            Some(vec![1])
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shared_coordination_open_uses_reconciled_snapshot_for_local_wal_state() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let snapshot = SharedWalCoordinationHeader {
            max_frame: 1,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 3,
            checkpoint_seq: 5,
            checkpoint_epoch: 7,
            page_size: 4096,
            salt_1: 17,
            salt_2: 23,
            checksum_1: 31,
            checksum_2: 37,
            reader_slot_count: 64,
        };
        authority.install_snapshot(snapshot);
        authority.record_frame(7, 1);

        let buffer_pool = BufferPool::begin_init(&io, BufferPool::TEST_ARENA_SIZE);
        buffer_pool.finalize_with_page_size(4096).unwrap();
        let wal =
            WalFile::new_with_shared_coordination(io, shared, authority, ((0, 0), 0), buffer_pool);

        assert_eq!(wal.get_max_frame(), 1);
        assert_eq!(wal.get_last_checksum(), (31, 37));
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_rebuilds_from_disk_when_snapshot_is_stale() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-stale.db-wal");
        let shm_path = dir.path().join("test-stale.db-tshm");
        let io = shared_wal_test_io();
        let valid_snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        authority.install_snapshot(SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: 0,
            visibility_generation: 0,
            checkpoint_seq: valid_snapshot.checkpoint_seq,
            checkpoint_epoch: 0,
            page_size: valid_snapshot.page_size,
            salt_1: valid_snapshot.salt_1,
            salt_2: valid_snapshot.salt_2,
            checksum_1: 0,
            checksum_2: 0,
            reader_slot_count: 64,
        });

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();

        let shared = shared.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 1);
        assert_eq!(
            shared.metadata.last_checksum,
            (valid_snapshot.checksum_1, valid_snapshot.checksum_2)
        );
        assert!(shared
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
        assert_eq!(
            shared.runtime.frame_cache.lock().get(&7).cloned(),
            Some(vec![1])
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_rebuilt_authority_persists_across_exclusive_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-republish.db-wal");
        let shm_path = dir.path().join("test-republish.db-tshm");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        authority.install_snapshot(snapshot);

        let exclusive = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();
        assert!(exclusive
            .read()
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
        assert!(
            authority.iter_latest_frames(0, u64::MAX).is_empty(),
            "open_shared_from_authority_if_exists should not republish authority before coordination reconciliation"
        );

        let exclusive_coordination = ShmWalCoordination::new(exclusive, authority.clone());
        assert_eq!(authority.iter_latest_frames(0, u64::MAX), vec![(7, 1)]);
        assert_eq!(exclusive_coordination.find_frame(7, 0, 1, None), Some(1));

        drop(exclusive_coordination);
        drop(authority);

        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let reopened_shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();
        assert!(!reopened_shared
            .read()
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
        let reopened_coordination = ShmWalCoordination::new(reopened_shared, reopened_authority);
        assert_eq!(reopened_coordination.find_frame(7, 0, 1, None), Some(1));
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_exclusive_disk_scan_does_not_downgrade_newer_zero_frame_generation(
    ) {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-zero-frame-reopen.db-wal");
        let shm_path = dir.path().join("test-zero-frame-reopen.db-tshm");
        let io = shared_wal_test_io();
        let prior_generation = write_test_wal_with_single_commit_frame(&io, &wal_path);
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let restarted_generation = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: prior_generation.transaction_count,
            visibility_generation: prior_generation.visibility_generation,
            checkpoint_seq: prior_generation.checkpoint_seq.wrapping_add(1),
            checkpoint_epoch: prior_generation.checkpoint_epoch,
            page_size: prior_generation.page_size,
            salt_1: prior_generation.salt_1.wrapping_add(1),
            salt_2: prior_generation.salt_2.wrapping_add(1),
            checksum_1: prior_generation.checksum_1,
            checksum_2: prior_generation.checksum_2,
            reader_slot_count: prior_generation.reader_slot_count,
        };
        authority.install_snapshot(restarted_generation);

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();
        assert!(shared
            .read()
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));

        let coordination = ShmWalCoordination::new(shared.clone(), authority.clone());
        let reopened = coordination.load_snapshot();
        assert_eq!(reopened.max_frame, 0);
        assert_eq!(reopened.nbackfills, 0);
        assert_eq!(reopened.checkpoint_seq, restarted_generation.checkpoint_seq);
        assert_eq!(
            authority.snapshot().checkpoint_seq,
            restarted_generation.checkpoint_seq
        );
        assert!(
            !coordination.wal_is_initialized(),
            "preserving a newer zero-frame generation must require the first append to rewrite the WAL header"
        );
        assert!(
            shared.read().runtime.frame_cache.lock().is_empty(),
            "older WAL frames from a prior generation must not survive zero-frame authority recovery"
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_ignores_unpublished_backfill_proof_after_exclusive_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-unpublished-proof.db-wal");
        let shm_path = dir.path().join("test-unpublished-proof.db-tshm");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);
        {
            let authority =
                Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
            authority.install_snapshot(snapshot);
            authority.install_backfill_proof(
                SharedWalCoordinationHeader {
                    nbackfills: snapshot.max_frame,
                    ..snapshot
                },
                11,
                0xAABB_CCDD,
            );
        }
        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();

        let shared = shared.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 1);
        assert_eq!(shared.metadata.nbackfills.load(Ordering::Acquire), 0);
        assert!(shared
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_restart_checkpoint_clears_backfill_proof_and_later_replaces_it() {
        let (db, path) = get_database();
        let wal_path = path.join("test.db-wal");
        let wal_path_str = wal_path.to_str().unwrap();
        let conn = db.connect().unwrap();
        conn.wal_auto_actions_disable();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 8, 2);

        let pager = conn.pager.load();
        let partial = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Passive {
                upper_bound_inclusive: Some(1),
            },
        );
        assert!(
            partial.wal_total_backfilled > 0 && !partial.everything_backfilled(),
            "setup must create a partial checkpoint with a positive durable backfill proof"
        );

        let authority = db.shared_wal_coordination().unwrap().unwrap();
        let snapshot_before_restart = authority.snapshot();
        let (db_size_before, db_crc_before) =
            super::read_database_identity_from_file_path(&db.io, wal_path_str)
                .unwrap()
                .unwrap();
        assert!(
            authority.validate_backfill_proof(
                snapshot_before_restart,
                db_size_before,
                db_crc_before
            ),
            "setup must install a valid proof before RESTART"
        );

        let restart = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
        assert!(
            restart.everything_backfilled(),
            "RESTART should fully backfill before resetting the WAL generation"
        );

        let snapshot_after_restart = authority.snapshot();
        assert_eq!(snapshot_after_restart.max_frame, 0);
        assert_eq!(snapshot_after_restart.nbackfills, 0);
        assert!(
            !authority.validate_backfill_proof(
                snapshot_before_restart,
                db_size_before,
                db_crc_before
            ),
            "RESTART must clear the proof for the old WAL generation"
        );

        bulk_inserts(&conn, 6, 2);
        let replacement = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Passive {
                upper_bound_inclusive: Some(1),
            },
        );
        assert!(
            replacement.wal_total_backfilled > 0 && !replacement.everything_backfilled(),
            "replacement setup must create a new partial checkpoint after RESTART"
        );

        let snapshot_after_replacement = authority.snapshot();
        let (db_size_after, db_crc_after) =
            super::read_database_identity_from_file_path(&db.io, wal_path_str)
                .unwrap()
                .unwrap();
        assert!(
            authority.validate_backfill_proof(
                snapshot_after_replacement,
                db_size_after,
                db_crc_after
            ),
            "partial checkpoint after RESTART must install a replacement proof for the new generation"
        );
        assert_ne!(
            snapshot_after_replacement.checkpoint_seq, snapshot_before_restart.checkpoint_seq,
            "replacement proof must belong to the restarted WAL generation"
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_truncate_checkpoint_clears_backfill_proof_and_later_replaces_it() {
        let (db, path) = get_database();
        let wal_path = path.join("test.db-wal");
        let wal_path_str = wal_path.to_str().unwrap();
        let conn = db.connect().unwrap();
        conn.wal_auto_actions_disable();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 8, 2);

        let pager = conn.pager.load();
        let partial = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Passive {
                upper_bound_inclusive: Some(1),
            },
        );
        assert!(
            partial.wal_total_backfilled > 0 && !partial.everything_backfilled(),
            "setup must create a partial checkpoint with a positive durable backfill proof"
        );

        let authority = db.shared_wal_coordination().unwrap().unwrap();
        let snapshot_before_truncate = authority.snapshot();
        let (db_size_before, db_crc_before) =
            super::read_database_identity_from_file_path(&db.io, wal_path_str)
                .unwrap()
                .unwrap();
        assert!(
            authority.validate_backfill_proof(
                snapshot_before_truncate,
                db_size_before,
                db_crc_before
            ),
            "setup must install a valid proof before TRUNCATE"
        );

        let truncate = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Truncate {
                upper_bound_inclusive: None,
            },
        );
        assert!(
            truncate.everything_backfilled(),
            "TRUNCATE should fully backfill before truncating the WAL"
        );

        let snapshot_after_truncate = authority.snapshot();
        assert_eq!(snapshot_after_truncate.max_frame, 0);
        assert_eq!(snapshot_after_truncate.nbackfills, 0);
        assert!(
            !authority.validate_backfill_proof(
                snapshot_before_truncate,
                db_size_before,
                db_crc_before
            ),
            "TRUNCATE must clear the proof for the truncated WAL generation"
        );
        assert_eq!(
            std::fs::metadata(&wal_path).unwrap().len(),
            0,
            "TRUNCATE must leave the WAL file empty before the new generation begins"
        );

        bulk_inserts(&conn, 6, 2);
        let replacement = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Passive {
                upper_bound_inclusive: Some(1),
            },
        );
        assert!(
            replacement.wal_total_backfilled > 0 && !replacement.everything_backfilled(),
            "replacement setup must create a new partial checkpoint after TRUNCATE"
        );

        let snapshot_after_replacement = authority.snapshot();
        let (db_size_after, db_crc_after) =
            super::read_database_identity_from_file_path(&db.io, wal_path_str)
                .unwrap()
                .unwrap();
        assert!(
            authority.validate_backfill_proof(
                snapshot_after_replacement,
                db_size_after,
                db_crc_after
            ),
            "partial checkpoint after TRUNCATE must install a replacement proof for the new generation"
        );
        assert_ne!(
            snapshot_after_replacement.checkpoint_seq, snapshot_before_truncate.checkpoint_seq,
            "replacement proof must belong to the truncated WAL generation"
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_classify_authority_snapshot_marks_truncated_wal_for_rebuild() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-truncated.db-wal");
        let io = shared_wal_test_io();
        let snapshot = write_test_wal_with_single_commit_frame(&io, &wal_path);

        let wal_len = std::fs::metadata(&wal_path).unwrap().len();
        std::fs::OpenOptions::new()
            .write(true)
            .open(&wal_path)
            .unwrap()
            .set_len(wal_len - 1)
            .unwrap();

        assert_eq!(
            classify_authority_snapshot_against_wal(
                &io,
                &io.open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
                    .unwrap(),
                snapshot,
            )
            .unwrap(),
            AuthoritySnapshotValidation::RebuildFromDisk(
                AuthoritySnapshotRebuildReason::WalLengthMismatch
            )
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_classify_authority_snapshot_marks_corrupt_header_for_rebuild() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-corrupt-header.db-wal");
        let io = shared_wal_test_io();
        std::fs::write(&wal_path, [0u8; WAL_HEADER_SIZE]).unwrap();

        let snapshot = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 1,
            checkpoint_seq: 5,
            checkpoint_epoch: 7,
            page_size: 4096,
            salt_1: 17,
            salt_2: 23,
            checksum_1: 31,
            checksum_2: 37,
            reader_slot_count: 64,
        };

        assert_eq!(
            classify_authority_snapshot_against_wal(
                &io,
                &io.open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
                    .unwrap(),
                snapshot,
            )
            .unwrap(),
            AuthoritySnapshotValidation::RebuildFromDisk(
                AuthoritySnapshotRebuildReason::WalHeaderUnreadable
            )
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_open_shared_from_authority_keeps_zero_length_wal_uninitialized_after_exclusive_reopen()
    {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test-empty.db-wal");
        let shm_path = dir.path().join("test-empty.db-tshm");
        let io = shared_wal_test_io();

        io.open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        {
            let authority =
                Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
            authority.install_snapshot(SharedWalCoordinationHeader {
                max_frame: 0,
                nbackfills: 0,
                transaction_count: 9,
                visibility_generation: 1,
                checkpoint_seq: 5,
                checkpoint_epoch: 7,
                page_size: 4096,
                salt_1: 17,
                salt_2: 23,
                checksum_1: 31,
                checksum_2: 37,
                reader_slot_count: 64,
            });
        }
        let reopened_authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        assert_eq!(
            reopened_authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let shared = WalFileShared::open_shared_from_authority_if_exists(
            &io,
            wal_path.to_str().unwrap(),
            crate::OpenFlags::Create,
            &reopened_authority,
            &open_test_db_file_for_wal(&io, &wal_path),
        )
        .unwrap();

        let shared = shared.read();
        assert_eq!(shared.metadata.max_frame.load(Ordering::Acquire), 0);
        assert_eq!(shared.metadata.last_checksum, (31, 37));
        assert!(!shared.metadata.initialized.load(Ordering::Acquire));
        assert!(!shared
            .metadata
            .loaded_from_disk_scan
            .load(Ordering::Acquire));
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_secondary_disk_scan_does_not_reseed_authority_while_writer_active() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let authoritative = WalSnapshot {
            max_frame: 5,
            nbackfills: 0,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, authoritative);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
        }
        let (authority, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        coordination_a.cache_frame(7, 2);
        coordination_a.cache_frame(7, 5);
        assert!(authority.try_acquire_writer(authority.owner_record()));

        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        let stale = WalSnapshot {
            max_frame: 2,
            nbackfills: 0,
            last_checksum: (11, 13),
            checkpoint_seq: 4,
            transaction_count: 3,
        };
        set_shared_snapshot(&shared_b, stale);
        {
            let shared = shared_b.write();
            shared
                .metadata
                .loaded_from_disk_scan
                .store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = stale.last_checksum.0;
            header.checksum_2 = stale.last_checksum.1;
            shared.runtime.frame_cache.lock().insert(7, vec![2]);
        }

        let (_authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);

        assert_eq!(coordination_b.load_snapshot(), authoritative);
        assert_eq!(authority.snapshot().max_frame, authoritative.max_frame);
        assert_eq!(
            authority.snapshot().transaction_count,
            authoritative.transaction_count
        );
        assert_eq!(coordination_b.find_frame(7, 0, 5, None), Some(5));
        authority.release_writer(authority.owner_record());
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_disk_scan_matching_authority_keeps_frame_index() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let authoritative = WalSnapshot {
            max_frame: 5,
            nbackfills: 2,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, authoritative);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
        }
        let (authority, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        coordination_a.cache_frame(7, 2);
        coordination_a.cache_frame(9, 5);

        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        set_shared_snapshot(&shared_b, authoritative);
        {
            let shared = shared_b.write();
            shared
                .metadata
                .loaded_from_disk_scan
                .store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
            let mut frame_cache = shared.runtime.frame_cache.lock();
            frame_cache.insert(7, vec![2]);
            frame_cache.insert(9, vec![5]);
        }

        let (_authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);

        let reopened = coordination_b.load_snapshot();
        assert_eq!(reopened.max_frame, authoritative.max_frame);
        assert_eq!(reopened.last_checksum, authoritative.last_checksum);
        assert_eq!(reopened.checkpoint_seq, authoritative.checkpoint_seq);
        assert_eq!(reopened.transaction_count, authoritative.transaction_count);
        assert_eq!(
            reopened.nbackfills, 0,
            "disk-scan reconciliation must preserve the frame index without reviving positive nbackfills"
        );
        assert_eq!(authority.find_frame(7, 0, 5, None), Some(2));
        assert_eq!(authority.find_frame(9, 0, 5, None), Some(5));
        assert_eq!(
            authority.iter_latest_frames(0, authoritative.max_frame),
            vec![(7, 2), (9, 5)]
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_disk_scan_matching_snapshot_rebuilds_stale_frame_index() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let authoritative = WalSnapshot {
            max_frame: 5,
            nbackfills: 0,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, authoritative);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
        }
        {
            let (_authority, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
            coordination_a.cache_frame(7, 2);
            coordination_a.cache_frame(9, 4);
        }

        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        set_shared_snapshot(&shared_b, authoritative);
        {
            let shared = shared_b.write();
            shared
                .metadata
                .loaded_from_disk_scan
                .store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
            shared.runtime.frame_cache.lock().insert(7, vec![2]);
            shared.runtime.frame_cache.lock().insert(9, vec![5]);
        }

        let (authority, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);
        assert_eq!(
            authority.open_mode(),
            SharedWalCoordinationOpenMode::Exclusive
        );

        let reopened = coordination_b.load_snapshot();
        assert_eq!(reopened.max_frame, authoritative.max_frame);
        assert_eq!(reopened.last_checksum, authoritative.last_checksum);
        assert_eq!(reopened.checkpoint_seq, authoritative.checkpoint_seq);
        assert_eq!(reopened.transaction_count, authoritative.transaction_count);
        assert_eq!(authority.find_frame(7, 0, 5, None), Some(2));
        assert_eq!(
            authority.find_frame(9, 0, 5, None),
            Some(5),
            "matching snapshot metadata must not preserve a stale shared frame index across restart recovery"
        );
        assert_eq!(
            authority.iter_latest_frames(0, authoritative.max_frame),
            vec![(7, 2), (9, 5)]
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_coordination_empty_disk_scan_keeps_zero_frame_authority_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let authoritative = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 3,
            checkpoint_seq: 5,
            checkpoint_epoch: 7,
            page_size: 4096,
            salt_1: 17,
            salt_2: 23,
            checksum_1: 31,
            checksum_2: 37,
            reader_slot_count: 64,
        };
        authority.install_snapshot(authoritative);

        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        {
            let shared = shared.write();
            shared
                .metadata
                .loaded_from_disk_scan
                .store(true, Ordering::Release);
        }

        let coordination = ShmWalCoordination::new(shared, authority.clone());
        let snapshot = authority.snapshot();
        assert_eq!(snapshot, authoritative);
        let header = coordination.wal_header();
        assert_eq!(header.page_size, 4096);
        assert_eq!(header.checkpoint_seq, authoritative.checkpoint_seq);
        assert_eq!(header.salt_1, authoritative.salt_1);
        assert_eq!(header.salt_2, authoritative.salt_2);
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_coordination_empty_disk_scan_does_not_clobber_positive_authority() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let authoritative = WalSnapshot {
            max_frame: 5,
            nbackfills: 0,
            last_checksum: (31, 37),
            checkpoint_seq: 5,
            transaction_count: 9,
        };
        set_shared_snapshot(&shared_a, authoritative);
        {
            let shared = shared_a.write();
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = authoritative.last_checksum.0;
            header.checksum_2 = authoritative.last_checksum.1;
        }
        let (authority, coordination_a) = make_test_shm_coordination(&shared_a, &shm_path);
        coordination_a.cache_frame(7, 2);
        coordination_a.cache_frame(9, 5);

        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        {
            let shared = shared_b.write();
            shared
                .metadata
                .loaded_from_disk_scan
                .store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.page_size = 4096;
            header.checkpoint_seq = authoritative.checkpoint_seq;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = 11;
            header.checksum_2 = 13;
        }

        let (_authority_b, coordination_b) = make_test_shm_coordination(&shared_b, &shm_path);
        let reopened = coordination_b.load_snapshot();
        assert_eq!(reopened.max_frame, authoritative.max_frame);
        assert_eq!(reopened.checkpoint_seq, authoritative.checkpoint_seq);
        assert_eq!(reopened.transaction_count, authoritative.transaction_count);
        assert_eq!(
            authority.find_frame(7, 0, authoritative.max_frame, None),
            Some(2)
        );
        assert_eq!(
            authority.find_frame(9, 0, authoritative.max_frame, None),
            Some(5)
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_zero_frame_authority_invalidates_stale_local_initialized_state() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let authoritative = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 3,
            checkpoint_seq: 5,
            checkpoint_epoch: 7,
            page_size: 4096,
            salt_1: 17,
            salt_2: 23,
            checksum_1: 31,
            checksum_2: 37,
            reader_slot_count: 64,
        };
        authority.install_snapshot(authoritative);

        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        {
            let mut shared = shared.write();
            shared.metadata.max_frame.store(11, Ordering::Release);
            shared.metadata.nbackfills.store(11, Ordering::Release);
            shared.metadata.last_checksum = (11, 13);
            shared
                .metadata
                .transaction_count
                .store(3, Ordering::Release);
            shared.metadata.initialized.store(true, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.checkpoint_seq = 2;
            header.page_size = 4096;
            header.salt_1 = 7;
            header.salt_2 = 13;
            header.checksum_1 = 11;
            header.checksum_2 = 13;
            shared.runtime.epoch.store(1, Ordering::Release);
        }

        let coordination = ShmWalCoordination::new(shared.clone(), authority);
        assert!(
            !coordination.wal_is_initialized(),
            "a stale local initialized bit must not suppress the first header rewrite after RESTART/TRUNCATE"
        );
        {
            let shared = shared.read();
            assert!(
                !shared.metadata.initialized.load(Ordering::Acquire),
                "stale local initialized state must be cleared"
            );
            let header = shared.metadata.wal_header.lock();
            assert_eq!(header.checkpoint_seq, authoritative.checkpoint_seq);
            assert_eq!(header.page_size, authoritative.page_size);
            assert_eq!(header.salt_1, authoritative.salt_1);
            assert_eq!(header.salt_2, authoritative.salt_2);
            assert_eq!(header.checksum_1, authoritative.checksum_1);
            assert_eq!(header.checksum_2, authoritative.checksum_2);
        }

        let prepared = coordination
            .prepare_wal_header(io.as_ref(), PageSize::new(4096).unwrap())
            .expect("zero-frame authority should force a header rewrite");
        assert_eq!(prepared.checkpoint_seq, authoritative.checkpoint_seq);
        coordination.mark_initialized();
        assert!(
            coordination.wal_is_initialized(),
            "once the current-generation header is durably rewritten, wal_is_initialized should succeed"
        );
    }

    #[cfg(host_shared_wal)]
    #[test]
    fn test_shm_prepare_wal_header_seeds_uninitialized_authority_from_prepared_header() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let coordination = ShmWalCoordination::new(shared, authority.clone());

        let prepared = coordination
            .prepare_wal_header(io.as_ref(), PageSize::new(4096).unwrap())
            .expect("fresh authority should accept the first prepared header");

        let snapshot = authority.snapshot();
        assert_eq!(
            snapshot.page_size, prepared.page_size,
            "authority must publish the prepared page size for later writers and checkpointers"
        );
        assert_eq!(
            snapshot.checkpoint_seq, prepared.checkpoint_seq,
            "authority must publish the prepared checkpoint generation"
        );
        assert_eq!(snapshot.salt_1, prepared.salt_1);
        assert_eq!(snapshot.salt_2, prepared.salt_2);
    }

    #[cfg(host_shared_wal)]
    #[test]
    #[cfg_attr(
        windows,
        ignore = "Windows file locks are mandatory; opening the same WAL twice in one process clashes"
    )]
    fn test_shm_prepare_wal_header_does_not_clobber_zero_frame_authority_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.db-wal");
        let shm_path = dir.path().join("test.db-tshm");
        let io = shared_wal_test_io();

        let file_a = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_a = WalFileShared::new_shared(file_a).unwrap();
        let authoritative = SharedWalCoordinationHeader {
            max_frame: 0,
            nbackfills: 0,
            transaction_count: 9,
            visibility_generation: 3,
            checkpoint_seq: 5,
            checkpoint_epoch: 7,
            page_size: 4096,
            salt_1: 17,
            salt_2: 23,
            checksum_1: 31,
            checksum_2: 37,
            reader_slot_count: 64,
        };
        {
            let mut shared = shared_a.write();
            shared.metadata.max_frame.store(0, Ordering::Release);
            shared.metadata.nbackfills.store(0, Ordering::Release);
            shared
                .metadata
                .transaction_count
                .store(authoritative.transaction_count, Ordering::Release);
            shared.metadata.last_checksum = (31, 37);
            let mut header = shared.metadata.wal_header.lock();
            header.checkpoint_seq = authoritative.checkpoint_seq;
            header.page_size = authoritative.page_size;
            header.salt_1 = authoritative.salt_1;
            header.salt_2 = authoritative.salt_2;
            header.checksum_1 = authoritative.checksum_1;
            header.checksum_2 = authoritative.checksum_2;
            shared
                .runtime
                .epoch
                .store(authoritative.checkpoint_epoch, Ordering::Release);
            shared.metadata.initialized.store(false, Ordering::Release);
        }
        let authority =
            Arc::new(MappedSharedWalCoordination::create_or_open(&io, &shm_path, 64).unwrap());
        authority.install_snapshot(authoritative);

        let file_b = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared_b = WalFileShared::new_shared(file_b).unwrap();
        let coordination_b = ShmWalCoordination::new(shared_b.clone(), authority.clone());
        // Simulate a long-lived process whose process-wide shared WAL metadata
        // fell behind the authority after another process checkpointed and
        // restarted the WAL back to frame 0.
        {
            let mut shared = shared_b.write();
            shared.metadata.max_frame.store(0, Ordering::Release);
            shared.metadata.nbackfills.store(0, Ordering::Release);
            shared.metadata.last_checksum = (11, 13);
            shared
                .metadata
                .transaction_count
                .store(3, Ordering::Release);
            let mut header = shared.metadata.wal_header.lock();
            header.checkpoint_seq = 2;
            header.page_size = 4096;
            header.salt_1 = 17;
            header.salt_2 = 23;
            header.checksum_1 = 11;
            header.checksum_2 = 13;
            shared.runtime.epoch.store(1, Ordering::Release);
            shared.metadata.initialized.store(false, Ordering::Release);
        }

        let page_size = PageSize::new(4096).unwrap();
        let prepared = coordination_b
            .prepare_wal_header(io.as_ref(), page_size)
            .expect("prepare_wal_header should produce a header");

        let snapshot = authority.snapshot();
        assert_eq!(
            snapshot.transaction_count, authoritative.transaction_count,
            "first writer after restart must not downgrade authority transaction_count"
        );
        assert_eq!(
            snapshot.checkpoint_seq, authoritative.checkpoint_seq,
            "first writer after restart must not downgrade checkpoint metadata"
        );
        assert_eq!(
            prepared.checkpoint_seq, authoritative.checkpoint_seq,
            "header written after restart must use authority checkpoint metadata"
        );
        assert_eq!(prepared.page_size, authoritative.page_size);
        assert_eq!(prepared.salt_1, authoritative.salt_1);
        assert_eq!(prepared.salt_2, authoritative.salt_2);
        let refreshed = authority.snapshot();
        assert_eq!(
            refreshed.checksum_1, prepared.checksum_1,
            "preparing the first zero-frame header must refresh the authoritative checksum seed"
        );
        assert_eq!(
            refreshed.checksum_2, prepared.checksum_2,
            "preparing the first zero-frame header must refresh the authoritative checksum seed"
        );
    }

    #[test]
    fn test_in_process_coordination_lock_primitives() {
        let (shared, _wal) = make_test_wal();
        let coordination = make_test_coordination(&shared);

        assert!(coordination.try_checkpoint_lock());
        coordination.unlock_checkpoint_lock();

        assert!(coordination.try_write_lock());
        assert!(!coordination.try_write_lock());
        coordination.unlock_write_lock();

        assert!(coordination.try_read_mark_exclusive(1));
        coordination.set_read_mark_value_exclusive(1, 42);
        assert_eq!(coordination.read_mark_value(1), 42);
        coordination.unlock_read_mark(1);

        assert!(coordination.try_read_mark_shared(1));
        assert!(coordination.try_upgrade_read_mark(1));
        coordination.downgrade_read_mark(1);
        coordination.unlock_read_mark(1);

        // The coordination backend should still observe the shared state underneath.
        assert_eq!(shared.read().runtime.read_locks[1].get_value(), 42);
    }

    #[test]
    fn test_in_process_coordination_prepare_truncate_marks_wal_uninitialized() {
        let io = shared_wal_test_io();
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let coordination = make_test_coordination(&shared);

        shared
            .read()
            .metadata
            .initialized
            .store(true, Ordering::Release);
        let file = coordination.prepare_truncate().unwrap();

        assert!(file.size().is_ok());
        assert!(!shared.read().metadata.initialized.load(Ordering::Acquire));
    }

    #[test]
    fn test_in_process_coordination_exposes_wal_io_state() {
        let io = shared_wal_test_io();
        let dir = tempfile::tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let file = io
            .open_file(wal_path.to_str().unwrap(), crate::OpenFlags::Create, false)
            .unwrap();
        let shared = WalFileShared::new_shared(file).unwrap();
        let coordination = make_test_coordination(&shared);

        assert!(!coordination.wal_is_initialized());
        assert_eq!(coordination.wal_header().page_size, 0);
        assert!(coordination.wal_file().unwrap().size().is_ok());

        let header = coordination
            .prepare_wal_header(io.as_ref(), PageSize::new(4096).unwrap())
            .unwrap();
        assert_eq!(header.page_size, 4096);
        assert_eq!(
            coordination.load_snapshot().last_checksum,
            (header.checksum_1, header.checksum_2)
        );
        assert!(!coordination.wal_is_initialized());

        coordination.mark_initialized();
        assert!(coordination.wal_is_initialized());
        assert!(coordination
            .prepare_wal_header(io.as_ref(), PageSize::new(4096).unwrap())
            .is_none());
    }

    #[test]
    fn test_vacuum_lock_blocks_new_read_transactions_until_release() {
        let (shared, vacuum_wal) = make_test_wal();
        let reader_wal = make_test_wal_from_shared(shared);

        vacuum_wal.try_begin_vacuum_checkpoint_lock().unwrap();
        vacuum_wal.begin_vacuum_blocking_tx().unwrap();

        assert!(
            matches!(reader_wal.try_begin_read_tx(), TryBeginReadResult::Busy),
            "VACUUM lock should block new WAL readers before they take a read-mark slot"
        );
        assert!(
            !vacuum_wal.holds_read_lock(),
            "exclusive VACUUM snapshot must not masquerade as a read-mark lock"
        );
        assert!(
            vacuum_wal.holds_write_lock(),
            "begin_vacuum_blocking_tx should acquire the source write lock"
        );

        vacuum_wal.end_write_tx();
        vacuum_wal.release_vacuum_lock();
        vacuum_wal.release_vacuum_checkpoint_lock();

        assert!(
            matches!(reader_wal.try_begin_read_tx(), TryBeginReadResult::Ok(_)),
            "reader should start after VACUUM releases the lock"
        );
        reader_wal.end_read_tx();
    }

    #[test]
    fn test_active_reader_blocks_vacuum_exclusive_tx() {
        let (shared, reader_wal) = make_test_wal();
        let vacuum_wal = make_test_wal_from_shared(shared);

        assert!(matches!(
            reader_wal.try_begin_read_tx(),
            TryBeginReadResult::Ok(_)
        ));
        vacuum_wal.try_begin_vacuum_checkpoint_lock().unwrap();

        assert!(
            matches!(vacuum_wal.begin_vacuum_blocking_tx(), Err(LimboError::Busy)),
            "active reader should prevent VACUUM from acquiring its exclusive lock"
        );

        reader_wal.end_read_tx();
        vacuum_wal.begin_vacuum_blocking_tx().unwrap();
        vacuum_wal.end_write_tx();
        vacuum_wal.release_vacuum_lock();
        vacuum_wal.release_vacuum_checkpoint_lock();
    }

    #[test]
    fn test_read_retry_does_not_leak_vacuum_guard_or_block_vacuum() {
        let (shared, _) = make_test_wal();
        let retry_reader = make_test_wal_from_shared(shared.clone());
        let vacuum_wal = make_test_wal_from_shared(shared.clone());

        set_shared_snapshot(
            &shared,
            WalSnapshot {
                max_frame: 5,
                nbackfills: 0,
                last_checksum: (0, 0),
                checkpoint_seq: 0,
                transaction_count: 1,
            },
        );

        for idx in 1..5 {
            assert!(
                shared.read().runtime.read_locks[idx].write(),
                "expected setup to occupy read-mark slot {idx}"
            );
        }

        assert!(
            matches!(retry_reader.try_begin_read_tx(), TryBeginReadResult::Retry),
            "reader should retry when all read-mark slots are transiently unavailable"
        );
        assert!(
            !retry_reader.has_vacuum_read_lock_guard(),
            "retry path must not retain a shared VACUUM lock guard"
        );
        assert_eq!(
            retry_reader
                .max_frame_read_lock_index
                .load(Ordering::Acquire),
            NO_LOCK_HELD,
            "retry path must not retain a read-mark slot"
        );

        for idx in 1..5 {
            shared.read().runtime.read_locks[idx].unlock();
        }

        vacuum_wal.try_begin_vacuum_checkpoint_lock().unwrap();
        vacuum_wal.begin_vacuum_blocking_tx().unwrap();
        vacuum_wal.end_write_tx();
        vacuum_wal.release_vacuum_lock();
        vacuum_wal.release_vacuum_checkpoint_lock();
    }

    #[test]
    fn test_held_vacuum_checkpoint_locks_do_not_release_vacuum_lock() {
        let (shared, vacuum_wal) = make_test_wal();
        let contender_wal = make_test_wal_from_shared(shared);

        vacuum_wal.try_begin_vacuum_checkpoint_lock().unwrap();
        vacuum_wal.begin_vacuum_blocking_tx().unwrap();

        assert!(vacuum_wal.holds_write_lock());
        assert!(!vacuum_wal.holds_read_lock());
        assert!(
            matches!(
                contender_wal.try_begin_vacuum_checkpoint_lock(),
                Err(LimboError::Busy)
            ),
            "held checkpoint lock should block other checkpointers"
        );

        vacuum_wal.end_write_tx();
        assert!(!vacuum_wal.holds_write_lock());

        let guard =
            CheckpointLocks::from_held_vacuum_checkpoint_lock(vacuum_wal.coordination.clone())
                .unwrap();
        assert!(
            matches!(contender_wal.try_begin_read_tx(), TryBeginReadResult::Busy),
            "VACUUM lock should continue blocking readers during final checkpoint"
        );

        drop(guard);
        assert!(
            contender_wal.try_begin_vacuum_checkpoint_lock().is_ok(),
            "checkpoint cleanup should release the checkpoint lock"
        );
        contender_wal.release_vacuum_checkpoint_lock();
        assert!(
            matches!(contender_wal.try_begin_read_tx(), TryBeginReadResult::Busy),
            "checkpoint cleanup must not release the VACUUM lock"
        );

        vacuum_wal.release_vacuum_lock();
        assert!(matches!(
            contender_wal.try_begin_read_tx(),
            TryBeginReadResult::Ok(_)
        ));
        contender_wal.end_read_tx();
    }

    #[test]
    fn restart_checkpoint_reset_wal_state_handling() {
        let (db, path) = get_database();

        let walpath = {
            let mut p = path.clone().into_os_string().into_string().unwrap();
            p.push_str("/test.db-wal");
            std::path::PathBuf::from(p)
        };

        let conn = db.connect().unwrap();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 20, 3);
        let IOResult::Done(completions) = conn.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }

        // Snapshot header & counters before the RESTART checkpoint.
        let wal_shared = db.shared_wal.clone();
        let (seq_before, salt1_before, salt2_before, _ps_before) = wal_header_snapshot(&wal_shared);
        let (mx_before, backfill_before) = {
            let s = wal_shared.read();
            (
                s.metadata.max_frame.load(Ordering::SeqCst),
                s.metadata.nbackfills.load(Ordering::SeqCst),
            )
        };
        assert!(mx_before > 0);
        assert_eq!(backfill_before, 0);

        let meta_before = std::fs::metadata(&walpath).unwrap();
        #[cfg(unix)]
        let size_before = meta_before.blocks();
        #[cfg(not(unix))]
        let size_before = meta_before.len();
        // Run a RESTART checkpoint, should backfill everything and reset WAL counters,
        // but NOT truncate the file.
        {
            let pager = conn.pager.load();
            let res = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
            assert_eq!(res.wal_max_frame, mx_before);
            assert_eq!(res.wal_total_backfilled, mx_before);
            assert_eq!(res.wal_checkpoint_backfilled, mx_before);
        }

        // Validate post‑RESTART header & counters.
        let (seq_after, salt1_after, salt2_after, _ps_after) = wal_header_snapshot(&wal_shared);
        assert_eq!(
            seq_after,
            seq_before.wrapping_add(1),
            "checkpoint_seq must increment on RESTART"
        );
        assert_eq!(
            salt1_after,
            salt1_before.wrapping_add(1),
            "salt_1 is incremented"
        );
        assert_ne!(salt2_after, salt2_before, "salt_2 is randomized");

        let (mx_after, backfill_after) = {
            let s = wal_shared.read();
            (
                s.metadata.max_frame.load(Ordering::SeqCst),
                s.metadata.nbackfills.load(Ordering::SeqCst),
            )
        };
        assert_eq!(mx_after, 0, "mxFrame reset to 0 after RESTART");
        assert_eq!(backfill_after, 0, "nBackfill reset to 0 after RESTART");

        // File size should be unchanged for RESTART (no truncate).
        let meta_after = std::fs::metadata(&walpath).unwrap();
        #[cfg(unix)]
        let size_after = meta_after.blocks();
        #[cfg(not(unix))]
        let size_after = meta_after.len();
        assert_eq!(
            size_before, size_after,
            "RESTART must not change WAL file size"
        );

        // Next write should start a new sequence at frame 1.
        conn.execute("insert into test(value) values ('post_restart')")
            .unwrap();
        conn.pager
            .load()
            .wal
            .as_ref()
            .unwrap()
            .finish_append_frames_commit()
            .unwrap();
        let new_max = wal_shared.read().metadata.max_frame.load(Ordering::SeqCst);
        assert_eq!(new_max, 1, "first append after RESTART starts at frame 1");

        std::fs::remove_dir_all(path).unwrap();
    }

    #[test]
    fn test_wal_passive_partial_then_complete() {
        let (db, _tmp) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        conn1
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn1, 15, 2);
        let IOResult::Done(completions) = conn1.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }

        // Force a read transaction that will freeze a lower read mark
        let readmark = {
            let pager = conn2.pager.load();
            let wal2 = pager.wal.as_ref().unwrap();
            wal2.begin_read_tx().unwrap();
            wal2.get_max_frame()
        };

        // generate more frames that the reader will not see.
        bulk_inserts(&conn1, 15, 2);
        let IOResult::Done(completions) = conn1.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }

        // Run passive checkpoint, expect partial
        let (res1, max_before) = {
            let pager = conn1.pager.load();
            let res = run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            );
            let maxf = db
                .shared_wal
                .read()
                .metadata
                .max_frame
                .load(Ordering::SeqCst);
            (res, maxf)
        };
        assert_eq!(res1.wal_max_frame, max_before);
        assert!(
            res1.wal_total_backfilled < res1.wal_max_frame,
            "Partial backfill expected, {} : {}",
            res1.wal_total_backfilled,
            res1.wal_max_frame
        );
        assert_eq!(
            res1.wal_total_backfilled, readmark,
            "Checkpointed frames should match read mark"
        );
        // Release reader
        {
            let pager = conn2.pager.load();
            let wal2 = pager.wal.as_ref().unwrap();
            wal2.end_read_tx();
        }

        // Second passive checkpoint should finish
        let pager = conn1.pager.load();
        let res2 = run_checkpoint_until_done(
            &pager,
            CheckpointMode::Passive {
                upper_bound_inclusive: None,
            },
        );
        assert_eq!(
            res2.wal_total_backfilled, res2.wal_max_frame,
            "Second checkpoint completes remaining frames"
        );
    }

    #[test]
    fn test_wal_restart_blocks_readers() {
        let (db, _) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        // Start a read transaction
        conn2
            .pager
            .load()
            .wal
            .as_ref()
            .unwrap()
            .begin_read_tx()
            .unwrap();

        // checkpoint should succeed here because the wal is fully checkpointed (empty)
        // so the reader is using readmark0 to read directly from the db file.
        let p = conn1.pager.load();
        let w = p.wal.as_ref().unwrap();
        loop {
            match w.checkpoint(&p, CheckpointMode::Restart) {
                Ok(IOResult::IO(io)) => {
                    io.wait(db.io.as_ref()).unwrap();
                }
                e => {
                    assert!(
                        matches!(e, Err(LimboError::Busy)),
                        "reader is holding readmark0 we should return Busy"
                    );
                    break;
                }
            }
        }
        conn2.pager.load().end_read_tx();

        conn1
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        for i in 0..10 {
            conn1
                .execute(format!("insert into test(value) values ('value{i}')"))
                .unwrap();
        }
        // now that we have some frames to checkpoint, try again
        conn2.pager.load().begin_read_tx().unwrap();
        let p = conn1.pager.load();
        let w = p.wal.as_ref().unwrap();
        loop {
            match w.checkpoint(&p, CheckpointMode::Restart) {
                Ok(IOResult::IO(io)) => {
                    io.wait(db.io.as_ref()).unwrap();
                }
                Ok(IOResult::Done(_)) => {
                    panic!("Checkpoint should not have succeeded");
                }
                Err(e) => {
                    assert!(
                        matches!(e, LimboError::Busy),
                        "should return busy if we have readers"
                    );
                    break;
                }
            }
        }
    }

    #[test]
    fn test_wal_read_marks_after_restart() {
        let (db, _path) = get_database();
        let wal_shared = db.shared_wal.clone();

        let conn = db.connect().unwrap();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 10, 5);
        // Checkpoint with restart
        {
            let pager = conn.pager.load();
            let result = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
            assert!(result.everything_backfilled());
        }

        // Verify read marks after restart
        let read_marks_after: Vec<_> = {
            let s = wal_shared.read();
            (0..5)
                .map(|i| s.runtime.read_locks[i].get_value())
                .collect()
        };

        assert_eq!(read_marks_after[0], 0, "Slot 0 should remain 0");
        assert_eq!(
            read_marks_after[1], 0,
            "Slot 1 (default reader) should be reset to 0"
        );
        for (i, item) in read_marks_after.iter().take(5).skip(2).enumerate() {
            assert_eq!(
                *item, READMARK_NOT_USED,
                "Slot {i} should be READMARK_NOT_USED after restart",
            );
        }
    }

    #[test]
    fn test_wal_concurrent_readers_during_checkpoint() {
        let (db, _path) = get_database();
        let conn_writer = db.connect().unwrap();

        conn_writer
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn_writer, 5, 10);

        // Start multiple readers at different points
        let conn_r1 = db.connect().unwrap();
        let conn_r2 = db.connect().unwrap();

        // R1 starts reading
        let r1_max_frame = {
            let pager = conn_r1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_read_tx().unwrap();
            wal.get_max_frame()
        };
        bulk_inserts(&conn_writer, 5, 10);

        // R2 starts reading, sees more frames than R1
        let r2_max_frame = {
            let pager = conn_r2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_read_tx().unwrap();
            wal.get_max_frame()
        };

        // try passive checkpoint, should only checkpoint up to R1's position
        let checkpoint_result = {
            let pager = conn_writer.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            )
        };

        assert!(
            checkpoint_result.wal_total_backfilled < checkpoint_result.wal_max_frame,
            "Should not checkpoint all frames when readers are active"
        );
        assert_eq!(
            checkpoint_result.wal_total_backfilled, r1_max_frame,
            "Should have checkpointed up to R1's max frame"
        );

        // Verify R2 still sees its frames
        assert_eq!(
            conn_r2.pager.load().wal.as_ref().unwrap().get_max_frame(),
            r2_max_frame,
            "Reader should maintain its snapshot"
        );
    }

    #[test]
    fn test_wal_checkpoint_updates_read_marks() {
        let (db, _path) = get_database();
        let wal_shared = db.shared_wal.clone();

        let conn = db.connect().unwrap();
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 10, 5);

        // get max frame before checkpoint
        let max_frame_before = wal_shared.read().metadata.max_frame.load(Ordering::SeqCst);

        {
            let pager = conn.pager.load();
            let _result = run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            );
        }

        // check that read mark 1 (default reader) was updated to max_frame
        let read_mark_1 = wal_shared.read().runtime.read_locks[1].get_value();

        assert_eq!(
            read_mark_1 as u64, max_frame_before,
            "Read mark 1 should be updated to max frame during checkpoint"
        );
    }

    #[test]
    fn test_wal_writer_blocks_restart_checkpoint() {
        let (db, _path) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        conn1
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn1, 5, 5);

        // start a write transaction
        {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            let _ = wal.begin_read_tx().unwrap();
            wal.begin_write_tx(WalAutoActions::all_enabled()).unwrap();
        }

        // should fail because writer lock is held
        let result = {
            let pager = conn1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.checkpoint(&pager, CheckpointMode::Restart)
        };

        assert!(
            matches!(result, Err(LimboError::Busy)),
            "Restart checkpoint should fail when write lock is held"
        );

        conn2.pager.load().wal.as_ref().unwrap().end_read_tx();
        // release write lock
        conn2.pager.load().wal.as_ref().unwrap().end_write_tx();

        // now restart should succeed
        let result = {
            let pager = conn1.pager.load();
            run_checkpoint_until_done(&pager, CheckpointMode::Restart)
        };

        assert!(result.everything_backfilled());
    }

    #[test]
    #[should_panic(expected = "must have a read transaction to begin a write transaction")]
    fn test_wal_read_transaction_required_before_write() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();

        // Attempt to start a write transaction without a read transaction
        let pager = conn.pager.load();
        let wal = pager.wal.as_ref().unwrap();
        let _ = wal.begin_write_tx(WalAutoActions::all_enabled());
    }

    fn check_read_lock_slot(conn: &Arc<Connection>, _expected_slot: usize) -> bool {
        let pager = conn.pager.load();
        let _wal = pager.wal.as_ref().unwrap();
        #[cfg(debug_assertions)]
        {
            let wal_any = _wal.as_any();
            if let Some(wal_file) = wal_any.downcast_ref::<crate::WalFile>() {
                return wal_file.max_frame_read_lock_index.load(Ordering::Acquire)
                    == _expected_slot;
            }
        }

        false
    }

    #[test]
    fn test_wal_multiple_readers_at_different_frames() {
        let (db, _path) = get_database();
        let conn_writer = db.connect().unwrap();

        conn_writer
            .execute("CREATE TABLE test(id INTEGER PRIMARY KEY, value TEXT)")
            .unwrap();

        fn start_reader(conn: &Arc<Connection>) -> (u64, crate::Statement) {
            conn.execute("BEGIN").unwrap();
            let mut stmt = conn.prepare("SELECT * FROM test").unwrap();
            stmt.step().unwrap();
            let frame = conn.pager.load().wal.as_ref().unwrap().get_max_frame();
            (frame, stmt)
        }

        bulk_inserts(&conn_writer, 3, 5);

        let conn1 = &db.connect().unwrap();
        let (r1_frame, _stmt) = start_reader(conn1); // reader 1

        bulk_inserts(&conn_writer, 3, 5);

        let conn_r2 = db.connect().unwrap();
        let (r2_frame, _stmt2) = start_reader(&conn_r2); // reader 2

        bulk_inserts(&conn_writer, 3, 5);

        let conn_r3 = db.connect().unwrap();
        let (r3_frame, _stmt3) = start_reader(&conn_r3); // reader 3

        assert!(r1_frame < r2_frame && r2_frame < r3_frame);

        // passive checkpoint #1
        let result1 = {
            let pager = conn_writer.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            )
        };
        assert_eq!(result1.wal_total_backfilled, r1_frame);

        // finish reader‑1
        conn1.execute("COMMIT").unwrap();

        // passive checkpoint #2
        let result2 = {
            let pager = conn_writer.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            )
        };
        assert_eq!(
            result1.wal_checkpoint_backfilled + result2.wal_checkpoint_backfilled,
            r2_frame
        );

        // verify visible rows
        let r2_cnt = count_test_table(&conn_r2);
        let r3_cnt = count_test_table(&conn_r3);

        assert_eq!(r2_cnt, 30);
        assert_eq!(r3_cnt, 45);
    }

    #[test]
    fn test_checkpoint_truncate_reset_handling() {
        let (db, path) = get_database();
        let conn = db.connect().unwrap();

        let walpath = {
            let mut p = path.clone().into_os_string().into_string().unwrap();
            p.push_str("/test.db-wal");
            std::path::PathBuf::from(p)
        };

        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 10, 10);

        // Get size before checkpoint
        let size_before = std::fs::metadata(&walpath).unwrap().len();
        assert!(size_before > 0, "WAL file should have content");

        // Do a TRUNCATE checkpoint
        {
            let pager = conn.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Truncate {
                    upper_bound_inclusive: None,
                },
            );
        }

        // Check file size after truncate
        let size_after = std::fs::metadata(&walpath).unwrap().len();
        assert_eq!(size_after, 0, "WAL file should be truncated to 0 bytes");

        // Verify we can still write to the database
        conn.execute("INSERT INTO test VALUES (1001, 'after-truncate')")
            .unwrap();

        // Check WAL has new content
        let new_size = std::fs::metadata(&walpath).unwrap().len();
        assert!(new_size >= 32, "WAL file too small");
        let hdr = read_wal_header(&walpath);
        let expected_magic = if cfg!(target_endian = "big") {
            sqlite3_ondisk::WAL_MAGIC_BE
        } else {
            sqlite3_ondisk::WAL_MAGIC_LE
        };
        assert!(
            hdr.magic == expected_magic,
            "bad WAL magic: {:#X}, expected: {:#X}",
            hdr.magic,
            sqlite3_ondisk::WAL_MAGIC_BE
        );
        assert_eq!(hdr.file_format, 3007000);
        assert_eq!(hdr.page_size, 4096, "invalid page size");
        assert_eq!(hdr.checkpoint_seq, 1, "invalid checkpoint_seq");
        std::fs::remove_dir_all(path).unwrap();
    }

    #[test]
    fn test_wal_checkpoint_truncate_db_file_contains_data() {
        let (db, path) = get_database();
        let conn = db.connect().unwrap();

        let walpath = {
            let mut p = path.clone().into_os_string().into_string().unwrap();
            p.push_str("/test.db-wal");
            std::path::PathBuf::from(p)
        };

        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 10, 100);

        // Get size before checkpoint
        let size_before = std::fs::metadata(&walpath).unwrap().len();
        assert!(size_before > 0, "WAL file should have content");

        // Do a TRUNCATE checkpoint
        {
            let pager = conn.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Truncate {
                    upper_bound_inclusive: None,
                },
            );
        }

        // Check file size after truncate
        let size_after = std::fs::metadata(&walpath).unwrap().len();
        assert_eq!(size_after, 0, "WAL file should be truncated to 0 bytes");

        // Verify we can still write to the database
        conn.execute("INSERT INTO test VALUES (1001, 'after-truncate')")
            .unwrap();

        // Check WAL has new content
        let new_size = std::fs::metadata(&walpath).unwrap().len();
        assert!(new_size >= 32, "WAL file too small");
        let hdr = read_wal_header(&walpath);
        let expected_magic = if cfg!(target_endian = "big") {
            sqlite3_ondisk::WAL_MAGIC_BE
        } else {
            sqlite3_ondisk::WAL_MAGIC_LE
        };
        assert!(
            hdr.magic == expected_magic,
            "bad WAL magic: {:#X}, expected: {:#X}",
            hdr.magic,
            sqlite3_ondisk::WAL_MAGIC_BE
        );
        assert_eq!(hdr.file_format, 3007000);
        assert_eq!(hdr.page_size, 4096, "invalid page size");
        assert_eq!(hdr.checkpoint_seq, 1, "invalid checkpoint_seq");
        {
            let pager = conn.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            );
        }
        // delete the WAL file so we can read right from db and assert
        // that everything was backfilled properly
        std::fs::remove_file(&walpath).unwrap();

        let count = count_test_table(&conn);
        assert_eq!(
            count, 1001,
            "we should have 1001 rows in the table all together"
        );
        std::fs::remove_dir_all(path).unwrap();
    }

    fn read_wal_header(path: &std::path::Path) -> sqlite3_ondisk::WalHeader {
        use std::{fs::File, io::Read};
        let mut hdr = [0u8; 32];
        File::open(path).unwrap().read_exact(&mut hdr).unwrap();
        let be = |i| u32::from_be_bytes(hdr[i..i + 4].try_into().unwrap());
        sqlite3_ondisk::WalHeader {
            magic: be(0x00),
            file_format: be(0x04),
            page_size: be(0x08),
            checkpoint_seq: be(0x0C),
            salt_1: be(0x10),
            salt_2: be(0x14),
            checksum_1: be(0x18),
            checksum_2: be(0x1C),
        }
    }

    #[test]
    fn test_wal_stale_snapshot_in_write_transaction() {
        let (db, _path) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        conn1
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        // Start a read transaction on conn2
        {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_read_tx().unwrap();
        }
        // Make changes using conn1
        bulk_inserts(&conn1, 5, 5);
        // Try to start a write transaction on conn2 with a stale snapshot
        let result = {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_write_tx(WalAutoActions::all_enabled())
        };
        // Should get BusySnapShot due to stale snapshot
        assert!(matches!(result, Err(LimboError::BusySnapshot)));

        // End read transaction and start a fresh one
        {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.end_read_tx();
            wal.begin_read_tx().unwrap();
        }
        // Now write transaction should work
        let result = {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_write_tx(WalAutoActions::all_enabled())
        };
        assert!(matches!(result, Ok(())));
    }

    #[test]
    fn test_wal_readlock0_optimization_behavior() {
        let (db, _path) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        conn1
            .execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn1, 5, 5);
        // Do a full checkpoint to move all data to DB file
        {
            let pager = conn1.pager.load();
            run_checkpoint_until_done(
                &pager,
                CheckpointMode::Passive {
                    upper_bound_inclusive: None,
                },
            );
        }

        // Start a read transaction on conn2
        {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_read_tx().unwrap();
        }
        // should use slot 0, as everything is backfilled
        assert!(check_read_lock_slot(&conn2, 0));
        {
            let pager = conn1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            let frame = wal.find_frame(5, None);
            // since we hold readlock0, we should ignore the db file and find_frame should return none
            assert!(frame.is_ok_and(|f| f.is_none()));
        }
        // Try checkpoint, should fail because reader has slot 0
        {
            let pager = conn1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            let result = wal.checkpoint(&pager, CheckpointMode::Restart);

            assert!(
                matches!(result, Err(LimboError::Busy)),
                "RESTART checkpoint should fail when a reader is using slot 0"
            );
        }
        // End the read transaction
        {
            let pager = conn2.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.end_read_tx();
        }
        {
            let pager = conn1.pager.load();
            let result = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
            assert!(
                result.everything_backfilled(),
                "RESTART checkpoint should succeed after reader releases slot 0"
            );
        }
    }

    #[test]
    fn test_wal_full_backfills_all() {
        let (db, _tmp) = get_database();
        let conn = db.connect().unwrap();

        // Write some data to put frames in the WAL
        conn.execute("create table test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 8, 4);

        // Ensure frames are flushed to the WAL
        let IOResult::Done(completions) = conn.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }

        // Snapshot the current mxFrame before running FULL
        let wal_shared = db.shared_wal.clone();
        let mx_before = wal_shared.read().metadata.max_frame.load(Ordering::SeqCst);
        assert!(mx_before > 0, "expected frames in WAL before FULL");

        // Run FULL checkpoint - must backfill *all* frames up to mx_before
        let result = {
            let pager = conn.pager.load();
            run_checkpoint_until_done(&pager, CheckpointMode::Full)
        };

        assert_eq!(result.wal_checkpoint_backfilled, mx_before);
        assert_eq!(result.wal_total_backfilled, mx_before);
    }

    #[test]
    fn test_wal_full_waits_for_old_reader_then_succeeds() {
        let (db, _tmp) = get_database();
        let writer = db.connect().unwrap();
        let reader = db.connect().unwrap();

        writer
            .execute("create table test(id integer primary key, value text)")
            .unwrap();

        // First commit some data and flush (reader will snapshot here)
        bulk_inserts(&writer, 2, 3);
        let IOResult::Done(completions) = writer.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }

        // Start a read transaction pinned at the current snapshot
        {
            let pager = reader.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.begin_read_tx().unwrap();
        }
        let r_snapshot = {
            let pager = reader.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.get_max_frame()
        };

        // Advance WAL beyond the reader's snapshot
        bulk_inserts(&writer, 3, 4);
        let IOResult::Done(completions) = writer.pager.load().cacheflush().unwrap() else {
            panic!()
        };
        for c in completions {
            db.io.wait_for_completion(c).unwrap();
        }
        let mx_now = db
            .shared_wal
            .read()
            .metadata
            .max_frame
            .load(Ordering::SeqCst);
        assert!(mx_now > r_snapshot);

        // FULL must return Busy while a reader is stuck behind
        {
            let pager = writer.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            loop {
                match wal.checkpoint(&pager, CheckpointMode::Full) {
                    Ok(IOResult::IO(io)) => {
                        // Drive any pending IO (should quickly become Busy or Done)
                        io.wait(db.io.as_ref()).unwrap();
                    }
                    Err(LimboError::Busy) => {
                        break;
                    }
                    other => panic!("expected Busy from FULL with old reader, got {other:?}"),
                }
            }
        }
        assert_eq!(
            db.shared_wal
                .read()
                .metadata
                .nbackfills
                .load(Ordering::SeqCst),
            0,
            "a FULL checkpoint that returns Busy must not publish positive nbackfills before DB sync"
        );

        // Release the reader, now full mode should succeed and backfill everything
        {
            let pager = reader.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            wal.end_read_tx();
        }

        let result = {
            let pager = writer.pager.load();
            run_checkpoint_until_done(&pager, CheckpointMode::Full)
        };

        assert_eq!(
            result.wal_checkpoint_backfilled, mx_now,
            "the successful FULL reruns from the last durable backfill point because the Busy attempt did not publish progress"
        );
        assert!(result.everything_backfilled());
    }

    #[test]
    fn test_rollback_releases_read_lock() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("CREATE TABLE t(x)").unwrap();
        conn.execute("BEGIN").unwrap();
        conn.execute("INSERT INTO t VALUES(1)").unwrap();

        {
            let pager = conn.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            assert!(
                wal.holds_read_lock(),
                "read lock must be held during write tx"
            );
        }

        conn.execute("ROLLBACK").unwrap();

        {
            let pager = conn.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            assert!(
                !wal.holds_read_lock(),
                "read lock must be released after ROLLBACK"
            );
        }
    }

    #[test]
    fn test_rollback_releases_shared_read_lock_slot() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("CREATE TABLE t(x)").unwrap();
        conn.execute("BEGIN").unwrap();
        conn.execute("INSERT INTO t VALUES(1)").unwrap();

        let locked_slots_before = {
            let shared = db.shared_wal.read();
            read_slots_with_readers(&shared)
        };
        assert_eq!(
            locked_slots_before.len(),
            1,
            "expected exactly one shared read-lock slot while transaction is active"
        );

        conn.execute("ROLLBACK").unwrap();

        let locked_slots_after = {
            let shared = db.shared_wal.read();
            read_slots_with_readers(&shared)
        };
        assert!(
            locked_slots_after.is_empty(),
            "ROLLBACK must release the shared read-lock slot"
        );
    }

    #[test]
    fn test_rollback_releases_slot_zero_read_lock() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("CREATE TABLE test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 3, 3);
        {
            let pager = conn.pager.load();
            let result = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
            assert!(
                result.everything_backfilled(),
                "restart checkpoint setup must fully backfill WAL"
            );
        }

        conn.execute("BEGIN").unwrap();
        conn.execute("INSERT INTO test(value) VALUES('slot0')")
            .unwrap();

        let locked_slots_before = {
            let shared = db.shared_wal.read();
            read_slots_with_readers(&shared)
        };
        assert_eq!(
            locked_slots_before,
            vec![0],
            "writer should use slot 0 when WAL is fully checkpointed"
        );

        conn.execute("ROLLBACK").unwrap();

        let locked_slots_after = {
            let shared = db.shared_wal.read();
            read_slots_with_readers(&shared)
        };
        assert!(
            locked_slots_after.is_empty(),
            "ROLLBACK must release slot 0 shared read-lock as well"
        );
    }

    #[test]
    fn test_savepoint_rollback_preserves_read_lock() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("CREATE TABLE t(x INTEGER PRIMARY KEY)")
            .unwrap();
        conn.execute("BEGIN").unwrap();
        conn.execute("INSERT INTO t VALUES(1)").unwrap();

        // Trigger a statement failure that causes savepoint rollback.
        // A duplicate primary key on the second INSERT will fail the
        // statement, rolling back to the anonymous savepoint while
        // keeping the write transaction open.
        let res = conn.execute("INSERT INTO t VALUES(1)");
        assert!(res.is_err(), "duplicate PK insert must fail");

        {
            let pager = conn.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            assert!(
                wal.holds_read_lock(),
                "read lock must still be held after savepoint rollback"
            );
            assert!(
                wal.holds_write_lock(),
                "write lock must still be held after savepoint rollback"
            );
        }

        // The transaction should still be usable: commit succeeds and
        // the first insert is preserved.
        conn.execute("COMMIT").unwrap();

        let mut stmt = conn.prepare("SELECT count(*) FROM t").unwrap();
        let mut count: i64 = 0;
        stmt.run_with_row_callback(|row| {
            count = row.get(0).unwrap();
            Ok(())
        })
        .unwrap();
        assert_eq!(count, 1, "first insert should survive savepoint rollback");
    }

    #[test]
    fn test_savepoint_then_tx_rollback_allows_restart_checkpoint_from_other_connection() {
        let (db, _path) = get_database();
        let conn1 = db.connect().unwrap();
        let conn2 = db.connect().unwrap();

        conn1
            .execute("CREATE TABLE test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn1, 2, 2);
        let count_before = count_test_table(&conn1);

        conn1.execute("BEGIN").unwrap();
        conn1
            .execute("INSERT INTO test(id, value) VALUES(1000, 'first')")
            .unwrap();
        let duplicate = conn1.execute("INSERT INTO test(id, value) VALUES(1000, 'dup')");
        assert!(duplicate.is_err(), "duplicate PK insert must fail");

        {
            let pager = conn1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            assert!(
                wal.holds_read_lock(),
                "read lock must still be held after savepoint rollback"
            );
            assert!(
                wal.holds_write_lock(),
                "write lock must still be held after savepoint rollback"
            );
        }

        conn1.execute("ROLLBACK").unwrap();

        {
            let pager = conn1.pager.load();
            let wal = pager.wal.as_ref().unwrap();
            assert!(
                !wal.holds_read_lock(),
                "read lock must be released after transaction rollback"
            );
            assert!(
                !wal.holds_write_lock(),
                "write lock must be released after transaction rollback"
            );
        }

        let locked_slots_after_rollback = {
            let shared = db.shared_wal.read();
            read_slots_with_readers(&shared)
        };
        assert!(
            locked_slots_after_rollback.is_empty(),
            "transaction rollback after savepoint failure must not leak shared read locks"
        );
        assert_eq!(
            count_test_table(&conn1),
            count_before,
            "transaction rollback should remove writes made before savepoint failure"
        );

        let result = {
            let pager = conn2.pager.load();
            run_checkpoint_until_done(&pager, CheckpointMode::Restart)
        };
        assert!(
            result.everything_backfilled(),
            "restart checkpoint from another connection must succeed after full rollback"
        );
    }

    #[test]
    fn test_checkpoint_succeeds_after_rollback() {
        let (db, _path) = get_database();
        let conn = db.connect().unwrap();

        conn.execute("CREATE TABLE test(id integer primary key, value text)")
            .unwrap();
        bulk_inserts(&conn, 5, 3);

        conn.execute("BEGIN").unwrap();
        conn.execute("INSERT INTO test(value) VALUES('rollback_me')")
            .unwrap();
        conn.execute("ROLLBACK").unwrap();

        let pager = conn.pager.load();
        let result = run_checkpoint_until_done(&pager, CheckpointMode::Restart);
        assert!(
            result.everything_backfilled(),
            "checkpoint must succeed after rollback, not return Busy"
        );
    }
}