interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Write-ahead log for durability and crash recovery.
//!
//! The WAL (Write-Ahead Log) provides atomicity and durability for graph mutations.
//! All operations are logged to the WAL before being applied to the main data file,
//! ensuring that committed transactions can be recovered after a crash.
//!
//! # WAL Entry Format
//!
//! Each WAL entry on disk consists of:
//!
//! ```text
//! ┌──────────────┬──────────────┬───────────────────┐
//! │   CRC32      │    Length    │   Entry Data      │
//! │   (4 bytes)  │   (4 bytes)  │   (variable)      │
//! └──────────────┴──────────────┴───────────────────┘
//! ```
//!
//! - **CRC32**: Checksum of the entry data for corruption detection
//! - **Length**: Length of the serialized entry data in bytes
//! - **Entry Data**: Bincode-serialized [`WalEntry`]
//!
//! # Transaction Protocol
//!
//! 1. `BeginTx` - Start a new transaction
//! 2. Zero or more operation entries (InsertNode, InsertEdge, etc.)
//! 3. `CommitTx` - Mark transaction as committed
//!    - OR `AbortTx` - Mark transaction as aborted
//!
//! Only committed transactions are replayed during recovery.
//!
//! # Recovery Process
//!
//! On database open:
//! 1. Scan WAL for all transactions
//! 2. Identify committed transactions (have BeginTx + CommitTx)
//! 3. Replay committed transactions in order
//! 4. Discard aborted/incomplete transactions
//! 5. Truncate WAL after successful recovery

use serde::{Deserialize, Serialize};

use crate::index::IndexSpec;
use crate::value::{EdgeId, Value, VertexId};

use super::records::{EdgeRecord, NodeRecord};

// =============================================================================
// WAL Header Constants
// =============================================================================

/// Size of the WAL entry header in bytes (CRC32 + Length)
pub const WAL_ENTRY_HEADER_SIZE: usize = 8;

// =============================================================================
// WAL Entry Header
// =============================================================================

/// On-disk header for a WAL entry.
///
/// Each WAL entry is prefixed with this header containing:
/// - A CRC32 checksum of the entry data for integrity verification
/// - The length of the serialized entry data
///
/// # Layout
///
/// ```text
/// Offset | Size | Field
/// -------|------|-------
/// 0      | 4    | crc32
/// 4      | 4    | len
/// ```
#[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub struct WalEntryHeader {
    /// CRC32 checksum of the serialized entry data
    pub crc32: u32,
    /// Length of the serialized entry data in bytes
    pub len: u32,
}

impl WalEntryHeader {
    /// Create a new WAL entry header
    pub fn new(crc32: u32, len: u32) -> Self {
        Self { crc32, len }
    }

    /// Read header from bytes
    ///
    /// # Safety
    ///
    /// Uses `read_unaligned` because the struct is `#[repr(C, packed)]`.
    pub fn from_bytes(bytes: &[u8]) -> Self {
        assert!(
            bytes.len() >= WAL_ENTRY_HEADER_SIZE,
            "Buffer too small for WalEntryHeader"
        );

        unsafe {
            let ptr = bytes.as_ptr() as *const WalEntryHeader;
            ptr.read_unaligned()
        }
    }

    /// Write header to bytes
    ///
    /// # Safety
    ///
    /// Creates a byte slice from the packed struct.
    pub fn to_bytes(&self) -> [u8; WAL_ENTRY_HEADER_SIZE] {
        unsafe {
            let ptr = self as *const WalEntryHeader as *const u8;
            let slice = std::slice::from_raw_parts(ptr, WAL_ENTRY_HEADER_SIZE);
            let mut result = [0u8; WAL_ENTRY_HEADER_SIZE];
            result.copy_from_slice(slice);
            result
        }
    }
}

// =============================================================================
// WAL Entry Types
// =============================================================================

/// A write-ahead log entry representing a database operation.
///
/// WAL entries capture all mutations to the database in a format that can be
/// replayed during crash recovery. Each entry is serialized using bincode
/// and written with a CRC32 checksum for integrity.
///
/// # Transaction Entries
///
/// - [`WalEntry::BeginTx`] - Starts a new transaction
/// - [`WalEntry::CommitTx`] - Marks a transaction as committed
/// - [`WalEntry::AbortTx`] - Marks a transaction as aborted (rolled back)
///
/// # Data Modification Entries
///
/// - [`WalEntry::InsertNode`] - Insert a new vertex
/// - [`WalEntry::InsertEdge`] - Insert a new edge
/// - [`WalEntry::UpdateProperty`] - Modify a property value
/// - [`WalEntry::DeleteNode`] - Delete a vertex
/// - [`WalEntry::DeleteEdge`] - Delete an edge
///
/// # Checkpoint Entry
///
/// - [`WalEntry::Checkpoint`] - Marks a safe truncation point
///
/// # Serialization
///
/// All entries are serialized using bincode. The `NodeRecord` and `EdgeRecord`
/// types are converted to serializable representations for WAL storage.
///
/// # Example
///
/// ```ignore
/// use interstellar::storage::mmap::wal::{WalEntry, WalEntryHeader};
///
/// // Create a begin transaction entry
/// let entry = WalEntry::BeginTx {
///     tx_id: 1,
///     timestamp: 1704067200,
/// };
///
/// // Serialize with bincode
/// let data = bincode::serialize(&entry).unwrap();
///
/// // Create header
/// let crc = crc32fast::hash(&data);
/// let header = WalEntryHeader::new(crc, data.len() as u32);
/// ```
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum WalEntry {
    /// Begin a new transaction.
    ///
    /// Every transaction starts with this entry. The `tx_id` is a unique
    /// identifier that links all operations in the transaction.
    BeginTx {
        /// Unique transaction identifier
        tx_id: u64,
        /// Unix timestamp when the transaction started (seconds since epoch)
        timestamp: u64,
    },

    /// Insert a new vertex into the graph.
    ///
    /// Contains the vertex ID and a serializable copy of the node record.
    InsertNode {
        /// The ID assigned to the new vertex
        id: VertexId,
        /// The node record data
        record: SerializableNodeRecord,
    },

    /// Insert a new edge into the graph.
    ///
    /// Contains the edge ID and a serializable copy of the edge record.
    InsertEdge {
        /// The ID assigned to the new edge
        id: EdgeId,
        /// The edge record data
        record: SerializableEdgeRecord,
    },

    /// Update a property on a vertex or edge.
    ///
    /// Stores both old and new values to support undo/redo operations.
    UpdateProperty {
        /// Whether this is a vertex (true) or edge (false)
        is_vertex: bool,
        /// The element ID (vertex or edge)
        element_id: u64,
        /// String table ID for the property key
        key_id: u32,
        /// Previous value (for rollback)
        old_value: Value,
        /// New value being set
        new_value: Value,
    },

    /// Delete a vertex from the graph.
    ///
    /// The vertex is marked as deleted; its slot may be reused later.
    DeleteNode {
        /// ID of the vertex to delete
        id: VertexId,
    },

    /// Delete an edge from the graph.
    ///
    /// The edge is marked as deleted; its slot may be reused later.
    DeleteEdge {
        /// ID of the edge to delete
        id: EdgeId,
    },

    /// Commit a transaction.
    ///
    /// Marks all operations in this transaction as permanent. During recovery,
    /// only operations from committed transactions are replayed.
    CommitTx {
        /// Transaction ID to commit
        tx_id: u64,
    },

    /// Abort a transaction.
    ///
    /// Marks all operations in this transaction as rolled back. During recovery,
    /// operations from aborted transactions are discarded.
    AbortTx {
        /// Transaction ID to abort
        tx_id: u64,
    },

    /// Create a checkpoint.
    ///
    /// Indicates that all prior committed transactions have been flushed to
    /// the main data file. The WAL can be safely truncated at this point.
    Checkpoint {
        /// Monotonically increasing version number
        version: u64,
    },

    /// Update the schema in the database.
    ///
    /// Contains the serialized schema data and the offset where it was written.
    /// This allows schema changes to be replayed during crash recovery.
    SchemaUpdate {
        /// Byte offset where schema data was written
        offset: u64,
        /// Serialized schema data
        data: Vec<u8>,
    },

    /// Create a property index.
    ///
    /// Contains the index specification. The index will be built from existing
    /// data when this entry is replayed during recovery.
    CreateIndex {
        /// The index specification
        spec: IndexSpec,
    },

    /// Drop a property index.
    ///
    /// Contains the name of the index to drop.
    DropIndex {
        /// Name of the index to drop
        name: String,
    },
}

// =============================================================================
// Serializable Record Types
// =============================================================================

/// A serializable representation of a [`NodeRecord`].
///
/// The on-disk `NodeRecord` uses `#[repr(C, packed)]` which doesn't play well
/// with serde/bincode. This type provides a serializable equivalent that can
/// be converted to/from `NodeRecord`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializableNodeRecord {
    /// Vertex ID (0-based)
    pub id: u64,
    /// String table ID for label
    pub label_id: u32,
    /// Status flags
    pub flags: u32,
    /// First outgoing edge ID (u64::MAX if none)
    pub first_out_edge: u64,
    /// First incoming edge ID (u64::MAX if none)
    pub first_in_edge: u64,
    /// Property list head offset (u64::MAX if none)
    pub prop_head: u64,
}

impl From<NodeRecord> for SerializableNodeRecord {
    fn from(record: NodeRecord) -> Self {
        // Copy fields to avoid unaligned reference issues with packed struct
        Self {
            id: record.id,
            label_id: record.label_id,
            flags: record.flags,
            first_out_edge: record.first_out_edge,
            first_in_edge: record.first_in_edge,
            prop_head: record.prop_head,
        }
    }
}

impl From<SerializableNodeRecord> for NodeRecord {
    fn from(ser: SerializableNodeRecord) -> Self {
        let mut record = NodeRecord::new(ser.id, ser.label_id);
        record.flags = ser.flags;
        record.first_out_edge = ser.first_out_edge;
        record.first_in_edge = ser.first_in_edge;
        record.prop_head = ser.prop_head;
        record
    }
}

/// A serializable representation of an [`EdgeRecord`].
///
/// The on-disk `EdgeRecord` uses `#[repr(C, packed)]` which doesn't play well
/// with serde/bincode. This type provides a serializable equivalent that can
/// be converted to/from `EdgeRecord`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SerializableEdgeRecord {
    /// Edge ID (0-based)
    pub id: u64,
    /// String table ID for label
    pub label_id: u32,
    /// Status flags
    pub flags: u32,
    /// Source vertex ID
    pub src: u64,
    /// Destination vertex ID
    pub dst: u64,
    /// Next outgoing edge from src (u64::MAX if last)
    pub next_out: u64,
    /// Next incoming edge to dst (u64::MAX if last)
    pub next_in: u64,
    /// Property list head offset (u64::MAX if none)
    pub prop_head: u64,
}

impl From<EdgeRecord> for SerializableEdgeRecord {
    fn from(record: EdgeRecord) -> Self {
        // Copy fields to avoid unaligned reference issues with packed struct
        Self {
            id: record.id,
            label_id: record.label_id,
            flags: record.flags,
            src: record.src,
            dst: record.dst,
            next_out: record.next_out,
            next_in: record.next_in,
            prop_head: record.prop_head,
        }
    }
}

impl From<SerializableEdgeRecord> for EdgeRecord {
    fn from(ser: SerializableEdgeRecord) -> Self {
        let mut record = EdgeRecord::new(ser.id, ser.label_id, ser.src, ser.dst);
        record.flags = ser.flags;
        record.next_out = ser.next_out;
        record.next_in = ser.next_in;
        record.prop_head = ser.prop_head;
        record
    }
}

// =============================================================================
// Tests
// =============================================================================

use crate::error::StorageError;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

// =============================================================================
// WriteAheadLog Implementation
// =============================================================================

/// Write-ahead log for transaction durability.
///
/// The `WriteAheadLog` provides atomicity and durability for graph mutations.
/// All operations are logged to the WAL before being applied to the main data file,
/// ensuring that committed transactions can be recovered after a crash.
///
/// # Usage
///
/// ```ignore
/// use interstellar::storage::mmap::wal::{WriteAheadLog, WalEntry};
///
/// let mut wal = WriteAheadLog::open("my_graph.wal")?;
///
/// // Begin a transaction
/// let tx_id = wal.begin_transaction()?;
///
/// // Log operations
/// wal.log(WalEntry::InsertNode { id: VertexId(0), record: node_record.into() })?;
///
/// // Commit the transaction
/// wal.log(WalEntry::CommitTx { tx_id })?;
/// wal.sync()?;
/// ```
///
/// # Thread Safety
///
/// `WriteAheadLog` is NOT thread-safe. It should be protected by an external
/// lock (like `RwLock<WriteAheadLog>`) when used in concurrent contexts.
///
/// # File Format
///
/// Each WAL entry on disk consists of:
/// - 4 bytes: CRC32 checksum of the entry data
/// - 4 bytes: Length of the serialized entry data  
/// - N bytes: Bincode-serialized WalEntry
pub struct WriteAheadLog {
    /// File handle for WAL writes
    file: File,

    /// Next transaction ID to assign
    next_tx_id: AtomicU64,

    /// Reusable buffer for serialization to avoid repeated allocations
    buffer: Vec<u8>,
}

impl WriteAheadLog {
    /// Open or create a WAL file at the given path.
    ///
    /// If the file doesn't exist, it will be created. If it exists, it will be
    /// opened for appending. The file is opened with read, write, and create
    /// permissions.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the WAL file (typically `<database>.wal`)
    ///
    /// # Returns
    ///
    /// A new `WriteAheadLog` instance ready for writing.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if the file cannot be opened or created.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let wal = WriteAheadLog::open("my_graph.wal")?;
    /// ```
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, StorageError> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)?;

        let mut wal = Self {
            file,
            next_tx_id: AtomicU64::new(0),
            buffer: Vec::with_capacity(4096),
        };

        // Scan WAL to find the maximum transaction ID to avoid ID collisions after restart.
        // This fixes a critical bug where next_tx_id would reset to 0 on every open,
        // causing transaction ID reuse after database restart.
        if let Some(max_tx_id) = wal.scan_max_tx_id()? {
            wal.next_tx_id = AtomicU64::new(max_tx_id.saturating_add(1));
        }
        // If no transactions found (empty WAL), next_tx_id stays at 0

        // Seek to end of file for appending new entries
        wal.file.seek(SeekFrom::End(0))?;

        Ok(wal)
    }

    /// Scan the WAL to find the maximum transaction ID.
    ///
    /// This is used during `open()` to initialize `next_tx_id` correctly,
    /// preventing transaction ID collisions after database restart.
    ///
    /// # Returns
    ///
    /// `Some(max_tx_id)` if any transactions were found, `None` if the WAL is empty.
    fn scan_max_tx_id(&mut self) -> Result<Option<u64>, StorageError> {
        // Seek to start of file
        self.file.seek(SeekFrom::Start(0))?;

        let mut max_tx_id: Option<u64> = None;

        // Read all entries and track maximum transaction ID
        loop {
            match self.read_entry() {
                Ok(entry) => {
                    let tx_id = match &entry {
                        WalEntry::BeginTx { tx_id, .. } => Some(*tx_id),
                        WalEntry::CommitTx { tx_id } => Some(*tx_id),
                        WalEntry::AbortTx { tx_id } => Some(*tx_id),
                        _ => None,
                    };
                    if let Some(id) = tx_id {
                        max_tx_id = Some(max_tx_id.map_or(id, |max| max.max(id)));
                    }
                }
                Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    // End of file reached - this is expected
                    break;
                }
                Err(StorageError::WalCorrupted(_)) => {
                    // Corrupted entry at end of file - stop scanning but don't fail
                    // The WAL may have been truncated mid-write during a crash
                    break;
                }
                Err(e) => return Err(e),
            }
        }

        Ok(max_tx_id)
    }

    /// Begin a new transaction.
    ///
    /// This logs a `BeginTx` entry to the WAL and returns a unique transaction ID.
    /// All subsequent operations should use this transaction ID until either
    /// `CommitTx` or `AbortTx` is logged.
    ///
    /// # Returns
    ///
    /// The unique transaction ID assigned to this transaction.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if writing to the WAL fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let tx_id = wal.begin_transaction()?;
    /// // ... perform operations ...
    /// wal.log(WalEntry::CommitTx { tx_id })?;
    /// ```
    pub fn begin_transaction(&mut self) -> Result<u64, StorageError> {
        let tx_id = self.next_tx_id.fetch_add(1, Ordering::SeqCst);

        self.log(WalEntry::BeginTx {
            tx_id,
            timestamp: Self::now(),
        })?;

        Ok(tx_id)
    }

    /// Log an entry to the WAL.
    ///
    /// This serializes the entry using bincode, computes a CRC32 checksum,
    /// and writes the entry to the WAL file. The entry is appended to the
    /// end of the file.
    ///
    /// # Format
    ///
    /// Each entry is written as:
    /// ```text
    /// ┌──────────────┬──────────────┬───────────────────┐
    /// │   CRC32      │    Length    │   Entry Data      │
    /// │   (4 bytes)  │   (4 bytes)  │   (variable)      │
    /// └──────────────┴──────────────┴───────────────────┘
    /// ```
    ///
    /// # Arguments
    ///
    /// * `entry` - The WAL entry to log
    ///
    /// # Returns
    ///
    /// The byte offset where the entry was written (useful for debugging).
    ///
    /// # Errors
    ///
    /// - [`StorageError::Io`] if writing to the file fails
    /// - [`StorageError::WalCorrupted`] if serialization fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// let offset = wal.log(WalEntry::InsertNode {
    ///     id: VertexId(0),
    ///     record: node_record.into(),
    /// })?;
    /// ```
    pub fn log(&mut self, entry: WalEntry) -> Result<u64, StorageError> {
        // Clear and serialize to buffer
        self.buffer.clear();
        bincode::serialize_into(&mut self.buffer, &entry)
            .map_err(|e| StorageError::WalCorrupted(format!("serialization error: {}", e)))?;

        // Calculate CRC32
        let crc = crc32fast::hash(&self.buffer);

        // Create header
        let header = WalEntryHeader::new(crc, self.buffer.len() as u32);
        let header_bytes = header.to_bytes();

        // Seek to end and get current position
        let offset = self.file.seek(SeekFrom::End(0))?;

        // Write header
        self.file.write_all(&header_bytes)?;

        // Write entry data
        self.file.write_all(&self.buffer)?;

        Ok(offset)
    }

    /// Sync the WAL to disk (fsync).
    ///
    /// This ensures all logged entries are durably written to disk. For
    /// transaction durability, `sync()` should be called after logging
    /// the `CommitTx` entry.
    ///
    /// # Performance Note
    ///
    /// `fsync` is relatively expensive (1-5ms on typical SSDs). For better
    /// performance with many small transactions, consider batching multiple
    /// transactions before calling `sync()`.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if the sync operation fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// wal.log(WalEntry::CommitTx { tx_id })?;
    /// wal.sync()?;  // Ensure transaction is durable
    /// ```
    pub fn sync(&mut self) -> Result<(), StorageError> {
        self.file.sync_data()?;
        Ok(())
    }

    /// Get the current Unix timestamp in seconds.
    ///
    /// This is used for transaction timestamps in `BeginTx` entries.
    ///
    /// # Returns
    ///
    /// Seconds since Unix epoch (January 1, 1970).
    fn now() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    }

    /// Get the current file position (for testing).
    ///
    /// Returns the current write position in the WAL file.
    #[cfg(test)]
    fn position(&mut self) -> Result<u64, StorageError> {
        Ok(self.file.seek(SeekFrom::Current(0))?)
    }

    /// Get the current transaction ID counter (for testing).
    #[cfg(test)]
    fn current_tx_id(&self) -> u64 {
        self.next_tx_id.load(Ordering::SeqCst)
    }

    // =========================================================================
    // Reading Methods (Phase 3.4)
    // =========================================================================

    /// Read the next WAL entry from the current file position.
    ///
    /// This reads a single entry from the WAL file, verifying its CRC32 checksum.
    /// The file position is advanced past the entry after reading.
    ///
    /// # Entry Format
    ///
    /// ```text
    /// ┌──────────────┬──────────────┬───────────────────┐
    /// │   CRC32      │    Length    │   Entry Data      │
    /// │   (4 bytes)  │   (4 bytes)  │   (variable)      │
    /// └──────────────┴──────────────┴───────────────────┘
    /// ```
    ///
    /// # Returns
    ///
    /// The deserialized `WalEntry`.
    ///
    /// # Errors
    ///
    /// - [`StorageError::Io`] if reading from the file fails (including EOF)
    /// - [`StorageError::WalCorrupted`] if the CRC32 checksum doesn't match
    /// - [`StorageError::WalCorrupted`] if deserialization fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Seek to start of WAL
    /// wal.seek_to_start()?;
    ///
    /// // Read entries until EOF
    /// loop {
    ///     match wal.read_entry() {
    ///         Ok(entry) => println!("Read: {:?}", entry),
    ///         Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
    ///         Err(e) => return Err(e),
    ///     }
    /// }
    /// ```
    pub fn read_entry(&mut self) -> Result<WalEntry, StorageError> {
        // Read header bytes
        let mut header_bytes = [0u8; WAL_ENTRY_HEADER_SIZE];
        self.file.read_exact(&mut header_bytes)?;

        let header = WalEntryHeader::from_bytes(&header_bytes);
        let crc32 = header.crc32;
        let len = header.len;

        // Validate length to prevent excessive allocation
        if len > 100_000_000 {
            // 100MB limit
            return Err(StorageError::WalCorrupted(format!(
                "entry length {} exceeds maximum",
                len
            )));
        }

        // Read entry data
        let mut entry_data = vec![0u8; len as usize];
        self.file.read_exact(&mut entry_data)?;

        // Verify CRC32
        let computed_crc = crc32fast::hash(&entry_data);
        if computed_crc != crc32 {
            return Err(StorageError::WalCorrupted(format!(
                "CRC32 mismatch: expected {:08x}, got {:08x}",
                crc32, computed_crc
            )));
        }

        // Deserialize entry
        let entry: WalEntry = bincode::deserialize(&entry_data)
            .map_err(|e| StorageError::WalCorrupted(format!("deserialization error: {}", e)))?;

        Ok(entry)
    }

    /// Check if the WAL needs recovery.
    ///
    /// Recovery is needed when there are uncommitted transactions in the WAL.
    /// This scans the entire WAL file looking for `BeginTx` entries without
    /// matching `CommitTx` or `AbortTx` entries.
    ///
    /// # Algorithm
    ///
    /// 1. Scan all WAL entries from the beginning
    /// 2. Track transaction IDs that have started but not completed
    /// 3. Return `true` if any transactions remain open
    ///
    /// # Returns
    ///
    /// - `true` if there are uncommitted transactions requiring recovery
    /// - `false` if the WAL is empty or all transactions are complete
    ///
    /// # Note
    ///
    /// This method seeks to the beginning of the file and reads all entries,
    /// then seeks back to the end. It does not modify the file.
    ///
    /// # Example
    ///
    /// ```ignore
    /// if wal.needs_recovery() {
    ///     println!("WAL recovery required");
    ///     // Perform recovery...
    /// }
    /// ```
    pub fn needs_recovery(&mut self) -> bool {
        // Remember current position
        let original_pos = match self.file.stream_position() {
            Ok(pos) => pos,
            Err(_) => return false,
        };

        // Seek to start
        if self.file.seek(SeekFrom::Start(0)).is_err() {
            return false;
        }

        // Track active transactions
        let mut active_transactions: HashSet<u64> = HashSet::new();

        // Read all entries
        loop {
            match self.read_entry() {
                Ok(entry) => match entry {
                    WalEntry::BeginTx { tx_id, .. } => {
                        active_transactions.insert(tx_id);
                    }
                    WalEntry::CommitTx { tx_id } | WalEntry::AbortTx { tx_id } => {
                        active_transactions.remove(&tx_id);
                    }
                    WalEntry::Checkpoint { .. } => {
                        // Checkpoint means all prior transactions are complete
                        active_transactions.clear();
                    }
                    _ => {
                        // Other entries don't affect transaction state
                    }
                },
                Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    // End of file reached
                    break;
                }
                Err(_) => {
                    // Error reading entry - might indicate incomplete write (needs recovery)
                    // Restore original position
                    let _ = self.file.seek(SeekFrom::Start(original_pos));
                    return true;
                }
            }
        }

        // Restore original position
        let _ = self.file.seek(SeekFrom::Start(original_pos));

        // Recovery needed if there are uncommitted transactions
        !active_transactions.is_empty()
    }

    /// Truncate the WAL file, removing all entries.
    ///
    /// This is called after a successful checkpoint or recovery to clear the WAL.
    /// After truncation, the WAL file will be empty and the file position will
    /// be at the beginning.
    ///
    /// # Safety
    ///
    /// This is a destructive operation. Only call this after ensuring all
    /// committed transactions have been applied to the main data file.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if the truncation or seek fails.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // After successful recovery or checkpoint
    /// wal.truncate()?;
    /// assert_eq!(wal.file_size()?, 0);
    /// ```
    pub fn truncate(&mut self) -> Result<(), StorageError> {
        self.file.set_len(0)?;
        self.file.seek(SeekFrom::Start(0))?;
        Ok(())
    }

    /// Seek to the start of the WAL file.
    ///
    /// This positions the file cursor at the beginning, ready to read entries
    /// from the start.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if the seek fails.
    pub fn seek_to_start(&mut self) -> Result<(), StorageError> {
        self.file.seek(SeekFrom::Start(0))?;
        Ok(())
    }

    /// Get the current size of the WAL file in bytes.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Io`] if getting the file metadata fails.
    pub fn file_size(&self) -> Result<u64, StorageError> {
        let metadata = self.file.metadata()?;
        Ok(metadata.len())
    }

    /// Read all entries from the WAL file.
    ///
    /// This seeks to the beginning of the file and reads all entries,
    /// returning them in order. The file position is left at the end
    /// after reading.
    ///
    /// # Returns
    ///
    /// A vector of all WAL entries in the file.
    ///
    /// # Errors
    ///
    /// - [`StorageError::Io`] if reading fails
    /// - [`StorageError::WalCorrupted`] if any entry is corrupted
    ///
    /// # Example
    ///
    /// ```ignore
    /// let entries = wal.read_all_entries()?;
    /// for entry in entries {
    ///     println!("{:?}", entry);
    /// }
    /// ```
    pub fn read_all_entries(&mut self) -> Result<Vec<WalEntry>, StorageError> {
        self.seek_to_start()?;

        let mut entries = Vec::new();

        loop {
            match self.read_entry() {
                Ok(entry) => entries.push(entry),
                Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    break;
                }
                Err(e) => return Err(e),
            }
        }

        Ok(entries)
    }

    /// Get committed transaction entries from the WAL.
    ///
    /// This reads all entries and returns only those from committed transactions,
    /// in the order they were logged. Entries from aborted or incomplete
    /// transactions are excluded.
    ///
    /// # Returns
    ///
    /// A vector of WAL entries from committed transactions only.
    /// BeginTx and CommitTx entries are excluded from the result.
    ///
    /// # Errors
    ///
    /// - [`StorageError::Io`] if reading fails
    /// - [`StorageError::WalCorrupted`] if any entry is corrupted
    ///
    /// # Example
    ///
    /// ```ignore
    /// let committed = wal.get_committed_entries()?;
    /// for entry in committed {
    ///     // Replay this entry
    /// }
    /// ```
    pub fn get_committed_entries(&mut self) -> Result<Vec<WalEntry>, StorageError> {
        use std::collections::HashMap;

        self.seek_to_start()?;

        // Track entries for each transaction
        let mut tx_entries: HashMap<u64, Vec<WalEntry>> = HashMap::new();
        let mut committed_tx_ids: Vec<u64> = Vec::new();
        let mut current_tx_id: Option<u64> = None;

        loop {
            match self.read_entry() {
                Ok(entry) => match &entry {
                    WalEntry::BeginTx { tx_id, .. } => {
                        current_tx_id = Some(*tx_id);
                        tx_entries.insert(*tx_id, Vec::new());
                    }
                    WalEntry::CommitTx { tx_id } => {
                        committed_tx_ids.push(*tx_id);
                        current_tx_id = None;
                    }
                    WalEntry::AbortTx { tx_id } => {
                        tx_entries.remove(tx_id);
                        current_tx_id = None;
                    }
                    WalEntry::Checkpoint { .. } => {
                        // Checkpoint doesn't contain data to replay
                    }
                    _ => {
                        // Add operation to current transaction
                        if let Some(tx_id) = current_tx_id {
                            if let Some(entries) = tx_entries.get_mut(&tx_id) {
                                entries.push(entry);
                            }
                        }
                    }
                },
                Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    break;
                }
                Err(e) => return Err(e),
            }
        }

        // Collect entries from committed transactions in order
        let mut result = Vec::new();
        for tx_id in committed_tx_ids {
            if let Some(entries) = tx_entries.remove(&tx_id) {
                result.extend(entries);
            }
        }

        Ok(result)
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    // =========================================================================
    // WalEntryHeader Tests
    // =========================================================================

    #[test]
    fn test_wal_entry_header_size() {
        assert_eq!(
            std::mem::size_of::<WalEntryHeader>(),
            WAL_ENTRY_HEADER_SIZE,
            "WalEntryHeader size must be exactly 8 bytes"
        );
    }

    #[test]
    fn test_wal_entry_header_alignment() {
        // crc32: u32 (4 bytes) + len: u32 (4 bytes) = 8 bytes
        assert_eq!(
            std::mem::size_of::<WalEntryHeader>(),
            4 + 4,
            "WalEntryHeader fields should sum to 8 bytes"
        );
    }

    #[test]
    fn test_wal_entry_header_new() {
        let header = WalEntryHeader::new(0x12345678, 256);
        let crc32 = header.crc32;
        let len = header.len;
        assert_eq!(crc32, 0x12345678);
        assert_eq!(len, 256);
    }

    #[test]
    fn test_wal_entry_header_roundtrip() {
        let header = WalEntryHeader::new(0xDEADBEEF, 1024);
        let orig_crc32 = header.crc32;
        let orig_len = header.len;

        let bytes = header.to_bytes();
        assert_eq!(bytes.len(), WAL_ENTRY_HEADER_SIZE);

        let recovered = WalEntryHeader::from_bytes(&bytes);
        let rec_crc32 = recovered.crc32;
        let rec_len = recovered.len;

        assert_eq!(rec_crc32, orig_crc32);
        assert_eq!(rec_len, orig_len);
    }

    #[test]
    fn test_wal_entry_header_byte_order() {
        let header = WalEntryHeader::new(0x01020304, 0x05060708);
        let bytes = header.to_bytes();

        // CRC32 at offset 0 (little-endian)
        let crc_bytes: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
        assert_eq!(crc_bytes[0], 0x04); // LSB first
        assert_eq!(crc_bytes[3], 0x01);

        // len at offset 4 (little-endian)
        let len_bytes: [u8; 4] = [bytes[4], bytes[5], bytes[6], bytes[7]];
        assert_eq!(len_bytes[0], 0x08); // LSB first
        assert_eq!(len_bytes[3], 0x05);
    }

    // =========================================================================
    // WalEntry Serialization Tests
    // =========================================================================

    #[test]
    fn test_begin_tx_serializes() {
        let entry = WalEntry::BeginTx {
            tx_id: 42,
            timestamp: 1704067200,
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_commit_tx_serializes() {
        let entry = WalEntry::CommitTx { tx_id: 123 };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_abort_tx_serializes() {
        let entry = WalEntry::AbortTx { tx_id: 456 };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_checkpoint_serializes() {
        let entry = WalEntry::Checkpoint { version: 789 };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_insert_node_serializes() {
        let record = SerializableNodeRecord {
            id: 100,
            label_id: 5,
            flags: 0,
            first_out_edge: u64::MAX,
            first_in_edge: u64::MAX,
            prop_head: 1024,
        };

        let entry = WalEntry::InsertNode {
            id: VertexId(100),
            record,
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_insert_edge_serializes() {
        let record = SerializableEdgeRecord {
            id: 200,
            label_id: 10,
            flags: 0,
            src: 1,
            dst: 2,
            next_out: u64::MAX,
            next_in: u64::MAX,
            prop_head: 2048,
        };

        let entry = WalEntry::InsertEdge {
            id: EdgeId(200),
            record,
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_update_property_serializes() {
        let entry = WalEntry::UpdateProperty {
            is_vertex: true,
            element_id: 42,
            key_id: 7,
            old_value: Value::Int(10),
            new_value: Value::Int(20),
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_update_property_with_complex_values() {
        let mut old_map = crate::value::ValueMap::new();
        old_map.insert("name".to_string(), Value::String("Alice".to_string()));

        let mut new_map = crate::value::ValueMap::new();
        new_map.insert("name".to_string(), Value::String("Bob".to_string()));
        new_map.insert("age".to_string(), Value::Int(30));

        let entry = WalEntry::UpdateProperty {
            is_vertex: false,
            element_id: 99,
            key_id: 15,
            old_value: Value::Map(old_map),
            new_value: Value::Map(new_map),
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_delete_node_serializes() {
        let entry = WalEntry::DeleteNode { id: VertexId(555) };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    #[test]
    fn test_delete_edge_serializes() {
        let entry = WalEntry::DeleteEdge { id: EdgeId(666) };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    // =========================================================================
    // WalEntry Clone and Debug Tests
    // =========================================================================

    #[test]
    fn test_wal_entry_is_clone() {
        let entry = WalEntry::BeginTx {
            tx_id: 1,
            timestamp: 1000,
        };
        let cloned = entry.clone();
        assert_eq!(entry, cloned);
    }

    #[test]
    fn test_wal_entry_is_debug() {
        let entry = WalEntry::BeginTx {
            tx_id: 1,
            timestamp: 1000,
        };
        let debug_str = format!("{:?}", entry);
        assert!(debug_str.contains("BeginTx"));
        assert!(debug_str.contains("tx_id"));
    }

    // =========================================================================
    // SerializableNodeRecord Tests
    // =========================================================================

    #[test]
    fn test_serializable_node_record_from_node_record() {
        let node = NodeRecord::new(42, 7);
        let ser: SerializableNodeRecord = node.into();

        assert_eq!(ser.id, 42);
        assert_eq!(ser.label_id, 7);
        assert_eq!(ser.flags, 0);
        assert_eq!(ser.first_out_edge, u64::MAX);
        assert_eq!(ser.first_in_edge, u64::MAX);
        assert_eq!(ser.prop_head, u64::MAX);
    }

    #[test]
    fn test_node_record_from_serializable() {
        let ser = SerializableNodeRecord {
            id: 100,
            label_id: 10,
            flags: 1,
            first_out_edge: 200,
            first_in_edge: 300,
            prop_head: 400,
        };

        let node: NodeRecord = ser.into();
        // Copy packed struct fields to local variables before assertions
        let id = node.id;
        let label_id = node.label_id;
        let flags = node.flags;
        let first_out_edge = node.first_out_edge;
        let first_in_edge = node.first_in_edge;
        let prop_head = node.prop_head;

        assert_eq!(id, 100);
        assert_eq!(label_id, 10);
        assert_eq!(flags, 1);
        assert_eq!(first_out_edge, 200);
        assert_eq!(first_in_edge, 300);
        assert_eq!(prop_head, 400);
    }

    #[test]
    fn test_node_record_roundtrip_through_serializable() {
        let mut original = NodeRecord::new(50, 5);
        original.flags = 3;
        original.first_out_edge = 100;
        original.first_in_edge = 200;
        original.prop_head = 300;

        // Copy original values (packed struct fields)
        let orig_id = original.id;
        let orig_label_id = original.label_id;
        let orig_flags = original.flags;
        let orig_first_out = original.first_out_edge;
        let orig_first_in = original.first_in_edge;
        let orig_prop_head = original.prop_head;

        let ser: SerializableNodeRecord = original.into();
        let recovered: NodeRecord = ser.into();

        // Copy recovered values (packed struct fields)
        let rec_id = recovered.id;
        let rec_label_id = recovered.label_id;
        let rec_flags = recovered.flags;
        let rec_first_out = recovered.first_out_edge;
        let rec_first_in = recovered.first_in_edge;
        let rec_prop_head = recovered.prop_head;

        assert_eq!(rec_id, orig_id);
        assert_eq!(rec_label_id, orig_label_id);
        assert_eq!(rec_flags, orig_flags);
        assert_eq!(rec_first_out, orig_first_out);
        assert_eq!(rec_first_in, orig_first_in);
        assert_eq!(rec_prop_head, orig_prop_head);
    }

    // =========================================================================
    // SerializableEdgeRecord Tests
    // =========================================================================

    #[test]
    fn test_serializable_edge_record_from_edge_record() {
        let edge = EdgeRecord::new(42, 7, 10, 20);
        let ser: SerializableEdgeRecord = edge.into();

        assert_eq!(ser.id, 42);
        assert_eq!(ser.label_id, 7);
        assert_eq!(ser.flags, 0);
        assert_eq!(ser.src, 10);
        assert_eq!(ser.dst, 20);
        assert_eq!(ser.next_out, u64::MAX);
        assert_eq!(ser.next_in, u64::MAX);
        assert_eq!(ser.prop_head, u64::MAX);
    }

    #[test]
    fn test_edge_record_from_serializable() {
        let ser = SerializableEdgeRecord {
            id: 100,
            label_id: 10,
            flags: 1,
            src: 5,
            dst: 15,
            next_out: 200,
            next_in: 300,
            prop_head: 400,
        };

        let edge: EdgeRecord = ser.into();
        // Copy packed struct fields to local variables before assertions
        let id = edge.id;
        let label_id = edge.label_id;
        let flags = edge.flags;
        let src = edge.src;
        let dst = edge.dst;
        let next_out = edge.next_out;
        let next_in = edge.next_in;
        let prop_head = edge.prop_head;

        assert_eq!(id, 100);
        assert_eq!(label_id, 10);
        assert_eq!(flags, 1);
        assert_eq!(src, 5);
        assert_eq!(dst, 15);
        assert_eq!(next_out, 200);
        assert_eq!(next_in, 300);
        assert_eq!(prop_head, 400);
    }

    #[test]
    fn test_edge_record_roundtrip_through_serializable() {
        let mut original = EdgeRecord::new(50, 5, 1, 2);
        original.flags = 1;
        original.next_out = 100;
        original.next_in = 200;
        original.prop_head = 300;

        // Copy original values (packed struct fields)
        let orig_id = original.id;
        let orig_label_id = original.label_id;
        let orig_flags = original.flags;
        let orig_src = original.src;
        let orig_dst = original.dst;
        let orig_next_out = original.next_out;
        let orig_next_in = original.next_in;
        let orig_prop_head = original.prop_head;

        let ser: SerializableEdgeRecord = original.into();
        let recovered: EdgeRecord = ser.into();

        // Copy recovered values (packed struct fields)
        let rec_id = recovered.id;
        let rec_label_id = recovered.label_id;
        let rec_flags = recovered.flags;
        let rec_src = recovered.src;
        let rec_dst = recovered.dst;
        let rec_next_out = recovered.next_out;
        let rec_next_in = recovered.next_in;
        let rec_prop_head = recovered.prop_head;

        assert_eq!(rec_id, orig_id);
        assert_eq!(rec_label_id, orig_label_id);
        assert_eq!(rec_flags, orig_flags);
        assert_eq!(rec_src, orig_src);
        assert_eq!(rec_dst, orig_dst);
        assert_eq!(rec_next_out, orig_next_out);
        assert_eq!(rec_next_in, orig_next_in);
        assert_eq!(rec_prop_head, orig_prop_head);
    }

    // =========================================================================
    // All Entry Types Serialize Tests
    // =========================================================================

    #[test]
    fn test_all_entry_types_serialize_with_bincode() {
        let entries = vec![
            WalEntry::BeginTx {
                tx_id: 1,
                timestamp: 1000,
            },
            WalEntry::InsertNode {
                id: VertexId(1),
                record: SerializableNodeRecord {
                    id: 1,
                    label_id: 1,
                    flags: 0,
                    first_out_edge: u64::MAX,
                    first_in_edge: u64::MAX,
                    prop_head: u64::MAX,
                },
            },
            WalEntry::InsertEdge {
                id: EdgeId(1),
                record: SerializableEdgeRecord {
                    id: 1,
                    label_id: 1,
                    flags: 0,
                    src: 0,
                    dst: 1,
                    next_out: u64::MAX,
                    next_in: u64::MAX,
                    prop_head: u64::MAX,
                },
            },
            WalEntry::UpdateProperty {
                is_vertex: true,
                element_id: 0,
                key_id: 0,
                old_value: Value::Null,
                new_value: Value::Int(42),
            },
            WalEntry::DeleteNode { id: VertexId(0) },
            WalEntry::DeleteEdge { id: EdgeId(0) },
            WalEntry::CommitTx { tx_id: 1 },
            WalEntry::AbortTx { tx_id: 2 },
            WalEntry::Checkpoint { version: 1 },
        ];

        for entry in entries {
            let serialized = bincode::serialize(&entry).expect(&format!("serialize {:?}", entry));
            let deserialized: WalEntry =
                bincode::deserialize(&serialized).expect(&format!("deserialize {:?}", entry));
            assert_eq!(
                entry, deserialized,
                "Entry {:?} did not roundtrip correctly",
                entry
            );
        }
    }

    // =========================================================================
    // Constant Value Tests
    // =========================================================================

    #[test]
    fn test_wal_entry_header_size_constant() {
        assert_eq!(WAL_ENTRY_HEADER_SIZE, 8);
    }

    // =========================================================================
    // Value Serialization within WAL Tests
    // =========================================================================

    #[test]
    fn test_wal_entry_with_all_value_types() {
        let value_variants = vec![
            Value::Null,
            Value::Bool(true),
            Value::Bool(false),
            Value::Int(i64::MIN),
            Value::Int(i64::MAX),
            Value::Float(f64::MIN),
            Value::Float(f64::MAX),
            Value::String("test string".to_string()),
            Value::String(String::new()),
            Value::List(vec![Value::Int(1), Value::Bool(true)]),
            Value::List(vec![]),
            Value::Vertex(VertexId(0)),
            Value::Vertex(VertexId(u64::MAX)),
            Value::Edge(EdgeId(0)),
            Value::Edge(EdgeId(u64::MAX)),
        ];

        for old_val in &value_variants {
            for new_val in &value_variants {
                let entry = WalEntry::UpdateProperty {
                    is_vertex: true,
                    element_id: 42,
                    key_id: 7,
                    old_value: old_val.clone(),
                    new_value: new_val.clone(),
                };

                let serialized = bincode::serialize(&entry)
                    .expect(&format!("serialize with {:?} -> {:?}", old_val, new_val));
                let deserialized: WalEntry = bincode::deserialize(&serialized)
                    .expect(&format!("deserialize with {:?} -> {:?}", old_val, new_val));

                assert_eq!(entry, deserialized);
            }
        }
    }

    #[test]
    fn test_wal_entry_with_nested_map_value() {
        let mut inner_map = crate::value::ValueMap::new();
        inner_map.insert("nested_key".to_string(), Value::Int(100));

        let mut outer_map = crate::value::ValueMap::new();
        outer_map.insert("inner".to_string(), Value::Map(inner_map));
        outer_map.insert(
            "list".to_string(),
            Value::List(vec![Value::Int(1), Value::Int(2)]),
        );

        let entry = WalEntry::UpdateProperty {
            is_vertex: false,
            element_id: 1,
            key_id: 2,
            old_value: Value::Null,
            new_value: Value::Map(outer_map),
        };

        let serialized = bincode::serialize(&entry).expect("serialize");
        let deserialized: WalEntry = bincode::deserialize(&serialized).expect("deserialize");

        assert_eq!(entry, deserialized);
    }

    // =========================================================================
    // WriteAheadLog Tests
    // =========================================================================

    #[test]
    fn test_wal_open_creates_new_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");

        assert!(!wal_path.exists(), "WAL file should not exist initially");

        let wal = WriteAheadLog::open(&wal_path).expect("open WAL");
        drop(wal);

        assert!(wal_path.exists(), "WAL file should be created");
    }

    #[test]
    fn test_wal_open_existing_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");

        // Create and write to WAL
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");
            let tx_id = wal.begin_transaction().expect("begin tx");
            assert_eq!(tx_id, 0, "first tx_id should be 0");
        }

        // Re-open and verify tx_id continues from where it left off
        let mut wal = WriteAheadLog::open(&wal_path).expect("reopen WAL");
        let tx_id = wal.begin_transaction().expect("begin another tx");
        // After fix: tx_id should continue from max(0) + 1 = 1
        assert_eq!(
            tx_id, 1,
            "tx_id should continue after reopen, not reset to 0"
        );
    }

    #[test]
    fn test_wal_tx_id_continues_after_multiple_reopens() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");

        // Create WAL and write several transactions
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");
            let tx1 = wal.begin_transaction().expect("begin tx 1");
            wal.log(WalEntry::CommitTx { tx_id: tx1 }).expect("commit");
            let tx2 = wal.begin_transaction().expect("begin tx 2");
            wal.log(WalEntry::CommitTx { tx_id: tx2 }).expect("commit");
            let tx3 = wal.begin_transaction().expect("begin tx 3");
            wal.log(WalEntry::CommitTx { tx_id: tx3 }).expect("commit");
            wal.sync().expect("sync");
            assert_eq!(tx3, 2, "third tx should be 2");
        }

        // Reopen and verify tx_id continues
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("reopen WAL");
            let tx4 = wal.begin_transaction().expect("begin tx 4");
            assert_eq!(tx4, 3, "tx_id should be 3 after reopening with max=2");
            wal.log(WalEntry::CommitTx { tx_id: tx4 }).expect("commit");
            wal.sync().expect("sync");
        }

        // Reopen again
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("reopen WAL again");
            let tx5 = wal.begin_transaction().expect("begin tx 5");
            assert_eq!(tx5, 4, "tx_id should be 4 after second reopen");
        }
    }

    #[test]
    fn test_wal_begin_transaction_returns_unique_ids() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let tx1 = wal.begin_transaction().expect("begin tx 1");
        let tx2 = wal.begin_transaction().expect("begin tx 2");
        let tx3 = wal.begin_transaction().expect("begin tx 3");

        assert_eq!(tx1, 0);
        assert_eq!(tx2, 1);
        assert_eq!(tx3, 2);
    }

    #[test]
    fn test_wal_begin_transaction_increments_counter() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        assert_eq!(wal.current_tx_id(), 0);

        let _ = wal.begin_transaction().expect("begin tx");
        assert_eq!(wal.current_tx_id(), 1);

        let _ = wal.begin_transaction().expect("begin tx");
        assert_eq!(wal.current_tx_id(), 2);
    }

    #[test]
    fn test_wal_log_entry_increases_file_size() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let pos_before = wal.position().expect("get position");
        assert_eq!(pos_before, 0, "should start at position 0");

        let _ = wal.begin_transaction().expect("begin tx");

        let pos_after = wal.position().expect("get position");
        assert!(
            pos_after > pos_before,
            "position should increase after logging"
        );
    }

    #[test]
    fn test_wal_log_returns_offset() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let offset1 = wal
            .log(WalEntry::BeginTx {
                tx_id: 0,
                timestamp: 1000,
            })
            .expect("log entry");
        assert_eq!(offset1, 0, "first entry should be at offset 0");

        let offset2 = wal.log(WalEntry::CommitTx { tx_id: 0 }).expect("log entry");
        assert!(offset2 > offset1, "second entry should be at higher offset");
    }

    #[test]
    fn test_wal_log_multiple_entries() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Log a complete transaction
        let tx_id = wal.begin_transaction().expect("begin tx");

        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert node");

        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert node");

        wal.log(WalEntry::InsertEdge {
            id: EdgeId(0),
            record: SerializableEdgeRecord {
                id: 0,
                label_id: 2,
                flags: 0,
                src: 0,
                dst: 1,
                next_out: u64::MAX,
                next_in: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert edge");

        wal.log(WalEntry::CommitTx { tx_id }).expect("log commit");

        // Verify file has content
        let pos = wal.position().expect("get position");
        assert!(pos > 0, "WAL should have content");
    }

    #[test]
    fn test_wal_sync_succeeds() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::CommitTx { tx_id }).expect("log commit");
        wal.sync().expect("sync should succeed");
    }

    #[test]
    fn test_wal_entries_are_append_only() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Log several entries and track positions
        let offsets: Vec<u64> = (0..5)
            .map(|i| {
                wal.log(WalEntry::BeginTx {
                    tx_id: i,
                    timestamp: 1000 + i,
                })
                .expect("log entry")
            })
            .collect();

        // Verify offsets are strictly increasing
        for i in 1..offsets.len() {
            assert!(
                offsets[i] > offsets[i - 1],
                "offsets should be strictly increasing"
            );
        }
    }

    #[test]
    fn test_wal_crc32_is_written_correctly() {
        use std::io::Read;

        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");

        // Write an entry
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");
            wal.log(WalEntry::BeginTx {
                tx_id: 42,
                timestamp: 1704067200,
            })
            .expect("log entry");
            wal.sync().expect("sync");
        }

        // Read the file and verify CRC
        let mut file = File::open(&wal_path).expect("open file");
        let mut header_bytes = [0u8; WAL_ENTRY_HEADER_SIZE];
        file.read_exact(&mut header_bytes).expect("read header");

        let header = WalEntryHeader::from_bytes(&header_bytes);
        let crc = header.crc32;
        let len = header.len;

        // Read entry data
        let mut entry_data = vec![0u8; len as usize];
        file.read_exact(&mut entry_data).expect("read entry data");

        // Verify CRC
        let computed_crc = crc32fast::hash(&entry_data);
        assert_eq!(crc, computed_crc, "CRC32 should match");

        // Verify entry deserializes correctly
        let entry: WalEntry = bincode::deserialize(&entry_data).expect("deserialize");
        match entry {
            WalEntry::BeginTx { tx_id, timestamp } => {
                assert_eq!(tx_id, 42);
                assert_eq!(timestamp, 1704067200);
            }
            _ => panic!("Expected BeginTx entry"),
        }
    }

    #[test]
    fn test_wal_log_all_entry_types() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Log all entry types
        let entries = vec![
            WalEntry::BeginTx {
                tx_id: 0,
                timestamp: 1000,
            },
            WalEntry::InsertNode {
                id: VertexId(0),
                record: SerializableNodeRecord {
                    id: 0,
                    label_id: 1,
                    flags: 0,
                    first_out_edge: u64::MAX,
                    first_in_edge: u64::MAX,
                    prop_head: u64::MAX,
                },
            },
            WalEntry::InsertEdge {
                id: EdgeId(0),
                record: SerializableEdgeRecord {
                    id: 0,
                    label_id: 1,
                    flags: 0,
                    src: 0,
                    dst: 1,
                    next_out: u64::MAX,
                    next_in: u64::MAX,
                    prop_head: u64::MAX,
                },
            },
            WalEntry::UpdateProperty {
                is_vertex: true,
                element_id: 0,
                key_id: 1,
                old_value: Value::Null,
                new_value: Value::Int(42),
            },
            WalEntry::DeleteNode { id: VertexId(0) },
            WalEntry::DeleteEdge { id: EdgeId(0) },
            WalEntry::CommitTx { tx_id: 0 },
            WalEntry::AbortTx { tx_id: 1 },
            WalEntry::Checkpoint { version: 1 },
        ];

        for entry in entries {
            wal.log(entry).expect("log entry");
        }

        // Verify all were written
        let pos = wal.position().expect("get position");
        assert!(
            pos > 0,
            "WAL should have content after logging all entry types"
        );
    }

    #[test]
    fn test_wal_log_large_property_value() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Create a large string value
        let large_string = "x".repeat(100_000);

        wal.log(WalEntry::UpdateProperty {
            is_vertex: true,
            element_id: 0,
            key_id: 1,
            old_value: Value::Null,
            new_value: Value::String(large_string),
        })
        .expect("log large property");

        wal.sync().expect("sync");

        let pos = wal.position().expect("get position");
        assert!(pos > 100_000, "WAL should contain the large value");
    }

    #[test]
    fn test_wal_multiple_transactions() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Transaction 1: committed
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert node");
        wal.log(WalEntry::CommitTx { tx_id: tx1 })
            .expect("commit tx1");

        // Transaction 2: aborted
        let tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert node");
        wal.log(WalEntry::AbortTx { tx_id: tx2 })
            .expect("abort tx2");

        // Transaction 3: committed
        let tx3 = wal.begin_transaction().expect("begin tx3");
        wal.log(WalEntry::InsertNode {
            id: VertexId(2),
            record: SerializableNodeRecord {
                id: 2,
                label_id: 2,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert node");
        wal.log(WalEntry::CommitTx { tx_id: tx3 })
            .expect("commit tx3");

        wal.sync().expect("sync");

        // Verify file has expected transaction IDs
        assert_eq!(tx1, 0);
        assert_eq!(tx2, 1);
        assert_eq!(tx3, 2);
    }

    #[test]
    fn test_wal_now_returns_reasonable_timestamp() {
        // This test verifies that `now()` returns a reasonable Unix timestamp
        // We can't test the exact value, but we can verify it's in a reasonable range
        let timestamp = WriteAheadLog::now();

        // Should be after 2024-01-01 (1704067200)
        assert!(
            timestamp > 1704067200,
            "timestamp should be after 2024-01-01"
        );

        // Should be before 2100-01-01 (4102444800) - gives us plenty of runway
        assert!(
            timestamp < 4102444800,
            "timestamp should be before 2100-01-01"
        );
    }

    // =========================================================================
    // Phase 3.4: Reading and Recovery Tests
    // =========================================================================

    #[test]
    fn test_read_entry_single() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write a single entry
        wal.log(WalEntry::BeginTx {
            tx_id: 42,
            timestamp: 1704067200,
        })
        .expect("log entry");
        wal.sync().expect("sync");

        // Read it back
        wal.seek_to_start().expect("seek");
        let entry = wal.read_entry().expect("read entry");

        match entry {
            WalEntry::BeginTx { tx_id, timestamp } => {
                assert_eq!(tx_id, 42);
                assert_eq!(timestamp, 1704067200);
            }
            _ => panic!("Expected BeginTx entry"),
        }
    }

    #[test]
    fn test_read_entry_multiple() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write multiple entries
        let entries_to_write = vec![
            WalEntry::BeginTx {
                tx_id: 0,
                timestamp: 1000,
            },
            WalEntry::InsertNode {
                id: VertexId(0),
                record: SerializableNodeRecord {
                    id: 0,
                    label_id: 1,
                    flags: 0,
                    first_out_edge: u64::MAX,
                    first_in_edge: u64::MAX,
                    prop_head: u64::MAX,
                },
            },
            WalEntry::CommitTx { tx_id: 0 },
        ];

        for entry in &entries_to_write {
            wal.log(entry.clone()).expect("log entry");
        }
        wal.sync().expect("sync");

        // Read all entries back
        wal.seek_to_start().expect("seek");
        let mut read_entries = Vec::new();
        loop {
            match wal.read_entry() {
                Ok(entry) => read_entries.push(entry),
                Err(StorageError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
                Err(e) => panic!("Unexpected error: {:?}", e),
            }
        }

        assert_eq!(read_entries.len(), 3);
        assert_eq!(read_entries[0], entries_to_write[0]);
        assert_eq!(read_entries[1], entries_to_write[1]);
        assert_eq!(read_entries[2], entries_to_write[2]);
    }

    #[test]
    fn test_read_entry_crc_mismatch_detected() {
        use std::io::Write;

        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");

        // Write a valid entry
        {
            let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");
            wal.log(WalEntry::BeginTx {
                tx_id: 0,
                timestamp: 1000,
            })
            .expect("log entry");
            wal.sync().expect("sync");
        }

        // Corrupt the entry data (after the header)
        {
            let mut file = OpenOptions::new()
                .read(true)
                .write(true)
                .open(&wal_path)
                .expect("open file");

            // Corrupt byte at offset 10 (past header)
            file.seek(SeekFrom::Start(10)).expect("seek");
            file.write_all(&[0xFF]).expect("write");
            file.sync_all().expect("sync");
        }

        // Try to read - should detect CRC mismatch
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");
        wal.seek_to_start().expect("seek");

        let result = wal.read_entry();
        assert!(result.is_err(), "Should detect CRC mismatch");

        match result {
            Err(StorageError::WalCorrupted(msg)) => {
                assert!(
                    msg.contains("CRC32 mismatch"),
                    "Error should mention CRC mismatch: {}",
                    msg
                );
            }
            _ => panic!("Expected WalCorrupted error"),
        }
    }

    #[test]
    fn test_read_entry_eof_error() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Don't write anything - file is empty
        let result = wal.read_entry();

        assert!(result.is_err());
        match result {
            Err(StorageError::Io(e)) => {
                assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
            }
            _ => panic!("Expected EOF error"),
        }
    }

    #[test]
    fn test_read_all_entries() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write multiple entries
        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert");
        wal.log(WalEntry::CommitTx { tx_id }).expect("log commit");
        wal.sync().expect("sync");

        // Read all entries
        let entries = wal.read_all_entries().expect("read all");

        assert_eq!(entries.len(), 3);
        assert!(matches!(entries[0], WalEntry::BeginTx { .. }));
        assert!(matches!(entries[1], WalEntry::InsertNode { .. }));
        assert!(matches!(entries[2], WalEntry::CommitTx { .. }));
    }

    #[test]
    fn test_read_all_entries_empty_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let entries = wal.read_all_entries().expect("read all");
        assert!(entries.is_empty(), "Empty WAL should have no entries");
    }

    #[test]
    fn test_needs_recovery_empty_wal() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        assert!(!wal.needs_recovery(), "Empty WAL should not need recovery");
    }

    #[test]
    fn test_needs_recovery_committed_transaction() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write a committed transaction
        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert");
        wal.log(WalEntry::CommitTx { tx_id }).expect("log commit");
        wal.sync().expect("sync");

        assert!(
            !wal.needs_recovery(),
            "Committed transaction should not need recovery"
        );
    }

    #[test]
    fn test_needs_recovery_uncommitted_transaction() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write an uncommitted transaction
        let _tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert");
        // No CommitTx!
        wal.sync().expect("sync");

        assert!(
            wal.needs_recovery(),
            "Uncommitted transaction should need recovery"
        );
    }

    #[test]
    fn test_needs_recovery_aborted_transaction() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write an aborted transaction
        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("log insert");
        wal.log(WalEntry::AbortTx { tx_id }).expect("log abort");
        wal.sync().expect("sync");

        assert!(
            !wal.needs_recovery(),
            "Aborted transaction should not need recovery"
        );
    }

    #[test]
    fn test_needs_recovery_mixed_transactions() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Transaction 1: committed
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx1 })
            .expect("commit tx1");

        // Transaction 2: uncommitted
        let _tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        // No CommitTx!

        wal.sync().expect("sync");

        assert!(
            wal.needs_recovery(),
            "Mixed transactions with one uncommitted should need recovery"
        );
    }

    #[test]
    fn test_needs_recovery_checkpoint_clears_state() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write committed transaction followed by checkpoint
        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id }).expect("commit");
        wal.log(WalEntry::Checkpoint { version: 1 })
            .expect("checkpoint");
        wal.sync().expect("sync");

        assert!(
            !wal.needs_recovery(),
            "After checkpoint, should not need recovery"
        );
    }

    #[test]
    fn test_truncate_clears_file() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write some entries
        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id }).expect("commit");
        wal.sync().expect("sync");

        // Verify file has content
        let size_before = wal.file_size().expect("get size");
        assert!(size_before > 0, "WAL should have content before truncate");

        // Truncate
        wal.truncate().expect("truncate");

        // Verify file is empty
        let size_after = wal.file_size().expect("get size");
        assert_eq!(size_after, 0, "WAL should be empty after truncate");
    }

    #[test]
    fn test_truncate_allows_new_writes() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write, truncate, write again
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::CommitTx { tx_id: tx1 })
            .expect("commit tx1");

        wal.truncate().expect("truncate");

        let tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::CommitTx { tx_id: tx2 })
            .expect("commit tx2");
        wal.sync().expect("sync");

        // Read back entries - should only see tx2's entries
        let entries = wal.read_all_entries().expect("read all");
        assert_eq!(entries.len(), 2, "Should have 2 entries from tx2");
    }

    #[test]
    fn test_file_size() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Empty file
        let size0 = wal.file_size().expect("get size");
        assert_eq!(size0, 0, "New WAL should be empty");

        // After one entry
        wal.log(WalEntry::BeginTx {
            tx_id: 0,
            timestamp: 1000,
        })
        .expect("log");
        wal.sync().expect("sync");

        let size1 = wal.file_size().expect("get size");
        assert!(size1 > 0, "WAL should have content after logging");
    }

    #[test]
    fn test_seek_to_start() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Write an entry
        wal.log(WalEntry::BeginTx {
            tx_id: 42,
            timestamp: 1000,
        })
        .expect("log");
        wal.sync().expect("sync");

        // Seek to start and read
        wal.seek_to_start().expect("seek");
        let entry = wal.read_entry().expect("read");

        match entry {
            WalEntry::BeginTx { tx_id, .. } => assert_eq!(tx_id, 42),
            _ => panic!("Expected BeginTx"),
        }

        // Seek to start again and read again
        wal.seek_to_start().expect("seek");
        let entry2 = wal.read_entry().expect("read");

        match entry2 {
            WalEntry::BeginTx { tx_id, .. } => assert_eq!(tx_id, 42),
            _ => panic!("Expected BeginTx"),
        }
    }

    #[test]
    fn test_get_committed_entries_single_committed() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let tx_id = wal.begin_transaction().expect("begin tx");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 2,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id }).expect("commit");
        wal.sync().expect("sync");

        let committed = wal.get_committed_entries().expect("get committed");

        // Should have 2 InsertNode entries (not BeginTx or CommitTx)
        assert_eq!(committed.len(), 2);
        assert!(matches!(
            committed[0],
            WalEntry::InsertNode {
                id: VertexId(0),
                ..
            }
        ));
        assert!(matches!(
            committed[1],
            WalEntry::InsertNode {
                id: VertexId(1),
                ..
            }
        ));
    }

    #[test]
    fn test_get_committed_entries_excludes_aborted() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Transaction 1: committed
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx1 }).expect("commit");

        // Transaction 2: aborted
        let tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 2,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::AbortTx { tx_id: tx2 }).expect("abort");

        wal.sync().expect("sync");

        let committed = wal.get_committed_entries().expect("get committed");

        // Should only have entries from tx1
        assert_eq!(committed.len(), 1);
        assert!(matches!(
            committed[0],
            WalEntry::InsertNode {
                id: VertexId(0),
                ..
            }
        ));
    }

    #[test]
    fn test_get_committed_entries_excludes_uncommitted() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Transaction 1: committed
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx1 }).expect("commit");

        // Transaction 2: uncommitted
        let _tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 2,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        // No commit!

        wal.sync().expect("sync");

        let committed = wal.get_committed_entries().expect("get committed");

        // Should only have entries from tx1
        assert_eq!(committed.len(), 1);
        assert!(matches!(
            committed[0],
            WalEntry::InsertNode {
                id: VertexId(0),
                ..
            }
        ));
    }

    #[test]
    fn test_get_committed_entries_preserves_order() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        // Transaction 1
        let tx1 = wal.begin_transaction().expect("begin tx1");
        wal.log(WalEntry::InsertNode {
            id: VertexId(0),
            record: SerializableNodeRecord {
                id: 0,
                label_id: 1,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx1 }).expect("commit");

        // Transaction 2
        let tx2 = wal.begin_transaction().expect("begin tx2");
        wal.log(WalEntry::InsertNode {
            id: VertexId(1),
            record: SerializableNodeRecord {
                id: 1,
                label_id: 2,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx2 }).expect("commit");

        // Transaction 3
        let tx3 = wal.begin_transaction().expect("begin tx3");
        wal.log(WalEntry::InsertNode {
            id: VertexId(2),
            record: SerializableNodeRecord {
                id: 2,
                label_id: 3,
                flags: 0,
                first_out_edge: u64::MAX,
                first_in_edge: u64::MAX,
                prop_head: u64::MAX,
            },
        })
        .expect("insert");
        wal.log(WalEntry::CommitTx { tx_id: tx3 }).expect("commit");

        wal.sync().expect("sync");

        let committed = wal.get_committed_entries().expect("get committed");

        // Should have entries in order: 0, 1, 2
        assert_eq!(committed.len(), 3);
        assert!(matches!(
            committed[0],
            WalEntry::InsertNode {
                id: VertexId(0),
                ..
            }
        ));
        assert!(matches!(
            committed[1],
            WalEntry::InsertNode {
                id: VertexId(1),
                ..
            }
        ));
        assert!(matches!(
            committed[2],
            WalEntry::InsertNode {
                id: VertexId(2),
                ..
            }
        ));
    }

    #[test]
    fn test_get_committed_entries_empty_wal() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let committed = wal.get_committed_entries().expect("get committed");
        assert!(committed.is_empty());
    }

    #[test]
    fn test_roundtrip_write_read_all_entry_types() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let wal_path = dir.path().join("test.wal");
        let mut wal = WriteAheadLog::open(&wal_path).expect("open WAL");

        let entries_to_write = vec![
            WalEntry::BeginTx {
                tx_id: 0,
                timestamp: 1000,
            },
            WalEntry::InsertNode {
                id: VertexId(0),
                record: SerializableNodeRecord {
                    id: 0,
                    label_id: 1,
                    flags: 0,
                    first_out_edge: u64::MAX,
                    first_in_edge: u64::MAX,
                    prop_head: 100,
                },
            },
            WalEntry::InsertEdge {
                id: EdgeId(0),
                record: SerializableEdgeRecord {
                    id: 0,
                    label_id: 2,
                    flags: 0,
                    src: 0,
                    dst: 1,
                    next_out: u64::MAX,
                    next_in: u64::MAX,
                    prop_head: 200,
                },
            },
            WalEntry::UpdateProperty {
                is_vertex: true,
                element_id: 0,
                key_id: 3,
                old_value: Value::Null,
                new_value: Value::String("hello".to_string()),
            },
            WalEntry::DeleteNode { id: VertexId(0) },
            WalEntry::DeleteEdge { id: EdgeId(0) },
            WalEntry::CommitTx { tx_id: 0 },
            WalEntry::AbortTx { tx_id: 1 },
            WalEntry::Checkpoint { version: 42 },
        ];

        // Write all entries
        for entry in &entries_to_write {
            wal.log(entry.clone()).expect("log entry");
        }
        wal.sync().expect("sync");

        // Read all entries
        let entries_read = wal.read_all_entries().expect("read all");

        // Verify they match
        assert_eq!(entries_read.len(), entries_to_write.len());
        for (i, (written, read)) in entries_to_write.iter().zip(entries_read.iter()).enumerate() {
            assert_eq!(written, read, "Entry {} mismatch", i);
        }
    }
}