stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Durability / Fault Injection Tests
//!
//! These tests write valid data, close the database, corrupt WAL/checkpoint
//! files in specific ways, then reopen and verify recovery consistency.
//!
//! Recovery invariants verified in every test:
//! 1. No partial transactions — all-or-nothing per transaction
//! 2. Consistent recovery — recovered data is a valid subset of committed data
//! 3. Database is usable — can INSERT after recovery
//! 4. Tables exist — DDL survived or was re-applied from WAL/volumes

use std::fs;
use std::path::{Path, PathBuf};
use stoolap::Database;
use tempfile::{tempdir, TempDir};

// ============================================================================
// WAL binary format constants (must match wal_manager.rs)
// ============================================================================

const WAL_ENTRY_MAGIC: u32 = 0x454C4157;
const WAL_HEADER_SIZE: usize = 32;
const CRC_SIZE: usize = 4;

// Flag bits
const COMPRESSED_FLAG: u8 = 0x01;
const COMMIT_MARKER_FLAG: u8 = 0x02;

// Checkpoint constants
const _CHECKPOINT_MAGIC: u32 = 0x43504F49;

// ============================================================================
// Helper structs
// ============================================================================

/// Information about a single WAL entry's byte boundaries in the file
#[derive(Debug, Clone)]
struct WalEntryInfo {
    /// Byte offset of this entry's start (magic bytes)
    offset: usize,
    /// Total size on disk: header + data + CRC
    total_size: usize,
    /// Log Sequence Number
    _lsn: u64,
    /// Flags byte
    flags: u8,
    /// Size of data portion (from header)
    entry_size: usize,
    /// Byte offset where data portion starts (after header)
    data_offset: usize,
    /// Byte offset of the CRC32 (last 4 bytes of entry)
    crc_offset: usize,
}

struct TestFixture {
    _dir: TempDir,
    db_path: PathBuf,
    dsn: String,
}

// ============================================================================
// Helper functions
// ============================================================================

/// Find all WAL files in the database's wal/ directory
fn find_wal_files(db_path: &Path) -> Vec<PathBuf> {
    let wal_dir = db_path.join("wal");
    if !wal_dir.exists() {
        return Vec::new();
    }
    let mut files: Vec<PathBuf> = fs::read_dir(&wal_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            (name.starts_with("wal-") || name.starts_with("wal_")) && name.ends_with(".log")
        })
        .map(|e| e.path())
        .collect();
    files.sort();
    files
}

/// Find checkpoint.meta file
fn find_checkpoint_file(db_path: &Path) -> Option<PathBuf> {
    let path = db_path.join("wal").join("checkpoint.meta");
    if path.exists() {
        Some(path)
    } else {
        None
    }
}

/// Parse WAL binary data to locate all entry boundaries
fn find_entry_boundaries(data: &[u8]) -> Vec<WalEntryInfo> {
    let mut entries = Vec::new();
    let mut pos = 0;

    while pos + WAL_HEADER_SIZE <= data.len() {
        // Check magic
        if pos + 4 > data.len() {
            break;
        }
        let magic = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
        if magic != WAL_ENTRY_MAGIC {
            pos += 1;
            continue;
        }

        // Parse header fields
        let flags = data[pos + 5];
        let header_size = u16::from_le_bytes(data[pos + 6..pos + 8].try_into().unwrap()) as usize;
        let lsn = u64::from_le_bytes(data[pos + 8..pos + 16].try_into().unwrap());
        let entry_size = u32::from_le_bytes(data[pos + 24..pos + 28].try_into().unwrap()) as usize;

        // Sanity check
        if entry_size > 64 * 1024 * 1024 || header_size < WAL_HEADER_SIZE {
            pos += 1;
            continue;
        }

        let data_offset = pos + header_size;
        let total_data_with_crc = entry_size + CRC_SIZE;
        let total_size = header_size + total_data_with_crc;

        if pos + total_size > data.len() {
            // Entry extends beyond file — incomplete
            break;
        }

        let crc_offset = data_offset + entry_size;

        entries.push(WalEntryInfo {
            offset: pos,
            total_size,
            _lsn: lsn,
            flags,
            entry_size,
            data_offset,
            crc_offset,
        });

        pos += total_size;
    }

    entries
}

/// Zero out a range of bytes in a buffer
fn zero_range(data: &mut [u8], offset: usize, len: usize) {
    let end = (offset + len).min(data.len());
    for byte in &mut data[offset..end] {
        *byte = 0;
    }
}

/// Flip a single bit at the given byte offset and bit position
fn flip_bit(data: &mut [u8], byte_offset: usize, bit_pos: u8) {
    if byte_offset < data.len() {
        data[byte_offset] ^= 1 << bit_pos;
    }
}

/// Zero a 4KB-aligned page
fn zero_page(data: &mut [u8], page_num: usize) {
    let page_size = 4096;
    let start = page_num * page_size;
    let end = (start + page_size).min(data.len());
    if start < data.len() {
        for byte in &mut data[start..end] {
            *byte = 0;
        }
    }
}

/// Remove the lock file so we can reopen the database
fn remove_lock_file(db_path: &Path) {
    let lock_file = db_path.join("db.lock");
    let _ = fs::remove_file(lock_file);
}

/// Create a database with known data, then close it.
/// Each transaction is auto-committed (one INSERT per execute call).
fn setup_test_db(num_txns: usize, rows_per_txn: usize) -> TestFixture {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();

        let mut id = 1;
        for txn in 0..num_txns {
            for row in 0..rows_per_txn {
                db.execute(
                    &format!(
                        "INSERT INTO test_data (id, value, seq) VALUES ({}, 'txn{}_row{}', {})",
                        id, txn, row, txn
                    ),
                    (),
                )
                .unwrap();
                id += 1;
            }
        }

        // Verify all data is in
        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(count, (num_txns * rows_per_txn) as i64);
    }

    // Database is now closed — WAL has been flushed
    remove_lock_file(&db_path);

    TestFixture {
        _dir: dir,
        db_path,
        dsn,
    }
}

/// Create a database with large TEXT values (> 64 bytes) to trigger LZ4 compression
fn setup_test_db_large_rows(num_txns: usize, rows_per_txn: usize) -> TestFixture {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();

        // Generate a large string (> 64 bytes to trigger compression)
        let large_prefix = "A".repeat(200);

        let mut id = 1;
        for txn in 0..num_txns {
            for row in 0..rows_per_txn {
                db.execute(
                    &format!(
                        "INSERT INTO test_data (id, value, seq) VALUES ({}, '{}_txn{}_row{}', {})",
                        id, large_prefix, txn, row, txn
                    ),
                    (),
                )
                .unwrap();
                id += 1;
            }
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(count, (num_txns * rows_per_txn) as i64);
    }

    remove_lock_file(&db_path);

    TestFixture {
        _dir: dir,
        db_path,
        dsn,
    }
}

/// Open the database after corruption and verify that at least min_rows recovered.
/// Also verifies the database is usable (can INSERT new data).
/// If the table doesn't exist (DDL was also corrupted), that's treated as 0 rows.
fn verify_recovery_at_least(fixture: &TestFixture, table: &str, min_rows: i64) {
    let db = Database::open(&fixture.dsn).unwrap();

    let result: Result<i64, _> = db.query_one(&format!("SELECT COUNT(*) FROM {}", table), ());
    match result {
        Ok(count) => {
            assert!(
                count >= min_rows,
                "Expected at least {} rows, got {} after recovery",
                min_rows,
                count
            );

            // Verify DB is usable — can insert new data
            let new_id = count + 10000;
            db.execute(
                &format!(
                    "INSERT INTO {} (id, value, seq) VALUES ({}, 'post_recovery', 999)",
                    table, new_id
                ),
                (),
            )
            .unwrap();

            let new_count: i64 = db
                .query_one(&format!("SELECT COUNT(*) FROM {}", table), ())
                .unwrap();
            assert_eq!(new_count, count + 1);
        }
        Err(_) => {
            // Table doesn't exist — DDL was corrupted too.
            // This is valid when min_rows == 0.
            assert_eq!(
                min_rows, 0,
                "Table '{}' doesn't exist after recovery, but expected at least {} rows",
                table, min_rows
            );
        }
    }
}

/// Open the database after corruption and verify exact row count.
/// Also verifies the database is usable.
fn verify_recovery_exact(fixture: &TestFixture, table: &str, exact_rows: i64) {
    let db = Database::open(&fixture.dsn).unwrap();

    let count: i64 = db
        .query_one(&format!("SELECT COUNT(*) FROM {}", table), ())
        .unwrap();
    assert_eq!(
        count, exact_rows,
        "Expected exactly {} rows, got {} after recovery",
        exact_rows, count
    );

    // Verify DB is usable
    let new_id = exact_rows + 10000;
    db.execute(
        &format!(
            "INSERT INTO {} (id, value, seq) VALUES ({}, 'post_recovery', 999)",
            table, new_id
        ),
        (),
    )
    .unwrap();
}

// ============================================================================
// 1. TORN WRITES — Truncate WAL at various offsets within the last entry
// ============================================================================

/// Helper: Setup 5 auto-committed transactions (3 rows each = 15 rows),
/// then truncate the WAL so the last entry is incomplete at `cut_into_last`.
/// `cut_into_last` is the number of bytes to keep from the last entry.
fn torn_write_test(cut_into_last: usize) {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty(), "No WAL files found");

    // Read WAL data
    let wal_path = &wal_files[wal_files.len() - 1]; // Use last WAL file
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(
        entries.len() >= 2,
        "Need at least 2 entries, found {}",
        entries.len()
    );

    let last = &entries[entries.len() - 1];
    let truncate_at = last.offset + cut_into_last;

    // Truncate the file
    let truncated = &data[..truncate_at.min(data.len())];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);

    // Recovery should restore all complete entries (prior entries intact)
    // We don't know the exact count because DDL and commit markers are also entries,
    // but we should have at least some data rows
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_torn_write_partial_header_1_byte() {
    torn_write_test(1);
}

#[test]
fn test_torn_write_partial_header_16_bytes() {
    torn_write_test(16);
}

#[test]
fn test_torn_write_partial_header_31_bytes() {
    torn_write_test(31);
}

#[test]
fn test_torn_write_after_header_no_data() {
    torn_write_test(WAL_HEADER_SIZE);
}

#[test]
fn test_torn_write_partial_data() {
    // Truncate halfway through the data portion of last entry
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2);

    let last = &entries[entries.len() - 1];
    let half_data = last.entry_size / 2;
    let truncate_at = last.data_offset + half_data;
    let truncated = &data[..truncate_at.min(data.len())];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_torn_write_after_data_no_crc() {
    // Keep full header + full data, but no CRC bytes
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2);

    let last = &entries[entries.len() - 1];
    let truncate_at = last.crc_offset; // Right before CRC
    let truncated = &data[..truncate_at.min(data.len())];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_torn_write_partial_crc_1_byte() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2);

    let last = &entries[entries.len() - 1];
    let truncate_at = last.crc_offset + 1; // Only 1 of 4 CRC bytes
    let truncated = &data[..truncate_at.min(data.len())];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_torn_write_partial_crc_3_bytes() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2);

    let last = &entries[entries.len() - 1];
    let truncate_at = last.crc_offset + 3; // 3 of 4 CRC bytes
    let truncated = &data[..truncate_at.min(data.len())];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 2. SECTOR-ALIGNED PAGE LOSS — Zero 4KB pages
// ============================================================================

#[test]
fn test_sector_loss_first_page() {
    // Write enough data to span multiple 4KB pages
    let fixture = setup_test_db(20, 5);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();

    // Only corrupt if the file is large enough
    if data.len() > 4096 {
        zero_page(&mut data, 0);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    // scan_for_magic should recover entries beyond page 0
    // We might get 0 rows if DDL was on page 0, or partial recovery
    let db = Database::open(&fixture.dsn).unwrap();
    // Just verify it opens and is usable (table may or may not exist)
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM test_data", ());
    if let Ok(count) = result {
        // If table exists, verify DB is usable
        let new_id = count + 10000;
        db.execute(
            &format!(
                "INSERT INTO test_data (id, value, seq) VALUES ({}, 'post_recovery', 999)",
                new_id
            ),
            (),
        )
        .unwrap();
    }
    // If table doesn't exist, that's also valid — DDL was on the zeroed page
}

#[test]
fn test_sector_loss_middle_page() {
    let fixture = setup_test_db(20, 5);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let num_pages = data.len() / 4096;

    if num_pages >= 3 {
        let middle = num_pages / 2;
        zero_page(&mut data, middle);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    // Entries on intact pages should be recovered
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_sector_loss_last_page() {
    let fixture = setup_test_db(20, 5);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let num_pages = data.len() / 4096;

    if num_pages >= 2 {
        let last = num_pages - 1;
        zero_page(&mut data, last);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_sector_loss_alternating_pages() {
    let fixture = setup_test_db(20, 5);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let num_pages = data.len() / 4096;

    // Zero every other page (starting from page 1 to preserve DDL on page 0)
    for page in (1..num_pages).step_by(2) {
        zero_page(&mut data, page);
    }
    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 3. BIT CORRUPTION — Single-bit flips in specific fields
// ============================================================================

#[test]
fn test_bit_flip_magic_bytes() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Flip a bit in a middle entry's magic bytes
    if entries.len() >= 3 {
        let target = &entries[entries.len() / 2];
        flip_bit(&mut data, target.offset, 0); // Flip bit 0 of first magic byte
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // scan_for_magic skips the corrupted entry, recovers the rest
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_bit_flip_crc() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Flip a bit in a middle entry's CRC
    if entries.len() >= 3 {
        let target = &entries[entries.len() / 2];
        flip_bit(&mut data, target.crc_offset, 3); // Flip bit 3 of CRC
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_bit_flip_data_portion() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Flip a bit in the data portion of a middle entry
    if entries.len() >= 3 {
        let target = &entries[entries.len() / 2];
        let data_mid = target.data_offset + target.entry_size / 2;
        flip_bit(&mut data, data_mid, 5);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // CRC mismatch -> entry skipped
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_bit_flip_entry_size() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Flip a high bit in entry_size field of a middle entry
    // This causes wrong size reading, cascading to magic scan recovery
    if entries.len() >= 3 {
        let target = &entries[entries.len() / 2];
        // entry_size is at offset +24 (4 bytes, little-endian)
        flip_bit(&mut data, target.offset + 24, 7); // Flip bit 7 -> adds 128 to low byte
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_bit_flip_flags_compressed() {
    // Create DB with small rows (uncompressed entries)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Set the COMPRESSED flag on an uncompressed entry
    if entries.len() >= 3 {
        let target = &entries[entries.len() / 2];
        // flags byte is at offset + 5
        data[target.offset + 5] |= COMPRESSED_FLAG;
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // LZ4 decompress fails on non-LZ4 data -> entry skipped
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 4. CHECKPOINT CORRUPTION
// ============================================================================

#[test]
fn test_checkpoint_corrupt_magic() {
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        let mut data = fs::read(&cp_path).unwrap();
        if data.len() >= 4 {
            zero_range(&mut data, 0, 4); // Zero magic bytes
            fs::write(&cp_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);
    // Falls back to WAL file scan, full recovery
    verify_recovery_exact(&fixture, "test_data", 15);
}

#[test]
fn test_checkpoint_corrupt_crc() {
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        let mut data = fs::read(&cp_path).unwrap();
        if data.len() >= 4 {
            let crc_offset = data.len() - 4;
            flip_bit(&mut data, crc_offset, 0); // Flip bit in CRC
            fs::write(&cp_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_exact(&fixture, "test_data", 15);
}

#[test]
fn test_checkpoint_truncated() {
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        let data = fs::read(&cp_path).unwrap();
        if data.len() > 10 {
            fs::write(&cp_path, &data[..10]).unwrap(); // Truncate to 10 bytes
        }
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_exact(&fixture, "test_data", 15);
}

#[test]
fn test_checkpoint_zeroed() {
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        let data = fs::read(&cp_path).unwrap();
        let zeroed = vec![0u8; data.len()];
        fs::write(&cp_path, &zeroed).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_exact(&fixture, "test_data", 15);
}

#[test]
fn test_checkpoint_deleted() {
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        fs::remove_file(&cp_path).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // No checkpoint, scans WAL dir from LSN 0, full recovery
    verify_recovery_exact(&fixture, "test_data", 15);
}

// ============================================================================
// 5. MULTI-ENTRY CORRUPTION
// ============================================================================

/// Find entries that are DML data entries (not DDL, not commit/abort markers)
fn find_dml_data_entries(entries: &[WalEntryInfo]) -> Vec<usize> {
    entries
        .iter()
        .enumerate()
        .filter(|(_, e)| {
            // Not a commit or abort marker
            (e.flags & COMMIT_MARKER_FLAG) == 0 && (e.flags & 0x04) == 0
        })
        .map(|(i, _)| i)
        .collect()
}

/// Find entries that are commit markers
fn find_commit_entries(entries: &[WalEntryInfo]) -> Vec<usize> {
    entries
        .iter()
        .enumerate()
        .filter(|(_, e)| (e.flags & COMMIT_MARKER_FLAG) != 0)
        .map(|(i, _)| i)
        .collect()
}

#[test]
fn test_first_data_entry_corrupt() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);

    // Corrupt the first DML entry's magic
    if !dml_entries.is_empty() {
        let idx = dml_entries[0];
        let target = &entries[idx];
        zero_range(&mut data, target.offset, 4); // Zero magic
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // DDL (CREATE TABLE) must survive; first DML skipped, rest may recover
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_last_entry_corrupt() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(!entries.is_empty());

    // Truncate the last entry (most common crash scenario)
    let last = &entries[entries.len() - 1];
    let truncated = &data[..last.offset];
    fs::write(wal_path, truncated).unwrap();

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_middle_entry_corrupt() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Zero the magic of a middle entry
    if entries.len() >= 3 {
        let mid_idx = entries.len() / 2;
        let target = &entries[mid_idx];
        zero_range(&mut data, target.offset, 4);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // scan_for_magic skips it, entries before/after recovered
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_commit_marker_destroyed() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let commit_entries = find_commit_entries(&entries);

    // Zero the last commit marker -> that transaction becomes "in-doubt" -> aborted
    if !commit_entries.is_empty() {
        let last_commit_idx = commit_entries[commit_entries.len() - 1];
        let target = &entries[last_commit_idx];
        zero_range(&mut data, target.offset, target.total_size);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // The transaction whose commit marker was destroyed should be treated as aborted
    // Other transactions should be fine
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_data_entries_destroyed_commit_intact() {
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);

    // Zero all DML entries for the last batch while keeping commit markers
    // (Zero magic of the last few DML entries)
    if dml_entries.len() >= 3 {
        // Zero last 3 DML entries
        for &idx in &dml_entries[dml_entries.len() - 3..] {
            let target = &entries[idx];
            zero_range(&mut data, target.offset, 4); // Zero magic
        }
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Commit marker found but data entries gone -> those rows won't be recovered
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 6. WAL TRUNCATION CRASH RECOVERY
// ============================================================================

#[test]
fn test_truncation_crash_bak_exists() {
    // Simulate: WAL was backed up to .bak, then original .log was deleted
    // but new .log was never created -> crash
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[0];
    let bak_path = wal_path.with_extension("log.bak");

    // Rename .log to .log.bak (simulate incomplete truncation)
    fs::rename(wal_path, &bak_path).unwrap();

    // Verify: no .log files, only .bak
    let remaining_wals = find_wal_files(&fixture.db_path);
    assert!(
        remaining_wals.is_empty() || !remaining_wals.contains(wal_path),
        "Original WAL file should be gone"
    );

    remove_lock_file(&fixture.db_path);

    // recover_interrupted_truncation should restore .bak -> .log
    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
    assert!(
        count > 0,
        "Should recover data from .bak file, got {} rows",
        count
    );

    // Verify usable
    db.execute(
        &format!(
            "INSERT INTO test_data (id, value, seq) VALUES ({}, 'post_recovery', 999)",
            count + 10000
        ),
        (),
    )
    .unwrap();
}

#[test]
fn test_truncation_crash_temp_and_bak() {
    // Both wal-temp-*.log and .log.bak exist
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_dir = fixture.db_path.join("wal");

    // Create a temp file (simulates incomplete truncation)
    let temp_path = wal_dir.join("wal-temp-20250101120000.log");
    fs::write(&temp_path, b"temporary data").unwrap();

    // Create a .bak file from the real WAL
    let wal_path = &wal_files[0];
    let bak_path = wal_path.with_extension("log.bak");
    fs::copy(wal_path, &bak_path).unwrap();

    remove_lock_file(&fixture.db_path);

    // Temp file should be cleaned up, .bak should be handled
    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
    assert_eq!(count, 15);

    // Verify temp file was cleaned up
    assert!(!temp_path.exists(), "Temp file should have been cleaned up");
}

#[test]
fn test_truncation_crash_temp_only() {
    // Only wal-temp-*.log exists alongside valid .log
    let fixture = setup_test_db(5, 3);

    let wal_dir = fixture.db_path.join("wal");
    let temp_path = wal_dir.join("wal-temp-20250101120000.log");
    fs::write(&temp_path, b"temporary data").unwrap();

    remove_lock_file(&fixture.db_path);

    // Normal recovery, temp file cleaned up
    verify_recovery_exact(&fixture, "test_data", 15);

    // Verify temp file was cleaned up
    assert!(!temp_path.exists(), "Temp file should have been cleaned up");
}

// ============================================================================
// 7. LSN CHAIN INTEGRITY
// ============================================================================

#[test]
fn test_lsn_gap_in_sequence() {
    // Remove one complete entry from the middle (splice bytes out)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 5 {
        let remove_idx = entries.len() / 2;
        let target = &entries[remove_idx];
        let before = &data[..target.offset];
        let after = &data[target.offset + target.total_size..];

        let mut spliced = Vec::with_capacity(before.len() + after.len());
        spliced.extend_from_slice(before);
        spliced.extend_from_slice(after);
        fs::write(wal_path, &spliced).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Remaining entries have valid magic/CRC, should be recovered normally
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_duplicate_entry_in_wal() {
    // Duplicate one entry (append a copy)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 3 {
        let dup_idx = entries.len() / 2;
        let target = &entries[dup_idx];
        let entry_bytes = &data[target.offset..target.offset + target.total_size];

        let mut new_data = data.clone();
        new_data.extend_from_slice(entry_bytes);
        fs::write(wal_path, &new_data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Duplicate entry may cause PK conflict but recovery should still succeed
    // (either ignoring the duplicate or handling the error gracefully)
    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
    assert!(count >= 0, "Recovery should produce a consistent state");
}

#[test]
fn test_recovery_without_checkpoint() {
    // Delete checkpoint.meta entirely, keep WAL
    let fixture = setup_test_db(5, 3);

    if let Some(cp_path) = find_checkpoint_file(&fixture.db_path) {
        fs::remove_file(&cp_path).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // from_lsn=0, all entries replayed from WAL scan
    verify_recovery_exact(&fixture, "test_data", 15);
}

// ============================================================================
// 8. COMPRESSION-RELATED CORRUPTION
// ============================================================================

#[test]
fn test_corrupt_compressed_payload() {
    // Use large rows to trigger LZ4 compression
    let fixture = setup_test_db_large_rows(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Find a compressed entry
    let compressed: Vec<usize> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| (e.flags & COMPRESSED_FLAG) != 0)
        .map(|(i, _)| i)
        .collect();

    if !compressed.is_empty() {
        let target_idx = compressed[compressed.len() / 2];
        let target = &entries[target_idx];

        // Flip bytes in the compressed payload, then recompute CRC
        let data_mid = target.data_offset + target.entry_size / 2;
        if data_mid < data.len() {
            data[data_mid] ^= 0xFF;
            data[data_mid.saturating_sub(1)] ^= 0xAA;

            // Recompute CRC over the data portion
            let data_start = target.data_offset;
            let data_end = target.crc_offset;
            let new_crc = crc32fast::hash(&data[data_start..data_end]);
            data[target.crc_offset..target.crc_offset + 4].copy_from_slice(&new_crc.to_le_bytes());

            fs::write(wal_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);
    // Valid CRC but LZ4 decompress fails -> entry skipped
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_force_compressed_flag_on_uncompressed() {
    // Small rows -> uncompressed entries. Set COMPRESSED flag.
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Find an uncompressed DML entry
    let uncompressed: Vec<usize> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| (e.flags & COMPRESSED_FLAG) == 0 && (e.flags & COMMIT_MARKER_FLAG) == 0)
        .map(|(i, _)| i)
        .collect();

    if uncompressed.len() >= 2 {
        let target_idx = uncompressed[uncompressed.len() / 2];
        let target = &entries[target_idx];
        // Set COMPRESSED flag (flags byte is at offset + 5)
        data[target.offset + 5] |= COMPRESSED_FLAG;
        // Note: We do NOT update CRC — flags are in the header, not in CRC-covered data portion
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // LZ4 decompress fails on non-LZ4 data -> entry skipped
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_clear_compressed_flag_on_compressed() {
    // Large rows -> compressed entries. Clear COMPRESSED flag.
    let fixture = setup_test_db_large_rows(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Find a compressed entry
    let compressed: Vec<usize> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| (e.flags & COMPRESSED_FLAG) != 0)
        .map(|(i, _)| i)
        .collect();

    if !compressed.is_empty() {
        let target_idx = compressed[compressed.len() / 2];
        let target = &entries[target_idx];
        // Clear COMPRESSED flag
        data[target.offset + 5] &= !COMPRESSED_FLAG;
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Raw compressed bytes interpreted as row data -> deserialization fails -> entry skipped
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 9. COMBINED STRESS TESTS
// ============================================================================

#[test]
fn test_combined_torn_write_plus_bit_flip() {
    let fixture = setup_test_db(10, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Bit flip in a middle entry
    if entries.len() >= 5 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        flip_bit(&mut data, target.data_offset + 5, 2);
    }

    // Truncate the last entry
    if entries.len() >= 2 {
        let last = &entries[entries.len() - 1];
        let truncate_at = last.offset + WAL_HEADER_SIZE / 2;
        data.truncate(truncate_at);
    }

    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);
    // Both failures handled, partial recovery
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_many_transactions_last_commit_corrupt() {
    let fixture = setup_test_db(20, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let commit_entries = find_commit_entries(&entries);

    // Corrupt the last commit marker
    if !commit_entries.is_empty() {
        let last_commit_idx = commit_entries[commit_entries.len() - 1];
        let target = &entries[last_commit_idx];
        zero_range(&mut data, target.offset, target.total_size);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // 19 transactions should be recovered, last one treated as uncommitted
    // Each transaction has 3 rows, so at least 19*3 - some potential loss = many rows
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_recovery_then_new_data_then_recovery() {
    // Phase 1: Create DB with data, corrupt, recover
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();

        let mut id = 1;
        for txn in 0..5 {
            for row in 0..3 {
                db.execute(
                    &format!(
                        "INSERT INTO test_data (id, value, seq) VALUES ({}, 'txn{}_row{}', {})",
                        id, txn, row, txn
                    ),
                    (),
                )
                .unwrap();
                id += 1;
            }
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(count, 15);
    }

    remove_lock_file(&db_path);

    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());

    // Corrupt: truncate last entry
    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    if entries.len() >= 2 {
        let last = &entries[entries.len() - 1];
        let truncated = &data[..last.offset + 10]; // 10 bytes into last entry
        fs::write(wal_path, truncated).unwrap();
    }

    remove_lock_file(&db_path);

    // Phase 2: Recover and insert new data
    let initial_count;
    {
        let db = Database::open(&dsn).unwrap();
        let count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        initial_count = count;

        // Insert more data after recovery
        for i in 0..5 {
            db.execute(
                &format!(
                    "INSERT INTO test_data (id, value, seq) VALUES ({}, 'new_data_{}', 100)",
                    10000 + i,
                    i
                ),
                (),
            )
            .unwrap();
        }

        let after_insert: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        assert_eq!(after_insert, initial_count + 5);
    }

    remove_lock_file(&db_path);

    // Phase 3: Reopen again — post-recovery data should persist
    {
        let db = Database::open(&dsn).unwrap();
        let final_count: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        // The 5 new inserts should definitely persist. The initial_count rows
        // may vary slightly across recoveries due to WAL truncation effects,
        // but we should have at least the new inserts.
        assert!(
            final_count >= initial_count,
            "Post-recovery count ({}) should be at least initial count ({})",
            final_count,
            initial_count
        );

        // Verify still usable
        db.execute(
            "INSERT INTO test_data (id, value, seq) VALUES (99999, 'final_test', 200)",
            (),
        )
        .unwrap();
    }
}

#[test]
fn test_complete_wal_destruction_with_checkpoint() {
    // Create DB, checkpoint to volumes, add more data, then zero entire WAL
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    // Phase 1: Create table and insert initial data
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE test_data (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO test_data (id, value, seq) VALUES ({}, 'checkpoint_data_{}', 1)",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Force a checkpoint to seal data into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data after checkpoint
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO test_data (id, value, seq) VALUES ({}, 'post_checkpoint_{}', 2)",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Phase 2: Zero entire WAL (but volume files should be intact)
    let wal_files = find_wal_files(&db_path);
    for wal_path in &wal_files {
        let data = fs::read(wal_path).unwrap();
        let zeroed = vec![0u8; data.len()];
        fs::write(wal_path, &zeroed).unwrap();
    }

    // Phase 3: Try to recover
    let db = Database::open(&dsn).unwrap();

    // The volume data should survive, post-checkpoint WAL data may be lost
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM test_data", ());
    match result {
        Ok(count) => {
            // If table exists, volume data should be intact
            // Post-checkpoint data depends on whether WAL was needed
            assert!(count >= 0, "Should have consistent state after recovery");
        }
        Err(_) => {
            // If both WAL and volumes are damaged, table may not exist
            // This is still a valid recovery outcome (no data)
        }
    }
}

// ============================================================================
// Additional edge case tests
// ============================================================================

#[test]
fn test_empty_wal_file() {
    // Create an empty WAL file (0 bytes)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    // Replace the WAL file with an empty file
    let wal_path = &wal_files[wal_files.len() - 1];
    fs::write(wal_path, []).unwrap();

    remove_lock_file(&fixture.db_path);

    // Recovery should handle empty file gracefully
    let db = Database::open(&fixture.dsn).unwrap();
    // Table might not exist if DDL was in the zeroed WAL
    let _result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM test_data", ());
}

#[test]
fn test_wal_file_with_only_header_garbage() {
    // WAL file contains exactly 32 bytes of garbage
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let garbage = vec![0xDE; 32];
    fs::write(wal_path, &garbage).unwrap();

    remove_lock_file(&fixture.db_path);

    // Should handle garbage gracefully
    let db = Database::open(&fixture.dsn).unwrap();
    let _result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM test_data", ());
}

#[test]
fn test_wal_magic_at_very_end_of_file() {
    // WAL file with valid data but magic bytes at the very end (incomplete entry)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(!entries.is_empty());

    // Truncate to end of second-to-last entry, then append just magic bytes
    if entries.len() >= 2 {
        let second_to_last = &entries[entries.len() - 2];
        let end_of_stl = second_to_last.offset + second_to_last.total_size;
        data.truncate(end_of_stl);
        // Append just the magic bytes (incomplete header)
        data.extend_from_slice(&WAL_ENTRY_MAGIC.to_le_bytes());
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_multiple_wal_files_one_corrupt() {
    // Create enough data to potentially generate multiple WAL files
    // Even if only one WAL file, we simulate by splitting
    let fixture = setup_test_db(20, 5);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    // Corrupt the first WAL file if there are multiple
    if wal_files.len() >= 2 {
        let mut data = fs::read(&wal_files[0]).unwrap();
        // Zero the first 100 bytes
        zero_range(&mut data, 0, 100);
        fs::write(&wal_files[0], &data).unwrap();
    } else {
        // Only one WAL file — corrupt the first page but leave the rest
        let mut data = fs::read(&wal_files[0]).unwrap();
        if data.len() > 4096 {
            // Corrupt middle portion, leave start and end intact
            let mid = data.len() / 2;
            zero_range(&mut data, mid, 100);
            fs::write(&wal_files[0], &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_all_commit_markers_destroyed() {
    // Zero every commit marker in the WAL — all transactions should be aborted
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let commit_entries = find_commit_entries(&entries);

    // Zero all commit markers (but not DDL commit markers)
    for &idx in &commit_entries {
        let target = &entries[idx];
        zero_range(&mut data, target.offset, target.total_size);
    }
    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);

    // Without commit markers, all DML transactions are treated as aborted.
    // DDL (CREATE TABLE) uses DDL_TXN_ID which may or may not have a commit marker.
    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM test_data", ());
    match result {
        Ok(count) => {
            // Table exists but data transactions were aborted
            assert!(count >= 0, "Count should be non-negative");
        }
        Err(_) => {
            // Table doesn't exist is also valid if DDL was also treated as aborted
        }
    }
}

#[test]
fn test_repeated_recovery_idempotent() {
    // Corrupt WAL, recover multiple times — should always get same result
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Corrupt a middle entry
    if entries.len() >= 3 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        flip_bit(&mut data, target.crc_offset, 0);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    // Recovery #1
    let count1;
    {
        let db = Database::open(&fixture.dsn).unwrap();
        let c: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        count1 = c;
    }

    remove_lock_file(&fixture.db_path);

    // Recovery #2
    {
        let db = Database::open(&fixture.dsn).unwrap();
        let count2: i64 = db.query_one("SELECT COUNT(*) FROM test_data", ()).unwrap();
        // Second recovery should produce same or more rows (since first recovery
        // may have written new WAL entries that are now also recovered)
        assert!(
            count2 >= count1,
            "Second recovery ({}) should have at least as many rows as first ({})",
            count2,
            count1
        );
    }
}

#[test]
fn test_concurrent_corruption_patterns() {
    // Apply multiple corruption patterns simultaneously
    let fixture = setup_test_db(10, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 8 {
        // Corruption 1: Flip bit in entry 2's CRC
        let target1 = &entries[2];
        flip_bit(&mut data, target1.crc_offset, 4);

        // Corruption 2: Zero magic of entry 4
        let target2 = entries[4].clone();
        zero_range(&mut data, target2.offset, 4);

        // Corruption 3: Flip compressed flag on entry 6
        let target3 = &entries[6];
        data[target3.offset + 5] |= COMPRESSED_FLAG;
    }

    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);
    // Multiple corruptions handled, some entries skipped, partial recovery
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_wal_with_garbage_appended() {
    // Append random garbage after valid WAL data
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();

    // Append 1KB of non-magic garbage
    let garbage: Vec<u8> = (0..1024).map(|i| ((i * 7 + 13) % 256) as u8).collect();
    data.extend_from_slice(&garbage);
    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);
    // All valid entries should be recovered, garbage at end ignored
    verify_recovery_exact(&fixture, "test_data", 15);
}

#[test]
fn test_wal_entry_size_zero() {
    // Set entry_size to 0 for a middle entry
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 3 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        // Set entry_size (bytes 24-27) to 0
        data[target.offset + 24] = 0;
        data[target.offset + 25] = 0;
        data[target.offset + 26] = 0;
        data[target.offset + 27] = 0;
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Size 0 means 0 data bytes + 4 CRC bytes = 4 bytes total.
    // CRC will mismatch, entry skipped, scan_for_magic finds next entry.
    verify_recovery_at_least(&fixture, "test_data", 0);
}

#[test]
fn test_wal_entry_size_very_large() {
    // Set entry_size to a very large value (> 64MB limit)
    let fixture = setup_test_db(5, 3);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 3 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        // Set entry_size to 0x10000000 (256MB) — exceeds 64MB sanity check
        data[target.offset + 24] = 0;
        data[target.offset + 25] = 0;
        data[target.offset + 26] = 0;
        data[target.offset + 27] = 0x10;
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);
    // Sanity check triggers scan_for_magic, skips corrupted entry
    verify_recovery_at_least(&fixture, "test_data", 0);
}

// ============================================================================
// 10. MULTI-TABLE RECOVERY
// ============================================================================

/// Setup a database with multiple tables
fn setup_multi_table_db() -> TestFixture {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, amount FLOAT)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price FLOAT)",
            (),
        )
        .unwrap();

        // Populate users
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO users (id, name, email) VALUES ({}, 'user{}', 'user{}@test.com')",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }

        // Populate orders
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO orders (id, user_id, amount) VALUES ({}, {}, {})",
                    i,
                    (i % 10) + 1,
                    i as f64 * 9.99
                ),
                (),
            )
            .unwrap();
        }

        // Populate products
        for i in 1..=15 {
            db.execute(
                &format!(
                    "INSERT INTO products (id, name, price) VALUES ({}, 'product{}', {})",
                    i,
                    i,
                    i as f64 * 5.50
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);
    TestFixture {
        _dir: dir,
        db_path,
        dsn,
    }
}

#[test]
fn test_multi_table_corrupt_middle_entry() {
    // Corrupt a middle entry — only one table's data may be affected
    let fixture = setup_multi_table_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 5 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        flip_bit(&mut data, target.crc_offset, 0);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // All three tables should exist
    let users: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
    let orders: i64 = db.query_one("SELECT COUNT(*) FROM orders", ()).unwrap();
    let products: i64 = db.query_one("SELECT COUNT(*) FROM products", ()).unwrap();

    // At least some data in each table (the corrupted entry only affects one row)
    let total = users + orders + products;
    assert!(
        total >= 40,
        "Expected at least 40 total rows across tables, got {} (users={}, orders={}, products={})",
        total,
        users,
        orders,
        products
    );

    // All tables should be usable
    db.execute(
        "INSERT INTO users (id, name, email) VALUES (999, 'new_user', 'new@test.com')",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO orders (id, user_id, amount) VALUES (999, 1, 100.0)",
        (),
    )
    .unwrap();
    db.execute(
        "INSERT INTO products (id, name, price) VALUES (999, 'new_product', 50.0)",
        (),
    )
    .unwrap();
}

#[test]
fn test_multi_table_one_tables_commit_destroyed() {
    // Destroy a commit marker — the transaction's data for ALL tables in that txn is lost
    let fixture = setup_multi_table_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let commit_entries = find_commit_entries(&entries);

    // Destroy a middle commit marker
    if commit_entries.len() >= 3 {
        let mid_commit = commit_entries[commit_entries.len() / 2];
        let target = &entries[mid_commit];
        zero_range(&mut data, target.offset, target.total_size);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // All three tables should exist (DDL is separate from DML commits)
    let users: i64 = db.query_one("SELECT COUNT(*) FROM users", ()).unwrap();
    let orders: i64 = db.query_one("SELECT COUNT(*) FROM orders", ()).unwrap();
    let products: i64 = db.query_one("SELECT COUNT(*) FROM products", ()).unwrap();

    // Should lose exactly one transaction's worth of data
    let total = users + orders + products;
    assert!(
        total >= 30,
        "Expected at least 30 total rows, got {} (users={}, orders={}, products={})",
        total,
        users,
        orders,
        products
    );
}

#[test]
fn test_multi_table_first_page_zeroed() {
    // Zero page 0 — DDL for some tables may be lost
    let fixture = setup_multi_table_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();

    if data.len() > 4096 {
        zero_page(&mut data, 0);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    // Some tables may not exist, but the DB should still open
    let db = Database::open(&fixture.dsn).unwrap();

    // Check which tables survived
    let mut surviving_tables = 0;
    for table in &["users", "orders", "products"] {
        let result: Result<i64, _> = db.query_one(&format!("SELECT COUNT(*) FROM {}", table), ());
        if result.is_ok() {
            surviving_tables += 1;
        }
    }

    // At least the DB opened successfully — table survival depends on entry order
    assert!(surviving_tables >= 0); // Always true, but documents the invariant
}

#[test]
fn test_multi_table_cross_table_join_after_recovery() {
    // After partial corruption, verify cross-table joins still work
    let fixture = setup_multi_table_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    // Truncate last entry (mild corruption)
    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    if entries.len() >= 2 {
        let last = &entries[entries.len() - 1];
        let truncated = &data[..last.offset];
        fs::write(wal_path, truncated).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // Execute a cross-table join — this exercises the full query engine post-recovery
    let result = db.query(
        "SELECT u.name, o.amount FROM users u JOIN orders o ON u.id = o.user_id ORDER BY o.id LIMIT 5",
        (),
    );

    match result {
        Ok(rows) => {
            // Consume the iterator — verifies join execution doesn't panic
            let collected: Vec<_> = rows.filter_map(|r| r.ok()).collect();
            // Count may be 0 or more depending on what survived
            assert!(collected.len() <= 100, "Sanity check: not too many rows");
        }
        Err(_) => {
            // If a table was lost, join might fail — that's acceptable
        }
    }
}

// ============================================================================
// 11. INDEX RECOVERY
// ============================================================================

/// Setup a database with indexes
fn setup_indexed_db() -> TestFixture {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE indexed_data (id INTEGER PRIMARY KEY, category TEXT NOT NULL, value FLOAT, active BOOLEAN)",
            (),
        )
        .unwrap();

        // Create indexes of different types
        db.execute("CREATE INDEX idx_value ON indexed_data(value)", ())
            .unwrap();
        db.execute("CREATE INDEX idx_category ON indexed_data(category)", ())
            .unwrap();

        // Insert data
        for i in 1..=50 {
            let category = format!("cat{}", i % 5);
            let active = i % 2 == 0;
            db.execute(
                &format!(
                    "INSERT INTO indexed_data (id, category, value, active) VALUES ({}, '{}', {}, {})",
                    i, category, i as f64 * 1.5, active
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);
    TestFixture {
        _dir: dir,
        db_path,
        dsn,
    }
}

#[test]
fn test_index_recovery_after_torn_write() {
    let fixture = setup_indexed_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    // Truncate last entry
    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    if entries.len() >= 2 {
        let last = &entries[entries.len() - 1];
        let truncated = &data[..last.offset];
        fs::write(wal_path, truncated).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // Index-accelerated queries should work after recovery
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data WHERE value > 50.0", ())
        .unwrap();
    assert!(count >= 0, "Index query should work");

    let count2: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM indexed_data WHERE category = 'cat1'",
            (),
        )
        .unwrap();
    assert!(count2 >= 0, "Hash index query should work");
}

#[test]
fn test_index_recovery_after_bit_corruption() {
    let fixture = setup_indexed_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Flip bit in a middle entry's data
    if entries.len() >= 5 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        flip_bit(&mut data, target.data_offset + 10, 3);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // Verify indexed queries produce consistent results
    let total: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data", ())
        .unwrap();
    let indexed: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data WHERE value > 0.0", ())
        .unwrap();

    // Index count should match or be less than total (never more)
    assert!(
        indexed <= total,
        "Index query ({}) should never return more rows than total ({})",
        indexed,
        total
    );
}

#[test]
fn test_index_consistency_after_corruption() {
    // Verify that index results match full scan results after corruption
    let fixture = setup_indexed_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    // Corrupt a middle entry
    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 3 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        zero_range(&mut data, target.offset, 4); // Zero magic
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // Compare index-scanned results vs full-scan results
    // Both should return the same data
    let total: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data", ())
        .unwrap();

    // Category index query
    let cat_total: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM indexed_data WHERE category IN ('cat0', 'cat1', 'cat2', 'cat3', 'cat4')",
            (),
        )
        .unwrap();

    assert_eq!(
        total, cat_total,
        "Index scan over all categories ({}) should match full scan ({})",
        cat_total, total
    );

    // Verify insertions work with indexes
    db.execute(
        "INSERT INTO indexed_data (id, category, value, active) VALUES (999, 'cat_new', 999.0, true)",
        (),
    )
    .unwrap();

    let after: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data", ())
        .unwrap();
    assert_eq!(after, total + 1);
}

#[test]
fn test_index_ddl_corrupt_but_data_intact() {
    // Corrupt the CREATE INDEX WAL entry, but keep data intact
    // Index should not exist, but data queries should still work (full scan)
    let fixture = setup_indexed_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);

    // The CREATE INDEX entries are DDL (non-commit, non-DML data entries)
    // They appear early in the WAL. Corrupt entries 1 and 2 (likely DDL for indexes)
    // We'll corrupt entries right after the CREATE TABLE entries
    if dml_entries.len() >= 2 && entries.len() > dml_entries[0] {
        // Find entries that are NOT DML data and NOT commit markers (likely DDL)
        let ddl_like: Vec<usize> = entries
            .iter()
            .enumerate()
            .filter(|(i, e)| {
                (e.flags & COMMIT_MARKER_FLAG) == 0
                    && (e.flags & 0x04) == 0
                    && !dml_entries.contains(i)
            })
            .map(|(i, _)| i)
            .collect();

        // Corrupt a few DDL-like entries (skip entry 0 which is CREATE TABLE)
        for &idx in ddl_like.iter().skip(1).take(2) {
            let target = &entries[idx];
            flip_bit(&mut data, target.crc_offset, 5);
        }
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();

    // Table should exist and data should be queryable (even without indexes)
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data", ())
        .unwrap();
    assert!(count >= 0, "Data should be accessible even without indexes");

    // Queries that would normally use indexes should fall back to full scan
    let result: i64 = db
        .query_one("SELECT COUNT(*) FROM indexed_data WHERE value > 50.0", ())
        .unwrap();
    assert!(result >= 0);
}

#[test]
fn test_multi_column_index_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount FLOAT)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE INDEX idx_cust_date ON orders(customer_id, order_date)",
            (),
        )
        .unwrap();

        for i in 1..=30 {
            db.execute(
                &format!(
                    "INSERT INTO orders (id, customer_id, order_date, amount) VALUES ({}, {}, '2024-01-{:02}', {})",
                    i, i % 5, (i % 28) + 1, i as f64 * 10.0
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt a middle entry
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());
    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() >= 3 {
        let mid = entries.len() / 2;
        let target = &entries[mid];
        flip_bit(&mut data, target.data_offset + 5, 1);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&db_path);

    let fixture = TestFixture {
        _dir: dir,
        db_path,
        dsn,
    };

    let db = Database::open(&fixture.dsn).unwrap();

    // Multi-column index query
    let count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM orders WHERE customer_id = 1 AND order_date = '2024-01-01'",
            (),
        )
        .unwrap();
    assert!(count >= 0);

    // Verify insertions work
    db.execute(
        "INSERT INTO orders (id, customer_id, order_date, amount) VALUES (999, 1, '2024-12-25', 500.0)",
        (),
    )
    .unwrap();
}

// ============================================================================
// 12. MULTI-STATEMENT TRANSACTION CORRUPTION
// ============================================================================

/// Setup a database using explicit BEGIN/COMMIT transactions
fn setup_explicit_txn_db() -> TestFixture {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE txn_data (id INTEGER PRIMARY KEY, value TEXT NOT NULL, batch INTEGER)",
            (),
        )
        .unwrap();

        // 5 explicit transactions, each inserting 4 rows
        for batch in 0..5 {
            db.execute("BEGIN", ()).unwrap();
            for row in 0..4 {
                let id = batch * 4 + row + 1;
                db.execute(
                    &format!(
                        "INSERT INTO txn_data (id, value, batch) VALUES ({}, 'batch{}_row{}', {})",
                        id, batch, row, batch
                    ),
                    (),
                )
                .unwrap();
            }
            db.execute("COMMIT", ()).unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_data", ()).unwrap();
        assert_eq!(count, 20);
    }

    remove_lock_file(&db_path);
    TestFixture {
        _dir: dir,
        db_path,
        dsn,
    }
}

#[test]
fn test_explicit_txn_one_insert_corrupt() {
    // Corrupt one INSERT entry within a committed multi-statement transaction
    let fixture = setup_explicit_txn_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);

    // Corrupt one DML entry from a middle batch
    if dml_entries.len() >= 10 {
        let target_idx = dml_entries[dml_entries.len() / 2];
        let target = &entries[target_idx];
        flip_bit(&mut data, target.data_offset + 8, 4); // Corrupt data portion
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_data", ()).unwrap();

    // One entry corrupted — that row is lost but the rest should survive
    // The transaction's commit marker is intact, so other rows in the txn are applied
    assert!(
        count >= 15,
        "Expected at least 15 rows (lost at most a few from corruption), got {}",
        count
    );

    // DB is usable
    db.execute(
        "INSERT INTO txn_data (id, value, batch) VALUES (999, 'post_recovery', 99)",
        (),
    )
    .unwrap();
}

#[test]
fn test_explicit_txn_commit_marker_corrupt() {
    // Destroy one transaction's commit marker — all 4 rows from that txn should be lost
    let fixture = setup_explicit_txn_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let commit_entries = find_commit_entries(&entries);

    // Destroy the 3rd commit marker (middle batch)
    if commit_entries.len() >= 5 {
        let target_idx = commit_entries[2]; // 3rd transaction's commit
        let target = &entries[target_idx];
        zero_range(&mut data, target.offset, target.total_size);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_data", ()).unwrap();

    // Lost one transaction (4 rows), rest should survive
    // Could be fewer if DDL commit was also corrupted
    assert!(
        count >= 12,
        "Expected at least 12 rows (lost 1 txn of 4 rows + possible side effects), got {}",
        count
    );

    // Verify batch consistency: each surviving batch should have all 4 rows or 0
    for batch in 0..5 {
        let batch_count: i64 = db
            .query_one(
                &format!("SELECT COUNT(*) FROM txn_data WHERE batch = {}", batch),
                (),
            )
            .unwrap();
        assert!(
            batch_count == 0 || batch_count == 4,
            "Batch {} has {} rows — expected 0 (aborted) or 4 (committed)",
            batch,
            batch_count
        );
    }
}

#[test]
fn test_explicit_txn_all_inserts_in_one_txn_corrupt() {
    // Corrupt all INSERT entries within one transaction, but keep commit marker
    let fixture = setup_explicit_txn_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);
    let commit_entries = find_commit_entries(&entries);

    // Each batch: 4 DML entries + 1 commit marker
    // Corrupt all 4 DML entries of batch 2 (entries at dml indices 8-11 approximately)
    if dml_entries.len() >= 12 && commit_entries.len() >= 3 {
        // Corrupt DML entries 8, 9, 10, 11 (batch 2)
        for &idx in &dml_entries[8..12] {
            let target = &entries[idx];
            zero_range(&mut data, target.offset, 4); // Zero magic
        }
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_data", ()).unwrap();

    // Batch 2's data is corrupted — commit marker exists but data is gone
    // Other 4 batches should be intact: 4 * 4 = 16 rows
    assert!(
        count >= 12,
        "Expected at least 12 rows (4 batches intact minus possible losses), got {}",
        count
    );
}

#[test]
fn test_explicit_txn_interleaved_corruption() {
    // Corrupt entries from different transactions
    let fixture = setup_explicit_txn_db();
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    let dml_entries = find_dml_data_entries(&entries);

    // Corrupt one entry from batch 1 and one from batch 3
    if dml_entries.len() >= 16 {
        // Batch 1 entry (index 4-7), corrupt index 5
        let target = &entries[dml_entries[5]];
        flip_bit(&mut data, target.crc_offset, 2);

        // Batch 3 entry (index 12-15), corrupt index 13
        let target2 = entries[dml_entries[13]].clone();
        flip_bit(&mut data, target2.crc_offset, 6);

        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM txn_data", ()).unwrap();

    // Lost 2 individual rows from 2 different transactions
    assert!(
        count >= 16,
        "Expected at least 16 rows (lost 2 individual rows), got {}",
        count
    );
}

// ============================================================================
// 13. VOLUME FILE CORRUPTION
// ============================================================================
//
// These tests verify recovery when cold storage (.vol files) and manifests
// are corrupted. The volume system seals hot buffer rows into immutable
// .vol files via PRAGMA CHECKPOINT. Recovery loads manifests + volumes
// first, then replays WAL from checkpoint_lsn.

/// Find volume files (.vol) for a given table
fn find_volume_files(db_path: &Path, table: &str) -> Vec<PathBuf> {
    let vol_dir = db_path.join("volumes").join(table);
    if !vol_dir.exists() {
        return Vec::new();
    }
    let mut files: Vec<PathBuf> = fs::read_dir(&vol_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            name.starts_with("vol_") && name.ends_with(".vol")
        })
        .map(|e| e.path())
        .collect();
    files.sort();
    files
}

/// Find manifest.bin for a given table
fn find_manifest_file(db_path: &Path, table: &str) -> Option<PathBuf> {
    let path = db_path.join("volumes").join(table).join("manifest.bin");
    if path.exists() {
        Some(path)
    } else {
        None
    }
}

/// Setup a database, checkpoint to seal data into volumes, then add more data in WAL
fn setup_db_with_volumes() -> (TestFixture, i64) {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    let pre_checkpoint_count;

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE vol_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL, phase INTEGER)",
            (),
        )
        .unwrap();

        // Phase 1: Data that will be sealed into a volume
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO vol_test (id, value, phase) VALUES ({}, 'sealed_{}', 1)",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        pre_checkpoint_count = 20;

        // Checkpoint: seal hot rows into .vol files, truncate WAL
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: Post-checkpoint data (in WAL only)
        for i in 21..=40 {
            db.execute(
                &format!(
                    "INSERT INTO vol_test (id, value, phase) VALUES ({}, 'wal_only_{}', 2)",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);
    (
        TestFixture {
            _dir: dir,
            db_path,
            dsn,
        },
        pre_checkpoint_count,
    )
}

#[test]
fn test_volume_corrupt_with_valid_wal() {
    // Corrupt .vol file magic bytes. Recovery should skip the corrupt volume
    // and recover what it can from WAL.
    let (fixture, _) = setup_db_with_volumes();

    let vol_files = find_volume_files(&fixture.db_path, "vol_test");
    for vol_path in &vol_files {
        let mut data = fs::read(vol_path).unwrap();
        if data.len() > 10 {
            // Corrupt the magic bytes (first 4 bytes: "STVL")
            zero_range(&mut data, 0, 4);
            fs::write(vol_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM vol_test", ());

    match result {
        Ok(count) => {
            // Volume data may be lost but WAL data (phase 2) should survive
            assert!(
                count >= 0,
                "Should have non-negative row count, got {}",
                count
            );
            // DB should be usable
            db.execute(
                "INSERT INTO vol_test (id, value, phase) VALUES (999, 'post_recovery', 3)",
                (),
            )
            .unwrap();
        }
        Err(_) => {
            // If DDL was also lost (in truncated WAL), table may not exist
        }
    }
}

#[test]
fn test_volume_deleted_with_valid_wal() {
    // Delete all .vol files but keep manifest and WAL.
    // Recovery should detect missing volumes and fall back to WAL replay.
    let (fixture, _) = setup_db_with_volumes();

    let vol_files = find_volume_files(&fixture.db_path, "vol_test");
    assert!(
        !vol_files.is_empty(),
        "PRAGMA CHECKPOINT should have created volume files"
    );
    for vol_path in &vol_files {
        let _ = fs::remove_file(vol_path);
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM vol_test", ());

    match result {
        Ok(count) => {
            // Post-checkpoint WAL data should survive at minimum
            assert!(
                count >= 0,
                "Should have non-negative row count, got {}",
                count
            );
        }
        Err(_) => {
            // If both volume and WAL can't reconstruct the table, acceptable
        }
    }
}

#[test]
fn test_volume_valid_wal_corrupt() {
    // Volumes are valid, but WAL is partially corrupted.
    // Should recover volume data (phase 1) + surviving WAL entries.
    let (fixture, pre_count) = setup_db_with_volumes();

    // Corrupt the WAL (post-checkpoint entries)
    let wal_files = find_wal_files(&fixture.db_path);
    if !wal_files.is_empty() {
        let wal_path = &wal_files[wal_files.len() - 1];
        let mut data = fs::read(wal_path).unwrap();

        if data.len() > 200 {
            let corrupt_start = data.len() * 3 / 4;
            let corrupt_len = 200.min(data.len() - corrupt_start);
            zero_range(&mut data, corrupt_start, corrupt_len);
            fs::write(wal_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM vol_test", ()).unwrap();

    // Volume data (phase 1) must survive; some WAL data may be lost
    assert!(
        count >= pre_count,
        "Expected at least {} rows (volume data), got {}",
        pre_count,
        count
    );

    // Verify usable
    db.execute(
        "INSERT INTO vol_test (id, value, phase) VALUES (999, 'post_recovery', 3)",
        (),
    )
    .unwrap();
}

#[test]
fn test_manifest_corrupt_with_valid_volumes() {
    // Corrupt manifest.bin but leave .vol files intact.
    // Recovery may lose track of which volumes exist.
    let (fixture, _) = setup_db_with_volumes();

    if let Some(manifest_path) = find_manifest_file(&fixture.db_path, "vol_test") {
        let mut data = fs::read(&manifest_path).unwrap();
        if data.len() > 10 {
            // Corrupt the magic bytes (first 4 bytes: "STMF")
            zero_range(&mut data, 0, 4);
            fs::write(&manifest_path, &data).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);

    // Database should still open; volumes without valid manifest may be skipped
    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM vol_test", ());

    match result {
        Ok(count) => {
            assert!(count >= 0, "Should have non-negative row count");
            db.execute(
                "INSERT INTO vol_test (id, value, phase) VALUES (999, 'post_recovery', 3)",
                (),
            )
            .unwrap();
        }
        Err(_) => {
            // Table may not exist if manifest + WAL both can't reconstruct it
        }
    }
}

#[test]
fn test_manifest_deleted() {
    // Delete manifest.bin entirely. Volume files exist but won't be discovered.
    let (fixture, _) = setup_db_with_volumes();

    if let Some(manifest_path) = find_manifest_file(&fixture.db_path, "vol_test") {
        fs::remove_file(&manifest_path).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM vol_test", ());

    match result {
        Ok(count) => {
            assert!(count >= 0, "Should have non-negative row count");
        }
        Err(_) => {
            // Acceptable: without manifest, volumes are orphaned
        }
    }
}

#[test]
fn test_volume_truncated() {
    // Truncate a .vol file to partial state (simulates torn write during seal)
    let (fixture, _) = setup_db_with_volumes();

    let vol_files = find_volume_files(&fixture.db_path, "vol_test");
    for vol_path in &vol_files {
        let data = fs::read(vol_path).unwrap();
        if data.len() > 100 {
            // Truncate to 1/4 of original size
            fs::write(vol_path, &data[..data.len() / 4]).unwrap();
        }
    }

    remove_lock_file(&fixture.db_path);

    let db = Database::open(&fixture.dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM vol_test", ());

    match result {
        Ok(count) => {
            assert!(count >= 0);
        }
        Err(_) => {
            // Acceptable if truncated volume causes load failure
        }
    }
}

// ============================================================================
// 14. CHECKPOINT-BASED WAL TRUNCATION AND VOLUME RECOVERY
// ============================================================================
//
// These tests verify that PRAGMA CHECKPOINT correctly seals hot rows into
// immutable .vol files, truncates the WAL, and that recovery works from
// volumes + remaining WAL entries. The checkpoint cycle is:
//   seal hot → write .vol → persist manifest → compact → truncate WAL

/// Helper: Get total WAL file size in bytes
fn total_wal_size(db_path: &Path) -> u64 {
    find_wal_files(db_path)
        .iter()
        .map(|p| fs::metadata(p).map(|m| m.len()).unwrap_or(0))
        .sum()
}

#[test]
fn test_checkpoint_single_then_recover() {
    // After a single PRAGMA CHECKPOINT, data is sealed into volumes and WAL is truncated.
    // Post-checkpoint WAL data should also survive recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE safe_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert data
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint: seal hot rows into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data after checkpoint (WAL only)
        for i in 21..=40 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Volumes should have phase 1 data, WAL should have phase 2 data
    let vol_files = find_volume_files(&db_path, "safe_test");
    assert!(!vol_files.is_empty(), "Should have at least 1 volume file");

    // Reopen — volumes provide phase 1, WAL provides phase 2
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM safe_test", ()).unwrap();
    assert_eq!(count, 40, "All 40 rows should be recovered (volumes + WAL)");
}

#[test]
fn test_checkpoint_two_cycles_recovery() {
    // Two checkpoints: phase 1 sealed, phase 2 sealed, phase 3 in WAL.
    // All data should survive recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE safe_test2 (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert 10 rows, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test2 (id, value) VALUES ({}, 'phase1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: Insert 10 more rows, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test2 (id, value) VALUES ({}, 'phase2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 3: Insert 10 more rows (in WAL only)
        for i in 21..=30 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test2 (id, value) VALUES ({}, 'phase3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Reopen — volumes have phases 1+2, WAL has phase 3
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM safe_test2", ()).unwrap();
    assert_eq!(
        count, 30,
        "All 30 rows should be recovered from volumes + WAL"
    );
}

#[test]
fn test_checkpoint_volume_corrupt_wal_truncated() {
    // Checkpoint seals data into volumes and truncates WAL.
    // If the volume is then corrupted, data sealed before WAL truncation
    // may be lost. This tests the expected behavior.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE safe_test3 (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert data and checkpoint (seals to volume, truncates WAL)
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test3 (id, value) VALUES ({}, 'data_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data (in WAL)
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test3 (id, value) VALUES ({}, 'data_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt the volume files
    let vol_files = find_volume_files(&db_path, "safe_test3");
    for vol_path in &vol_files {
        let mut data = fs::read(vol_path).unwrap();
        if data.len() > 10 {
            zero_range(&mut data, 0, 10);
            fs::write(vol_path, &data).unwrap();
        }
    }

    // Reopen — volume data (phase 1) may be lost since WAL was truncated,
    // but WAL data (phase 2) should survive. Table DDL re-recorded after
    // checkpoint ensures table exists.
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM safe_test3", ());
    match result {
        Ok(count) => {
            // WAL data should survive; volume data depends on WAL truncation extent
            assert!(count >= 0, "Should have non-negative count, got {}", count);
        }
        Err(_) => {
            // If DDL was also in truncated WAL region, table may not exist
        }
    }
}

#[test]
fn test_checkpoint_three_cycles_recovery() {
    // With 3 checkpoints, all data should be in volumes.
    // Recovery loads volumes + replays remaining WAL.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE safe_test4 (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert rows, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test4 (id, value) VALUES ({}, 'p1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: Insert rows, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test4 (id, value) VALUES ({}, 'p2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 3: Insert rows, checkpoint 3
        for i in 21..=30 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test4 (id, value) VALUES ({}, 'p3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 4: More data in WAL only
        for i in 31..=40 {
            db.execute(
                &format!(
                    "INSERT INTO safe_test4 (id, value) VALUES ({}, 'p4_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Reopen — volumes have phases 1-3, WAL has phase 4
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM safe_test4", ()).unwrap();
    assert_eq!(
        count, 40,
        "All 40 rows should be recovered from volumes + WAL"
    );
}

#[test]
fn test_safe_truncation_keep_count_one() {
    // Checkpoint seals hot rows into volumes and truncates WAL.
    // Two checkpoints ensure earlier data is in volumes, WAL is truncated,
    // and post-checkpoint data in WAL survives recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?keep_snapshots=1&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE keep1_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert 10 rows, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO keep1_test (id, value) VALUES ({}, 'p1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 2: Insert 10 more rows, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO keep1_test (id, value) VALUES ({}, 'p2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 3: Insert 10 more rows (WAL only, no checkpoint)
        for i in 21..=30 {
            db.execute(
                &format!(
                    "INSERT INTO keep1_test (id, value) VALUES ({}, 'p3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Reopen — volumes provide phases 1+2, WAL provides phase 3
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM keep1_test", ()).unwrap();
    assert_eq!(
        count, 30,
        "All 30 rows should be recovered (volumes + WAL replay)"
    );
}

#[test]
fn test_checkpoint_leftover_tmp_volume_cleaned_up() {
    // If a leftover .vol.tmp file sits on disk from a crashed seal,
    // it should not interfere with recovery. The next checkpoint should succeed.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE cleanup_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Checkpoint 1
        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO cleanup_test (id, value) VALUES ({}, 'v{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Checkpoint 2
        for i in 6..=10 {
            db.execute(
                &format!(
                    "INSERT INTO cleanup_test (id, value) VALUES ({}, 'v{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert phase 3 (WAL only)
        for i in 11..=15 {
            db.execute(
                &format!(
                    "INSERT INTO cleanup_test (id, value) VALUES ({}, 'v{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Create a fake .vol.tmp leftover (simulates crashed seal)
    let vol_dir = db_path.join("volumes").join("cleanup_test");
    if vol_dir.exists() {
        fs::write(
            vol_dir.join("vol_ffffffffffffffff.vol.tmp"),
            b"leftover garbage from crashed seal",
        )
        .unwrap();
    }

    // Reopen — leftover .tmp files should not interfere
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM cleanup_test", ())
        .unwrap();
    assert_eq!(count, 15, "All 15 rows should be recovered");
}

#[test]
fn test_checkpoint_multi_table_one_volume_corrupt() {
    // Two tables: checkpoint both, then corrupt ONE table's volume files.
    // The corrupt table may lose data; the healthy table should be intact.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE multi_a (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE multi_b (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert into both tables, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO multi_a (id, value) VALUES ({}, 'a{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO multi_b (id, value) VALUES ({}, 'b{}')", i, i),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: Insert more, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!("INSERT INTO multi_a (id, value) VALUES ({}, 'a{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO multi_b (id, value) VALUES ({}, 'b{}')", i, i),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 3: Insert more (WAL only)
        for i in 21..=30 {
            db.execute(
                &format!("INSERT INTO multi_a (id, value) VALUES ({}, 'a{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO multi_b (id, value) VALUES ({}, 'b{}')", i, i),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt ONLY table A's volume files
    let vols_a = find_volume_files(&db_path, "multi_a");
    for vol_path in &vols_a {
        let mut data = fs::read(vol_path).unwrap();
        if data.len() > 10 {
            zero_range(&mut data, 0, 10);
            fs::write(vol_path, &data).unwrap();
        }
    }

    // Reopen — table B should be fully intact from volumes + WAL
    let db = Database::open(&dsn).unwrap();
    let count_b: i64 = db.query_one("SELECT COUNT(*) FROM multi_b", ()).unwrap();
    assert_eq!(count_b, 30, "Table B: all 30 rows from volumes + WAL");

    // Table A: volume data may be lost (WAL was truncated), but WAL data (phase 3) should survive
    let result_a: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM multi_a", ());
    match result_a {
        Ok(count) => {
            assert!(
                count >= 0,
                "Table A should have non-negative count, got {}",
                count
            );
        }
        Err(_) => {
            // If DDL was in truncated WAL region, table may not exist
        }
    }
}

#[test]
fn test_safe_truncation_table_created_between_snapshots() {
    // Create table A, checkpoint, then create table B, checkpoint again.
    // Each checkpoint seals all hot rows into volumes and truncates WAL.
    // Tables created between checkpoints get their data sealed on the next checkpoint.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE early_table (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert into early_table, first checkpoint
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO early_table (id, value) VALUES ({}, 'e{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let wal_before_first = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_after_first = total_wal_size(&db_path);

        // WAL should be truncated after first checkpoint
        assert!(
            wal_after_first < wal_before_first,
            "WAL should be truncated after first checkpoint: before={}, after={}",
            wal_before_first,
            wal_after_first
        );

        // Now create a new table AFTER the first checkpoint
        db.execute(
            "CREATE TABLE late_table (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO late_table (id, value) VALUES ({}, 'l{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Insert more data into both tables
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO early_table (id, value) VALUES ({}, 'e{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
            db.execute(
                &format!(
                    "INSERT INTO late_table (id, value) VALUES ({}, 'l{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Second checkpoint — seals all hot data (both tables) into volumes
        let wal_before_second = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_after_second = total_wal_size(&db_path);

        // WAL should be truncated after second checkpoint
        assert!(
            wal_after_second < wal_before_second,
            "WAL should be truncated after second checkpoint: before={}, after={}",
            wal_before_second,
            wal_after_second
        );
    }

    remove_lock_file(&db_path);

    // Verify all data recovers from volumes
    let db = Database::open(&dsn).unwrap();
    let count_early: i64 = db
        .query_one("SELECT COUNT(*) FROM early_table", ())
        .unwrap();
    let count_late: i64 = db.query_one("SELECT COUNT(*) FROM late_table", ()).unwrap();
    assert_eq!(count_early, 20, "early_table should have all 20 rows");
    assert_eq!(count_late, 20, "late_table should have all 20 rows");
}

#[test]
fn test_safe_truncation_drop_table_no_block() {
    // After DROP TABLE, checkpoint should still truncate WAL for remaining tables.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE keeper (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE dropper (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert into both tables, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO keeper (id, value) VALUES ({}, 'k{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO dropper (id, value) VALUES ({}, 'd{}')", i, i),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Drop one table
        db.execute("DROP TABLE dropper", ()).unwrap();

        // Insert more into keeper, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!("INSERT INTO keeper (id, value) VALUES ({}, 'k{}')", i, i),
                (),
            )
            .unwrap();
        }
        let wal_before = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_after = total_wal_size(&db_path);

        // WAL should be truncated — dropped table must not block it.
        assert!(
            wal_after < wal_before,
            "WAL should be truncated after drop + checkpoint: before={}, after={}",
            wal_before,
            wal_after
        );

        // Insert more data
        for i in 21..=30 {
            db.execute(
                &format!("INSERT INTO keeper (id, value) VALUES ({}, 'k{}')", i, i),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Verify recovery
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM keeper", ()).unwrap();
    assert_eq!(count, 30, "All 30 rows in keeper should be recovered");

    // dropper should not exist
    let result: std::result::Result<i64, _> = db.query_one("SELECT COUNT(*) FROM dropper", ());
    assert!(result.is_err(), "dropper table should not exist after drop");
}

#[test]
fn test_checkpoint_all_volumes_corrupt_one_table() {
    // Multi-table: ALL volumes for one table are corrupted after checkpoint.
    // The healthy table should be fully recovered from its volumes.
    // The doomed table may lose data since WAL was truncated.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE healthy (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE doomed (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO healthy (id, value) VALUES ({}, 'h{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO doomed (id, value) VALUES ({}, 'd{}')", i, i),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        for i in 11..=20 {
            db.execute(
                &format!("INSERT INTO healthy (id, value) VALUES ({}, 'h{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO doomed (id, value) VALUES ({}, 'd{}')", i, i),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        for i in 21..=30 {
            db.execute(
                &format!("INSERT INTO healthy (id, value) VALUES ({}, 'h{}')", i, i),
                (),
            )
            .unwrap();
            db.execute(
                &format!("INSERT INTO doomed (id, value) VALUES ({}, 'd{}')", i, i),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt ALL of doomed's volume files
    let doomed_vols = find_volume_files(&db_path, "doomed");
    for vol in &doomed_vols {
        let mut data = fs::read(vol).unwrap();
        if data.len() > 10 {
            zero_range(&mut data, 0, 10);
            fs::write(vol, &data).unwrap();
        }
    }

    // Reopen — healthy recovers from volumes + WAL.
    // Doomed's volumes are corrupt and WAL was truncated, so data sealed
    // before checkpoint may be lost. This is expected: volume corruption
    // after WAL truncation means data loss for that table.
    let db = Database::open(&dsn).unwrap();
    let healthy_count: i64 = db.query_one("SELECT COUNT(*) FROM healthy", ()).unwrap();
    assert_eq!(
        healthy_count, 30,
        "Healthy table should have all 30 rows from volumes + WAL"
    );

    // Doomed table: volumes are corrupt, WAL was truncated.
    // The table may not exist or may have partial data.
    let doomed_result: std::result::Result<i64, _> =
        db.query_one("SELECT COUNT(*) FROM doomed", ());
    if let Ok(count) = doomed_result {
        assert!(
            count <= 30,
            "Doomed should have at most 30 rows (got {})",
            count
        );
    }
}

#[test]
fn test_checkpoint_drop_and_recreate_same_name() {
    // DROP TABLE then CREATE TABLE with the same name.
    // Checkpoint must not confuse volumes from the old and new table.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create table, insert data, checkpoint
        db.execute(
            "CREATE TABLE reborn (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO reborn (id, value) VALUES ({}, 'old{}')", i, i),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Drop and recreate with same name
        db.execute("DROP TABLE reborn", ()).unwrap();
        db.execute(
            "CREATE TABLE reborn (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=5 {
            db.execute(
                &format!("INSERT INTO reborn (id, value) VALUES ({}, 'new{}')", i, i),
                (),
            )
            .unwrap();
        }

        // Checkpoint again — the "reborn" table exists in schemas
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data
        for i in 6..=15 {
            db.execute(
                &format!("INSERT INTO reborn (id, value) VALUES ({}, 'new{}')", i, i),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Verify the new table's data survives
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM reborn", ()).unwrap();
    assert_eq!(count, 15, "Recreated table should have 15 rows");

    // Verify old data is gone (values should be 'new*', not 'old*')
    let val: String = db
        .query_one("SELECT value FROM reborn WHERE id = 1", ())
        .unwrap();
    assert_eq!(val, "new1", "Data should be from the recreated table");
}

#[test]
fn test_safe_truncation_keep_count_zero_no_cleanup() {
    // Checkpoint seals hot rows into volumes and truncates WAL.
    // Multiple checkpoints ensure all data is persisted in volumes
    // and WAL is truncated after each cycle.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?keep_snapshots=0&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE keep_all (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert, checkpoint 1
        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO keep_all (id, value) VALUES ({}, 'v{}')", i, i),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 2: Insert, checkpoint 2
        for i in 11..=20 {
            db.execute(
                &format!("INSERT INTO keep_all (id, value) VALUES ({}, 'v{}')", i, i),
                (),
            )
            .unwrap();
        }
        let wal_before = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_after = total_wal_size(&db_path);

        // Checkpoint seals all hot data and truncates WAL
        assert!(
            wal_after < wal_before,
            "WAL should be truncated after checkpoint: before={}, after={}",
            wal_before,
            wal_after
        );

        // Phase 3: Insert, checkpoint 3
        for i in 21..=30 {
            db.execute(
                &format!("INSERT INTO keep_all (id, value) VALUES ({}, 'v{}')", i, i),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());
    }

    remove_lock_file(&db_path);

    // All data should be recovered from volumes
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM keep_all", ()).unwrap();
    assert_eq!(count, 30, "All 30 rows recovered from volumes");
}

#[test]
fn test_safe_truncation_with_updates_and_deletes() {
    // Verify checkpoint works correctly with UPDATE and DELETE operations,
    // not just INSERTs. Volumes must preserve tombstones and updated rows.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE mut_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL, status TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Insert rows, checkpoint 1
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO mut_test (id, value, status) VALUES ({}, 'original{}', 'active')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: UPDATE some, DELETE others, INSERT new
        for i in 1..=5 {
            db.execute(
                &format!(
                    "UPDATE mut_test SET value = 'updated{}', status = 'modified' WHERE id = {}",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        for i in 16..=20 {
            db.execute(&format!("DELETE FROM mut_test WHERE id = {}", i), ())
                .unwrap();
        }
        for i in 21..=25 {
            db.execute(
                &format!(
                    "INSERT INTO mut_test (id, value, status) VALUES ({}, 'new{}', 'active')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 3: More mutations (WAL only)
        db.execute("UPDATE mut_test SET status = 'final' WHERE id <= 5", ())
            .unwrap();
        db.execute("DELETE FROM mut_test WHERE id = 21", ())
            .unwrap();
        for i in 26..=30 {
            db.execute(
                &format!(
                    "INSERT INTO mut_test (id, value, status) VALUES ({}, 'late{}', 'active')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Recovery from volumes (phases 1+2) + WAL (phase 3)
    let db = Database::open(&dsn).unwrap();

    // Verify UPDATEs were preserved
    let updated_val: String = db
        .query_one("SELECT value FROM mut_test WHERE id = 3", ())
        .unwrap();
    assert_eq!(updated_val, "updated3", "UPDATE should be preserved");

    let final_status: String = db
        .query_one("SELECT status FROM mut_test WHERE id = 3", ())
        .unwrap();
    assert_eq!(final_status, "final", "Second UPDATE should be preserved");

    // Verify DELETEs were preserved
    let deleted_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM mut_test WHERE id BETWEEN 16 AND 20",
            (),
        )
        .unwrap();
    assert_eq!(deleted_count, 0, "DELETEd rows should stay deleted");

    let late_delete: i64 = db
        .query_one("SELECT COUNT(*) FROM mut_test WHERE id = 21", ())
        .unwrap();
    assert_eq!(late_delete, 0, "Late DELETE should be preserved");

    // Verify total count: 20 original - 5 deleted(16-20) + 5 new(21-25) - 1 deleted(21) + 5 late(26-30) = 24
    let total: i64 = db.query_one("SELECT COUNT(*) FROM mut_test", ()).unwrap();
    assert_eq!(total, 24, "Total rows after all mutations");
}

#[test]
fn test_safe_truncation_survives_restart_cycles() {
    // Verify checkpoint state is consistent across multiple close/reopen cycles.
    // Each cycle: insert data, checkpoint, close, reopen, verify.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    // Cycle 1: Create and populate
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE cycle (id INTEGER PRIMARY KEY, cycle_num INTEGER NOT NULL, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO cycle (id, cycle_num, value) VALUES ({}, 1, 'c1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Cycle 2: Reopen, add data, checkpoint
    {
        let db = Database::open(&dsn).unwrap();
        let count: i64 = db.query_one("SELECT COUNT(*) FROM cycle", ()).unwrap();
        assert_eq!(count, 10, "Cycle 2 open: should have 10 rows");

        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO cycle (id, cycle_num, value) VALUES ({}, 2, 'c2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Cycle 3: Reopen, add data, checkpoint
    {
        let db = Database::open(&dsn).unwrap();
        let count: i64 = db.query_one("SELECT COUNT(*) FROM cycle", ()).unwrap();
        assert_eq!(count, 20, "Cycle 3 open: should have 20 rows");

        for i in 21..=30 {
            db.execute(
                &format!(
                    "INSERT INTO cycle (id, cycle_num, value) VALUES ({}, 3, 'c3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Cycle 4: Reopen, verify all data survived multiple cycles
    {
        let db = Database::open(&dsn).unwrap();
        let count: i64 = db.query_one("SELECT COUNT(*) FROM cycle", ()).unwrap();
        assert_eq!(
            count, 30,
            "All 30 rows should be recovered from volumes across 3 checkpoint cycles"
        );

        // Verify data from each cycle
        for cycle_num in 1..=3 {
            let cycle_count: i64 = db
                .query_one(
                    &format!("SELECT COUNT(*) FROM cycle WHERE cycle_num = {}", cycle_num),
                    (),
                )
                .unwrap();
            assert_eq!(cycle_count, 10, "Cycle {} should have 10 rows", cycle_num);
        }
    }
}

// ============================================================================
// 15. DURABILITY EDGE CASES
// ============================================================================
//
// Tests for high-priority durability gaps:
// - Gap 1: Manifest corruption (manifest.bin)
// - Gap 2: Crash during checkpoint/seal
// - Gap 3: DDL durability under corruption
// - Gap 4: View persistence after corruption
// - Gap 5: Transactions spanning checkpoint boundary
// - Gap 6: Constraint enforcement after recovery

// ---------------------------------------------------------------------------
// Gap 1: Manifest Corruption (manifest.bin)
// ---------------------------------------------------------------------------

#[test]
fn test_manifest_corrupt_magic_bytes() {
    // Corrupt first 4 bytes (magic "STMF") of manifest.bin.
    // Recovery should handle the corrupt manifest gracefully.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE meta_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=15 {
            db.execute(
                &format!(
                    "INSERT INTO meta_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data after checkpoint (in WAL)
        for i in 16..=20 {
            db.execute(
                &format!(
                    "INSERT INTO meta_test (id, value) VALUES ({}, 'wal_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Corrupt magic bytes in manifest.bin
    if let Some(manifest_path) = find_manifest_file(&db_path, "meta_test") {
        let mut data = fs::read(&manifest_path).unwrap();
        if data.len() >= 4 {
            zero_range(&mut data, 0, 4); // zero out magic
            fs::write(&manifest_path, &data).unwrap();
        }
    }

    // Reopen — manifest is corrupt, volumes may not load, but WAL data should survive
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM meta_test", ());
    match result {
        Ok(count) => {
            assert!(count >= 0, "Should have non-negative count, got {}", count);
            db.execute(
                "INSERT INTO meta_test (id, value) VALUES (100, 'post_recovery')",
                (),
            )
            .unwrap();
        }
        Err(_) => {
            // If DDL was in truncated WAL, table may not exist
        }
    }
}

#[test]
fn test_manifest_corrupt_checkpoint_lsn() {
    // Corrupt the checkpoint_lsn field in manifest.bin.
    // Recovery may replay incorrect WAL range but should not crash.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE meta_lsn (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO meta_lsn (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Corrupt the manifest by flipping bits in the middle (where checkpoint_lsn is stored)
    if let Some(manifest_path) = find_manifest_file(&db_path, "meta_lsn") {
        let mut data = fs::read(&manifest_path).unwrap();
        if data.len() > 20 {
            // Flip bits in the data section
            flip_bit(&mut data, 12, 5);
            flip_bit(&mut data, 16, 3);
            fs::write(&manifest_path, &data).unwrap();
        }
    }

    // Database should open without crashing
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM meta_lsn", ());
    if let Ok(count) = result {
        assert!(count >= 0, "Should have non-negative count");
    }
}

#[test]
fn test_manifest_deleted_volumes_exist() {
    // Delete manifest.bin entirely, but .vol files remain on disk.
    // Without manifest, volumes are orphaned. Recovery relies on WAL.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE meta_del (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=12 {
            db.execute(
                &format!(
                    "INSERT INTO meta_del (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Verify volumes exist before deleting manifest
    let vol_files = find_volume_files(&db_path, "meta_del");
    assert!(!vol_files.is_empty(), "Should have volume files");

    // Delete manifest.bin
    if let Some(manifest_path) = find_manifest_file(&db_path, "meta_del") {
        fs::remove_file(&manifest_path).unwrap();
    }

    // Recovery should handle missing manifest
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM meta_del", ());
    if let Ok(count) = result {
        assert!(count >= 0, "Should have non-negative count");
    }
}

#[test]
fn test_manifest_truncated() {
    // Truncate manifest.bin to partial state (simulates torn write).
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE meta_trunc (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=8 {
            db.execute(
                &format!(
                    "INSERT INTO meta_trunc (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Truncate manifest.bin to half its size
    if let Some(manifest_path) = find_manifest_file(&db_path, "meta_trunc") {
        let data = fs::read(&manifest_path).unwrap();
        if data.len() > 10 {
            fs::write(&manifest_path, &data[..data.len() / 2]).unwrap();
        }
    }

    // Database should open without crashing
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM meta_trunc", ());
    if let Ok(count) = result {
        assert!(count >= 0, "Should have non-negative count");
    }
}

// ---------------------------------------------------------------------------
// Gap 2: Crash During Checkpoint/Seal
// ---------------------------------------------------------------------------

#[test]
fn test_crash_leftover_tmp_volume_file() {
    // Manually create a .vol.tmp file (simulates crash during seal).
    // PRAGMA CHECKPOINT should succeed and the .tmp file should not interfere.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE tmp_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO tmp_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Create a leftover .vol.tmp file in the volume directory
        let vol_dir = db_path.join("volumes").join("tmp_test");
        let _ = fs::create_dir_all(&vol_dir);
        fs::write(
            vol_dir.join("vol_ffffffffffffffff.vol.tmp"),
            b"leftover garbage data from crashed seal write",
        )
        .unwrap();

        // PRAGMA CHECKPOINT should still succeed (ignores .tmp files)
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Reopen — .tmp files are never loaded
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM tmp_test", ()).unwrap();
    assert_eq!(count, 10, "All 10 rows should be present");

    // Verify no .tmp files are treated as real volumes
    let vol_files = find_volume_files(&db_path, "tmp_test");
    for f in &vol_files {
        let name = f.file_name().unwrap().to_string_lossy();
        assert!(
            !name.ends_with(".tmp"),
            "No .tmp files should be in volume listing"
        );
    }
}

#[test]
fn test_crash_after_volume_write_before_manifest() {
    // Simulate crash after volume file was written but before manifest was updated.
    // Delete manifest.bin after checkpoint. Recovery should handle this gracefully.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE crash_manifest (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert 10 rows, first checkpoint
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO crash_manifest (id, value) VALUES ({}, 'batch1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert 10 more rows, second checkpoint
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO crash_manifest (id, value) VALUES ({}, 'batch2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Delete manifest.bin (simulates crash after volume write but before manifest persist)
    if let Some(manifest_path) = find_manifest_file(&db_path, "crash_manifest") {
        fs::remove_file(&manifest_path).unwrap();
    }

    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM crash_manifest", ());
    match result {
        Ok(count) => {
            // Without manifest, volumes are orphaned. Recovery depends on WAL.
            assert!(count >= 0, "Should have non-negative count, got {}", count);
        }
        Err(_) => {
            // Table may not exist if DDL was in truncated WAL
        }
    }
}

#[test]
fn test_crash_partial_volume_file() {
    // Valid checkpoint + truncated .vol file (simulates partial write crash during seal).
    // Recovery should skip the truncated volume.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE partial_vol (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=15 {
            db.execute(
                &format!(
                    "INSERT INTO partial_vol (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert more data after checkpoint
        for i in 16..=25 {
            db.execute(
                &format!(
                    "INSERT INTO partial_vol (id, value) VALUES ({}, 'post_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Truncate one of the volume files (simulates partial write)
    let vol_files = find_volume_files(&db_path, "partial_vol");
    if !vol_files.is_empty() {
        let vol_path = &vol_files[0];
        let data = fs::read(vol_path).unwrap();
        if data.len() > 50 {
            fs::write(vol_path, &data[..50]).unwrap();
        }
    }

    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM partial_vol", ());
    match result {
        Ok(count) => {
            // Truncated volume may fail to load; WAL data should survive
            assert!(count >= 0, "Should have non-negative count");
        }
        Err(_) => {
            // If volume load failure cascades, table may not exist
        }
    }
}

// ---------------------------------------------------------------------------
// Gap 3: DDL Durability Under Corruption
// ---------------------------------------------------------------------------

#[test]
fn test_ddl_create_index_survives_checkpoint_recovery() {
    // CREATE INDEX + data sealed into volumes via checkpoint. Close and reopen.
    // Verify all data and index survive through volume recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE idx_test (id INTEGER PRIMARY KEY, category TEXT NOT NULL, amount FLOAT)",
            (),
        )
        .unwrap();

        for i in 1..=20 {
            let cat = if i % 2 == 0 { "even" } else { "odd" };
            db.execute(
                &format!(
                    "INSERT INTO idx_test (id, category, amount) VALUES ({}, '{}', {})",
                    i,
                    cat,
                    i as f64 * 1.5
                ),
                (),
            )
            .unwrap();
        }

        db.execute("CREATE INDEX idx_cat ON idx_test(category)", ())
            .unwrap();

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Verify volume files were created
        let vol_files = find_volume_files(&db_path, "idx_test");
        assert!(
            !vol_files.is_empty(),
            "Checkpoint should create volume files"
        );
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM idx_test", ()).unwrap();
    assert_eq!(count, 20, "All 20 rows should be recovered from volumes");

    // Verify index is usable — query with indexed column filter
    let even_count: i64 = db
        .query_one("SELECT COUNT(*) FROM idx_test WHERE category = 'even'", ())
        .unwrap();
    assert_eq!(even_count, 10, "Should find 10 'even' rows via index");

    let odd_count: i64 = db
        .query_one("SELECT COUNT(*) FROM idx_test WHERE category = 'odd'", ())
        .unwrap();
    assert_eq!(odd_count, 10, "Should find 10 'odd' rows via index");
}

#[test]
fn test_ddl_multiple_operations_recovery() {
    // Multiple DDL operations: CREATE TABLE t1, INSERT, CREATE TABLE t2, INSERT,
    // CREATE INDEX on t1, DROP TABLE t2.
    // Pure WAL replay (no snapshot) should recover correct state.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        db.execute(
            "CREATE TABLE ddl_t1 (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            (),
        )
        .unwrap();
        for i in 1..=5 {
            db.execute(
                &format!("INSERT INTO ddl_t1 (id, name) VALUES ({}, 'name_{}')", i, i),
                (),
            )
            .unwrap();
        }

        db.execute(
            "CREATE TABLE ddl_t2 (id INTEGER PRIMARY KEY, data TEXT)",
            (),
        )
        .unwrap();
        for i in 1..=3 {
            db.execute(
                &format!("INSERT INTO ddl_t2 (id, data) VALUES ({}, 'data_{}')", i, i),
                (),
            )
            .unwrap();
        }

        db.execute("CREATE INDEX idx_name ON ddl_t1(name)", ())
            .unwrap();

        db.execute("DROP TABLE ddl_t2", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Reopen — pure WAL replay, no snapshot
    let db = Database::open(&dsn).unwrap();

    // t1 should exist with data and index
    let count: i64 = db.query_one("SELECT COUNT(*) FROM ddl_t1", ()).unwrap();
    assert_eq!(count, 5, "ddl_t1 should have 5 rows");

    // Verify index on t1 is usable
    let name_count: i64 = db
        .query_one("SELECT COUNT(*) FROM ddl_t1 WHERE name = 'name_3'", ())
        .unwrap();
    assert_eq!(name_count, 1, "Should find 1 row via index lookup");

    // t2 should NOT exist
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM ddl_t2", ());
    assert!(
        result.is_err(),
        "ddl_t2 should not exist after DROP TABLE was replayed"
    );
}

// ---------------------------------------------------------------------------
// Gap 4: View Persistence After Corruption
// ---------------------------------------------------------------------------

#[test]
fn test_view_survives_checkpoint_recovery() {
    // CREATE VIEW + data sealed into volumes via checkpoint. Close and reopen.
    // View should exist and return correct results from volume recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE view_base (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO view_base (id, name, score) VALUES ({}, 'user_{}', {})",
                    i,
                    i,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }

        db.execute(
            "CREATE VIEW high_scores AS SELECT id, UPPER(name) AS name, score FROM view_base WHERE score >= 50",
            (),
        )
        .unwrap();

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Verify volume files were created
        let vol_files = find_volume_files(&db_path, "view_base");
        assert!(
            !vol_files.is_empty(),
            "Checkpoint should create volume files"
        );
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // View should exist and return correct results from volume recovery
    let view_count: i64 = db
        .query_one("SELECT COUNT(*) FROM high_scores", ())
        .unwrap();
    assert_eq!(
        view_count, 6,
        "high_scores view should return 6 rows (scores 50-100)"
    );

    // Verify UPPER transformation works
    let name: String = db
        .query_one("SELECT name FROM high_scores WHERE id = 5", ())
        .unwrap();
    assert_eq!(name, "USER_5", "UPPER() should be applied in the view");
}

#[test]
fn test_view_drop_and_recreate_durability() {
    // CREATE VIEW v1 (def A), DROP VIEW v1, CREATE VIEW v1 (def B).
    // After WAL replay, v1 should use definition B.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE vdr_base (id INTEGER PRIMARY KEY, name TEXT NOT NULL, active INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=6 {
            let active = if i <= 3 { 1 } else { 0 };
            db.execute(
                &format!(
                    "INSERT INTO vdr_base (id, name, active) VALUES ({}, 'user_{}', {})",
                    i, i, active
                ),
                (),
            )
            .unwrap();
        }

        // First definition: SELECT *
        db.execute("CREATE VIEW vdr_view AS SELECT * FROM vdr_base", ())
            .unwrap();

        // Drop it
        db.execute("DROP VIEW vdr_view", ()).unwrap();

        // Recreate with different definition: only active users, with UPPER
        db.execute(
            "CREATE VIEW vdr_view AS SELECT id, UPPER(name) AS name FROM vdr_base WHERE active = 1",
            (),
        )
        .unwrap();
    }
    remove_lock_file(&db_path);

    // Reopen — WAL replays all three DDL ops in order
    let db = Database::open(&dsn).unwrap();

    // View should use the NEW definition (only active users)
    let count: i64 = db.query_one("SELECT COUNT(*) FROM vdr_view", ()).unwrap();
    assert_eq!(count, 3, "View should return only 3 active users");

    // Verify UPPER transformation is applied (new definition)
    let name: String = db
        .query_one("SELECT name FROM vdr_view WHERE id = 1", ())
        .unwrap();
    assert_eq!(name, "USER_1", "New view definition should apply UPPER()");
}

// ---------------------------------------------------------------------------
// Gap 5: Transactions Spanning Checkpoint Boundary
// ---------------------------------------------------------------------------

#[test]
fn test_uncommitted_data_not_in_checkpoint() {
    // Uncommitted transaction data should NOT survive across close/reopen.
    // PRAGMA CHECKPOINT captures only committed data.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE uncommit_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert 10 committed rows
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO uncommit_test (id, value) VALUES ({}, 'committed_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Begin transaction and insert 5 more (uncommitted)
        let mut tx = db.begin().unwrap();
        for i in 11..=15 {
            tx.execute(
                &format!(
                    "INSERT INTO uncommit_test (id, value) VALUES ({}, 'uncommitted_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint while transaction is open
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Drop tx without committing (implicit rollback)
        drop(tx);
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM uncommit_test", ())
        .unwrap();
    assert_eq!(
        count, 10,
        "Only 10 committed rows should survive, uncommitted are lost"
    );
}

#[test]
fn test_data_committed_after_checkpoint_survives() {
    // Data committed AFTER checkpoint should survive via WAL.
    // Even if volumes are corrupted, WAL preserves post-checkpoint data.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE post_snap (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert 10 rows, then checkpoint
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO post_snap (id, value) VALUES ({}, 'pre_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Insert 10 more rows after checkpoint (committed)
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO post_snap (id, value) VALUES ({}, 'post_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Verify all 20 rows survive (volumes have pre-checkpoint, WAL has post-checkpoint)
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM post_snap", ()).unwrap();
    assert_eq!(count, 20, "All 20 rows should survive (volumes + WAL)");
}

// ---------------------------------------------------------------------------
// Gap 6: Constraint Enforcement After Recovery
// ---------------------------------------------------------------------------

#[test]
fn test_check_constraint_enforced_after_checkpoint_recovery() {
    // CHECK constraint schema and data sealed into volumes via checkpoint.
    // After close/reopen, constraint must still be enforced.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE check_test (id INTEGER PRIMARY KEY, age INTEGER CHECK (age >= 0 AND age <= 150))",
            (),
        )
        .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO check_test (id, age) VALUES ({}, {})",
                    i,
                    i * 20
                ),
                (),
            )
            .unwrap();
        }

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // Data should be recovered from volumes
    let count: i64 = db.query_one("SELECT COUNT(*) FROM check_test", ()).unwrap();
    assert_eq!(count, 5, "All 5 rows should be recovered from volumes");

    // CHECK constraint should be enforced — negative age should fail
    let result = db.execute("INSERT INTO check_test (id, age) VALUES (100, -1)", ());
    assert!(
        result.is_err(),
        "CHECK constraint should reject age = -1 after recovery"
    );

    // Age > 150 should also fail
    let result = db.execute("INSERT INTO check_test (id, age) VALUES (101, 200)", ());
    assert!(
        result.is_err(),
        "CHECK constraint should reject age = 200 after recovery"
    );

    // Valid age should succeed
    db.execute("INSERT INTO check_test (id, age) VALUES (102, 50)", ())
        .unwrap();
}

#[test]
fn test_not_null_constraint_after_recovery() {
    // NOT NULL constraint should be enforced after close/reopen.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE notnull_test (id INTEGER PRIMARY KEY, name TEXT NOT NULL, score INTEGER)",
            (),
        )
        .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO notnull_test (id, name, score) VALUES ({}, 'user_{}', {})",
                    i,
                    i,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // Data should be present
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM notnull_test", ())
        .unwrap();
    assert_eq!(count, 5, "All 5 rows should be recovered");

    // NOT NULL constraint should be enforced — NULL name should fail
    let result = db.execute(
        "INSERT INTO notnull_test (id, name, score) VALUES (100, NULL, 50)",
        (),
    );
    assert!(
        result.is_err(),
        "NOT NULL constraint should reject NULL name after recovery"
    );

    // Valid insert should succeed
    db.execute(
        "INSERT INTO notnull_test (id, name, score) VALUES (101, 'valid', 60)",
        (),
    )
    .unwrap();
}

#[test]
fn test_unique_index_enforced_after_checkpoint_recovery() {
    // UNIQUE INDEX + data sealed into volumes via checkpoint.
    // After close/reopen, unique constraint must still be enforced.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE unique_test (id INTEGER PRIMARY KEY, email TEXT NOT NULL)",
            (),
        )
        .unwrap();

        db.execute("CREATE UNIQUE INDEX idx_email ON unique_test(email)", ())
            .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO unique_test (id, email) VALUES ({}, 'user{}@example.com')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // Data should be recovered from volumes
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM unique_test", ())
        .unwrap();
    assert_eq!(count, 5, "All 5 rows should be recovered from volumes");

    // UNIQUE constraint should be enforced — duplicate email should fail
    let result = db.execute(
        "INSERT INTO unique_test (id, email) VALUES (100, 'user1@example.com')",
        (),
    );
    assert!(
        result.is_err(),
        "UNIQUE constraint should reject duplicate email after recovery"
    );

    // New unique email should succeed
    db.execute(
        "INSERT INTO unique_test (id, email) VALUES (101, 'new@example.com')",
        (),
    )
    .unwrap();
}

// ============================================================================
// 16. ADVANCED DURABILITY SCENARIOS
// ============================================================================

// ----------------------------------------------------------------------------
// Gap 1: Concurrent Write + Crash (4 tests)
// ----------------------------------------------------------------------------

/// 4 threads each INSERT 25 rows concurrently, close, reopen → all 100 rows present
#[test]
fn test_concurrent_writers_recovery() {
    use std::sync::{Arc, Barrier};
    use std::thread;

    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE conc_test (id INTEGER PRIMARY KEY, thread_id INTEGER, value TEXT)",
            (),
        )
        .unwrap();

        let barrier = Arc::new(Barrier::new(4));
        let mut handles = Vec::new();

        for t in 0..4u32 {
            let db_clone = db.clone();
            let bar = Arc::clone(&barrier);
            handles.push(thread::spawn(move || {
                bar.wait();
                for i in 0..25u32 {
                    let id = t * 25 + i + 1;
                    db_clone
                        .execute(
                            &format!(
                                "INSERT INTO conc_test (id, thread_id, value) VALUES ({}, {}, 'row_{}')",
                                id, t, id
                            ),
                            (),
                        )
                        .unwrap();
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM conc_test", ()).unwrap();
        assert_eq!(count, 100);
    }

    remove_lock_file(&db_path);

    // Verify all 100 rows recovered
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM conc_test", ()).unwrap();
    assert_eq!(count, 100, "All 100 concurrent rows should be recovered");
    db.execute(
        "INSERT INTO conc_test (id, thread_id, value) VALUES (9999, 0, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Concurrent writes + WAL corruption → at least some rows recovered, DB usable
#[test]
fn test_concurrent_writers_with_wal_corruption() {
    use std::sync::{Arc, Barrier};
    use std::thread;

    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE conc_corrupt (id INTEGER PRIMARY KEY, value TEXT)",
            (),
        )
        .unwrap();

        let barrier = Arc::new(Barrier::new(4));
        let mut handles = Vec::new();

        for t in 0..4u32 {
            let db_clone = db.clone();
            let bar = Arc::clone(&barrier);
            handles.push(thread::spawn(move || {
                bar.wait();
                for i in 0..25u32 {
                    let id = t * 25 + i + 1;
                    db_clone
                        .execute(
                            &format!(
                                "INSERT INTO conc_corrupt (id, value) VALUES ({}, 'data_{}')",
                                id, id
                            ),
                            (),
                        )
                        .unwrap();
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt middle of WAL
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());
    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    if entries.len() > 4 {
        // Flip bits in a few middle entries
        let mid = entries.len() / 2;
        for entry in entries.iter().skip(mid).take(3.min(entries.len() - mid)) {
            if entry.data_offset + 4 < data.len() {
                flip_bit(&mut data, entry.data_offset + 2, 3);
            }
        }
        fs::write(wal_path, &data).unwrap();
    }

    // Recovery — at least some rows should survive; DB must be usable
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM conc_corrupt", ());
    match result {
        Ok(count) => {
            assert!(count >= 0, "Should recover some rows, got {}", count);
            db.execute(
                "INSERT INTO conc_corrupt (id, value) VALUES (9999, 'post_recovery')",
                (),
            )
            .unwrap();
        }
        Err(_) => {
            // Table DDL was also corrupted — that's valid
        }
    }
}

/// Concurrent writes + checkpoint + more writes → corrupt volumes → all rows from WAL
#[test]
fn test_concurrent_writers_checkpoint_recovery() {
    use std::sync::{Arc, Barrier};
    use std::thread;

    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE conc_snap (id INTEGER PRIMARY KEY, phase INTEGER, value TEXT)",
            (),
        )
        .unwrap();

        // Phase 1: 4 threads x 25 rows = 100
        let barrier = Arc::new(Barrier::new(4));
        let mut handles = Vec::new();
        for t in 0..4u32 {
            let db_clone = db.clone();
            let bar = Arc::clone(&barrier);
            handles.push(thread::spawn(move || {
                bar.wait();
                for i in 0..25u32 {
                    let id = t * 25 + i + 1;
                    db_clone
                        .execute(
                            &format!(
                                "INSERT INTO conc_snap (id, phase, value) VALUES ({}, 1, 'p1_{}')",
                                id, id
                            ),
                            (),
                        )
                        .unwrap();
                }
            }));
        }
        for h in handles {
            h.join().unwrap();
        }

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: 4 threads x 25 more rows = 200 total
        let barrier2 = Arc::new(Barrier::new(4));
        let mut handles2 = Vec::new();
        for t in 0..4u32 {
            let db_clone = db.clone();
            let bar = Arc::clone(&barrier2);
            handles2.push(thread::spawn(move || {
                bar.wait();
                for i in 0..25u32 {
                    let id = 100 + t * 25 + i + 1;
                    db_clone
                        .execute(
                            &format!(
                                "INSERT INTO conc_snap (id, phase, value) VALUES ({}, 2, 'p2_{}')",
                                id, id
                            ),
                            (),
                        )
                        .unwrap();
                }
            }));
        }
        for h in handles2 {
            h.join().unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM conc_snap", ()).unwrap();
        assert_eq!(count, 200);
    }

    remove_lock_file(&db_path);

    // Volumes provide phase 1 (100 rows), WAL provides phase 2 (100 rows)
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM conc_snap", ()).unwrap();
    assert_eq!(count, 200, "All 200 rows should survive (volumes + WAL)");
    db.execute(
        "INSERT INTO conc_snap (id, phase, value) VALUES (9999, 0, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Uncommitted transactions should be lost after recovery
#[test]
fn test_concurrent_transactions_uncommitted_lost() {
    use std::sync::{Arc, Barrier};
    use std::thread;

    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE uncommit_test (id INTEGER PRIMARY KEY, source TEXT)",
            (),
        )
        .unwrap();

        let barrier = Arc::new(Barrier::new(2));

        // Thread 1: committed inserts
        let db1 = db.clone();
        let bar1 = Arc::clone(&barrier);
        let h1 = thread::spawn(move || {
            bar1.wait();
            for i in 1..=10 {
                db1.execute(
                    &format!(
                        "INSERT INTO uncommit_test (id, source) VALUES ({}, 'committed')",
                        i
                    ),
                    (),
                )
                .unwrap();
            }
        });

        // Thread 2: uncommitted transaction (begun, not committed)
        let db2 = db.clone();
        let bar2 = Arc::clone(&barrier);
        let h2 = thread::spawn(move || {
            bar2.wait();
            let mut tx = db2.begin().unwrap();
            for i in 11..=20 {
                tx.execute(
                    &format!(
                        "INSERT INTO uncommit_test (id, source) VALUES ({}, 'uncommitted')",
                        i
                    ),
                    (),
                )
                .unwrap();
            }
            // Intentionally drop tx without commit
            drop(tx);
        });

        h1.join().unwrap();
        h2.join().unwrap();
    }

    remove_lock_file(&db_path);

    // Only committed rows should survive
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM uncommit_test", ())
        .unwrap();
    assert_eq!(
        count, 10,
        "Only 10 committed rows should survive, got {}",
        count
    );
    db.execute(
        "INSERT INTO uncommit_test (id, source) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

// ----------------------------------------------------------------------------
// Gap 2: WAL Rotation During Crash (4 tests)
// ----------------------------------------------------------------------------

/// Simulate crash during WAL truncation: only .bak file remains (no .log)
/// recover_interrupted_truncation should restore the .bak → data recovered
#[test]
fn test_rotation_artifacts_bak_file_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE bak_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO bak_test (id, value, seq) VALUES ({}, 'row_{}', {})",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Find the WAL file and rename it to .bak (simulating interrupted truncation)
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty(), "No WAL files found");

    let wal_path = &wal_files[0];
    let bak_path = wal_path.with_extension("log.bak");
    fs::rename(wal_path, &bak_path).unwrap();

    // Verify .bak exists and no .log WAL file
    assert!(bak_path.exists());
    let remaining = find_wal_files(&db_path);
    assert!(remaining.is_empty(), "Should have no .log WAL files");

    // Reopen — recovery should restore .bak → .log
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM bak_test", ()).unwrap();
    assert_eq!(count, 20, "All 20 rows should be recovered from .bak file");

    // Verify DB is usable
    db.execute(
        "INSERT INTO bak_test (id, value, seq) VALUES (999, 'post_recovery', 999)",
        (),
    )
    .unwrap();
}

/// Temp WAL file alongside valid WAL → temp cleaned up, data intact
#[test]
fn test_rotation_artifacts_temp_file_cleanup() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE temp_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO temp_test (id, value, seq) VALUES ({}, 'row_{}', {})",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Create a fake temp file alongside the valid WAL
    let wal_dir = db_path.join("wal");
    let temp_file = wal_dir.join("wal-temp-999.log");
    fs::write(&temp_file, b"garbage data that should be cleaned up").unwrap();
    assert!(temp_file.exists());

    // Reopen — temp should be cleaned up, all data intact
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM temp_test", ()).unwrap();
    assert_eq!(
        count, 20,
        "All 20 rows should survive with temp file present"
    );

    // Temp file should be cleaned up
    assert!(
        !temp_file.exists(),
        "Temp file should be cleaned up during recovery"
    );
}

/// Multiple WAL files where the newest is corrupted → data from valid file survives
#[test]
fn test_multiple_wal_files_newest_corrupt() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE multi_wal (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=30 {
            db.execute(
                &format!(
                    "INSERT INTO multi_wal (id, value, seq) VALUES ({}, 'row_{}', {})",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Create a second (newer by name) WAL file with garbage
    let wal_dir = db_path.join("wal");
    let corrupt_wal = wal_dir.join("wal_00000001-99999999-lsn-99999.log");
    fs::write(&corrupt_wal, b"this is not a valid WAL file at all").unwrap();

    // Reopen — recovery should handle the corrupt newer file and still read the valid one
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM multi_wal", ()).unwrap();
    assert!(
        count >= 1,
        "At least some rows should survive from valid WAL file, got {}",
        count
    );

    // Verify DB usable
    db.execute(
        "INSERT INTO multi_wal (id, value, seq) VALUES (9999, 'post_recovery', 0)",
        (),
    )
    .unwrap();
}

/// Stale checkpoint.meta pointing to nonexistent WAL → recovery discovers actual files
#[test]
fn test_stale_checkpoint_references_missing_wal() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE stale_cp (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO stale_cp (id, value, seq) VALUES ({}, 'row_{}', {})",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Overwrite checkpoint.meta with a reference to a nonexistent WAL file
    if let Some(cp_path) = find_checkpoint_file(&db_path) {
        // Write garbage checkpoint that references a missing file
        // The format is binary, so we just corrupt it entirely —
        // this forces recovery to scan WAL directory for actual files
        let mut cp_data = fs::read(&cp_path).unwrap();
        if cp_data.len() > 8 {
            // Corrupt the checkpoint data so it's invalid
            for b in cp_data.iter_mut().skip(4).take(20) {
                *b = 0xFF;
            }
            fs::write(&cp_path, &cp_data).unwrap();
        }
    }

    // Reopen → recovery should handle corrupt checkpoint and find actual WAL files
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM stale_cp", ()).unwrap();
    assert!(
        count >= 1,
        "Data should be recovered despite corrupt checkpoint, got {}",
        count
    );

    // Verify DB usable
    db.execute(
        "INSERT INTO stale_cp (id, value, seq) VALUES (9999, 'post_recovery', 0)",
        (),
    )
    .unwrap();
}

// ----------------------------------------------------------------------------
// Gap 3: Power Loss Simulation (4 tests)
// ----------------------------------------------------------------------------

/// Simulate power loss: last WAL entry truncated in half (mid-data)
#[test]
fn test_power_loss_truncated_last_entry() {
    let fixture = setup_test_db(20, 1);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2, "Need at least 2 entries");

    // Truncate the file to cut the last entry in half
    let last = &entries[entries.len() - 1];
    let cut_point = last.offset + last.total_size / 2;
    fs::write(wal_path, &data[..cut_point]).unwrap();

    remove_lock_file(&fixture.db_path);

    // At least all but the last entry's data should survive
    verify_recovery_at_least(&fixture, "test_data", 0);
}

/// Simulate power loss: garbage appended after valid WAL entries
#[test]
fn test_power_loss_garbage_appended() {
    let fixture = setup_test_db(15, 1);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();

    // Append 200 bytes of garbage (simulates partial write of next entry)
    data.extend_from_slice(&[0xDE; 200]);
    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);

    // All 15 rows should survive — garbage fails magic check
    verify_recovery_at_least(&fixture, "test_data", 15);
}

/// Simulate power loss: last 4KB page of WAL zeroed
#[test]
fn test_power_loss_last_page_zeroed() {
    let fixture = setup_test_db(20, 1);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let file_len = data.len();

    if file_len > 4096 {
        // Zero the last 4KB page
        let last_page = (file_len - 1) / 4096;
        zero_page(&mut data, last_page);
        fs::write(wal_path, &data).unwrap();
    }

    remove_lock_file(&fixture.db_path);

    // Earlier entries should survive, entries in last page lost
    verify_recovery_at_least(&fixture, "test_data", 0);
}

/// Simulate power loss: last commit marker torn in half
#[test]
fn test_power_loss_commit_marker_torn() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE commit_torn (id INTEGER PRIMARY KEY, value TEXT NOT NULL, seq INTEGER)",
            (),
        )
        .unwrap();

        // 4 explicit transactions × 5 rows each
        for txn in 0..4 {
            let mut tx = db.begin().unwrap();
            for row in 0..5 {
                let id = txn * 5 + row + 1;
                tx.execute(
                    &format!(
                        "INSERT INTO commit_torn (id, value, seq) VALUES ({}, 'txn{}_row{}', {})",
                        id, txn, row, txn
                    ),
                    (),
                )
                .unwrap();
            }
            tx.commit().unwrap();
        }

        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM commit_torn", ())
            .unwrap();
        assert_eq!(count, 20);
    }

    remove_lock_file(&db_path);

    // Find the last commit marker entry and truncate to cut it in half
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Find commit marker entries
    let commit_entries: Vec<_> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| e.flags & COMMIT_MARKER_FLAG != 0)
        .collect();

    if !commit_entries.is_empty() {
        // Truncate at the middle of the last commit marker
        let (_, last_commit) = commit_entries[commit_entries.len() - 1];
        let cut_point = last_commit.offset + last_commit.total_size / 2;
        fs::write(wal_path, &data[..cut_point]).unwrap();
    }

    let fixture = TestFixture {
        _dir: dir,
        db_path,
        dsn,
    };

    // Last txn's commit marker is torn → treated as uncommitted
    // At least the first 3 txns (15 rows) should survive
    verify_recovery_at_least(&fixture, "commit_torn", 0);
}

// ----------------------------------------------------------------------------
// Gap 4: Large Data / Boundary Conditions (4 tests)
// ----------------------------------------------------------------------------

/// Test rows at compression threshold boundary (63 bytes uncompressed, 65 bytes may compress)
#[test]
fn test_compression_threshold_boundary() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    // Create strings at the compression threshold boundary (64 bytes)
    let small_value = "x".repeat(63); // Below threshold
    let large_value = "y".repeat(65); // Above threshold, may compress

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE threshold_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert rows with values just below threshold
        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO threshold_test (id, value) VALUES ({}, '{}')",
                    i, small_value
                ),
                (),
            )
            .unwrap();
        }

        // Insert rows with values just above threshold
        for i in 11..=20 {
            db.execute(
                &format!(
                    "INSERT INTO threshold_test (id, value) VALUES ({}, '{}')",
                    i, large_value
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM threshold_test", ())
            .unwrap();
        assert_eq!(count, 20);
    }

    remove_lock_file(&db_path);

    // Reopen and verify all rows recovered with correct values
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM threshold_test", ())
        .unwrap();
    assert_eq!(count, 20, "All 20 rows should be recovered");

    // Verify values are correct
    let small_count: i64 = db
        .query_one(
            &format!(
                "SELECT COUNT(*) FROM threshold_test WHERE value = '{}'",
                small_value
            ),
            (),
        )
        .unwrap();
    assert_eq!(small_count, 10, "All 10 small rows should match exactly");

    let large_count: i64 = db
        .query_one(
            &format!(
                "SELECT COUNT(*) FROM threshold_test WHERE value = '{}'",
                large_value
            ),
            (),
        )
        .unwrap();
    assert_eq!(large_count, 10, "All 10 large rows should match exactly");
}

/// Large rows (100KB each) with bit corruption → corrupted entry skipped, rest recovered
#[test]
fn test_large_row_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    let large_text = "L".repeat(100_000); // 100KB each

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE large_row (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO large_row (id, value) VALUES ({}, '{}')",
                    i, large_text
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM large_row", ()).unwrap();
        assert_eq!(count, 5);
    }

    remove_lock_file(&db_path);

    // Flip a bit in the data section of the WAL
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    // Find a DML data entry (not DDL, not commit marker) to corrupt
    let dml_entries: Vec<_> = entries
        .iter()
        .filter(|e| e.flags & COMMIT_MARKER_FLAG == 0 && e.entry_size > 100)
        .collect();

    if !dml_entries.is_empty() {
        // Corrupt one data entry
        let target = dml_entries[dml_entries.len() / 2];
        flip_bit(&mut data, target.data_offset + 50, 5);
        fs::write(wal_path, &data).unwrap();
    }

    // At least some large rows should survive
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM large_row", ());
    match result {
        Ok(count) => {
            assert!(count >= 0, "Should recover some rows, got {}", count);
            db.execute(
                "INSERT INTO large_row (id, value) VALUES (9999, 'post_recovery')",
                (),
            )
            .unwrap();
        }
        Err(_) => {
            // Table DDL was also corrupted — that's valid
        }
    }
}

/// 1000 small rows, corrupt one entry in middle → ≥999 rows recovered
#[test]
fn test_many_small_rows_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE many_rows (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Batch into 10 transactions × 100 rows to avoid 1000 individual WAL commits
        let mut id = 1;
        for _ in 0..10 {
            let mut tx = db.begin().unwrap();
            for _ in 0..100 {
                tx.execute(
                    &format!(
                        "INSERT INTO many_rows (id, value) VALUES ({}, 'small_{}')",
                        id, id
                    ),
                    (),
                )
                .unwrap();
                id += 1;
            }
            tx.commit().unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM many_rows", ()).unwrap();
        assert_eq!(count, 1000);
    }

    remove_lock_file(&db_path);

    // Corrupt one entry in the middle of the WAL
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);

    if entries.len() > 10 {
        // Corrupt a single entry in the middle
        let mid_entry = &entries[entries.len() / 2];
        // Zero the CRC to ensure it's detected as corrupt
        zero_range(&mut data, mid_entry.crc_offset, CRC_SIZE);
        fs::write(wal_path, &data).unwrap();
    }

    // Most rows should survive — only the corrupted entry's data lost
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM many_rows", ()).unwrap();
    assert!(
        count >= 900,
        "At least 900 of 1000 rows should survive, got {}",
        count
    );
    db.execute(
        "INSERT INTO many_rows (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Mixed-size rows with checkpoint + corruption → all recovered from WAL
#[test]
fn test_mixed_size_rows_with_checkpoint() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    let tiny = "t".repeat(5);
    let medium = "m".repeat(200);
    let large = "L".repeat(50_000);

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE mixed_size (id INTEGER PRIMARY KEY, category TEXT, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: insert mixed sizes
        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO mixed_size (id, category, value) VALUES ({}, 'tiny', '{}')",
                    i, tiny
                ),
                (),
            )
            .unwrap();
        }
        for i in 6..=10 {
            db.execute(
                &format!(
                    "INSERT INTO mixed_size (id, category, value) VALUES ({}, 'medium', '{}')",
                    i, medium
                ),
                (),
            )
            .unwrap();
        }
        for i in 11..=13 {
            db.execute(
                &format!(
                    "INSERT INTO mixed_size (id, category, value) VALUES ({}, 'large', '{}')",
                    i, large
                ),
                (),
            )
            .unwrap();
        }

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: more mixed rows after checkpoint
        for i in 14..=18 {
            db.execute(
                &format!(
                    "INSERT INTO mixed_size (id, category, value) VALUES ({}, 'tiny', '{}')",
                    i, tiny
                ),
                (),
            )
            .unwrap();
        }
        for i in 19..=23 {
            db.execute(
                &format!(
                    "INSERT INTO mixed_size (id, category, value) VALUES ({}, 'medium', '{}')",
                    i, medium
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM mixed_size", ()).unwrap();
        assert_eq!(count, 23);
    }

    remove_lock_file(&db_path);

    // Reopen → volumes provide phase 1 (13 rows), WAL provides phase 2 (10 rows)
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM mixed_size", ()).unwrap();
    assert_eq!(count, 23, "All 23 mixed-size rows should be recovered");

    // Verify each category
    let tiny_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM mixed_size WHERE category = 'tiny'",
            (),
        )
        .unwrap();
    assert_eq!(tiny_count, 10, "10 tiny rows expected");

    let medium_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM mixed_size WHERE category = 'medium'",
            (),
        )
        .unwrap();
    assert_eq!(medium_count, 10, "10 medium rows expected");

    let large_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM mixed_size WHERE category = 'large'",
            (),
        )
        .unwrap();
    assert_eq!(large_count, 3, "3 large rows expected");

    // Verify DB is usable
    db.execute(
        "INSERT INTO mixed_size (id, category, value) VALUES (9999, 'post', 'recovery')",
        (),
    )
    .unwrap();
}

// ----------------------------------------------------------------------------
// Gap 5: WAL Truncation, Replay & Size Limits (4 tests)
// ----------------------------------------------------------------------------

/// Two snapshots trigger WAL truncation → WAL file is replaced,
/// post-truncation data in new WAL + snapshot = full recovery
#[test]
fn test_wal_truncation_and_replay() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: data + first checkpoint
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_test (id, value) VALUES ({}, 'phase1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        let wal_before = find_wal_files(&db_path);
        let wal_size_before = total_wal_size(&db_path);

        // Phase 2: more data + second checkpoint (triggers WAL truncation via safe_truncation)
        for i in 21..=40 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_test (id, value) VALUES ({}, 'phase2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // After 2 snapshots, WAL should have been truncated (old entries removed)
        let wal_after = find_wal_files(&db_path);
        let wal_size_after = total_wal_size(&db_path);

        // WAL file name should have changed (truncation creates a new file)
        if !wal_before.is_empty() && !wal_after.is_empty() {
            assert_ne!(
                wal_before[0].file_name(),
                wal_after[0].file_name(),
                "WAL filename should change after truncation"
            );
        }

        // WAL should be smaller (old entries were truncated)
        assert!(
            wal_size_after <= wal_size_before,
            "WAL should not grow after truncation: before={}, after={}",
            wal_size_before,
            wal_size_after
        );

        // Phase 3: data after truncation (only in new WAL, not in any snapshot)
        for i in 41..=50 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_test (id, value) VALUES ({}, 'phase3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
        assert_eq!(count, 50);
    }

    remove_lock_file(&db_path);

    // Reopen — snapshot provides phase1+phase2, new WAL provides phase3
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
    assert_eq!(
        count, 50,
        "All 50 rows should be recovered (snapshot + truncated WAL)"
    );

    db.execute(
        "INSERT INTO trunc_test (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// WAL truncation + corrupt new WAL → snapshot still provides earlier data
#[test]
fn test_wal_truncation_then_corrupt_new_wal() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_corrupt (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1 + checkpoint
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_corrupt (id, value) VALUES ({}, 'p1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 2 + second checkpoint → triggers truncation
        for i in 21..=40 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_corrupt (id, value) VALUES ({}, 'p2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 3: only in new (truncated) WAL
        for i in 41..=50 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_corrupt (id, value) VALUES ({}, 'p3_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    // Corrupt the post-truncation WAL file
    let wal_files = find_wal_files(&db_path);
    assert!(!wal_files.is_empty());
    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    if data.len() > 64 {
        // Zero a big chunk of the WAL — destroys phase 3 data
        let mid = data.len() / 2;
        let len = (data.len() - mid).min(256);
        zero_range(&mut data, mid, len);
        fs::write(wal_path, &data).unwrap();
    }

    // Snapshot has phase1+phase2 (40 rows). Phase 3 (10 rows) is in corrupted WAL.
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM trunc_corrupt", ())
        .unwrap();
    // Snapshot guarantees at least 40 rows from phases 1+2
    assert!(
        count >= 40,
        "Snapshot should provide at least 40 rows, got {}",
        count
    );

    db.execute(
        "INSERT INTO trunc_corrupt (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// WAL entry with entry_size field corrupted to exceed 64MB sanity limit → skipped
#[test]
fn test_wal_entry_size_exceeds_sanity_limit() {
    let fixture = setup_test_db(10, 1);
    let wal_files = find_wal_files(&fixture.db_path);
    assert!(!wal_files.is_empty());

    let wal_path = &wal_files[wal_files.len() - 1];
    let mut data = fs::read(wal_path).unwrap();
    let entries = find_entry_boundaries(&data);
    assert!(entries.len() >= 2, "Need at least 2 entries");

    // Corrupt one entry's size field to be > 64MB (the sanity limit)
    // Entry size is at offset +24 in the header (4 bytes, little-endian)
    let target = &entries[entries.len() / 2];
    let size_offset = target.offset + 24;
    // Write 0x05000000 = ~83MB > 64MB sanity limit
    let huge_size: u32 = 70 * 1024 * 1024;
    data[size_offset..size_offset + 4].copy_from_slice(&huge_size.to_le_bytes());
    fs::write(wal_path, &data).unwrap();

    remove_lock_file(&fixture.db_path);

    // Recovery should skip the entry with impossible size and recover what it can
    verify_recovery_at_least(&fixture, "test_data", 0);
}

/// Large WAL with data spread across many pages → full replay succeeds
#[test]
fn test_large_wal_full_replay() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE large_wal (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Each row gets a unique ~500-byte string that doesn't compress well.
        // Use varying characters based on id to defeat LZ4.
        let mut id = 1;
        for _ in 0..10 {
            let mut tx = db.begin().unwrap();
            for _ in 0..50 {
                // Build a high-entropy string: cycle through printable ASCII based on id
                // Alphanumeric only — safe for SQL, 62 distinct chars defeats LZ4
                const CHARS: &[u8] =
                    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                let value: String = (0..500)
                    .map(|j| CHARS[((id * 7 + j * 13 + 37) % CHARS.len() as i32) as usize] as char)
                    .collect();
                db.execute(
                    &format!(
                        "INSERT INTO large_wal (id, value) VALUES ({}, '{}')",
                        id, value
                    ),
                    (),
                )
                .unwrap();
                id += 1;
            }
            tx.commit().unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM large_wal", ()).unwrap();
        assert_eq!(count, 500);
    }

    remove_lock_file(&db_path);

    // Verify WAL is substantial — unique data per row means LZ4 can't compress it away
    let wal_size = total_wal_size(&db_path);
    assert!(
        wal_size > 100_000,
        "WAL should be > 100KB with high-entropy data, got {} bytes",
        wal_size
    );

    // Reopen — full replay of large WAL
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM large_wal", ()).unwrap();
    assert_eq!(
        count, 500,
        "All 500 rows should be recovered from large WAL"
    );

    // Verify a specific row's value survived correctly
    let row1_value: String = db
        .query_one("SELECT value FROM large_wal WHERE id = 1", ())
        .unwrap();
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let expected: String = (0..500)
        .map(|j| CHARS[((7 + j * 13 + 37) % CHARS.len() as i32) as usize] as char)
        .collect();
    assert_eq!(row1_value, expected, "Row 1 value should match exactly");

    db.execute(
        "INSERT INTO large_wal (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

// ----------------------------------------------------------------------------
// Gap 5b: WAL Rotation Tests (4 tests)
// These verify that wal_max_size config actually triggers rotation in production
// and that rotated files are cleaned up after snapshot-based truncation.
// ----------------------------------------------------------------------------

/// WAL rotation fires during normal commits when wal_max_size is small.
/// Multiple WAL files appear on disk, and multi-file replay recovers all data.
#[test]
fn test_wal_rotation_and_replay() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    // wal_max_size=500 triggers rotation after a few inserts
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_test", ()).unwrap();
        assert_eq!(count, 50);
    }

    // Verify multiple WAL files exist on disk (rotation happened)
    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Expected multiple WAL files from rotation, got {}",
        wal_files.len()
    );

    remove_lock_file(&db_path);

    // Reopen — multi-file replay should recover all 50 rows
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_test", ()).unwrap();
    assert_eq!(
        count, 50,
        "All 50 rows should be recovered from multi-file WAL replay"
    );

    // Verify DB is usable after recovery
    db.execute(
        "INSERT INTO rot_test (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Corrupt the oldest rotated WAL file — DDL may be lost but newer data survives.
#[test]
fn test_wal_rotation_oldest_corrupt() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_oldest (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_oldest (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Need multiple WAL files, got {}",
        wal_files.len()
    );

    // Corrupt the oldest WAL file (first in sorted order)
    let oldest = &wal_files[0];
    let mut data = fs::read(oldest).unwrap();
    if data.len() > 32 {
        let mid = data.len() / 2;
        let len = (data.len() - mid).min(256);
        zero_range(&mut data, mid, len);
        fs::write(oldest, &data).unwrap();
    }

    remove_lock_file(&db_path);

    // Recovery: DDL is in the oldest WAL. If it's corrupted, table may not exist.
    // But if DDL survived (only data entries were corrupted), newer WAL data survives.
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM rot_oldest", ());
    match result {
        Ok(count) => {
            // Some rows should survive from the non-corrupted WAL files
            assert!(
                count > 0,
                "At least some rows should survive from newer WAL files"
            );
        }
        Err(_) => {
            // Table doesn't exist — DDL was in the corrupted portion.
            // This is acceptable behavior: corruption of the first WAL file
            // can lose the CREATE TABLE statement.
        }
    }
}

/// Corrupt the newest rotated WAL file — older WAL data survives.
#[test]
fn test_wal_rotation_newest_corrupt() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_newest (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_newest (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }

    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Need multiple WAL files, got {}",
        wal_files.len()
    );

    // Zero out the newest (last) WAL file entirely
    let newest = &wal_files[wal_files.len() - 1];
    let len = fs::metadata(newest).unwrap().len() as usize;
    fs::write(newest, vec![0u8; len]).unwrap();

    remove_lock_file(&db_path);

    // Recovery: oldest WAL files should provide DDL + earlier rows.
    // With wal_max_size=500, most data is in older files, so zeroing the
    // newest file may lose only the last few rows (or none if it was empty).
    let db = Database::open(&dsn).unwrap();
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM rot_newest", ());
    match result {
        Ok(count) => {
            // Data from older WAL files should survive
            assert!(
                count > 0,
                "At least some rows should survive from older WAL files, got {}",
                count
            );
            // At most all 50 rows (if newest file had no unique data)
            assert!(count <= 50);
        }
        Err(_) => {
            // If DDL was in the newest file (unlikely with wal_max_size=500),
            // the table might not exist. This is still acceptable.
        }
    }
}

/// WAL rotation + snapshot-based truncation cleans up old rotated files.
/// Three snapshots are needed: 2nd triggers truncation to 1st's LSN (cleans phase 1 files),
/// 3rd triggers truncation to 2nd's LSN (cleans phase 2 files).
#[test]
fn test_wal_rotation_snapshot_cleans_old_files() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_clean (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: Generate multiple rotated WAL files
        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_clean (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let wal_phase1 = find_wal_files(&db_path);
        assert!(
            wal_phase1.len() >= 2,
            "Expected multiple WAL files from rotation, got {}",
            wal_phase1.len()
        );

        // First checkpoint — no truncation yet (need 2 checkpoints for safe truncation)
        let _ = db.execute("PRAGMA CHECKPOINT", ());

        // Phase 2: More data
        for i in 51..=80 {
            db.execute(
                &format!(
                    "INSERT INTO rot_clean (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Second checkpoint — truncation cleans phase 1 WAL data
        let wal_size_before_snap2 = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_size_after_snap2 = total_wal_size(&db_path);

        // WAL should shrink after checkpoint (old entries truncated)
        assert!(
            wal_size_after_snap2 < wal_size_before_snap2,
            "WAL size should decrease after 2nd checkpoint: before={}, after={}",
            wal_size_before_snap2,
            wal_size_after_snap2
        );

        // Phase 3: A few more rows + 3rd checkpoint
        for i in 81..=90 {
            db.execute(
                &format!(
                    "INSERT INTO rot_clean (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
        let wal_size_before_snap3 = total_wal_size(&db_path);
        let _ = db.execute("PRAGMA CHECKPOINT", ());
        let wal_size_after_snap3 = total_wal_size(&db_path);

        // After 3rd checkpoint, WAL should shrink again
        assert!(
            wal_size_after_snap3 < wal_size_before_snap3,
            "WAL size should decrease after 3rd checkpoint: before={}, after={}",
            wal_size_before_snap3,
            wal_size_after_snap3
        );

        // Verify all data is still accessible
        let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_clean", ()).unwrap();
        assert_eq!(count, 90);
    }

    remove_lock_file(&db_path);

    // Reopen — snapshot + remaining WAL should recover everything
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_clean", ()).unwrap();
    assert_eq!(
        count, 90,
        "All 90 rows should be recovered after rotation + truncation cleanup"
    );

    db.execute(
        "INSERT INTO rot_clean (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// After two checkpoints with WAL rotation, verify all data survives
/// close/reopen through volume recovery. Both phases should be in volumes.
#[test]
fn test_wal_rotation_cleanup_preserves_boundary_entries() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    let total_rows;
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_boundary (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Phase 1: bulk inserts (many rotations due to small wal_max_size)
        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_boundary (id, value) VALUES ({}, 'phase1_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint 1 — seals phase 1 data into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // Phase 2: more inserts (more rotations)
        for i in 51..=80 {
            db.execute(
                &format!(
                    "INSERT INTO rot_boundary (id, value) VALUES ({}, 'phase2_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint 2 — seals phase 2 data, triggers WAL truncation.
        // cleanup_old_wal_files runs and removes old rotated files.
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        total_rows = 80;
        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM rot_boundary", ())
            .unwrap();
        assert_eq!(count, total_rows);
    }

    remove_lock_file(&db_path);

    // Volumes should provide all data from both phases.
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM rot_boundary", ())
        .unwrap();
    assert_eq!(
        count, total_rows,
        "All {} rows must survive volume recovery (got {}).",
        total_rows, count
    );

    // DB must be usable after recovery
    db.execute(
        "INSERT INTO rot_boundary (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Simulate crash mid-rotation: the new rotated WAL file exists on disk but
/// checkpoint.meta still references the old file. On restart, the DB must
/// discover all WAL files (including the orphaned rotated one) and replay
/// everything without data loss.
#[test]
fn test_wal_rotation_crash_mid_rotate() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_crash (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        // Insert enough rows to trigger several rotations
        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO rot_crash (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_crash", ()).unwrap();
        assert_eq!(count, 50);
    }

    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Need multiple WAL files from rotation, got {}",
        wal_files.len()
    );

    // Simulate crash mid-rotation: rewrite checkpoint.meta to reference an
    // OLDER WAL file (as if the process died after creating the new file but
    // before updating checkpoint.meta).
    let wal_dir = db_path.join("wal");
    let checkpoint_path = wal_dir.join("checkpoint.meta");

    // Delete checkpoint.meta so with_config falls back to scanning all WAL files.
    if checkpoint_path.exists() {
        fs::remove_file(&checkpoint_path).unwrap();
    }

    // Also create a new empty rotated file to simulate the crash scenario:
    // new file was created but no data was written to it yet (crash before any writes).
    let orphan_path = wal_dir.join("wal_99999999-20260101-120000-lsn-999999.log");
    fs::write(&orphan_path, b"").unwrap();

    remove_lock_file(&db_path);

    // Reopen — with_config should scan all WAL files, find the real ones,
    // and replay_two_phase should recover everything from the scattered files.
    let db = Database::open(&dsn).unwrap();
    let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_crash", ()).unwrap();
    assert_eq!(
        count, 50,
        "All 50 rows should be recovered when checkpoint.meta is missing \
         and WAL files must be discovered by scanning"
    );

    // DB must be usable
    db.execute(
        "INSERT INTO rot_crash (id, value) VALUES (9999, 'post_crash')",
        (),
    )
    .unwrap();
}

/// UPDATE and DELETE operations must replay correctly when entries span
/// multiple rotated WAL files.
#[test]
fn test_wal_rotation_update_delete_replay() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!(
        "file://{}?wal_max_size=500&checkpoint_on_close=off",
        db_path.display()
    );

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_upd (id INTEGER PRIMARY KEY, value TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active')",
            (),
        )
        .unwrap();

        // Phase 1: INSERT 30 rows (triggers several rotations)
        for i in 1..=30 {
            db.execute(
                &format!(
                    "INSERT INTO rot_upd (id, value) VALUES ({}, 'original_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Phase 2: UPDATE some rows (these WAL entries land in later rotated files)
        for i in 1..=10 {
            db.execute(
                &format!(
                    "UPDATE rot_upd SET value = 'updated_{}', status = 'modified' WHERE id = {}",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Phase 3: DELETE some rows (more WAL entries in even later files)
        for i in 21..=25 {
            db.execute(&format!("DELETE FROM rot_upd WHERE id = {}", i), ())
                .unwrap();
        }

        // Verify final state: 30 inserted - 5 deleted = 25 rows
        let total: i64 = db.query_one("SELECT COUNT(*) FROM rot_upd", ()).unwrap();
        assert_eq!(total, 25);

        // 10 updated + 15 still active = 25
        let modified: i64 = db
            .query_one("SELECT COUNT(*) FROM rot_upd WHERE status = 'modified'", ())
            .unwrap();
        assert_eq!(modified, 10);

        let active: i64 = db
            .query_one("SELECT COUNT(*) FROM rot_upd WHERE status = 'active'", ())
            .unwrap();
        assert_eq!(active, 15);
    }

    // Verify rotation happened
    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Expected rotation to produce multiple WAL files, got {}",
        wal_files.len()
    );

    remove_lock_file(&db_path);

    // Reopen and verify the exact same state after multi-file replay
    let db = Database::open(&dsn).unwrap();

    let total: i64 = db.query_one("SELECT COUNT(*) FROM rot_upd", ()).unwrap();
    assert_eq!(
        total, 25,
        "Expected 25 rows (30 inserted - 5 deleted) after replay, got {}",
        total
    );

    let modified: i64 = db
        .query_one("SELECT COUNT(*) FROM rot_upd WHERE status = 'modified'", ())
        .unwrap();
    assert_eq!(
        modified, 10,
        "Expected 10 modified rows after replay, got {}",
        modified
    );

    let active: i64 = db
        .query_one("SELECT COUNT(*) FROM rot_upd WHERE status = 'active'", ())
        .unwrap();
    assert_eq!(
        active, 15,
        "Expected 15 active rows after replay, got {}",
        active
    );

    // Verify specific updated values
    let val: String = db
        .query_one("SELECT value FROM rot_upd WHERE id = 5", ())
        .unwrap();
    assert_eq!(val, "updated_5");

    // Verify deleted rows are really gone
    let deleted_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM rot_upd WHERE id BETWEEN 21 AND 25",
            (),
        )
        .unwrap();
    assert_eq!(deleted_count, 0, "Deleted rows should not reappear");

    // DB usable after recovery
    db.execute(
        "INSERT INTO rot_upd (id, value) VALUES (9999, 'post_recovery')",
        (),
    )
    .unwrap();
}

/// Explicit multi-statement transactions must remain atomic when WAL rotation
/// fires between statements within a BEGIN...COMMIT block.
#[test]
fn test_wal_rotation_explicit_transaction() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    // Very small wal_max_size to force rotation mid-transaction
    let dsn = format!("file://{}?wal_max_size=200", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE rot_txn (id INTEGER PRIMARY KEY, value TEXT NOT NULL, batch INTEGER NOT NULL)",
            (),
        )
        .unwrap();

        // 5 explicit transactions, each inserting 6 rows.
        // With wal_max_size=200, rotation WILL fire mid-transaction.
        for batch in 0..5 {
            db.execute("BEGIN", ()).unwrap();
            for row in 0..6 {
                let id = batch * 6 + row + 1;
                db.execute(
                    &format!(
                        "INSERT INTO rot_txn (id, value, batch) VALUES ({}, 'b{}_r{}', {})",
                        id, batch, row, batch
                    ),
                    (),
                )
                .unwrap();
            }
            db.execute("COMMIT", ()).unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_txn", ()).unwrap();
        assert_eq!(count, 30);
    }

    // Verify rotation happened
    let wal_files = find_wal_files(&db_path);
    assert!(
        wal_files.len() >= 2,
        "Expected rotation to fire mid-transaction with wal_max_size=200, got {} files",
        wal_files.len()
    );

    remove_lock_file(&db_path);

    // Reopen — all transactions must replay atomically
    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM rot_txn", ()).unwrap();
    assert_eq!(
        count, 30,
        "All 30 rows from 5 committed transactions should be recovered, got {}",
        count
    );

    // Verify atomicity: each batch must have exactly 6 rows (all-or-nothing)
    for batch in 0..5 {
        let batch_count: i64 = db
            .query_one(
                &format!("SELECT COUNT(*) FROM rot_txn WHERE batch = {}", batch),
                (),
            )
            .unwrap();
        assert_eq!(
            batch_count, 6,
            "Batch {} has {} rows — expected 6 (atomic commit across rotation boundary)",
            batch, batch_count
        );
    }

    // DB usable after recovery
    db.execute(
        "INSERT INTO rot_txn (id, value, batch) VALUES (9999, 'post', 99)",
        (),
    )
    .unwrap();
}

// ============================================================================
// Gap closure: DROP INDEX durability
// ============================================================================

/// DROP INDEX must persist across close/reopen. After recovery, the dropped
/// index must not exist and queries must still work (using table scan).
#[test]
fn test_drop_index_durability() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE idx_drop (id INTEGER PRIMARY KEY, category TEXT NOT NULL, value INTEGER)",
            (),
        )
        .unwrap();

        // Insert data
        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO idx_drop (id, category, value) VALUES ({}, 'cat_{}', {})",
                    i,
                    i % 5,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }

        // Create index, verify it works
        db.execute("CREATE INDEX idx_cat ON idx_drop(category)", ())
            .unwrap();

        let count: i64 = db
            .query_one("SELECT COUNT(*) FROM idx_drop WHERE category = 'cat_0'", ())
            .unwrap();
        assert_eq!(count, 4);

        // Drop the index
        db.execute("DROP INDEX idx_cat ON idx_drop", ()).unwrap();

        // Queries still work after drop (table scan)
        let count2: i64 = db
            .query_one("SELECT COUNT(*) FROM idx_drop WHERE category = 'cat_1'", ())
            .unwrap();
        assert_eq!(count2, 4);
    }

    remove_lock_file(&db_path);

    // Reopen — DROP INDEX must have persisted
    let db = Database::open(&dsn).unwrap();

    // Data must survive
    let count: i64 = db.query_one("SELECT COUNT(*) FROM idx_drop", ()).unwrap();
    assert_eq!(count, 20, "All 20 rows should survive after recovery");

    // Queries still work (index should not exist)
    let count2: i64 = db
        .query_one("SELECT COUNT(*) FROM idx_drop WHERE category = 'cat_2'", ())
        .unwrap();
    assert_eq!(count2, 4);

    // Creating the same index again should succeed (proves it was dropped)
    db.execute("CREATE INDEX idx_cat ON idx_drop(category)", ())
        .unwrap();

    // And the recreated index works
    let count3: i64 = db
        .query_one("SELECT COUNT(*) FROM idx_drop WHERE category = 'cat_3'", ())
        .unwrap();
    assert_eq!(count3, 4);
}

// ============================================================================
// TRUNCATE TABLE durability
// ============================================================================

#[test]
fn test_truncate_table_survives_close_reopen() {
    // TRUNCATE TABLE has its own WAL operation type (TruncateTable=13).
    // After close/reopen, the table should exist but be empty.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_test (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_test (id, value) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
        assert_eq!(count, 50);

        db.execute("TRUNCATE TABLE trunc_test", ()).unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
        assert_eq!(count, 0);
    }

    remove_lock_file(&db_path);

    // Reopen — table should exist but be empty
    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
    assert_eq!(count, 0, "TRUNCATE should persist — table must be empty");

    // Table is usable — can insert new data
    db.execute(
        "INSERT INTO trunc_test (id, value) VALUES (1, 'after_truncate')",
        (),
    )
    .unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_test", ()).unwrap();
    assert_eq!(count, 1);
}

#[test]
fn test_truncate_table_then_insert_survives_close_reopen() {
    // TRUNCATE followed by new inserts — both operations must persist.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_ins (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_ins (id, value) VALUES ({}, 'old_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        db.execute("TRUNCATE TABLE trunc_ins", ()).unwrap();

        // Insert new data after truncate
        for i in 100..=105 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_ins (id, value) VALUES ({}, 'new_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_ins", ()).unwrap();
        assert_eq!(count, 6);
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_ins", ()).unwrap();
    assert_eq!(count, 6, "Only post-truncate rows should exist");

    // Verify old data is gone
    let old: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM trunc_ins WHERE value LIKE 'old_%'",
            (),
        )
        .unwrap();
    assert_eq!(old, 0, "Pre-truncate rows must not reappear");

    let new: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM trunc_ins WHERE value LIKE 'new_%'",
            (),
        )
        .unwrap();
    assert_eq!(new, 6, "Post-truncate rows must all survive");
}

#[test]
fn test_truncate_table_with_checkpoint_recovery() {
    // Checkpoint taken before TRUNCATE, then TRUNCATE, then close/reopen.
    // WAL replay of TRUNCATE must override volume data.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_snap (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=30 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_snap (id, value) VALUES ({}, 'snap_row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint seals all 30 rows into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // TRUNCATE after checkpoint
        db.execute("TRUNCATE TABLE trunc_snap", ()).unwrap();

        // Insert a few new rows
        for i in 100..=102 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_snap (id, value) VALUES ({}, 'post_trunc_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_snap", ()).unwrap();
        assert_eq!(count, 3);
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM trunc_snap", ()).unwrap();
    assert_eq!(
        count, 3,
        "Only post-truncate rows should exist after checkpoint + WAL replay"
    );

    // Volume data must NOT reappear
    let old: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM trunc_snap WHERE value LIKE 'snap_row_%'",
            (),
        )
        .unwrap();
    assert_eq!(old, 0, "Volume data must not survive TRUNCATE in WAL");
}

#[test]
fn test_truncate_with_index_recovery() {
    // TRUNCATE should clear index state too. After recovery, index queries must
    // return correct (empty or post-truncate) results.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE trunc_idx (id INTEGER PRIMARY KEY, category TEXT NOT NULL, val INTEGER)",
            (),
        )
        .unwrap();

        db.execute("CREATE INDEX idx_trunc_cat ON trunc_idx(category)", ())
            .unwrap();

        for i in 1..=40 {
            db.execute(
                &format!(
                    "INSERT INTO trunc_idx (id, category, val) VALUES ({}, 'cat_{}', {})",
                    i,
                    i % 4,
                    i * 10
                ),
                (),
            )
            .unwrap();
        }

        db.execute("TRUNCATE TABLE trunc_idx", ()).unwrap();

        // Insert a few rows after truncate
        db.execute(
            "INSERT INTO trunc_idx (id, category, val) VALUES (100, 'cat_0', 999)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let total: i64 = db.query_one("SELECT COUNT(*) FROM trunc_idx", ()).unwrap();
    assert_eq!(total, 1, "Only the post-truncate row should exist");

    let cat0: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM trunc_idx WHERE category = 'cat_0'",
            (),
        )
        .unwrap();
    assert_eq!(
        cat0, 1,
        "Index query should find only the post-truncate row"
    );

    let cat1: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM trunc_idx WHERE category = 'cat_1'",
            (),
        )
        .unwrap();
    assert_eq!(cat1, 0, "Pre-truncate index entries must be gone");
}

// ============================================================================
// ALTER TABLE durability
// ============================================================================

#[test]
fn test_alter_table_add_column_durability() {
    // ALTER TABLE ADD COLUMN is recorded in WAL. Must survive close/reopen.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE alter_add (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO alter_add (id, name) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Add a new column
        db.execute("ALTER TABLE alter_add ADD COLUMN score INTEGER", ())
            .unwrap();

        // Insert row using the new column
        db.execute(
            "INSERT INTO alter_add (id, name, score) VALUES (11, 'with_score', 100)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM alter_add", ()).unwrap();
    assert_eq!(count, 11, "All 11 rows should survive");

    // The new column must exist — query it
    let score: i64 = db
        .query_one("SELECT score FROM alter_add WHERE id = 11", ())
        .unwrap();
    assert_eq!(score, 100, "New column value must survive recovery");

    // Old rows should have NULL for the new column
    let null_count: i64 = db
        .query_one("SELECT COUNT(*) FROM alter_add WHERE score IS NULL", ())
        .unwrap();
    assert_eq!(
        null_count, 10,
        "Old rows should have NULL in the new column"
    );

    // Can insert using the new schema
    db.execute(
        "INSERT INTO alter_add (id, name, score) VALUES (12, 'post_recovery', 200)",
        (),
    )
    .unwrap();
}

#[test]
fn test_alter_table_drop_column_durability() {
    // ALTER TABLE DROP COLUMN must persist across close/reopen.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE alter_drop (id INTEGER PRIMARY KEY, name TEXT NOT NULL, extra TEXT)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO alter_drop (id, name, extra) VALUES ({}, 'row_{}', 'extra_{}')",
                    i, i, i
                ),
                (),
            )
            .unwrap();
        }

        db.execute("ALTER TABLE alter_drop DROP COLUMN extra", ())
            .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM alter_drop", ()).unwrap();
    assert_eq!(count, 10, "All rows should survive");

    // 'extra' column must not exist
    let result: Result<i64, _> = db.query_one(
        "SELECT COUNT(*) FROM alter_drop WHERE extra IS NOT NULL",
        (),
    );
    assert!(
        result.is_err(),
        "Column 'extra' should not exist after DROP COLUMN recovery"
    );

    // Can insert using the reduced schema
    db.execute(
        "INSERT INTO alter_drop (id, name) VALUES (11, 'post_recovery')",
        (),
    )
    .unwrap();
}

#[test]
fn test_alter_table_rename_column_durability() {
    // ALTER TABLE RENAME COLUMN must persist across close/reopen.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE alter_rename (id INTEGER PRIMARY KEY, old_name TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO alter_rename (id, old_name) VALUES ({}, 'val_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        db.execute(
            "ALTER TABLE alter_rename RENAME COLUMN old_name TO new_name",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // New column name must work
    let count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM alter_rename WHERE new_name IS NOT NULL",
            (),
        )
        .unwrap();
    assert_eq!(count, 5, "All rows accessible via renamed column");

    // Old column name must not work
    let result: Result<i64, _> = db.query_one(
        "SELECT COUNT(*) FROM alter_rename WHERE old_name IS NOT NULL",
        (),
    );
    assert!(
        result.is_err(),
        "Old column name 'old_name' should not exist after RENAME recovery"
    );

    // Can insert using new column name
    db.execute(
        "INSERT INTO alter_rename (id, new_name) VALUES (6, 'post_recovery')",
        (),
    )
    .unwrap();
}

#[test]
fn test_alter_table_rename_table_durability() {
    // ALTER TABLE RENAME TO must persist across close/reopen.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE old_tbl (id INTEGER PRIMARY KEY, data TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!("INSERT INTO old_tbl (id, data) VALUES ({}, 'row_{}')", i, i),
                (),
            )
            .unwrap();
        }

        db.execute("ALTER TABLE old_tbl RENAME TO new_tbl", ())
            .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // New name must work
    let count: i64 = db.query_one("SELECT COUNT(*) FROM new_tbl", ()).unwrap();
    assert_eq!(
        count, 10,
        "All rows should be accessible via new table name"
    );

    // Old name must not work
    let result: Result<i64, _> = db.query_one("SELECT COUNT(*) FROM old_tbl", ());
    assert!(
        result.is_err(),
        "Old table name 'old_tbl' should not exist after RENAME recovery"
    );

    // Can insert via new name
    db.execute(
        "INSERT INTO new_tbl (id, data) VALUES (11, 'post_recovery')",
        (),
    )
    .unwrap();
}

#[test]
fn test_alter_table_with_checkpoint_recovery() {
    // ALTER TABLE after checkpoint — WAL replay must apply schema changes on top of volume state.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE alter_snap (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO alter_snap (id, name) VALUES ({}, 'row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint seals the original 2-column schema into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // ALTER after checkpoint
        db.execute("ALTER TABLE alter_snap ADD COLUMN status TEXT", ())
            .unwrap();

        db.execute(
            "INSERT INTO alter_snap (id, name, status) VALUES (11, 'new_row', 'active')",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM alter_snap", ()).unwrap();
    assert_eq!(count, 11, "All 11 rows should survive");

    // New column must exist
    let status: String = db
        .query_one("SELECT status FROM alter_snap WHERE id = 11", ())
        .unwrap();
    assert_eq!(status, "active", "New column value must survive");

    // Old rows have NULL for the new column
    let null_count: i64 = db
        .query_one("SELECT COUNT(*) FROM alter_snap WHERE status IS NULL", ())
        .unwrap();
    assert_eq!(null_count, 10);
}

#[test]
fn test_alter_table_multiple_operations_durability() {
    // Multiple ALTER operations on the same table in sequence.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE alter_multi (id INTEGER PRIMARY KEY, a TEXT, b TEXT, c TEXT)",
            (),
        )
        .unwrap();

        for i in 1..=5 {
            db.execute(
                &format!(
                    "INSERT INTO alter_multi (id, a, b, c) VALUES ({}, 'a{}', 'b{}', 'c{}')",
                    i, i, i, i
                ),
                (),
            )
            .unwrap();
        }

        // Chain of ALTER operations
        db.execute("ALTER TABLE alter_multi DROP COLUMN c", ())
            .unwrap();
        db.execute("ALTER TABLE alter_multi ADD COLUMN d INTEGER", ())
            .unwrap();
        db.execute("ALTER TABLE alter_multi RENAME COLUMN b TO beta", ())
            .unwrap();

        db.execute(
            "INSERT INTO alter_multi (id, a, beta, d) VALUES (6, 'a6', 'beta6', 42)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM alter_multi", ())
        .unwrap();
    assert_eq!(count, 6, "All rows should survive");

    // Column 'c' must not exist
    let result: Result<i64, _> =
        db.query_one("SELECT COUNT(*) FROM alter_multi WHERE c IS NOT NULL", ());
    assert!(result.is_err(), "Column 'c' should be dropped");

    // Column 'beta' must exist (renamed from 'b')
    let beta_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM alter_multi WHERE beta IS NOT NULL",
            (),
        )
        .unwrap();
    assert_eq!(beta_count, 6, "Column 'beta' (renamed from 'b') must exist");

    // Column 'd' must exist
    let d_val: i64 = db
        .query_one("SELECT d FROM alter_multi WHERE id = 6", ())
        .unwrap();
    assert_eq!(d_val, 42, "New column 'd' must have correct value");
}

// ============================================================================
// Empty table recovery
// ============================================================================

#[test]
fn test_empty_table_survives_close_reopen() {
    // CREATE TABLE with zero data rows. DDL must persist even without data entries.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE empty_tbl (id INTEGER PRIMARY KEY, value TEXT)",
            (),
        )
        .unwrap();
        // No inserts — table is empty
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM empty_tbl", ()).unwrap();
    assert_eq!(count, 0, "Empty table should exist with 0 rows");

    // Can insert into the recovered empty table
    db.execute(
        "INSERT INTO empty_tbl (id, value) VALUES (1, 'first_row')",
        (),
    )
    .unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM empty_tbl", ()).unwrap();
    assert_eq!(count, 1);
}

#[test]
fn test_multiple_empty_tables_survive() {
    // Multiple empty tables created in sequence — all must survive.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute("CREATE TABLE empty_a (id INTEGER PRIMARY KEY)", ())
            .unwrap();
        db.execute(
            "CREATE TABLE empty_b (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE empty_c (id INTEGER PRIMARY KEY, x INTEGER, y INTEGER)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    for tbl in &["empty_a", "empty_b", "empty_c"] {
        let count: i64 = db
            .query_one(&format!("SELECT COUNT(*) FROM {}", tbl), ())
            .unwrap();
        assert_eq!(count, 0, "Table '{}' should exist and be empty", tbl);
    }

    // All tables usable
    db.execute("INSERT INTO empty_a (id) VALUES (1)", ())
        .unwrap();
    db.execute("INSERT INTO empty_b (id, name) VALUES (1, 'test')", ())
        .unwrap();
    db.execute("INSERT INTO empty_c (id, x, y) VALUES (1, 10, 20)", ())
        .unwrap();
}

#[test]
fn test_empty_table_with_index_survives() {
    // CREATE TABLE + CREATE INDEX with zero data. Both must survive.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE empty_idx (id INTEGER PRIMARY KEY, category TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute("CREATE INDEX idx_empty_cat ON empty_idx(category)", ())
            .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM empty_idx", ()).unwrap();
    assert_eq!(count, 0);

    // Insert and query via index
    db.execute("INSERT INTO empty_idx (id, category) VALUES (1, 'A')", ())
        .unwrap();

    let cat_count: i64 = db
        .query_one("SELECT COUNT(*) FROM empty_idx WHERE category = 'A'", ())
        .unwrap();
    assert_eq!(
        cat_count, 1,
        "Index should work after recovery of empty table"
    );
}

// ============================================================================
// NULL value durability
// ============================================================================

#[test]
fn test_null_values_survive_wal_recovery() {
    // Insert rows with NULL in nullable columns. NULL must not become a default value.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE null_test (id INTEGER PRIMARY KEY, name TEXT, score INTEGER, active BOOLEAN)",
            (),
        )
        .unwrap();

        // Mix of NULL and non-NULL values
        db.execute(
            "INSERT INTO null_test (id, name, score, active) VALUES (1, 'alice', 100, TRUE)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO null_test (id, name, score, active) VALUES (2, NULL, NULL, NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO null_test (id, name, score, active) VALUES (3, 'charlie', NULL, TRUE)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO null_test (id, name, score, active) VALUES (4, NULL, 50, NULL)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let total: i64 = db.query_one("SELECT COUNT(*) FROM null_test", ()).unwrap();
    assert_eq!(total, 4, "All 4 rows must survive");

    // Verify NULLs are preserved, not coerced to defaults
    let null_names: i64 = db
        .query_one("SELECT COUNT(*) FROM null_test WHERE name IS NULL", ())
        .unwrap();
    assert_eq!(null_names, 2, "Rows 2 and 4 should have NULL name");

    let null_scores: i64 = db
        .query_one("SELECT COUNT(*) FROM null_test WHERE score IS NULL", ())
        .unwrap();
    assert_eq!(null_scores, 2, "Rows 2 and 3 should have NULL score");

    let null_active: i64 = db
        .query_one("SELECT COUNT(*) FROM null_test WHERE active IS NULL", ())
        .unwrap();
    assert_eq!(null_active, 2, "Rows 2 and 4 should have NULL active");

    // Non-NULL values are correct
    let alice_score: i64 = db
        .query_one("SELECT score FROM null_test WHERE id = 1", ())
        .unwrap();
    assert_eq!(alice_score, 100);

    let charlie_active: bool = db
        .query_one("SELECT active FROM null_test WHERE id = 3", ())
        .unwrap();
    assert!(charlie_active);
}

#[test]
fn test_null_values_survive_checkpoint_recovery() {
    // NULLs must survive through checkpoint (not just WAL).
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE null_snap (id INTEGER PRIMARY KEY, val TEXT, num FLOAT)",
            (),
        )
        .unwrap();

        db.execute(
            "INSERT INTO null_snap (id, val, num) VALUES (1, 'hello', 3.14)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO null_snap (id, val, num) VALUES (2, NULL, NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO null_snap (id, val, num) VALUES (3, NULL, 2.71)",
            (),
        )
        .unwrap();

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let total: i64 = db.query_one("SELECT COUNT(*) FROM null_snap", ()).unwrap();
    assert_eq!(total, 3);

    let null_vals: i64 = db
        .query_one("SELECT COUNT(*) FROM null_snap WHERE val IS NULL", ())
        .unwrap();
    assert_eq!(null_vals, 2, "NULLs must survive volume serialization");

    let null_nums: i64 = db
        .query_one("SELECT COUNT(*) FROM null_snap WHERE num IS NULL", ())
        .unwrap();
    assert_eq!(null_nums, 1, "Row 2 should have NULL num");

    let val: f64 = db
        .query_one("SELECT num FROM null_snap WHERE id = 3", ())
        .unwrap();
    assert!(
        (val - 2.71).abs() < 0.001,
        "Non-NULL float must be preserved"
    );
}

// ============================================================================
// Multiple consecutive crash-recovery cycles
// ============================================================================

#[test]
fn test_multiple_crash_recovery_cycles() {
    // Simulate: write data → corrupt WAL → recover → write more → close → reopen → verify
    // Tests that recovery writes valid WAL that can itself be recovered.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    // Cycle 1: Create table and insert initial data, then corrupt
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE cycle_test (id INTEGER PRIMARY KEY, cycle INTEGER NOT NULL, value TEXT)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO cycle_test (id, cycle, value) VALUES ({}, 1, 'cycle1_row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Corrupt: truncate last WAL entry
    let wal_files = find_wal_files(&db_path);
    if !wal_files.is_empty() {
        let wal_path = &wal_files[wal_files.len() - 1];
        let data = fs::read(wal_path).unwrap();
        let entries = find_entry_boundaries(&data);
        if entries.len() >= 2 {
            let last = &entries[entries.len() - 1];
            let truncated = &data[..last.offset];
            fs::write(wal_path, truncated).unwrap();
        }
    }

    // Cycle 2: Recover from corruption, write more data
    let cycle1_count: i64;
    {
        let db = Database::open(&dsn).unwrap();
        cycle1_count = db.query_one("SELECT COUNT(*) FROM cycle_test", ()).unwrap();
        assert!(
            cycle1_count > 0,
            "Should recover at least some cycle 1 data"
        );

        for i in 100..=110 {
            db.execute(
                &format!(
                    "INSERT INTO cycle_test (id, cycle, value) VALUES ({}, 2, 'cycle2_row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Corrupt again: flip a bit in the WAL
    let wal_files = find_wal_files(&db_path);
    if !wal_files.is_empty() {
        let wal_path = &wal_files[wal_files.len() - 1];
        let mut data = fs::read(wal_path).unwrap();
        let entries = find_entry_boundaries(&data);
        if entries.len() >= 3 {
            // Flip a bit in a middle entry's data
            let mid = &entries[entries.len() / 2];
            if mid.data_offset + 5 < data.len() {
                flip_bit(&mut data, mid.data_offset + 5, 3);
                fs::write(wal_path, &data).unwrap();
            }
        }
    }

    // Cycle 3: Recover from second corruption, write more data
    let cycle2_count: i64;
    {
        let db = Database::open(&dsn).unwrap();
        cycle2_count = db.query_one("SELECT COUNT(*) FROM cycle_test", ()).unwrap();
        assert!(
            cycle2_count >= cycle1_count,
            "Cycle 3 recovery ({}) should have at least cycle 1 data ({})",
            cycle2_count,
            cycle1_count
        );

        for i in 200..=205 {
            db.execute(
                &format!(
                    "INSERT INTO cycle_test (id, cycle, value) VALUES ({}, 3, 'cycle3_row_{}')",
                    i, i
                ),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Cycle 4: Clean recovery — no corruption. Everything from cycle 3 must survive.
    {
        let db = Database::open(&dsn).unwrap();
        let final_count: i64 = db.query_one("SELECT COUNT(*) FROM cycle_test", ()).unwrap();
        assert!(
            final_count >= cycle2_count + 6,
            "Final count ({}) should include cycle 3 inserts (>= {})",
            final_count,
            cycle2_count + 6
        );

        // Verify cycle 3 data is intact (no corruption was applied)
        let c3: i64 = db
            .query_one("SELECT COUNT(*) FROM cycle_test WHERE cycle = 3", ())
            .unwrap();
        assert_eq!(
            c3, 6,
            "All 6 cycle 3 rows must survive (no corruption applied)"
        );

        // DB is usable
        db.execute(
            "INSERT INTO cycle_test (id, cycle, value) VALUES (999, 4, 'final')",
            (),
        )
        .unwrap();
    }
}

#[test]
fn test_crash_recovery_with_checkpoint_between_cycles() {
    // Cycle 1: insert → checkpoint → close
    // Cycle 2: corrupt WAL → recover from volumes → insert more → close
    // Cycle 3: reopen → all data from both cycles present
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    // Cycle 1
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE snap_cycle (id INTEGER PRIMARY KEY, phase INTEGER NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=20 {
            db.execute(
                &format!("INSERT INTO snap_cycle (id, phase) VALUES ({}, 1)", i),
                (),
            )
            .unwrap();
        }

        db.execute("PRAGMA CHECKPOINT", ()).unwrap();
    }
    remove_lock_file(&db_path);

    // Corrupt WAL after checkpoint
    let wal_files = find_wal_files(&db_path);
    if !wal_files.is_empty() {
        let wal_path = &wal_files[wal_files.len() - 1];
        let mut data = fs::read(wal_path).unwrap();
        // Zero last 4KB page
        let file_len = data.len();
        if file_len > 4096 {
            let last_page = (file_len - 1) / 4096;
            zero_page(&mut data, last_page);
            fs::write(wal_path, &data).unwrap();
        }
    }

    // Cycle 2: recover (volumes provide base), insert more
    {
        let db = Database::open(&dsn).unwrap();
        let count: i64 = db.query_one("SELECT COUNT(*) FROM snap_cycle", ()).unwrap();
        // Volumes had 20 rows; WAL may have partial additional data
        assert!(
            count >= 20,
            "Volumes should guarantee at least 20 rows, got {}",
            count
        );

        for i in 100..=110 {
            db.execute(
                &format!("INSERT INTO snap_cycle (id, phase) VALUES ({}, 2)", i),
                (),
            )
            .unwrap();
        }
    }
    remove_lock_file(&db_path);

    // Cycle 3: clean recovery
    {
        let db = Database::open(&dsn).unwrap();
        let total: i64 = db.query_one("SELECT COUNT(*) FROM snap_cycle", ()).unwrap();
        assert!(
            total >= 31,
            "Should have at least 20 (volumes) + 11 (cycle 2) = 31 rows, got {}",
            total
        );

        let phase2: i64 = db
            .query_one("SELECT COUNT(*) FROM snap_cycle WHERE phase = 2", ())
            .unwrap();
        assert_eq!(
            phase2, 11,
            "All cycle 2 inserts must survive clean recovery"
        );
    }
}

// ============================================================================
// DEFAULT constraint enforcement after recovery
// ============================================================================

#[test]
fn test_default_constraint_after_recovery() {
    // DEFAULT values must be applied correctly after recovery.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE def_test (id INTEGER PRIMARY KEY, name TEXT NOT NULL, status TEXT DEFAULT 'pending', priority INTEGER DEFAULT 0)",
            (),
        )
        .unwrap();

        // Insert without specifying default columns
        db.execute("INSERT INTO def_test (id, name) VALUES (1, 'task_1')", ())
            .unwrap();
        // Insert with explicit values overriding defaults
        db.execute(
            "INSERT INTO def_test (id, name, status, priority) VALUES (2, 'task_2', 'active', 5)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM def_test", ()).unwrap();
    assert_eq!(count, 2);

    // After recovery, inserting should still apply defaults
    db.execute("INSERT INTO def_test (id, name) VALUES (3, 'task_3')", ())
        .unwrap();

    let status: String = db
        .query_one("SELECT status FROM def_test WHERE id = 3", ())
        .unwrap();
    assert_eq!(
        status, "pending",
        "DEFAULT value must be applied after recovery"
    );

    let priority: i64 = db
        .query_one("SELECT priority FROM def_test WHERE id = 3", ())
        .unwrap();
    assert_eq!(
        priority, 0,
        "DEFAULT integer value must be applied after recovery"
    );
}

// ============================================================================
// BOOLEAN and TIMESTAMP column types durability
// ============================================================================

#[test]
fn test_boolean_column_durability() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE bool_test (id INTEGER PRIMARY KEY, flag BOOLEAN NOT NULL, optional_flag BOOLEAN)",
            (),
        )
        .unwrap();

        db.execute(
            "INSERT INTO bool_test (id, flag, optional_flag) VALUES (1, TRUE, FALSE)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO bool_test (id, flag, optional_flag) VALUES (2, FALSE, TRUE)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO bool_test (id, flag, optional_flag) VALUES (3, TRUE, NULL)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM bool_test", ()).unwrap();
    assert_eq!(count, 3);

    let true_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bool_test WHERE flag = TRUE", ())
        .unwrap();
    assert_eq!(true_count, 2, "TRUE values must survive recovery");

    let false_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bool_test WHERE flag = FALSE", ())
        .unwrap();
    assert_eq!(false_count, 1, "FALSE values must survive recovery");

    let null_opt: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM bool_test WHERE optional_flag IS NULL",
            (),
        )
        .unwrap();
    assert_eq!(null_opt, 1, "NULL boolean must survive recovery");
}

#[test]
fn test_timestamp_column_durability() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE ts_test (id INTEGER PRIMARY KEY, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP)",
            (),
        )
        .unwrap();

        db.execute(
            "INSERT INTO ts_test (id, created_at, updated_at) VALUES (1, '2024-01-15 10:30:00', '2024-06-20 14:00:00')",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO ts_test (id, created_at, updated_at) VALUES (2, '2024-12-31 23:59:59', NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO ts_test (id, created_at, updated_at) VALUES (3, '2020-01-01 00:00:00', '2020-01-01 00:00:01')",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM ts_test", ()).unwrap();
    assert_eq!(count, 3);

    // Verify timestamps are not corrupted by checking ordering
    let ordered_count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM ts_test WHERE created_at >= '2024-01-01 00:00:00'",
            (),
        )
        .unwrap();
    assert_eq!(
        ordered_count, 2,
        "Timestamp comparison must work after recovery"
    );

    let null_updated: i64 = db
        .query_one("SELECT COUNT(*) FROM ts_test WHERE updated_at IS NULL", ())
        .unwrap();
    assert_eq!(null_updated, 1, "NULL timestamp must survive recovery");

    // Verify EXTRACT works on recovered timestamps
    let year: i64 = db
        .query_one(
            "SELECT EXTRACT(YEAR FROM created_at) FROM ts_test WHERE id = 2",
            (),
        )
        .unwrap();
    assert_eq!(year, 2024, "EXTRACT from recovered timestamp must work");
}

// ============================================================================
// Checkpoint with UPDATE/DELETE then close/reopen (volume + WAL recovery)
// ============================================================================

#[test]
fn test_update_after_checkpoint_recovery() {
    // Original rows sealed into volumes via checkpoint. Then UPDATE/DELETE in WAL.
    // Close and reopen — volumes provide base, WAL provides UPDATE/DELETE.
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}?checkpoint_on_close=off", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE upd_snap (id INTEGER PRIMARY KEY, value TEXT NOT NULL, version INTEGER)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO upd_snap (id, value, version) VALUES ({}, 'original_{}', 1)",
                    i, i
                ),
                (),
            )
            .unwrap();
        }

        // Checkpoint to seal original data into volumes
        db.execute("PRAGMA CHECKPOINT", ()).unwrap();

        // UPDATE some rows after checkpoint
        db.execute(
            "UPDATE upd_snap SET value = 'updated_5', version = 2 WHERE id = 5",
            (),
        )
        .unwrap();
        db.execute(
            "UPDATE upd_snap SET value = 'updated_10', version = 2 WHERE id = 10",
            (),
        )
        .unwrap();

        // DELETE a row after checkpoint
        db.execute("DELETE FROM upd_snap WHERE id = 3", ()).unwrap();
    }
    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let total: i64 = db.query_one("SELECT COUNT(*) FROM upd_snap", ()).unwrap();
    assert_eq!(total, 9, "10 inserted - 1 deleted = 9 rows");

    // Updated rows have new values
    let v5: String = db
        .query_one("SELECT value FROM upd_snap WHERE id = 5", ())
        .unwrap();
    assert_eq!(v5, "updated_5", "UPDATE must be replayed from WAL");

    let v10: String = db
        .query_one("SELECT value FROM upd_snap WHERE id = 10", ())
        .unwrap();
    assert_eq!(v10, "updated_10");

    // Deleted row must not exist
    let deleted: i64 = db
        .query_one("SELECT COUNT(*) FROM upd_snap WHERE id = 3", ())
        .unwrap();
    assert_eq!(deleted, 0, "DELETE must be replayed from WAL");

    // Unmodified rows still have original values
    let v1: String = db
        .query_one("SELECT value FROM upd_snap WHERE id = 1", ())
        .unwrap();
    assert_eq!(v1, "original_1");
}

// ============================================================================
// Multi-column UNIQUE index enforcement after recovery
// ============================================================================

#[test]
fn test_multi_column_unique_index_enforced_after_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE mc_unique (id INTEGER PRIMARY KEY, a TEXT NOT NULL, b TEXT NOT NULL, data TEXT)",
            (),
        )
        .unwrap();

        db.execute("CREATE UNIQUE INDEX idx_mc_ab ON mc_unique(a, b)", ())
            .unwrap();

        db.execute(
            "INSERT INTO mc_unique (id, a, b, data) VALUES (1, 'x', 'y', 'first')",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO mc_unique (id, a, b, data) VALUES (2, 'x', 'z', 'second')",
            (),
        )
        .unwrap();
        db.execute(
            "INSERT INTO mc_unique (id, a, b, data) VALUES (3, 'w', 'y', 'third')",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db.query_one("SELECT COUNT(*) FROM mc_unique", ()).unwrap();
    assert_eq!(count, 3);

    // Duplicate (a='x', b='y') must be rejected after recovery
    let result = db.execute(
        "INSERT INTO mc_unique (id, a, b, data) VALUES (4, 'x', 'y', 'duplicate')",
        (),
    );
    assert!(
        result.is_err(),
        "Multi-column UNIQUE constraint must be enforced after recovery"
    );

    // Different combination is allowed
    db.execute(
        "INSERT INTO mc_unique (id, a, b, data) VALUES (4, 'x', 'w', 'allowed')",
        (),
    )
    .unwrap();
}

// ============================================================================
// ALTER TABLE MODIFY COLUMN durability
// ============================================================================

/// ALTER TABLE MODIFY COLUMN must persist type and nullability changes
/// across close/reopen. The WAL records this as AlterTable op_type=4.
#[test]
fn test_alter_table_modify_column_durability() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE modify_test (id INTEGER PRIMARY KEY, score INTEGER NOT NULL, label TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=10 {
            db.execute(
                &format!(
                    "INSERT INTO modify_test (id, score, label) VALUES ({}, {}, 'item_{}')",
                    i,
                    i * 10,
                    i
                ),
                (),
            )
            .unwrap();
        }

        // Change score from NOT NULL to nullable
        db.execute("ALTER TABLE modify_test MODIFY COLUMN score INTEGER", ())
            .unwrap();

        // Insert a row with NULL score to prove the change took effect
        db.execute(
            "INSERT INTO modify_test (id, score, label) VALUES (11, NULL, 'null_score')",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // All rows must survive
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_test", ())
        .unwrap();
    assert_eq!(count, 11, "All 11 rows should survive after recovery");

    // Original data intact
    let score: i64 = db
        .query_one("SELECT score FROM modify_test WHERE id = 5", ())
        .unwrap();
    assert_eq!(score, 50, "Original score values must be preserved");

    // NULL score must survive (proves MODIFY to nullable persisted)
    let null_count: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_test WHERE score IS NULL", ())
        .unwrap();
    assert_eq!(
        null_count, 1,
        "NULL score row must survive — MODIFY COLUMN nullable change must persist"
    );

    // Can still insert NULL after recovery (proves schema change persisted)
    db.execute(
        "INSERT INTO modify_test (id, score, label) VALUES (12, NULL, 'post_recovery_null')",
        (),
    )
    .unwrap();

    let null_count2: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_test WHERE score IS NULL", ())
        .unwrap();
    assert_eq!(
        null_count2, 2,
        "Post-recovery NULL insert must work after MODIFY COLUMN"
    );
}

/// ALTER TABLE MODIFY COLUMN with snapshot — WAL replay must apply
/// the type change on top of snapshot state.
#[test]
fn test_alter_table_modify_column_with_snapshot() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE modify_snap (id INTEGER PRIMARY KEY, value TEXT NOT NULL, flag BOOLEAN NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=20 {
            db.execute(
                &format!(
                    "INSERT INTO modify_snap (id, value, flag) VALUES ({}, 'v_{}', {})",
                    i,
                    i,
                    if i % 2 == 0 { "TRUE" } else { "FALSE" }
                ),
                (),
            )
            .unwrap();
        }

        // Snapshot captures current schema (value NOT NULL, flag NOT NULL)
        db.execute("PRAGMA snapshot", ()).unwrap();

        // MODIFY after snapshot — must be replayed from WAL on recovery
        db.execute("ALTER TABLE modify_snap MODIFY COLUMN value TEXT", ())
            .unwrap();

        db.execute("ALTER TABLE modify_snap MODIFY COLUMN flag BOOLEAN", ())
            .unwrap();

        // Insert rows using new nullable schema
        db.execute(
            "INSERT INTO modify_snap (id, value, flag) VALUES (21, NULL, NULL)",
            (),
        )
        .unwrap();
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_snap", ())
        .unwrap();
    assert_eq!(count, 21, "All 21 rows must survive snapshot + WAL replay");

    // NULL values from post-MODIFY insert must survive
    let null_value_count: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_snap WHERE value IS NULL", ())
        .unwrap();
    assert_eq!(
        null_value_count, 1,
        "NULL value row must survive — MODIFY COLUMN must replay over snapshot"
    );

    let null_flag_count: i64 = db
        .query_one("SELECT COUNT(*) FROM modify_snap WHERE flag IS NULL", ())
        .unwrap();
    assert_eq!(
        null_flag_count, 1,
        "NULL flag row must survive — MODIFY COLUMN must replay over snapshot"
    );

    // Post-recovery inserts with NULLs must work
    db.execute(
        "INSERT INTO modify_snap (id, value, flag) VALUES (22, NULL, TRUE)",
        (),
    )
    .unwrap();

    db.execute(
        "INSERT INTO modify_snap (id, value, flag) VALUES (23, 'hello', NULL)",
        (),
    )
    .unwrap();
}

// ============================================================================
// Bitmap index durability
// ============================================================================

/// Bitmap index created with USING BITMAP must survive close/reopen.
/// This exercises the bitmap-specific WAL serialization (index_type byte = 2)
/// and the BitmapIndex reconstruction path in create_index_from_metadata.
#[test]
fn test_bitmap_index_durability() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE bitmap_test (id INTEGER PRIMARY KEY, active BOOLEAN NOT NULL, category TEXT NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=50 {
            db.execute(
                &format!(
                    "INSERT INTO bitmap_test (id, active, category) VALUES ({}, {}, '{}')",
                    i,
                    if i % 3 == 0 { "TRUE" } else { "FALSE" },
                    if i % 4 == 0 {
                        "A"
                    } else if i % 4 == 1 {
                        "B"
                    } else if i % 4 == 2 {
                        "C"
                    } else {
                        "D"
                    }
                ),
                (),
            )
            .unwrap();
        }

        // Create explicit bitmap indexes
        db.execute(
            "CREATE INDEX idx_active_bitmap ON bitmap_test(active) USING BITMAP",
            (),
        )
        .unwrap();

        db.execute(
            "CREATE INDEX idx_cat_bitmap ON bitmap_test(category) USING BITMAP",
            (),
        )
        .unwrap();

        // Verify indexes work before close
        let active_count: i64 = db
            .query_one("SELECT COUNT(*) FROM bitmap_test WHERE active = TRUE", ())
            .unwrap();
        assert_eq!(active_count, 16); // 3,6,9,...,48 → 16 values

        let cat_a_count: i64 = db
            .query_one("SELECT COUNT(*) FROM bitmap_test WHERE category = 'A'", ())
            .unwrap();
        assert_eq!(cat_a_count, 12); // 4,8,12,...,48 → 12 values
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    // All data must survive
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test", ())
        .unwrap();
    assert_eq!(count, 50, "All 50 rows must survive recovery");

    // Bitmap index on active must work after recovery
    let active_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test WHERE active = TRUE", ())
        .unwrap();
    assert_eq!(
        active_count, 16,
        "Bitmap index on active must return correct results after recovery"
    );

    let inactive_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test WHERE active = FALSE", ())
        .unwrap();
    assert_eq!(
        inactive_count, 34,
        "Bitmap index on active=FALSE must return correct results after recovery"
    );

    // Bitmap index on category must work after recovery
    let cat_b_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test WHERE category = 'B'", ())
        .unwrap();
    assert_eq!(
        cat_b_count, 13,
        "Bitmap index on category must return correct results after recovery"
    );

    // Inserts after recovery must update the bitmap index
    db.execute(
        "INSERT INTO bitmap_test (id, active, category) VALUES (51, TRUE, 'A')",
        (),
    )
    .unwrap();

    let new_active_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test WHERE active = TRUE", ())
        .unwrap();
    assert_eq!(
        new_active_count, 17,
        "Bitmap index must handle post-recovery inserts"
    );

    let new_cat_a_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_test WHERE category = 'A'", ())
        .unwrap();
    assert_eq!(
        new_cat_a_count, 13,
        "Bitmap index on category must handle post-recovery inserts"
    );
}

/// Bitmap index with snapshot — the index definition must survive snapshot + WAL replay.
#[test]
fn test_bitmap_index_with_snapshot_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE bitmap_snap (id INTEGER PRIMARY KEY, status BOOLEAN NOT NULL)",
            (),
        )
        .unwrap();

        for i in 1..=30 {
            db.execute(
                &format!(
                    "INSERT INTO bitmap_snap (id, status) VALUES ({}, {})",
                    i,
                    if i % 2 == 0 { "TRUE" } else { "FALSE" }
                ),
                (),
            )
            .unwrap();
        }

        // Snapshot before index creation
        db.execute("PRAGMA snapshot", ()).unwrap();

        // Create bitmap index after snapshot — must be replayed from WAL
        db.execute(
            "CREATE INDEX idx_status_bm ON bitmap_snap(status) USING BITMAP",
            (),
        )
        .unwrap();

        // Insert more data after index creation
        for i in 31..=40 {
            db.execute(
                &format!("INSERT INTO bitmap_snap (id, status) VALUES ({}, TRUE)", i),
                (),
            )
            .unwrap();
        }
    }

    remove_lock_file(&db_path);

    let db = Database::open(&dsn).unwrap();

    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_snap", ())
        .unwrap();
    assert_eq!(count, 40, "All 40 rows must survive snapshot + WAL replay");

    // Bitmap index must work — 15 TRUE from first batch + 10 TRUE from second
    let true_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_snap WHERE status = TRUE", ())
        .unwrap();
    assert_eq!(
        true_count, 25,
        "Bitmap index must return correct results after snapshot + WAL replay"
    );

    let false_count: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_snap WHERE status = FALSE", ())
        .unwrap();
    assert_eq!(
        false_count, 15,
        "Bitmap index must return correct FALSE count after recovery"
    );

    // Dropping and recreating the bitmap index should work (proves it was recovered)
    db.execute("DROP INDEX idx_status_bm ON bitmap_snap", ())
        .unwrap();
    db.execute(
        "CREATE INDEX idx_status_bm ON bitmap_snap(status) USING BITMAP",
        (),
    )
    .unwrap();

    let recheck: i64 = db
        .query_one("SELECT COUNT(*) FROM bitmap_snap WHERE status = TRUE", ())
        .unwrap();
    assert_eq!(recheck, 25, "Recreated bitmap index must work correctly");
}

/// FK constraints must survive snapshot + WAL truncation recovery.
/// Tests that the snapshot serializer preserves FK metadata so enforcement
/// works after the WAL entries that created the table are truncated away.
#[test]
fn test_foreign_key_with_snapshot_recovery() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.db");
    let dsn = format!("file://{}", db_path.display());

    {
        let db = Database::open(&dsn).unwrap();

        // Create parent + child with FK constraints
        db.execute(
            "CREATE TABLE fk_parent (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE fk_child (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES fk_parent(id) ON DELETE CASCADE, val TEXT)",
            (),
        )
        .unwrap();

        // Insert parent rows
        for i in 1..=5 {
            db.execute(
                &format!("INSERT INTO fk_parent (id, name) VALUES ({}, 'p{}')", i, i),
                (),
            )
            .unwrap();
        }
        // Insert child rows referencing parents
        for i in 1..=10 {
            let parent_id = (i % 5) + 1;
            db.execute(
                &format!(
                    "INSERT INTO fk_child (id, parent_id, val) VALUES ({}, {}, 'c{}')",
                    i, parent_id, i
                ),
                (),
            )
            .unwrap();
        }

        // Take TWO snapshots so WAL truncation can happen
        db.execute("PRAGMA snapshot", ()).unwrap();
        // Insert one more row to force a WAL entry after the first snapshot
        db.execute("INSERT INTO fk_parent (id, name) VALUES (100, 'extra')", ())
            .unwrap();
        db.execute("PRAGMA snapshot", ()).unwrap();
    }

    remove_lock_file(&db_path);

    // Reopen — schema should be loaded from snapshot (WAL may be truncated)
    let db = Database::open(&dsn).unwrap();

    // Verify data survived
    let parent_count: i64 = db.query_one("SELECT COUNT(*) FROM fk_parent", ()).unwrap();
    assert_eq!(parent_count, 6, "All 6 parent rows must survive");

    let child_count: i64 = db.query_one("SELECT COUNT(*) FROM fk_child", ()).unwrap();
    assert_eq!(child_count, 10, "All 10 child rows must survive");

    // FK enforcement must still work — insert with invalid parent must fail
    let err = db.execute(
        "INSERT INTO fk_child (id, parent_id, val) VALUES (99, 999, 'bad')",
        (),
    );
    assert!(
        err.is_err(),
        "FK constraint must be enforced after snapshot recovery"
    );

    // CASCADE must still work — delete parent 1, children referencing it should be deleted
    db.execute("DELETE FROM fk_child WHERE parent_id = 100", ())
        .unwrap_or_default(); // clean up extra parent's potential children
    db.execute("DELETE FROM fk_parent WHERE id = 1", ())
        .unwrap();

    let remaining: i64 = db
        .query_one("SELECT COUNT(*) FROM fk_child WHERE parent_id = 1", ())
        .unwrap();
    assert_eq!(
        remaining, 0,
        "CASCADE DELETE must work after snapshot recovery"
    );

    // Valid inserts must still work
    db.execute(
        "INSERT INTO fk_child (id, parent_id, val) VALUES (50, 2, 'valid')",
        (),
    )
    .unwrap();
}

/// Verify that DROP TABLE correctly strips FK references from child tables on WAL replay.
/// Without the fix, child tables retain orphaned FK constraints after recovery,
/// causing INSERT failures with "table not found" for the dropped parent.
#[test]
fn test_drop_parent_strips_child_fk_on_recovery() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("fk_drop_recovery.db");
    let dsn = format!("file://{}", db_path.display());

    // Phase 1: create parent + child, then drop parent
    {
        let db = Database::open(&dsn).unwrap();
        db.execute(
            "CREATE TABLE parent_drop (id INTEGER PRIMARY KEY, name TEXT)",
            (),
        )
        .unwrap();
        db.execute(
            "CREATE TABLE child_drop (
                id INTEGER PRIMARY KEY,
                pid INTEGER REFERENCES parent_drop(id),
                val TEXT
            )",
            (),
        )
        .unwrap();

        // Insert data into parent and child with NULL FK (so drop isn't blocked)
        db.execute("INSERT INTO parent_drop VALUES (1, 'Alice')", ())
            .unwrap();
        db.execute("INSERT INTO child_drop VALUES (1, NULL, 'x')", ())
            .unwrap();

        // Drop parent — in-memory, child FK is stripped
        db.execute("DROP TABLE parent_drop", ()).unwrap();

        // Verify child FK is gone in memory: insert with any pid should work
        db.execute("INSERT INTO child_drop VALUES (2, 999, 'y')", ())
            .unwrap();
    }

    // Phase 2: reopen — WAL replay must strip child FK
    {
        let db = Database::open(&dsn).unwrap();

        // parent_drop must not exist
        let err = db.execute("SELECT * FROM parent_drop", ());
        assert!(err.is_err(), "parent_drop should not exist after recovery");

        // child_drop must exist and FK must be gone
        let count: i64 = db.query_one("SELECT COUNT(*) FROM child_drop", ()).unwrap();
        assert_eq!(count, 2, "child_drop should have 2 rows");

        // Insert with arbitrary pid must succeed (no FK constraint)
        db.execute("INSERT INTO child_drop VALUES (3, 12345, 'z')", ())
            .unwrap();

        let count: i64 = db.query_one("SELECT COUNT(*) FROM child_drop", ()).unwrap();
        assert_eq!(count, 3);
    }
}